repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
xbib/z3950
|
z3950-common/src/main/java/org/xbib/z3950/common/v3/SearchResponse.java
|
<reponame>xbib/z3950
package org.xbib.z3950.common.v3;
import org.xbib.asn1.ASN1Any;
import org.xbib.asn1.ASN1Boolean;
import org.xbib.asn1.ASN1EncodingException;
import org.xbib.asn1.ASN1Exception;
import org.xbib.asn1.ASN1Integer;
import org.xbib.asn1.ASN1Sequence;
import org.xbib.asn1.BERConstructed;
import org.xbib.asn1.BEREncoding;
/**
* Class for representing a <code>SearchResponse</code> from <code>Z39-50-APDU-1995</code>.
* <pre>
* SearchResponse ::=
* SEQUENCE {
* referenceId ReferenceId OPTIONAL
* resultCount [23] IMPLICIT INTEGER
* numberOfRecordsReturned [24] IMPLICIT INTEGER
* nextResultSetPosition [25] IMPLICIT INTEGER
* searchStatus [22] IMPLICIT BOOLEAN
* resultSetStatus [26] IMPLICIT INTEGER OPTIONAL
* presentStatus PresentStatus OPTIONAL
* records Records OPTIONAL
* additionalSearchInfo [203] IMPLICIT OtherInformation OPTIONAL
* otherInfo OtherInformation OPTIONAL
* }
* </pre>
*/
public final class SearchResponse extends ASN1Any {
// Enumerated constants for resultSetStatus
public static final int E_subset = 1;
public static final int E_interim = 2;
public static final int E_none = 3;
public ReferenceId referenceId; // optional
public ASN1Integer resultCount;
public ASN1Integer numberOfRecordsReturned;
public ASN1Integer nextResultSetPosition;
public ASN1Boolean s_searchStatus;
public ASN1Integer s_resultSetStatus; // optional
public PresentStatus s_presentStatus; // optional
public Records s_records; // optional
public OtherInformation s_additionalSearchInfo; // optional
public OtherInformation s_otherInfo; // optional
/**
* Constructor for a SearchResponse from a BER encoding.
*
* @param ber the BER encoding.
* @param checkTag will check tag if true, use false
* if the BER has been implicitly tagged. You should
* usually be passing true.
* @throws ASN1Exception if the BER encoding is bad.
*/
public SearchResponse(BEREncoding ber, boolean checkTag) throws ASN1Exception {
super(ber, checkTag);
}
/**
* Initializing object from a BER encoding.
* This method is for internal use only. You should use
* the constructor that takes a BEREncoding.
*
* @param ber the BER to decode.
* @param checkTag if the tag should be checked.
* @throws ASN1Exception if the BER encoding is bad.
*/
@Override
public void berDecode(BEREncoding ber, boolean checkTag) throws ASN1Exception {
BERConstructed berConstructed;
try {
berConstructed = (BERConstructed) ber;
} catch (ClassCastException e) {
throw new ASN1EncodingException("bad BER form");
}
int numParts = berConstructed.numberComponents();
int part = 0;
BEREncoding p;
if (numParts <= part) {
throw new ASN1Exception("incomplete");
}
p = berConstructed.elementAt(part);
try {
referenceId = new ReferenceId(p, true);
part++; // yes, consumed
} catch (ASN1Exception e) {
referenceId = null; // no, not present
}
if (numParts <= part) {
throw new ASN1Exception("incomplete");
}
p = berConstructed.elementAt(part);
if (p.getTag() != 23 ||
p.getTagType() != BEREncoding.CONTEXT_SPECIFIC_TAG) {
throw new ASN1EncodingException("bad tag in s_resultCount");
}
resultCount = new ASN1Integer(p, false);
part++;
if (numParts <= part) {
throw new ASN1Exception("incomplete");
}
p = berConstructed.elementAt(part);
if (p.getTag() != 24 ||
p.getTagType() != BEREncoding.CONTEXT_SPECIFIC_TAG) {
throw new ASN1EncodingException("bad tag in s_numberOfRecordsReturned");
}
numberOfRecordsReturned = new ASN1Integer(p, false);
part++;
if (numParts <= part) {
throw new ASN1Exception("incomplete");
}
p = berConstructed.elementAt(part);
if (p.getTag() != 25 ||
p.getTagType() != BEREncoding.CONTEXT_SPECIFIC_TAG) {
throw new ASN1EncodingException("bad tag in s_nextResultSetPosition");
}
nextResultSetPosition = new ASN1Integer(p, false);
part++;
if (numParts <= part) {
throw new ASN1Exception("incomplete");
}
p = berConstructed.elementAt(part);
if (p.getTag() != 22 ||
p.getTagType() != BEREncoding.CONTEXT_SPECIFIC_TAG) {
throw new ASN1EncodingException("bad tag in s_searchStatus");
}
s_searchStatus = new ASN1Boolean(p, false);
part++;
s_resultSetStatus = null;
s_presentStatus = null;
s_records = null;
s_additionalSearchInfo = null;
s_otherInfo = null;
if (numParts <= part) {
return;
}
p = berConstructed.elementAt(part);
if (p.getTag() == 26 &&
p.getTagType() == BEREncoding.CONTEXT_SPECIFIC_TAG) {
s_resultSetStatus = new ASN1Integer(p, false);
part++;
}
// Decoding: presentStatus PresentStatus OPTIONAL
if (numParts <= part) {
return; // no more data, but ok (rest is optional)
}
p = berConstructed.elementAt(part);
try {
s_presentStatus = new PresentStatus(p, true);
part++; // yes, consumed
} catch (ASN1Exception e) {
s_presentStatus = null; // no, not present
}
// Decoding: records Records OPTIONAL
if (numParts <= part) {
return; // no more data, but ok (rest is optional)
}
p = berConstructed.elementAt(part);
try {
s_records = new Records(p, true);
part++; // yes, consumed
} catch (ASN1Exception e) {
s_records = null; // no, not present
}
// Decoding: additionalSearchInfo [203] IMPLICIT OtherInformation OPTIONAL
if (numParts <= part) {
return; // no more data, but ok (rest is optional)
}
p = berConstructed.elementAt(part);
if (p.getTag() == 203 &&
p.getTagType() == BEREncoding.CONTEXT_SPECIFIC_TAG) {
s_additionalSearchInfo = new OtherInformation(p, false);
part++;
}
// Decoding: otherInfo OtherInformation OPTIONAL
if (numParts <= part) {
return; // no more data, but ok (rest is optional)
}
p = berConstructed.elementAt(part);
try {
s_otherInfo = new OtherInformation(p, true);
part++; // yes, consumed
} catch (ASN1Exception e) {
s_otherInfo = null; // no, not present
}
// Should not be any more parts
if (part < numParts) {
throw new ASN1Exception("bad BER: extra data " + part + "/" + numParts + " processed");
}
}
/**
* Returns a BER encoding of the SearchResponse.
*
* @return The BER encoding.
* @throws ASN1Exception Invalid or cannot be encoded.
*/
@Override
public BEREncoding berEncode() throws ASN1Exception {
return berEncode(BEREncoding.UNIVERSAL_TAG, ASN1Sequence.SEQUENCE_TAG);
}
/**
* Returns a BER encoding of SearchResponse, implicitly tagged.
*
* @param tagType The type of the implicit tag.
* @param tag The implicit tag.
* @return The BER encoding of the object.
* @throws ASN1Exception When invalid or cannot be encoded.
*/
@Override
public BEREncoding berEncode(int tagType, int tag) throws ASN1Exception {
// Calculate the number of fields in the encoding
int numFields = 4; // number of mandatories
if (referenceId != null) {
numFields++;
}
if (s_resultSetStatus != null) {
numFields++;
}
if (s_presentStatus != null) {
numFields++;
}
if (s_records != null) {
numFields++;
}
if (s_additionalSearchInfo != null) {
numFields++;
}
if (s_otherInfo != null) {
numFields++;
}
// Encode it
BEREncoding fields[] = new BEREncoding[numFields];
int x = 0;
// Encoding s_referenceId: ReferenceId OPTIONAL
if (referenceId != null) {
fields[x++] = referenceId.berEncode();
}
// Encoding s_resultCount: INTEGER
fields[x++] = resultCount.berEncode(BEREncoding.CONTEXT_SPECIFIC_TAG, 23);
// Encoding s_numberOfRecordsReturned: INTEGER
fields[x++] = numberOfRecordsReturned.berEncode(BEREncoding.CONTEXT_SPECIFIC_TAG, 24);
// Encoding s_nextResultSetPosition: INTEGER
fields[x++] = nextResultSetPosition.berEncode(BEREncoding.CONTEXT_SPECIFIC_TAG, 25);
// Encoding s_searchStatus: BOOLEAN
fields[x++] = s_searchStatus.berEncode(BEREncoding.CONTEXT_SPECIFIC_TAG, 22);
// Encoding s_resultSetStatus: INTEGER OPTIONAL
if (s_resultSetStatus != null) {
fields[x++] = s_resultSetStatus.berEncode(BEREncoding.CONTEXT_SPECIFIC_TAG, 26);
}
// Encoding s_presentStatus: PresentStatus OPTIONAL
if (s_presentStatus != null) {
fields[x++] = s_presentStatus.berEncode();
}
// Encoding s_records: Records OPTIONAL
if (s_records != null) {
fields[x++] = s_records.berEncode();
}
// Encoding s_additionalSearchInfo: OtherInformation OPTIONAL
if (s_additionalSearchInfo != null) {
fields[x++] = s_additionalSearchInfo.berEncode(BEREncoding.CONTEXT_SPECIFIC_TAG, 203);
}
// Encoding s_otherInfo: OtherInformation OPTIONAL
if (s_otherInfo != null) {
fields[x] = s_otherInfo.berEncode();
}
return new BERConstructed(tagType, tag, fields);
}
/**
* Returns a new String object containing a text representing
* of the SearchResponse.
*/
@Override
public String toString() {
StringBuilder str = new StringBuilder("{");
int outputted = 0;
if (referenceId != null) {
str.append("referenceId ");
str.append(referenceId);
outputted++;
}
if (0 < outputted) {
str.append(", ");
}
str.append("resultCount ");
str.append(resultCount);
outputted++;
if (0 < outputted) {
str.append(", ");
}
str.append("numberOfRecordsReturned ");
str.append(numberOfRecordsReturned);
outputted++;
if (0 < outputted) {
str.append(", ");
}
str.append("nextResultSetPosition ");
str.append(nextResultSetPosition);
outputted++;
if (0 < outputted) {
str.append(", ");
}
str.append("searchStatus ");
str.append(s_searchStatus);
outputted++;
if (s_resultSetStatus != null) {
if (0 < outputted) {
str.append(", ");
}
str.append("resultSetStatus ");
str.append(s_resultSetStatus);
outputted++;
}
if (s_presentStatus != null) {
if (0 < outputted) {
str.append(", ");
}
str.append("presentStatus ");
str.append(s_presentStatus);
outputted++;
}
if (s_records != null) {
if (0 < outputted) {
str.append(", ");
}
str.append("records ");
str.append(s_records);
outputted++;
}
if (s_additionalSearchInfo != null) {
if (0 < outputted) {
str.append(", ");
}
str.append("additionalSearchInfo ");
str.append(s_additionalSearchInfo);
outputted++;
}
if (s_otherInfo != null) {
if (0 < outputted) {
str.append(", ");
}
str.append("otherInfo ");
str.append(s_otherInfo);
}
str.append("}");
return str.toString();
}
}
|
salimfadhley/funproxy
|
src/main/scala/web/ProxyInfo.scala
|
package web
/**
* Created by salim on 03/02/2016.
*/
case class ProxyInfo(url:String)
|
JulianBiancardi/Wolfenstein-Taller1
|
client/src/main/launcher/include/settings.h
|
<filename>client/src/main/launcher/include/settings.h
#ifndef SETTINGS_H
#define SETTINGS_H
#include <stddef.h>
class Settings {
private:
size_t screen_width;
size_t screen_height;
bool fullscreen;
size_t music_volume;
size_t effect_volume;
public:
Settings();
~Settings();
/*Change the resolution*/
void set_resolution(size_t screen_width, size_t screen_height,
bool fullscreen);
/*Change the music volume*/
void set_music_volume(size_t value);
/*Change the effect volume*/
void set_effect_volume(size_t value);
size_t get_screen_width() const;
size_t get_screen_height() const;
bool is_fullscreen() const;
size_t get_music_volume() const;
size_t get_effect_volume() const;
};
#endif // SETTINGS_H
|
brunolauze/MonoNative
|
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_GCHandle_Fixture.cpp
|
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Runtime.InteropServices
// Name: GCHandle
// C++ Typed Name: mscorlib::System::Runtime::InteropServices::GCHandle
#include <gtest/gtest.h>
#include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_GCHandle.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace InteropServices
{
//Public Methods Tests
// Method AddrOfPinnedObject
// Signature:
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,AddrOfPinnedObject_Test)
{
}
// Method Free
// Signature:
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,Free_Test)
{
}
// Method Equals
// Signature: mscorlib::System::Object o
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,Equals_Test)
{
}
// Method GetHashCode
// Signature:
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,GetHashCode_Test)
{
}
//Public Static Methods Tests
// Method Alloc
// Signature: mscorlib::System::Object value
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,Alloc_1_StaticTest)
{
}
// Method Alloc
// Signature: mscorlib::System::Object value, mscorlib::System::Runtime::InteropServices::GCHandleType::__ENUM__ type
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,Alloc_2_StaticTest)
{
}
// Method FromIntPtr
// Signature: mscorlib::System::IntPtr value
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,FromIntPtr_StaticTest)
{
}
// Method ToIntPtr
// Signature: mscorlib::System::Runtime::InteropServices::GCHandle value
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,ToIntPtr_StaticTest)
{
}
//Public Properties Tests
// Property IsAllocated
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,get_IsAllocated_Test)
{
}
// Property Target
// Return Type: mscorlib::System::Object
// Property Get Method
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,get_Target_Test)
{
}
// Property Target
// Return Type: mscorlib::System::Object
// Property Set Method
TEST(mscorlib_System_Runtime_InteropServices_GCHandle_Fixture,set_Target_Test)
{
}
}
}
}
}
|
liu8jianwei/JiaCrontab
|
pkg/crontab/crontab.go
|
package crontab
import (
"container/heap"
"errors"
"jiacrontab/pkg/pqueue"
"sync"
"time"
)
// Task 任务
type Task = pqueue.Item
type Crontab struct {
pq pqueue.PriorityQueue
mux sync.RWMutex
ready chan *Task
}
func New() *Crontab {
return &Crontab{
pq: pqueue.New(10000),
ready: make(chan *Task, 10000),
}
}
// AddJob 添加未经处理的job
func (c *Crontab) AddJob(j *Job) error {
nt, err := j.NextExecutionTime(time.Now())
if err != nil {
return errors.New("Invalid execution time")
}
c.mux.Lock()
heap.Push(&c.pq, &Task{
Priority: nt.UnixNano(),
Value: j,
})
c.mux.Unlock()
return nil
}
// AddJob 添加延时任务
func (c *Crontab) AddTask(t *Task) {
c.mux.Lock()
heap.Push(&c.pq, t)
c.mux.Unlock()
}
func (c *Crontab) Len() int {
c.mux.RLock()
len := len(c.pq)
c.mux.RUnlock()
return len
}
func (c *Crontab) GetAllTask() []*Task {
c.mux.Lock()
list := c.pq
c.mux.Unlock()
return list
}
func (c *Crontab) Ready() <-chan *Task {
return c.ready
}
func (c *Crontab) QueueScanWorker() {
refreshTicker := time.NewTicker(20 * time.Millisecond)
for {
select {
case <-refreshTicker.C:
if len(c.pq) == 0 {
continue
}
start:
c.mux.Lock()
now := time.Now().UnixNano()
job, _ := c.pq.PeekAndShift(now)
c.mux.Unlock()
if job == nil {
continue
}
c.ready <- job
goto start
}
}
}
|
DwayneJengSage/Synapse-Stack-Builder
|
src/main/java/org/sagebionetworks/template/repo/VelocityExceptionThrower.java
|
<reponame>DwayneJengSage/Synapse-Stack-Builder
package org.sagebionetworks.template.repo;
public class VelocityExceptionThrower {
public void throwException(String message) throws IllegalStateException {
throw new IllegalStateException(message);
}
}
|
moritzfl/DependencyFinder
|
tests/com/jeantessier/dependency/TestFeatureResolver.java
|
/*
* Copyright (c) 2001-2009, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Jean Tessier nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jeantessier.dependency;
import java.util.*;
import org.jmock.*;
import org.jmock.integration.junit3.*;
import org.jmock.lib.legacy.*;
public class TestFeatureResolver extends MockObjectTestCase {
private FeatureResolver sut;
protected void setUp() throws Exception {
super.setUp();
setImposteriser(ClassImposteriser.INSTANCE);
sut = new FeatureResolver();
}
public void testTraverseNodes() {
final Node mockNode1 = mock(Node.class, "node1");
final Node mockNode2 = mock(Node.class, "node2");
final Collection<Node> nodes = new LinkedList<Node>();
nodes.add(mockNode1);
nodes.add(mockNode2);
checking(new Expectations() {{
one (mockNode1).accept(sut);
one (mockNode2).accept(sut);
}});
sut.traverseNodes(nodes);
}
public void testVisitPackageNode() {
final PackageNode mockPackageNode = mock(PackageNode.class);
final ClassNode mockClassNode1 = mock(ClassNode.class, "class1");
final ClassNode mockClassNode2 = mock(ClassNode.class, "class2");
final Collection<ClassNode> classes = new LinkedList<ClassNode>();
classes.add(mockClassNode1);
classes.add(mockClassNode2);
checking(new Expectations() {{
one (mockPackageNode).getClasses();
will(returnValue(classes));
one (mockClassNode1).accept(sut);
one (mockClassNode2).accept(sut);
}});
sut.visitPackageNode(mockPackageNode);
}
public void testVisitInboundPackageNode() {
final PackageNode mockPackageNode = mock(PackageNode.class);
sut.visitInboundPackageNode(mockPackageNode);
}
public void testVisitOutboundPackageNode() {
final PackageNode mockPackageNode = mock(PackageNode.class);
sut.visitOutboundPackageNode(mockPackageNode);
}
public void testVisitClassNode() {
final ClassNode mockClassNode = mock(ClassNode.class);
final FeatureNode mockFeatureNode1 = mock(FeatureNode.class, "feature1");
final FeatureNode mockFeatureNode2 = mock(FeatureNode.class, "feature2");
final Collection<FeatureNode> features = new LinkedList<FeatureNode>();
features.add(mockFeatureNode1);
features.add(mockFeatureNode2);
checking(new Expectations() {{
one (mockClassNode).getFeatures();
will(returnValue(features));
one (mockFeatureNode1).accept(sut);
one (mockFeatureNode2).accept(sut);
}});
sut.visitClassNode(mockClassNode);
}
public void testVisitInboundClassNode() {
final ClassNode mockClassNode = mock(ClassNode.class);
sut.visitInboundClassNode(mockClassNode);
}
public void testVisitOutboundClassNode() {
final ClassNode mockClassNode = mock(ClassNode.class);
sut.visitOutboundClassNode(mockClassNode);
}
public void testVisitFeatureNode() {
final String TARGET_SIMPLE_NAME = "target()";
final String CHILD_NAME = "Child";
final String CHILD_TARGET_NAME = CHILD_NAME + "." + TARGET_SIMPLE_NAME;
final String PARENT_NAME = "Parent";
final String PARENT_TARGET_NAME = PARENT_NAME + "." + TARGET_SIMPLE_NAME;
final FeatureNode mockCallerSource = mock(FeatureNode.class, "Caller.source()");
final FeatureNode mockParentTarget = mock(FeatureNode.class, PARENT_TARGET_NAME);
final ClassNode mockChild = mock(ClassNode.class, CHILD_NAME);
final FeatureNode mockChildTarget = mock(FeatureNode.class, CHILD_TARGET_NAME);
checking(new Expectations() {{
atLeast(1).of (mockChildTarget).getSimpleName();
will(returnValue(TARGET_SIMPLE_NAME));
atLeast(1).of (mockChildTarget).getClassNode();
will(returnValue(mockChild));
one (mockChild).getInheritedFeatures(TARGET_SIMPLE_NAME);
will(returnValue(Collections.singleton(mockParentTarget)));
one (mockChildTarget).getInboundDependencies();
will(returnValue(Collections.singleton(mockCallerSource)));
one (mockCallerSource).addDependency(mockParentTarget);
}});
sut.visitFeatureNode(mockChildTarget);
}
public void testVisitInboundFeatureNode() {
final FeatureNode mockFeatureNode = mock(FeatureNode.class);
sut.visitInboundFeatureNode(mockFeatureNode);
}
public void testVisitOutboundFeatureNode() {
final FeatureNode mockFeatureNode = mock(FeatureNode.class);
sut.visitOutboundFeatureNode(mockFeatureNode);
}
}
|
Tomura/TacticalPrototypeCPP
|
TacticalFPS/Private/Weapons/TacticalGrenade.cpp
|
<filename>TacticalFPS/Private/Weapons/TacticalGrenade.cpp
// Copyright (c) 2015-2016, <NAME> - All rights reserved
#include "TacticalFPS.h"
#include "Net/UnrealNetwork.h"
#include "TacticalProjectile.h"
#include "TacticalGrenade.h"
#include "TacticalCharacter.h"
ATacticalGrenade::ATacticalGrenade(const FObjectInitializer& OI)
: Super(OI)
{
NumCharges = 3;
}
|
liangjisheng/go-books
|
projects/interview-everyday-2/day004.go
|
<gh_stars>1-10
package main
import (
"fmt"
"sync"
"time"
)
type data struct {
sync.Mutex
}
// 方法使用值接收器将导致锁失效 将 Mutex 作为匿名字段时
// 相关的方法必须使用指针接收者 否则会导致锁机制失效
func (d data) test(s string) {
d.Lock()
defer d.Unlock()
for i := 0; i < 5; i++ {
fmt.Println(s, i)
time.Sleep(time.Second)
}
}
func (d *data) test1(s string) {
d.Lock()
defer d.Unlock()
for i := 0; i < 5; i++ {
fmt.Println(s, i)
time.Sleep(time.Second)
}
}
func day004() {
var wg sync.WaitGroup
wg.Add(2)
var d data
go func() {
defer wg.Done()
// d.test("read") // 锁失效
d.test1("read")
}()
go func() {
defer wg.Done()
// d.test("write") // 锁失效
d.test1("write")
}()
wg.Wait()
}
|
omerio/ecarf
|
ecarf-core/src/main/java/io/ecarf/core/reason/rulebased/query/QueryGenerator.java
|
/**
* The contents of this file may be used under the terms of the Apache License, Version 2.0
* in which case, the provisions of the Apache License Version 2.0 are applicable instead of those above.
*
* Copyright 2014, Ecarf.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.ecarf.core.reason.rulebased.query;
import io.ecarf.core.reason.rulebased.GenericRule;
import io.ecarf.core.reason.rulebased.Rule;
import io.ecarf.core.triple.TermType;
import io.ecarf.core.triple.Triple;
import io.ecarf.core.utils.Utils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
/**
* This class takes in schema terms and their triples and generates a combined query for all the rules.
* The query is split according to size if it's too large
*
* @author <NAME> (omerio)
*
*/
public class QueryGenerator<T> {
private final static Log log = LogFactory.getLog(QueryGenerator.class);
//private static final String SELECT_FROM = "select subject, predicate, object from ";
private static final String SELECT = "select ";
private static final String FROM = " from ";
private String decoratedTable;
private Map<T, Set<Triple>> schemaTerms;
/**
*
*/
public QueryGenerator(Map<T, Set<Triple>> schemaTerms, String decoratedTable) {
this.decoratedTable = decoratedTable;
this.schemaTerms = schemaTerms;
}
public List<String> getQueries() {
return Lists.newArrayList(this.getQuery());
}
public String getQuery() {
//List<String> queries = new ArrayList<String>();
Map<Integer, Map<String, Set<String>>> parts = new HashMap<Integer, Map<String, Set<String>>>();
Set<String> selects = new HashSet<>();
boolean encoded = false;
for(T term: schemaTerms.keySet()) {
Set<Triple> triples = schemaTerms.get(term);
Triple schemaTriple = null;
Rule rule = null;
for(Triple sTriple: triples) {
rule = GenericRule.getRule(sTriple);
selects.addAll(rule.select());
if(schemaTriple == null) {
schemaTriple = sTriple;
encoded = schemaTriple.isEncoded();
}
}
Map<String, String> where = rule.where(schemaTriple);
Integer size = where.size();
Map<String, Set<String>> conditions = parts.get(size);
if(conditions == null) {
conditions = new HashMap<String, Set<String>>();
parts.put(size, conditions);
}
for(String triplePart: where.keySet()) {
Set<String> conditionParts = conditions.get(triplePart);
if(conditionParts == null) {
conditionParts = new HashSet<String>();
conditions.put(triplePart, conditionParts);
}
conditionParts.add(where.get(triplePart));
}
}
selects.add(TermType.predicate);
// only add the object_literal if the triple is encoded
if(!encoded) {
selects.remove(TermType.object_literal);
} else {
selects.add(TermType.subject);
selects.add(TermType.object);
}
String columns = StringUtils.join(GenericRule.getOrderedSelect(selects), ", ");
StringBuilder query = new StringBuilder(SELECT).append(columns)
.append(FROM).append(decoratedTable).append(" where ");
Set<String> conditions = new HashSet<String>();
Joiner joiner;
for(Integer key: parts.keySet()) {
Map<String, Set<String>> values = parts.get(key);
Set<String> conditionPart = new HashSet<String>();
StringBuilder condition = new StringBuilder();
for(String triplePart: values.keySet()) {
Set<String> terms = values.get(triplePart);
StringBuilder triplePartCondition = new StringBuilder(triplePart);
if(terms.size() == 1) {
triplePartCondition.append('=').append(terms.iterator().next());
} else {
joiner = Joiner.on(',');
triplePartCondition.append(" IN (").append(joiner.join(terms)).append(')');
}
conditionPart.add(triplePartCondition.toString());
}
joiner = Joiner.on(" and ");
condition.append('(').append(joiner.join(conditionPart)).append(')');
conditions.add(condition.toString());
}
joiner = Joiner.on(" OR ");
query.append(joiner.join(conditions)).append(';');
log.debug("Query size: " + Utils.getStringSize(query.toString()));
//queries.add(query.toString());
// TODO take care of query size
return query.toString();
}
/**
* @param decoratedTable the decoratedTable to set
*/
public void setDecoratedTable(String decoratedTable) {
this.decoratedTable = decoratedTable;
}
}
|
Copetan/CutefulCake
|
src/main/java/net/nullspace_mc/cutefulcake/players/FakeServerPlayerEntity.java
|
package net.nullspace_mc.cutefulcake.players;
import com.mojang.authlib.GameProfile;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.network.ServerPlayerInteractionManager;
import net.minecraft.server.world.ServerWorld;
public class FakeServerPlayerEntity extends ServerPlayerEntity {
public FakeServerPlayerEntity(MinecraftServer server, ServerWorld world, GameProfile profile, ServerPlayerInteractionManager interactionManager) {
super(server, world, profile, interactionManager);
}
@Override
public void onKilled(DamageSource source) {
super.onKilled(source);
server.getPlayerManager().remove(this);
}
}
|
thednp/color-picker
|
cypress/fixtures/getCEMarkup.js
|
<filename>cypress/fixtures/getCEMarkup.js
import ColorPickerElement from '../../src/js/color-picker-element';
import getRandomInt from './getRandomInt';
import testSample from './testSample';
import FORMAT from './format';
import colorNamesFrench from './colorNamesFrench';
import componentLabelsFrench from './componentLabelsFrench';
export default function getCEMarkup(body) {
const id = getRandomInt(0,9999);
const format = FORMAT[getRandomInt(0,3)];
const sample = testSample[getRandomInt(0,2)];
const value = sample[format];
// const cpe = document.createElement('color-picker');
const cpe = new ColorPickerElement();
cpe.setAttribute('data-id', `cpe-${format}-${id}`);
cpe.setAttribute('data-format', format);
cpe.setAttribute('data-value', value);
cpe.setAttribute('data-component-labels', JSON.stringify(componentLabelsFrench));
cpe.setAttribute('data-color-labels', colorNamesFrench);
cpe.setAttribute('data-color-keywords', 'red,gree,blue');
cpe.setAttribute('data-color-presets', '#330000,#990000,#ff0000,#ff6666,#ffcccc,#003333,#009999,#00ffff,#66ffff,#ccffff');
if (body) {
body.append(cpe);
}
return {value, id, format};
}
|
Manish3323/csw
|
csw-config/csw-config-server/src/main/scala/csw/config/server/cli/Options.scala
|
<reponame>Manish3323/csw
/*
* Copyright (c) [year] Thirty Meter Telescope International Observatory
* SPDX-License-Identifier: Apache-2.0
*/
package csw.config.server.cli
/**
* Command line options to start a config server
*
* @param initRepo a boolean value stating whether to initialize repository on server or not.
* @param port an optional port dictating where to start config server. If not provided, it is picked up from config file.
*/
case class Options(initRepo: Boolean = false, port: Option[Int] = None)
|
telenko/xdompath
|
src/Compiler/type/helper.js
|
<gh_stars>1-10
export function isArgNodeSubsetList(arg) {
return Array.isArray(arg) && arg.length > 0 && Array.isArray(arg[0]) && ((arg[0].length > 0 && arg[0][0] instanceof Node) || arg[0].length === 0);
}
|
hibernate/hibernate-semantic-query
|
src/main/java/org/hibernate/query/sqm/tree/expression/domain/SqmCollectionElementReferenceEmbedded.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.query.sqm.tree.expression.domain;
import org.hibernate.persister.common.spi.Navigable;
import org.hibernate.query.sqm.NotYetImplementedException;
import org.hibernate.query.sqm.consume.spi.SemanticQueryWalker;
import org.hibernate.query.sqm.domain.SqmExpressableTypeEmbedded;
import org.hibernate.query.sqm.domain.type.SqmDomainTypeEmbeddable;
import org.hibernate.query.sqm.tree.from.SqmFrom;
/**
* @author <NAME>
*/
public class SqmCollectionElementReferenceEmbedded
extends AbstractSqmCollectionElementReference
implements SqmCollectionElementReference, SqmEmbeddableTypedReference {
public SqmCollectionElementReferenceEmbedded(SqmPluralAttributeReference pluralAttributeBinding) {
super( pluralAttributeBinding );
}
@Override
public Navigable getReferencedNavigable() {
return (SqmExpressableTypeEmbedded) super.getReferencedNavigable();
}
@Override
public SqmDomainTypeEmbeddable getExportedDomainType() {
return (SqmDomainTypeEmbeddable) super.getExportedDomainType();
}
@Override
public SqmFrom getExportedFromElement() {
return getPluralAttributeBinding().getExportedFromElement();
}
@Override
public void injectExportedFromElement(SqmFrom sqmFrom) {
throw new NotYetImplementedException( "Cannot inject SqmFrom element into a CompositeBinding" );
}
@Override
public <T> T accept(SemanticQueryWalker<T> walker) {
throw new NotYetImplementedException( );
}
}
|
certego/certego-saas
|
certego_saas/apps/organization/serializers.py
|
<filename>certego_saas/apps/organization/serializers.py<gh_stars>1-10
from rest_flex_fields.serializers import FlexFieldsModelSerializer
from rest_framework import serializers as rfs
from certego_saas.user.models import User
from certego_saas.user.serializers import UserSerializer
from .invitation import Invitation
from .membership import Membership
from .organization import Organization
__all__ = [
"OrganizationSerializer",
"InvitationsListSerializer",
"InviteCreateSerializer",
]
class _UserMemberSerializer(FlexFieldsModelSerializer):
class Meta:
model = Membership
fields = ["username", "full_name", "joined"]
joined = rfs.DateTimeField(source="created_at")
username = rfs.CharField(source="user.username")
full_name = rfs.CharField(source="user.get_full_name")
class OrganizationSerializer(FlexFieldsModelSerializer):
class Meta:
model = Organization
exclude = ("id",)
expandable_fields = {
"members": (_UserMemberSerializer, {"many": True, "read_only": True}),
"pending_invitations": (
"certego_saas.apps.organization.InvitationsListSerializer",
{
"fields": ["id", "user", "created_at"],
"many": True,
},
),
}
members_count = rfs.IntegerField(read_only=True)
owner = _UserMemberSerializer(source="owner_membership", read_only=True)
is_user_owner = rfs.SerializerMethodField()
def get_is_user_owner(self, obj) -> bool:
user = self.context["request"].user
return obj.owner.pk == user.pk
def create(self, validated_data: dict) -> Organization:
"""
Create :class:`~.models.Organization` object.
"""
return Organization.create(
name=validated_data["name"], owner=validated_data["owner"]
)
class InvitationsListSerializer(FlexFieldsModelSerializer):
class Meta:
model = Invitation
fields = rfs.ALL_FIELDS
user = UserSerializer(fields=["username"])
organization = OrganizationSerializer(
fields=["name", "owner.username", "members_count"]
)
class InviteCreateSerializer(rfs.Serializer):
class Meta:
fields = ["username"]
username = rfs.CharField()
def create(self, validated_data) -> Invitation:
"""
Create :class:`~.models.Invitation` object.
"""
request = self.context["request"]
username: str = validated_data.get("username")
org: Organization = validated_data.get("organization")
try:
invitee = User.objects.get(username=username)
except User.DoesNotExist:
raise rfs.ValidationError({"detail": "Failed. No such user found."})
return org.invite(
invitee,
send_email=True,
request=request,
)
|
innocentdevil09/LeetCode
|
Problem 222/Problem222.java
|
<reponame>innocentdevil09/LeetCode
/**
* Given the root of a complete binary tree, return the number of the nodes in the tree.
*
* According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and
* all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last
* level h.
*
* Design an algorithm that runs in less than O(n) time complexity.
*
* Example 1:
* Input: root = [1,2,3,4,5,6]
* Output: 6
*
* Example 2:
* Input: root = []
* Output: 0
*
* Example 3:
* Input: root = [1]
* Output: 1
*
* Constraints:
* The number of nodes in the tree is in the range [0, 5 * 104].
* 0 <= Node.val <= 5 * 10^4
* The tree is guaranteed to be complete.
*/
public class Problem222 {
private static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
/**
* Binary Search
* Total no. of nodes till level (d - 1): 2^d - 1
*
* Then binary search to get no. of nodes in the last level
*
* Time Complexity: O((log N) ^ 2)
* Space Complexity: O(1)
*
* @param root
* @return
*/
private static int countNodes(Node root) {
if (root == null) { return 0; }
int depth = getDepth(root);
if (depth == 0) { return 1; }
int left = 1, right = (int) Math.pow(2, depth) - 1;
while (left <= right) {
int pivot = left + (right - left) / 2;
if (exists(pivot, depth, root)) {
left = pivot + 1;
} else {
right = pivot - 1;
}
}
return (int) Math.pow(2, depth) - 1 + left;
}
/**
* For the last level, the no. of nodes will be between 0 & 2^depth
* We use binary search to get the number of nodes present in the last level
*
* @param pivot
* @param depth
* @param x
* @return
*/
private static boolean exists(int pivot, int depth, Node x) {
int left = 0, right = (int) Math.pow(2, depth) - 1;
for (int i = 0; i < depth; i++) {
int idx = left + (right - left) / 2;
if (pivot > idx) {
x = x.right;
left = idx + 1;
} else {
x = x.left;
right = idx;
}
}
return x != null;
}
/**
* Method to get depth of node
*
* @param root
* @return
*/
private static int getDepth(Node root) {
int depth = 0;
for (Node x = root; x.left != null; x = x.left) {
depth++;
}
return depth;
}
/**
* Main method for test cases
*
* @param args
*/
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
System.out.println(countNodes(root));
}
}
|
yexiaoxiaogo/Java-demos
|
Weather/src/main/java/io/github/yexiaoxiaogo/repository/WeatherDao.java
|
package io.github.yexiaoxiaogo.repository;
import java.util.List;
import io.github.yexiaoxiaogo.Modle.WeatherModle;
public interface WeatherDao {
public WeatherModle fetchWeather(int id);
public WeatherModle insertWeather(WeatherModle weather);
public WeatherModle updateWeather(WeatherModle weather);
public List<WeatherModle> fetchAll();
}
|
afermon/freelancr
|
src/main/java/org/cosmicode/freelancr/repository/search/ProjectSearchRepository.java
|
package org.cosmicode.freelancr.repository.search;
import org.cosmicode.freelancr.domain.Project;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the Project entity.
*/
public interface ProjectSearchRepository extends ElasticsearchRepository<Project, Long> {
}
|
imorar/advanced-react
|
src/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import store from './Redux/Store';
import './Css/index.css';
import App from './Components/App';
import About from './Components/About';
import NotFound from './Components/NotFound';
import { registerObserver } from 'react-perf-devtool';
registerObserver();
ReactDOM.render(
<Provider store={store}>
<Router>
<main>
<Switch>
<Route exact path="/" component={App} />
<Route exact path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</main>
</Router>
</Provider>,
document.getElementById('root')
);
|
carlosprietobarron/group_payment
|
app/models/group.rb
|
<gh_stars>1-10
class Group < ApplicationRecord
validates :name, :icon, presence: true
belongs_to :user, foreign_key: 'user_id'
has_many :transactions
end
|
kevinoid/github-ci-status
|
lib/get-package-json.js
|
<filename>lib/get-package-json.js<gh_stars>0
/**
* @copyright Copyright 2021 <NAME> <<EMAIL>>
* @license MIT
*/
// TODO: Replace this module with `import packageJson from 'package.json';`
// once JSON modules are supported non-experimentally:
// https://github.com/nodejs/node/issues/37141
// TODO [engine:node@>=14]: import { readFile } from 'fs/promises'
import { promises as fsPromises } from 'fs';
const { readFile } = fsPromises;
let packageJsonP;
async function readJson(pathOrUrl, options) {
const content = await readFile(pathOrUrl, { encoding: 'utf8', ...options });
return JSON.parse(content);
}
/** Gets the parsed content of package.json for this module.
*
* @returns {!Promise<!object>} Parsed content of package.json.
*/
export default function getPackageJson() {
if (!packageJsonP) {
packageJsonP = readJson(new URL('../package.json', import.meta.url));
}
return packageJsonP;
}
|
amoudgl/leetcode-solutions
|
src/rotate-list.cpp
|
<filename>src/rotate-list.cpp<gh_stars>0
// Author: <NAME> [ https://leetcode.com/amoudgl/ ]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *ptr;
ListNode *HEAD;
ptr = head;
HEAD = head;
int l = 0;
while (ptr != NULL)
{
ptr = ptr->next;
l++;
}
if (l == 0) return NULL;
ptr = head;
k = k % l;
Rotate(HEAD, ptr, k);
return HEAD;
}
void Rotate(ListNode* &head, ListNode *ptr, int &k)
{
if (ptr == NULL)
return;
else if (ptr->next == NULL) ptr->next = head;
else Rotate(head, ptr->next, k);
k--;
if (k == -1)
{
head = ptr->next;
ptr->next = NULL;
}
}
};
|
lastaflute/lasta-remoteapi
|
src/main/java/org/dbflute/remoteapi/exception/translation/ClientErrorTranslatingResource.java
|
<reponame>lastaflute/lasta-remoteapi
/*
* Copyright 2015-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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.dbflute.remoteapi.exception.translation;
import java.lang.reflect.Type;
import java.util.function.BiFunction;
import org.dbflute.optional.OptionalThing;
import org.dbflute.remoteapi.exception.RemoteApiHttpClientErrorException;
/**
* @author jflute
* @since 0.3.3 (2017/09/21 Thursday)
*/
public class ClientErrorTranslatingResource {
// ===================================================================================
// Attribute
// =========
protected final Type returnType; // not null
protected final String url; // not null
protected final RemoteApiHttpClientErrorException clientError; // not null
protected final BiFunction<RemoteApiHttpClientErrorException, Object, RuntimeException> validationErrorProvider; // null allowed
// ===================================================================================
// Constructor
// ===========
public ClientErrorTranslatingResource(Type returnType, String url, RemoteApiHttpClientErrorException clientError,
BiFunction<RemoteApiHttpClientErrorException, Object, RuntimeException> validationErrorProvider) {
this.returnType = returnType;
this.url = url;
this.clientError = clientError;
this.validationErrorProvider = validationErrorProvider;
}
// ===================================================================================
// Facade
// ======
/**
* Create validation error for action response.
* <pre>
* e.g. unified failure and server-managed message
* rule.translateClientError(resource -> {
* RemoteApiHttpClientErrorException clientError = resource.getClientError();
* if (clientError.getHttpStatus() == 400) { // controlled client error
* RemoteHbUnifiedFailureResult result = (RemoteHbUnifiedFailureResult) clientError.getFailureResponse().get();
* if (RemoteUnifiedFailureType.VALIDATION_ERROR.equals(result.cause)) {
* UserMessages messages = new UserMessages();
* result.errors.forEach(error -> {
* error.messages.forEach(message -> {
* messages.add(error.field, UserMessage.asDirectMessage(message));
* });
* });
* return resource.asActionValidationError(messages);
* }
* }
* return null; // no translation
* });
*
* e.g. unified failure and client-managed message
* rule.translateClientError(resource -> {
* RemoteApiHttpClientErrorException clientError = resource.getClientError();
* if (clientError.getHttpStatus() == 400) { // controlled client error
* FaicliUnifiedFailureResult result = (FaicliUnifiedFailureResult) clientError.getFailureResponse().get();
* if (FaicliUnifiedFailureType.VALIDATION_ERROR.equals(result.cause)) {
* UserMessages messages = new UserMessages();
* result.errors.forEach(error -> {
* messages.add(error.field, toUserMessage(error));
* });
* return resource.asActionValidationError(messages);
* }
* }
* return null; // no translation
* });
* </pre>
* @param messages The messages from error response. (NotNull)
* @return The exception of validation error for action response. (NotNull)
*/
public RuntimeException asActionValidationError(Object messages) {
if (messages == null) {
throw new IllegalArgumentException("The argument 'messages' should not be null.");
}
assertValidationErrorPrepared(messages);
return validationErrorProvider.apply(clientError, messages); // errorHook is HtmlResponse or ApiFailureHook
}
/**
* @param messages The messages from error response. (NotNull)
* @return The exception of validation error for HTML response. (NotNull)
* @deprecated use asActionValidationError(), already not only for HTML but also AJAX
*/
public RuntimeException asHtmlValidationError(Object messages) {
return asActionValidationError(messages);
}
protected void assertValidationErrorPrepared(Object messages) {
if (validationErrorProvider == null) {
String msg = "Not found the validation error provider, unsupported?: messages=" + messages;
throw new IllegalStateException(msg);
}
}
// ===================================================================================
// Accessor
// ========
public Type getReturnType() {
return returnType;
}
public String getUrl() {
return url;
}
@Deprecated
public RemoteApiHttpClientErrorException getCause() { // use getClientError()
return clientError;
}
public RemoteApiHttpClientErrorException getClientError() {
return clientError;
}
public OptionalThing<BiFunction<RemoteApiHttpClientErrorException, Object, RuntimeException>> getValidationErrorHook() {
return OptionalThing.ofNullable(validationErrorProvider, () -> {
throw new IllegalStateException("Not found the validation error provider: url=" + url);
});
}
}
|
Fischaela/PSB
|
src/core/index.js
|
<filename>src/core/index.js<gh_stars>100-1000
import Vue from 'vue'
import { compose } from 'lodash/fp'
import { head } from 'lodash'
import { registerDirectives } from './directives'
import { registerLang } from './lang'
const registerApp = context => {
return new context.Renderer({
i18n: context.i18n,
el: head(document.getElementsByTagName(context.selector)),
render: h => h(context.App)
})
}
const boot = compose(registerApp, registerLang, registerDirectives)
export const createApp = (selector, App) => {
return boot({
Renderer: Vue,
App,
selector
})
}
|
Houbsi/cli
|
internal/cmd/placementgroup/labels.go
|
package placementgroup
import (
"context"
"fmt"
"github.com/hetznercloud/cli/internal/cmd/base"
"github.com/hetznercloud/cli/internal/hcapi2"
"github.com/hetznercloud/hcloud-go/hcloud"
)
var LabelCmds = base.LabelCmds{
ResourceNameSingular: "placement group",
ShortDescriptionAdd: "Add a label to a placement group",
ShortDescriptionRemove: "Remove a label from a placement group",
NameSuggestions: func(c hcapi2.Client) func() []string { return c.PlacementGroup().Names },
LabelKeySuggestions: func(c hcapi2.Client) func(idOrName string) []string { return c.PlacementGroup().LabelKeys },
FetchLabels: func(ctx context.Context, client hcapi2.Client, idOrName string) (map[string]string, int, error) {
placementGroup, _, err := client.PlacementGroup().Get(ctx, idOrName)
if err != nil {
return nil, 0, err
}
if placementGroup == nil {
return nil, 0, fmt.Errorf("placement group not found: %s", idOrName)
}
return placementGroup.Labels, placementGroup.ID, nil
},
SetLabels: func(ctx context.Context, client hcapi2.Client, id int, labels map[string]string) error {
opts := hcloud.PlacementGroupUpdateOpts{
Labels: labels,
}
_, _, err := client.PlacementGroup().Update(ctx, &hcloud.PlacementGroup{ID: id}, opts)
return err
},
}
|
Celebrate-future/openimaj
|
hadoop/tools/HadoopTwitterTokenTool/src/main/java/org/openimaj/hadoop/tools/twitter/token/outputmode/correlation/CorrelateWordTimeSeries.java
|
/**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.hadoop.tools.twitter.token.outputmode.correlation;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.openimaj.hadoop.mapreduce.stage.helper.SequenceFileTextStage;
import org.openimaj.util.pair.IndependentPair;
/**
* @author <NAME> (<EMAIL>)
*
*/
public class CorrelateWordTimeSeries extends SequenceFileTextStage<Text, BytesWritable, NullWritable, Text, NullWritable, Text>{
/**
* the directory this stage will output
*/
public static final String CORRELATE_WORDTIME = "correlate_wordtime";
public static final String PERIOD_START = "org.openimaj.hadoop.tools.twitter.time.startperiod";
public static final String PERIOD_END = "org.openimaj.hadoop.tools.twitter.time.endperiod";
public static final String FINANCE_DATA = "org.openimaj.hadoop.tools.twitter.finance.data";
private String finance;
private long start;
private long end;
public CorrelateWordTimeSeries(String financelocation,IndependentPair<Long, Long> startend) {
this.finance = financelocation;
this.start = startend.firstObject();
this.end = startend.secondObject();
}
@Override
public void setup(org.apache.hadoop.mapreduce.Job job) {
job.getConfiguration().setLong(PERIOD_START, start);
job.getConfiguration().setLong(PERIOD_END, end);
job.getConfiguration().setStrings(FINANCE_DATA, finance);
job.setNumReduceTasks(1);
};
@Override
public String outname() {
return CORRELATE_WORDTIME;
}
@Override
public Class<? extends Mapper<Text, BytesWritable, NullWritable, Text>> mapper() {
return WordTimeperiodValueMapper.class;
}
// @Override
// public Class<? extends Reducer<Text, BytesWritable, NullWritable, Text>> reducer() {
// return WordValueCorrelationReducer.class;
// }
}
|
mcsma01/DayTrader
|
modules/util/src/java/org/apache/geronimo/util/asn1/x509/X509Extension.java
|
/**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.util.asn1.x509;
import org.apache.geronimo.util.asn1.ASN1OctetString;
import org.apache.geronimo.util.asn1.DERBoolean;
/**
* an object for the elements in the X.509 V3 extension block.
*/
public class X509Extension
{
boolean critical;
ASN1OctetString value;
public X509Extension(
DERBoolean critical,
ASN1OctetString value)
{
this.critical = critical.isTrue();
this.value = value;
}
public X509Extension(
boolean critical,
ASN1OctetString value)
{
this.critical = critical;
this.value = value;
}
public boolean isCritical()
{
return critical;
}
public ASN1OctetString getValue()
{
return value;
}
public int hashCode()
{
if (this.isCritical())
{
return this.getValue().hashCode();
}
return ~this.getValue().hashCode();
}
public boolean equals(
Object o)
{
if (o == null || !(o instanceof X509Extension))
{
return false;
}
X509Extension other = (X509Extension)o;
return other.getValue().equals(this.getValue())
&& (other.isCritical() == this.isCritical());
}
}
|
hassen-abduse/CaringHub
|
caring_hub_client/src/organization/pages/volunteers/ShowVolunteersDialog.js
|
import { Grid, Container, Paper, Typography } from "@material-ui/core";
import React, { Component } from "react";
import Divider from "@material-ui/core/Divider";
import { Rate } from "antd";
import Avatar from "../../../volunteer/components/Avatars";
import { Badge } from "antd";
const desc = ["terrible", "bad", "normal", "good", "wonderful"];
class ShowVolunteersDialog extends Component {
state = {
value: 3,
};
handleChange = (value) => {
this.setState({ value });
};
render() {
const { value } = this.state;
return (
<div style={{ display: "flex", justifyContent: "center" }}>
<div style={{ maxWidth: "450px" }}>
<div className="col-lg-1 pr-2">
<img
style={{ borderRadius: "100%", width: "80px", height: "80px" }}
alt="Image placeholder"
src={this.props.applicant.profilePicture ? this.props.applicant.profilePicture : "https://demos.creative-tim.com/argon-dashboard-pro/assets/img/theme/team-4.jpg"}
></img>
</div>
<div className="col-lg-3">
<h4
style={{ marginLeft: "0rem", marginBottom: 0 }}
className="h2-heading"
>
{this.props.applicant.firstName + ' ' + this.props.applicant.lastName}
</h4>
<p style={{ marginLeft: "0rem", color: "#159197" }} className="">
Volunteer
</p>
</div>
<h4 className="teal mt-4">Skills</h4>
<div style={{ display: "flexStart" }}>
{
this.props.applicant.skillSets.map(skill => {
return <span
style={{ margin: "0.3rem", padding: "0.8rem" }}
className="btn-outline-sm "
>
{skill.name}
</span>
})
}
</div>
</div>
<div>
<div>
<div style={{ paddingLeft: "3rem" }} className="">
<div style={{ display: "flex" }}>
<p className="m-0">Accomplishments : </p>
<Badge
// className="site-badge-count-109"
count={2}
style={{
marginLeft: "5px",
backgroundColor: "#159197",
}}
/>
</div>
<div style={{ display: "flex" }}>
<p className="m-0">Status : </p>
<p className="teal m-0" style={{ paddingLeft: "5px" }}>
Ready To Volunteer
</p>
</div>
<div style={{ display: "flex" }}>
<p className="m-0">Rating : </p>
<Rate
style={{ paddingLeft: "10px" }}
disabled
defaultValue={2}
/>
</div>
</div>
</div>
<div>
<div
style={{
marginLeft: "3rem",
display: "flex",
flexDirection: "column",
}}
>
<h4 style={{ marginTop: "3rem" }} className="teal ">
Contact Address
</h4>
<div style={{ display: "flex" }}>
<h6
style={{
marginTop: "3px",
marginRight: "10px",
}}
className=" mb-0 teal"
>
Email :
</h6>
<p>{this.props.applicant.emailAddress}</p>
</div>
<div style={{ display: "flex" }}>
<h6
style={{
marginTop: "3px",
marginRight: "10px",
}}
className="mb-0 teal"
>
Phone Number :
</h6>
<p>{this.props.applicant.phoneNumber}</p>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default ShowVolunteersDialog;
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Category/NSObject+KVOCategory.h
|
//
// NSObject+KVOCategory.h
// CommonLibrary
//
// Created by Alexi on 5/16/14.
// Copyright (c) 2014 Alexi. All rights reserved.
//
#if kSupportNSObjectKVOCategory
#import <Foundation/Foundation.h>
@interface NSObject (KVOCategory)
- (void)observedBy:(NSObject *)observer forKeyPaths:(NSArray *)keyPaths;
- (void)observedBy:(NSObject *)observer forKeyPaths:(NSArray *)keyPaths options:(NSKeyValueObservingOptions)options;
- (void)cancelObservedBy:(NSObject *)observer forKeyPaths:(NSArray *)keyPaths;
@end
#endif
|
MaritimeConnectivityPlatform/MaritimeCloud
|
mc-core/src/test/java/net/maritimecloud/util/geometry/AbstractAreaTest.java
|
<filename>mc-core/src/test/java/net/maritimecloud/util/geometry/AbstractAreaTest.java
/* Copyright (c) 2011 Danish Maritime Authority.
*
* 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 net.maritimecloud.util.geometry;
import java.util.Arrays;
import java.util.Collection;
/**
*
* @author <NAME>
*/
public class AbstractAreaTest {
// Positions are order as telephone display (P5) being the center (0,0), P1 top left, P9 bottom right
static final Position P1 = Position.create(10, -10);
static final Position P2 = Position.create(10, 0);
static final Position P3 = Position.create(10, 10);
static final Position P4 = Position.create(0, -10);
static final Position P5 = Position.create(0, 0);
static final Position P6 = Position.create(0, 10);
static final Position P7 = Position.create(-10, -10);
static final Position P8 = Position.create(-10, 0);
static final Position P9 = Position.create(-10, 10);
static Collection<Position> PALL = Arrays.asList(P1, P2, P3, P4, P5, P6, P7, P8, P9);
}
|
xfarsx/StarUniverseApp
|
app/src/main/java/br/com/digitalhouse/staruniverse/view/quiz/QuizFragment.java
|
package br.com.digitalhouse.staruniverse.view.quiz;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.transition.Scene;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import java.util.ArrayList;
import java.util.List;
import br.com.digitalhouse.staruniverse.R;
import br.com.digitalhouse.staruniverse.interfaces.QuizComunicador;
import br.com.digitalhouse.staruniverse.model.quiz.Quiz;
import br.com.digitalhouse.staruniverse.viewmodel.QuizViewModel;
/**
* A simple {@link Fragment} subclass.
*/
public class QuizFragment extends Fragment {
private QuizViewModel quizViewModel;
private List<Quiz> perguntas = new ArrayList<>();
private List<Button> opcoes = new ArrayList<>();
private int qtnPerguntas;
private int pontuacao = 0;
private QuizComunicador comunicador;
private TextView textViewPergunta, mTextField;
private Button button;
private Button buttonA;
private Button buttonB;
private Button buttonC;
private Button buttonD;
private CountDownTimer contador;
private Button proximaPergunta;
private Button encerrarQuiz;
private int numeroPerguntas = 0;
public QuizFragment() {
// Required empty public constructor
}
public void onAttach(Context context) {
super.onAttach(context);
try {
comunicador = (QuizComunicador) context;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_quiz, container, false);
iniciarViews(view);
proximaPergunta = view.findViewById(R.id.proximaPergunta);
encerrarQuiz = view.findViewById(R.id.encerrarQuiz);
buttonA = view.findViewById(R.id.ButtonAlterA);
buttonB = view.findViewById(R.id.ButtonAlterB);
buttonC = view.findViewById(R.id.ButtonAlterC);
buttonD = view.findViewById(R.id.ButtonAlterD);
opcoes.add(buttonA);
opcoes.add(buttonB);
opcoes.add(buttonC);
opcoes.add(buttonD);
// Inicializa ViewModel
quizViewModel = ViewModelProviders.of(this).get(QuizViewModel.class);
quizViewModel.buscarPerguntas();
// Adicionar os observables
quizViewModel.getQuizLiveData().observe(this, pergunta -> {
getList(pergunta);
});
return view;
}
public void setarPergunta(Quiz quiz, TextView pergunta, List<Button> alternativas) {
//setando pergunta na tela
pergunta.setText(quiz.getPergunta());
contador();
for (int i = 0; i < quiz.getAlternativas().size(); i++) {
String alternativa = quiz.getAlternativas().get(i);
Button button;
button = alternativas.get(i);
button.setText(alternativa);
button.setBackgroundTintList(getResources().getColorStateList(R.color.black));
proximaPergunta.setVisibility(View.GONE);
encerrarQuiz.setVisibility(View.GONE);
button.setEnabled(true);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
button.setEnabled(false);
if (button.getText().toString().equals(quiz.getResposta())) {
setarAcertoOuErro("certo", button);
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
gerarPontuacao();
} else {
setarAcertoOuErro("", button);
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
numeroPerguntas++;
if (numeroPerguntas == 5 || numeroPerguntas == 10 || numeroPerguntas == 15) {
encerrarQuiz.setVisibility(View.VISIBLE);
encerrarQuiz.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
comunicador.receberMensagem(pontuacao);
}
});
} else {
encerrarQuiz.setVisibility(View.GONE);
}
esperarProximaPergunta();
}
});
}
}
public void contador()
{
CountDownTimer contadorM = new CountDownTimer(10000,1000){
@Override
public void onTick(long millisUntilFinished) {
mTextField.setText("" + millisUntilFinished / 1000);
}
@Override
public void onFinish() {
proximaPergunta();
}
}.start();
contador = contadorM;
}
public void proximaPergunta () {
if (qtnPerguntas != 0) {
setarPergunta(perguntas.get(qtnPerguntas - 1), this.textViewPergunta, this.opcoes);
qtnPerguntas--;
} else {
comunicador.receberMensagem(pontuacao);
}
}
private List<Quiz> getList(List<Quiz> quiz) {
perguntas.addAll(quiz);
qtnPerguntas = perguntas.size();
proximaPergunta();
return perguntas;
}
private void gerarPontuacao( ) {
this.pontuacao += 10;
}
public void iniciarViews(View view)
{
textViewPergunta = view.findViewById(R.id.textViewQuizPergunta);
mTextField = view.findViewById(R.id.contador);
}
public void esperarProximaPergunta()
{
contador.cancel();
proximaPergunta.setVisibility(View.VISIBLE);
proximaPergunta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
proximaPergunta();
}
});
}
public void LayoutTransition()
{
Scene primeiraCena;
Scene novaCena;
}
public void setarAcertoOuErro(String texto, Button button)
{
if (texto.equals("certo")){
button.setBackgroundTintList(getResources().getColorStateList(R.color.rightanswered));
button.setText("A C E R T O U!");}
else
{
button.setBackgroundTintList(getResources().getColorStateList(R.color.wronganswered));
button.setText("E R R O U!");}
}
public void setarAnimacao(Button button)
{
ObjectAnimator.ofFloat(button,"rotation",360).setDuration(500).setAutoCancel(true);
}
}
|
mass9/Cpp
|
Bjarne_Stroustrup_Books/programming_principles_and_practice_using_c_2nd_ed/Part-1/Chapter-5 { Writing a program}/Exercise/checking of praser/English_grammar_checker.cpp
|
#include"std_lib_facilities.h"
using namespace std;
vector<string>nouns;
vector<string>verbs;
vector<string>conjunctions;
void intialize()
{
nouns.push_back("birds");
nouns.push_back("fish");
nouns.push_back("C++");
verbs.push_back("rules");
verbs.push_back("fly");
verbs.push_back("swim");
conjunctions.push_back("and");
conjunctions.push_back("or");
conjunctions.push_back("but");
}
bool is_noun(string w)
{
for(int i = 0; i<nouns.size(); ++i)
if (w==nouns[i]) return true;
return false;
}
bool is_verb(string w)
{
for(int i = 0; i<verbs.size(); ++i)
if (w==verbs[i]) return true;
return false;
}
bool is_conjunction(string w)
{
for(int i = 0; i<conjunctions.size(); ++i)
if (w==conjunctions[i]) return true;
return false;
}
bool sentence()
{
string w;
cin >> w;
if (!is_noun(w)) return false;
string w2;
cin >> w2;
if (!is_verb(w2)) return false;
string w3;
cin >> w3;
if (w3 == ".") return true; // end of sentence
if (!is_conjunction(w3)) return false; // not end of sentence and not conjunction
// look for another sentence
}
int main()
{
cout<<"Enter the statment \n";
intialize();
while(cin)
{
bool b = sentence();
if (b)
cout << "OK\n";
else
cout << "not OK\n";
cout << "Try again: ";
}
}
|
weng271190436/operator
|
pkg/controller/migration/convert/testutils_test.go
|
package convert
import (
crdv1 "github.com/tigera/operator/pkg/apis/crd.projectcalico.org/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func emptyNodeSpec() *appsv1.DaemonSet {
return &appsv1.DaemonSet{
ObjectMeta: v1.ObjectMeta{
Name: "calico-node",
Namespace: "kube-system",
},
Spec: appsv1.DaemonSetSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Tolerations: []corev1.Toleration{
{
Effect: corev1.TaintEffectNoSchedule,
Operator: corev1.TolerationOpExists,
},
{
Key: "CriticalAddonsOnly",
Operator: corev1.TolerationOpExists,
},
{
Effect: corev1.TaintEffectNoExecute,
Operator: corev1.TolerationOpExists,
},
},
InitContainers: []corev1.Container{{
Name: "install-cni",
Env: []corev1.EnvVar{{
Name: "CNI_NETWORK_CONFIG",
Value: `{"type": "calico", "name": "k8s-pod-network", "ipam": {"type": "calico-ipam"}}`,
}},
}},
Containers: []corev1.Container{{
Name: "calico-node",
}},
Volumes: []corev1.Volume{
{
Name: "lib-modules",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/lib/modules",
},
},
},
{
Name: "var-run-calico",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/run/calico",
},
},
},
{
Name: "var-lib-calico",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/lib/calico",
},
},
},
{
Name: "xtables-lock",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/run/xtables.lock",
},
},
},
{
Name: "cni-bin-dir",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/opt/cni/bin",
},
},
},
{
Name: "cni-net-dir",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/etc/cni/net.d",
},
},
},
},
},
},
},
}
}
func emptyKubeControllerSpec() *appsv1.Deployment {
return &appsv1.Deployment{
ObjectMeta: v1.ObjectMeta{
Name: "calico-kube-controllers",
Namespace: "kube-system",
},
Spec: appsv1.DeploymentSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Tolerations: []corev1.Toleration{
{
Key: "CriticalAddonsOnly",
Operator: corev1.TolerationOpExists,
},
{
Effect: corev1.TaintEffectNoSchedule,
Key: "node-role.kubernetes.io/master",
},
},
Containers: []corev1.Container{{
Name: "calico-kube-controllers",
}},
},
},
},
}
}
func emptyTyphaDeployment() *appsv1.Deployment {
return &appsv1.Deployment{
ObjectMeta: v1.ObjectMeta{
Name: "calico-typha",
Namespace: "kube-system",
},
Spec: appsv1.DeploymentSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Tolerations: []corev1.Toleration{{
Key: "CriticalAddonsOnly",
Operator: corev1.TolerationOpExists,
}},
Containers: []corev1.Container{{
Name: "calico-typha",
}},
},
},
},
}
}
// emptyComponents is a convenience function for initializing a
// components object which meets basic validation requirements.
func emptyComponents() components {
return components{
node: CheckedDaemonSet{
*emptyNodeSpec(),
make(map[string]checkedFields),
},
kubeControllers: emptyKubeControllerSpec(),
typha: emptyTyphaDeployment(),
}
}
func emptyFelixConfig() *crdv1.FelixConfiguration {
return &crdv1.FelixConfiguration{
ObjectMeta: v1.ObjectMeta{
Name: "default",
},
}
}
|
fmal/wyspa-www
|
src/components/Footer.js
|
<filename>src/components/Footer.js
/** @jsx jsx */
import { jsx, Container } from 'theme-ui';
import { useTranslation } from 'react-i18next';
import SocialMediaLinks from './SocialMediaLinks';
const Footer = () => {
const { t } = useTranslation('common');
return (
<footer
sx={{
flex: 'none',
pt: [4, null, null, 5],
pb: [4, null, 5],
background:
'linear-gradient(180deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'
}}
>
<Container>
<div
sx={{
display: 'flex',
justifyContent: 'space-between',
flexDirection: ['column', 'column', 'row']
}}
>
<span sx={{ variant: 'text.default', color: 'textMuted' }}>
{'©'} {new Date().getFullYear()} {t('title')}
</span>
<SocialMediaLinks sx={{ variant: 'text.default', mt: [2, 0] }} />
</div>
</Container>
</footer>
);
};
export default Footer;
|
ririv/EmojiRecognition
|
src/main/java/com/riri/memerecognition/exception/UserAlreadyExistException.java
|
package com.riri.memerecognition.exception;
public final class UserAlreadyExistException extends RuntimeException {
public UserAlreadyExistException(final String message) {
super(message);
}
public UserAlreadyExistException() {
super("The user already exists");
}
}
|
SpaceWalkerRS/redstone-tweaks
|
src/main/java/redstonetweaks/world/client/TickInfoLabelRenderer.java
|
<filename>src/main/java/redstonetweaks/world/client/TickInfoLabelRenderer.java
package redstonetweaks.world.client;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.util.math.MatrixStack;
import redstonetweaks.world.common.WorldTickHandler.Task;
public class TickInfoLabelRenderer extends DrawableHelper {
private final static int BACKGROUND_MARGIN_X = 2;
private final static int BACKGROUND_MARGIN_Y = 2;
private final static int BACKGROUND_COLOR = 0x50333333;
private final static int TEXT_MARGIN_X = 1;
private final static int TEXT_MARGIN_Y = 1;
private final static int TEXT_SPACING = 1;
private final static int TEXT_COLOR = 0xFFEEEEEE;
private final TextRenderer font;
private long currentTime = 0L;
private String currentWorldName;
private Task currentTask;
private int bgL;
private int bgU;
private int bgR;
private int bgD;
private int tL;
private int tU;
private String line1;
private String line2;
private String line3;
public TickInfoLabelRenderer(MinecraftClient client) {
this.font = client.textRenderer;
initText();
}
private void initText() {
line1 = "Tick: -";
line2 = "Current world: -";
line3 = "Current task: -";
}
public void updateText() {
line1 = "Tick: " + String.valueOf(currentTime);
line2 = "Current world: " + (currentWorldName == null ? "-" : currentWorldName);
line3 = "Current task: " + (currentTask == null || !currentTask.display() ? "-" : currentTask.getName());
}
public void render(MatrixStack matrixStack) {
renderBackground(matrixStack);
renderText(matrixStack);
}
private void renderBackground(MatrixStack matrixStack) {
bgL = BACKGROUND_MARGIN_X;
bgU = BACKGROUND_MARGIN_Y;
bgR = bgL + getLabelWidth();
bgD = bgU + getLabelHeight();
fill(matrixStack, bgL, bgU, bgR, bgD, BACKGROUND_COLOR);
}
private void renderText(MatrixStack matrixStack) {
tL = bgL + TEXT_MARGIN_X ;
tU = bgU + TEXT_MARGIN_Y;
font.draw(matrixStack, line1, tL, tU, TEXT_COLOR);
font.draw(matrixStack, line2, tL, tU + font.fontHeight + TEXT_SPACING, TEXT_COLOR);
font.draw(matrixStack, line3, tL, tU + 2 * (font.fontHeight + TEXT_SPACING), TEXT_COLOR);
}
private int getLabelWidth() {
return getTextWidth() + 2 * TEXT_MARGIN_X;
}
private int getLabelHeight() {
return getTextHeight() + 2 * TEXT_MARGIN_Y;
}
private int getTextWidth() {
int width1 = font.getWidth(line1);
int width2 = font.getWidth(line2);
int width3 = font.getWidth(line3);
return Math.max(Math.max(width1, width2), width3);
}
private int getTextHeight() {
return 3 * font.fontHeight + 2 * TEXT_SPACING;
}
public void syncWorldTime(long worldTime) {
currentTime = worldTime;
updateText();
}
public void syncWorld(String worldName) {
currentWorldName = worldName;
updateText();
}
public void syncTask(Task task) {
currentTask = task;
updateText();
}
public void onDisconnect() {
currentTime = 0L;
currentWorldName = "";
currentTask = Task.NONE;
initText();
}
}
|
AaronFriel/pulumi-aws-native
|
sdk/python/pulumi_aws_native/finspace/outputs.py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from ._enums import *
__all__ = [
'EnvironmentFederationParameters',
'EnvironmentSuperuserParameters',
]
@pulumi.output_type
class EnvironmentFederationParameters(dict):
"""
Additional parameters to identify Federation mode
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "applicationCallBackURL":
suggest = "application_call_back_url"
elif key == "attributeMap":
suggest = "attribute_map"
elif key == "federationProviderName":
suggest = "federation_provider_name"
elif key == "federationURN":
suggest = "federation_urn"
elif key == "samlMetadataDocument":
suggest = "saml_metadata_document"
elif key == "samlMetadataURL":
suggest = "saml_metadata_url"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in EnvironmentFederationParameters. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
EnvironmentFederationParameters.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
EnvironmentFederationParameters.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
application_call_back_url: Optional[str] = None,
attribute_map: Optional[Any] = None,
federation_provider_name: Optional[str] = None,
federation_urn: Optional[str] = None,
saml_metadata_document: Optional[str] = None,
saml_metadata_url: Optional[str] = None):
"""
Additional parameters to identify Federation mode
:param str application_call_back_url: SAML metadata URL to link with the Environment
:param Any attribute_map: Attribute map for SAML configuration
:param str federation_provider_name: Federation provider name to link with the Environment
:param str federation_urn: SAML metadata URL to link with the Environment
:param str saml_metadata_document: SAML metadata document to link the federation provider to the Environment
:param str saml_metadata_url: SAML metadata URL to link with the Environment
"""
if application_call_back_url is not None:
pulumi.set(__self__, "application_call_back_url", application_call_back_url)
if attribute_map is not None:
pulumi.set(__self__, "attribute_map", attribute_map)
if federation_provider_name is not None:
pulumi.set(__self__, "federation_provider_name", federation_provider_name)
if federation_urn is not None:
pulumi.set(__self__, "federation_urn", federation_urn)
if saml_metadata_document is not None:
pulumi.set(__self__, "saml_metadata_document", saml_metadata_document)
if saml_metadata_url is not None:
pulumi.set(__self__, "saml_metadata_url", saml_metadata_url)
@property
@pulumi.getter(name="applicationCallBackURL")
def application_call_back_url(self) -> Optional[str]:
"""
SAML metadata URL to link with the Environment
"""
return pulumi.get(self, "application_call_back_url")
@property
@pulumi.getter(name="attributeMap")
def attribute_map(self) -> Optional[Any]:
"""
Attribute map for SAML configuration
"""
return pulumi.get(self, "attribute_map")
@property
@pulumi.getter(name="federationProviderName")
def federation_provider_name(self) -> Optional[str]:
"""
Federation provider name to link with the Environment
"""
return pulumi.get(self, "federation_provider_name")
@property
@pulumi.getter(name="federationURN")
def federation_urn(self) -> Optional[str]:
"""
SAML metadata URL to link with the Environment
"""
return pulumi.get(self, "federation_urn")
@property
@pulumi.getter(name="samlMetadataDocument")
def saml_metadata_document(self) -> Optional[str]:
"""
SAML metadata document to link the federation provider to the Environment
"""
return pulumi.get(self, "saml_metadata_document")
@property
@pulumi.getter(name="samlMetadataURL")
def saml_metadata_url(self) -> Optional[str]:
"""
SAML metadata URL to link with the Environment
"""
return pulumi.get(self, "saml_metadata_url")
@pulumi.output_type
class EnvironmentSuperuserParameters(dict):
"""
Parameters of the first Superuser for the FinSpace Environment
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "emailAddress":
suggest = "email_address"
elif key == "firstName":
suggest = "first_name"
elif key == "lastName":
suggest = "last_name"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in EnvironmentSuperuserParameters. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
EnvironmentSuperuserParameters.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
EnvironmentSuperuserParameters.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
email_address: Optional[str] = None,
first_name: Optional[str] = None,
last_name: Optional[str] = None):
"""
Parameters of the first Superuser for the FinSpace Environment
:param str email_address: Email address
:param str first_name: First name
:param str last_name: Last name
"""
if email_address is not None:
pulumi.set(__self__, "email_address", email_address)
if first_name is not None:
pulumi.set(__self__, "first_name", first_name)
if last_name is not None:
pulumi.set(__self__, "last_name", last_name)
@property
@pulumi.getter(name="emailAddress")
def email_address(self) -> Optional[str]:
"""
Email address
"""
return pulumi.get(self, "email_address")
@property
@pulumi.getter(name="firstName")
def first_name(self) -> Optional[str]:
"""
First name
"""
return pulumi.get(self, "first_name")
@property
@pulumi.getter(name="lastName")
def last_name(self) -> Optional[str]:
"""
Last name
"""
return pulumi.get(self, "last_name")
|
wrleskovec/thoughtcrime
|
node_modules/react-datepicker/lib/month_dropdown.js
|
'use strict';
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _month_dropdown_options = require('./month_dropdown_options');
var _month_dropdown_options2 = _interopRequireDefault(_month_dropdown_options);
var _reactOnclickoutside = require('react-onclickoutside');
var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside);
var _moment = require('moment');
var _moment2 = _interopRequireDefault(_moment);
var _range = require('lodash/range');
var _range2 = _interopRequireDefault(_range);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var WrappedMonthDropdownOptions = (0, _reactOnclickoutside2.default)(_month_dropdown_options2.default);
var MonthDropdown = _react2.default.createClass({
displayName: 'MonthDropdown',
propTypes: {
dropdownMode: _react2.default.PropTypes.oneOf(['scroll', 'select']).isRequired,
locale: _react2.default.PropTypes.string,
month: _react2.default.PropTypes.number.isRequired,
onChange: _react2.default.PropTypes.func.isRequired
},
getInitialState: function getInitialState() {
return {
dropdownVisible: false
};
},
renderSelectOptions: function renderSelectOptions(monthNames) {
return monthNames.map(function (M, i) {
return _react2.default.createElement(
'option',
{ key: i, value: i },
M
);
});
},
renderSelectMode: function renderSelectMode(monthNames) {
var _this = this;
return _react2.default.createElement(
'select',
{ value: this.props.month, className: 'react-datepicker__month-select', onChange: function onChange(e) {
return _this.onChange(e.target.value);
} },
this.renderSelectOptions(monthNames)
);
},
renderReadView: function renderReadView(visible, monthNames) {
return _react2.default.createElement(
'div',
{ key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__month-read-view', onClick: this.toggleDropdown },
_react2.default.createElement(
'span',
{ className: 'react-datepicker__month-read-view--selected-month' },
monthNames[this.props.month]
),
_react2.default.createElement('span', { className: 'react-datepicker__month-read-view--down-arrow' })
);
},
renderDropdown: function renderDropdown(monthNames) {
return _react2.default.createElement(WrappedMonthDropdownOptions, {
key: 'dropdown',
ref: 'options',
month: this.props.month,
monthNames: monthNames,
onChange: this.onChange,
onCancel: this.toggleDropdown });
},
renderScrollMode: function renderScrollMode(monthNames) {
var dropdownVisible = this.state.dropdownVisible;
var result = [this.renderReadView(!dropdownVisible, monthNames)];
if (dropdownVisible) {
result.unshift(this.renderDropdown(monthNames));
}
return result;
},
onChange: function onChange(month) {
this.toggleDropdown();
if (month !== this.props.month) {
this.props.onChange(month);
}
},
toggleDropdown: function toggleDropdown() {
this.setState({
dropdownVisible: !this.state.dropdownVisible
});
},
render: function render() {
var localeData = _moment2.default.localeData(this.props.locale);
var monthNames = (0, _range2.default)(0, 12).map(function (M) {
return localeData.months((0, _moment2.default)({ M: M }));
});
var renderedDropdown = void 0;
switch (this.props.dropdownMode) {
case 'scroll':
renderedDropdown = this.renderScrollMode(monthNames);
break;
case 'select':
renderedDropdown = this.renderSelectMode(monthNames);
break;
}
return _react2.default.createElement(
'div',
{
className: 'react-datepicker__month-dropdown-container react-datepicker__month-dropdown-container--' + this.props.dropdownMode },
renderedDropdown
);
}
});
module.exports = MonthDropdown;
|
cogentcloud/ef-cms
|
web-api/migrations/00002-qc-complete-for-trial.js
|
<gh_stars>0
const createApplicationContext = require('../src/applicationContext');
const { Case } = require('../../shared/src/business/entities/cases/Case');
const { isCaseRecord, upGenerator } = require('./utilities');
const applicationContext = createApplicationContext({});
const mutateRecord = item => {
if (isCaseRecord(item) && !item.qcCompleteForTrial) {
console.log(
`adding qcCompleteForTrial default value to case with id "${item.caseId}"`,
);
item.qcCompleteForTrial = {};
const caseEntity = new Case(item, { applicationContext })
.validate()
.toRawObject();
const itemToPut = {
...item,
...caseEntity,
};
return itemToPut;
}
};
module.exports = { mutateRecord, up: upGenerator(mutateRecord) };
|
Nels885/csd_dashboard
|
raspeedi/static/raspeedi/js/rasp-tables.js
|
<reponame>Nels885/csd_dashboard
// Call the dataTables jQuery plugin
$(document).ready(function () {
$('#raspTable').DataTable({
pagingType: "full_numbers",
scrollX: true,
order: [[2, "asc"]],
// Disable sorting for the Tags and Actions columns.
columnDefs: [{
targets: [0, 1],
searchable: false,
orderable: false,
}],
initComplete: function () {
this.api().columns([2, 3, 4, 5, 6, 7]).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
});
$('#unlockTable').DataTable({
pagingType: "full_numbers",
scrollX: true,
order: []
});
$('#unlockDeleteTable').DataTable({
pagingType: "full_numbers",
scrollX: true,
order: [],
// Disable sorting for the Tags and Actions columns.
columnDefs: [{
targets: 0,
searchable: false,
orderable: false,
}],
});
});
|
youhou90/pbtools
|
examples/address_book/main.c
|
<reponame>youhou90/pbtools
#include <assert.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "address_book.h"
int main(int argc, const char *argv[])
{
uint8_t encoded[128];
int size;
uint8_t workspace[1024];
struct address_book_address_book_t *address_book_p;
struct address_book_person_t *person_p;
struct address_book_person_phone_number_t *phone_number_p;
address_book_p = address_book_address_book_new(&workspace[0],
sizeof(workspace));
assert(address_book_p != NULL);
/* Add one person to the address book. */
assert(address_book_address_book_people_alloc(address_book_p, 1) == 0);
person_p = &address_book_p->people.items_p[0];
person_p->name_p = "<NAME>";
person_p->id = 56;
person_p->email_p = "<EMAIL>";
/* Add phone numbers. */
assert(address_book_person_phones_alloc(person_p, 2) == 0);
/* Home. */
phone_number_p = &person_p->phones.items_p[0];
phone_number_p->number_p = "+46701232345";
phone_number_p->type = address_book_person_phone_type_home_e;
/* Work. */
phone_number_p = &person_p->phones.items_p[1];
phone_number_p->number_p = "+46999999999";
phone_number_p->type = address_book_person_phone_type_work_e;
/* Encode the message. */
size = address_book_address_book_encode(address_book_p,
&encoded[0],
sizeof(encoded));
assert(size == 75);
assert(memcmp(&encoded[0],
"\x0a\x49\x0a\x0a\x4b\x61\x6c\x6c\x65\x20"
"\x4b\x75\x6c\x61\x10\x38\x1a\x15\x6b\x61"
"\x6c\x6c\x65\x2e\x6b\x75\x6c\x61\x40\x66"
"\x6f\x6f\x62\x61\x72\x2e\x63\x6f\x6d\x22"
"\x10\x0a\x0c\x2b\x34\x36\x37\x30\x31\x32"
"\x33\x32\x33\x34\x35\x10\x01\x22\x10\x0a"
"\x0c\x2b\x34\x36\x39\x39\x39\x39\x39\x39"
"\x39\x39\x39\x10\x02",
size) == 0);
/* Decode the message. */
address_book_p = address_book_address_book_new(&workspace[0],
sizeof(workspace));
assert(address_book_p != NULL);
size = address_book_address_book_decode(address_book_p, &encoded[0], size);
assert(size >= 0);
assert(address_book_p->people.length == 1);
/* Check the decoded person. */
person_p = &address_book_p->people.items_p[0];
assert(strcmp(person_p->name_p, "<NAME>") == 0);
assert(person_p->id == 56);
assert(strcmp(person_p->email_p, "<EMAIL>") == 0);
assert(person_p->phones.length == 2);
/* Check home phone number. */
phone_number_p = &person_p->phones.items_p[0];
assert(strcmp(phone_number_p->number_p, "+46701232345") == 0);
assert(phone_number_p->type == address_book_person_phone_type_home_e);
/* Check work phone number. */
phone_number_p = &person_p->phones.items_p[1];
assert(strcmp(phone_number_p->number_p, "+46999999999") == 0);
assert(phone_number_p->type == address_book_person_phone_type_work_e);
return (0);
}
|
ligson/ejbca
|
modules/systemtests/src-test/org/ejbca/ui/cli/roles/RemoveRoleCommandTest.java
|
/*************************************************************************
* *
* EJBCA Community: The OpenSource Certificate Authority *
* *
* This software 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 any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.ejbca.ui.cli.roles;
import static org.junit.Assert.assertNull;
import org.cesecore.authentication.tokens.AuthenticationToken;
import org.cesecore.certificates.ca.CaSessionRemote;
import org.cesecore.certificates.ca.X509CA;
import org.cesecore.keys.token.CryptoTokenManagementSessionRemote;
import org.cesecore.keys.token.CryptoTokenTestUtils;
import org.cesecore.mock.authentication.tokens.TestAlwaysAllowLocalAuthenticationToken;
import org.cesecore.roles.RoleData;
import org.cesecore.roles.access.RoleAccessSessionRemote;
import org.cesecore.roles.management.RoleManagementSessionRemote;
import org.cesecore.util.CryptoProviderTools;
import org.cesecore.util.EjbRemoteHelper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @version $Id: RemoveRoleCommandTest.java 18481 2014-02-10 16:08:27Z mikekushner $
*
*/
public class RemoveRoleCommandTest {
private static final String TESTCLASS_NAME = RemoveRoleCommandTest.class.getSimpleName();
private static final CaSessionRemote caSession = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class);
private static final CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE
.getRemoteSession(CryptoTokenManagementSessionRemote.class);
private final RoleAccessSessionRemote roleAccessSession = EjbRemoteHelper.INSTANCE.getRemoteSession(RoleAccessSessionRemote.class);
private final RoleManagementSessionRemote roleManagementSession = EjbRemoteHelper.INSTANCE.getRemoteSession(RoleManagementSessionRemote.class);
private static X509CA x509ca = null;
private RemoveRoleCommand command = new RemoveRoleCommand();
private static final AuthenticationToken authenticationToken = new TestAlwaysAllowLocalAuthenticationToken(TESTCLASS_NAME);
@BeforeClass
public static void beforeClass() throws Exception {
CryptoProviderTools.installBCProvider();
x509ca = CryptoTokenTestUtils.createTestCAWithSoftCryptoToken(authenticationToken, "C=SE,CN=" + TESTCLASS_NAME);
}
@AfterClass
public static void afterClass() throws Exception {
if (x509ca != null) {
final int caCryptoTokenId = caSession.getCAInfo(authenticationToken, x509ca.getCAId()).getCAToken().getCryptoTokenId();
cryptoTokenManagementSession.deleteCryptoToken(authenticationToken, caCryptoTokenId);
caSession.removeCA(authenticationToken, x509ca.getCAId());
}
}
@Before
public void setup() throws Exception {
roleManagementSession.create(authenticationToken, TESTCLASS_NAME);
}
@After
public void teardown() throws Exception {
RoleData role = roleAccessSession.findRole(TESTCLASS_NAME);
if (role != null) {
roleManagementSession.remove(authenticationToken, role);
}
}
@Test
public void testRemoveRole() {
String[] args = new String[] { TESTCLASS_NAME };
command.execute(args);
RoleData role = roleAccessSession.findRole(TESTCLASS_NAME);
assertNull("Role was not removed,", role);
}
}
|
skip5413/cassini
|
msgqueue/consumer.go
|
<gh_stars>1-10
//Package msgqueue 从消息队列服务收发消息
package msgqueue
import (
"errors"
"fmt"
"sync"
"time"
"github.com/QOSGroup/cassini/config"
"github.com/QOSGroup/cassini/consensus"
"github.com/QOSGroup/cassini/log"
"github.com/QOSGroup/cassini/types"
"github.com/nats-io/go-nats"
"github.com/tendermint/go-amino"
)
var wg sync.WaitGroup
// StartQcpConsume Start to consume tx msg
func StartQcpConsume(conf *config.Config) (err error) {
// qsconfigs := config.DefaultQscConfig()
qsconfigs := conf.Qscs
if len(qsconfigs) < 2 {
return errors.New("config error , at least two chain names ")
}
var subjects string
es := make(chan error, 1024) //TODO 1024参数按需修改
defer close(es)
engines := make([]*consensus.ConsEngine, 0)
var ce *consensus.ConsEngine
for i, qsconfig := range qsconfigs {
for j := i + 1; j < len(qsconfigs); j++ {
wg.Add(2)
ce = createConsEngine(qsconfigs[j].Name, qsconfig.Name, conf, es)
engines = append(engines, ce)
ce = createConsEngine(qsconfig.Name, qsconfigs[j].Name, conf, es)
engines = append(engines, ce)
subjects += fmt.Sprintf("[%s] [%s]", qsconfigs[j].Name+"2"+qsconfig.Name, qsconfig.Name+"2"+qsconfigs[j].Name)
}
}
wg.Wait()
if len(es) > 0 {
for e := range es {
log.Error(e)
}
return errors.New("couldn't start qcp consumer")
}
log.Infof("listening on subjects %s", subjects)
for _, ce := range engines {
go ce.StartEngine()
go ce.F.StartFerry()
}
return
}
func createConsEngine(from, to string, conf *config.Config, e chan<- error) (ce *consensus.ConsEngine) {
ce = consensus.NewConsEngine(from, to)
seq, err := ce.F.GetSequenceFromChain(from, to, "in") // seq= toChain's in/fromchain/maxseq
if err != nil {
log.Errorf("Create consensus engine error: %v", err)
} else {
log.Debugf("Create consensus engine query chain %s in-sequence: %d", to, seq)
ce.SetSequence(from, to, seq)
}
go qcpConsume(ce, from, to, conf, e)
return ce
}
//QcpConsumer consume the message from nats server
//
// from ,to is chain name for example "QOS"
func qcpConsume(ce *consensus.ConsEngine, from, to string, conf *config.Config, e chan<- error) {
log.Debugf("Consume qcp from [%s] to [%s]", from, to)
var i int64
defer wg.Done()
cb := func(m *nats.Msg) {
i++
tx := types.Event{}
amino.UnmarshalBinary(m.Data, &tx)
log.Infof("[#%d] Consume subject [%s] sequence [#%d] nodeAddress '%s'", i, m.Subject, tx.Sequence, tx.NodeAddress)
// 监听到交易事件后立即查询需要等待一段时间才能查询到交易数据;
//TODO 优化
// 需要监听下一个块的New Block 事件以确认交易数据入块,abci query 接口才能够查询出交易;
// 同时提供定时出发机制,以保证共识模块在交易事件丢失或网络错误等问题出现时仍然能够正常运行。
if conf.EventWaitMillitime > 0 {
time.Sleep(time.Duration(conf.EventWaitMillitime) * time.Millisecond)
}
ce.Add2Engine(m)
}
consummer := NATSConsumer{serverUrls: conf.Nats, subject: from + "2" + to, CallBack: cb}
nc, err := consummer.Connect()
if err != nil {
e <- err
return
}
if err = consummer.Consume(nc); err != nil {
e <- err
return
}
return
}
// NATSConsumer Gnatsd consumer
type NATSConsumer struct {
serverUrls string //消息队列服务地址,多个用","分割 例如 "nats://192.168.168.195:4222,nats://192.168.168.195:4223"
subject string //订阅主题
CallBack func(msg *nats.Msg) //处理消息的回调函数
}
// Connect Connect to gnatsd server
func (n *NATSConsumer) Connect() (nc *nats.Conn, err error) {
return connect2Nats(n.serverUrls)
}
// Consume Consume tx msg
func (n *NATSConsumer) Consume(nc *nats.Conn) (err error) {
if nc == nil {
return errors.New("the nats.Conn is nil")
}
//reconnect to nats server
i := nc.Status()
if i != nats.CONNECTED {
if i != nats.CLOSED {
nc.Close()
}
nc, err = n.Connect()
if err != nil {
return errors.New("the nats.Conn is not available")
}
}
//nc, err = n.Connect()
//if err != nil {
// return errors.New("the nats.Conn is not available")
//}
subscription, err := nc.Subscribe(n.subject, n.CallBack)
if err != nil {
return errors.New("subscribe failed :" + subscription.Subject)
}
nc.Flush()
if err := nc.LastError(); err != nil {
log.Error(err)
}
//log.Infof("Listening on [%s]\n", n.subject)
return nil
}
// Reply Consume tx msg and reply a msg
func (n *NATSConsumer) Reply(nc *nats.Conn) error {
i := 0
nc.Subscribe(n.subject, func(msg *nats.Msg) {
i++
log.Infof("[#%d] Received on [%s]: '%s' Relpy:'%s'\n", i, msg.Subject, string(msg.Data), msg.Reply)
nc.Publish(msg.Reply, []byte(" thereply"))
})
nc.Flush()
if err := nc.LastError(); err != nil {
log.Error(err)
}
log.Infof("Listening on [%s]\n", n.subject)
//runtime.Goexit()
return nil
}
func connect2Nats(serverUrls string) (nc *nats.Conn, err error) {
////for test
//if !strings.Contains(serverUrls, ",") {
// log.Debug("serverUrls not contains ','")
//}
log.Debugf("connectting to nats [%s]", serverUrls)
nc, err = nats.Connect(serverUrls)
if err != nil {
log.Errorf("Can't connect %v", err)
return nil, err
}
return
}
|
wuxiangwa/bricks
|
src/components/card/CardContent.js
|
import React from 'react';
import PropTypes from 'prop-types';
import {createClassName} from '../../utils/transform';
const CardContent = ({
className,
style,
children,
...props
}) => (<div {...props} style={style} className={createClassName(['card-content', className])}>{children}</div>)
CardContent.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.any
}
export default CardContent
|
vimalcvs/NOKRI
|
app/src/main/java/com/scriptsbundle/nokri/employeer/jobs/fragments/Nokri_InactiveJobsFragment.java
|
package com.scriptsbundle.nokri.employeer.jobs.fragments;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.JsonObject;
import com.scriptsbundle.nokri.manager.Nokri_DialogManager;
import com.scriptsbundle.nokri.manager.Nokri_RequestHeaderManager;
import com.scriptsbundle.nokri.manager.Nokri_SharedPrefManager;
import com.scriptsbundle.nokri.manager.Nokri_ToastManager;
import com.scriptsbundle.nokri.network.Nokri_ServiceGenerator;
import com.scriptsbundle.nokri.rest.RestService;
import com.scriptsbundle.nokri.R;
import com.scriptsbundle.nokri.employeer.jobs.adapters.Nokri_InactiveJobsAdapter;
import com.scriptsbundle.nokri.employeer.jobs.models.Nokri_InactiveJobsModel;
import com.scriptsbundle.nokri.manager.Nokri_FontManager;
import com.scriptsbundle.nokri.manager.Nokri_GoogleAnalyticsManager;
import com.scriptsbundle.nokri.manager.Nokri_PopupManager;
import com.scriptsbundle.nokri.utils.Nokri_Globals;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Nokri_InactiveJobsFragment extends Fragment implements Nokri_PopupManager.ConfirmInterface {
private RecyclerView recyclerView;
private Nokri_InactiveJobsAdapter adapter;
private List<Nokri_InactiveJobsModel> modelList;
private TextView emptyTextView;
private ImageView messageImage;
private LinearLayout messageContainer;
private boolean mUserSeen = false;
private boolean mViewCreated = false;
private nokri_pagerCallback listener;
private String id;
private Nokri_PopupManager popupManager;
private Nokri_DialogManager dialogManager;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (!mUserSeen && isVisibleToUser) {
mUserSeen = true;
onUserFirstSight();
tryViewCreatedFirstSight();
}
onUserVisibleChanged(isVisibleToUser);
}
@Override
public void onResume() {
super.onResume();
Nokri_GoogleAnalyticsManager.getInstance().trackScreenView(getClass().getSimpleName());
}
@Override
public void onDestroyView() {
super.onDestroyView();
mViewCreated = false;
mUserSeen = false;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Override this if you want to get savedInstanceState.
mViewCreated = true;
tryViewCreatedFirstSight();
}
private void tryViewCreatedFirstSight() {
if (mUserSeen && mViewCreated) {
onViewCreatedFirstSight(getView());
}
}
protected void onViewCreatedFirstSight(View view) {
}
protected void onUserFirstSight() {
}
protected void onUserVisibleChanged(boolean visible) {
if(getContext()!=null)
{
if(visible){
nokri_getInactiveJobs();
}
}
}
public Nokri_InactiveJobsFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
nokri_initialize();
// nokri_getInactiveJobs();
popupManager = new Nokri_PopupManager(getContext(),this);
if(Nokri_Globals.IS_RTL_ENABLED)
nokri_getInactiveJobs();
}
private void nokri_initialize(){
recyclerView = getView().findViewById(R.id.recyclerview);
emptyTextView = getView().findViewById(R.id.txt_empty);
messageImage = getView().findViewById(R.id.img_message);
messageContainer = getView().findViewById(R.id.msg_container);
new Nokri_FontManager().nokri_setOpenSenseFontTextView(emptyTextView,getActivity().getAssets());
// Picasso.with(getContext()).load(R.drawable.logo).into(messageImage);
recyclerView.setNestedScrollingEnabled(false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_nokri_inactive_jobs, container, false);
}
private void nokri_getInactiveJobs(){
dialogManager = new Nokri_DialogManager();
dialogManager.showAlertDialog(getActivity());
RestService restService = Nokri_ServiceGenerator.createService(RestService.class, Nokri_SharedPrefManager.getEmail(getContext()), Nokri_SharedPrefManager.getPassword(getContext()),getContext());
Call<ResponseBody> myCall;
if(Nokri_SharedPrefManager.isSocialLogin(getContext())) {
myCall = restService.getInActiveJobs(Nokri_RequestHeaderManager.addSocialHeaders());
} else
{
myCall = restService.getInActiveJobs( Nokri_RequestHeaderManager.addHeaders());
}
myCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObject) {
if(responseObject.isSuccessful()){
try {modelList = new ArrayList<>();
emptyTextView.setText("");
JSONObject response = new JSONObject(responseObject.body().string());
JSONObject data = response.getJSONObject("data");
JSONArray companiesArray = data.getJSONArray("jobs");
if(companiesArray.length() == 0){
messageContainer.setVisibility(View.VISIBLE);
emptyTextView.setText(response.getString("message"));
dialogManager.hideAlertDialog();
setupAdapter();
return;
}
else
messageContainer.setVisibility(View.GONE);
for(int i = 0;i<companiesArray.length();i++){
JSONArray dataArray = companiesArray.getJSONArray(i);
Nokri_InactiveJobsModel model = new Nokri_InactiveJobsModel();
for(int j =0;j<dataArray.length();j++)
{
JSONObject object = dataArray.getJSONObject(j);
if(object.getString("field_type_name").equals("job_id"))
model.setJobId(object.getString("value"));
else if (object.getString("field_type_name").equals("job_title"))
model.setJobTitle(object.getString("value"));
else if (object.getString("field_type_name").equals("job_expiry"))
{ model.setJobExpireDate(object.getString("value"));
model.setJobExpire(object.getString("key"));
}
else if (object.getString("field_type_name").equals("job_type"))
model.setJobType(object.getString("value"));
else if (object.getString("field_type_name").equals("job_location"))
model.setAddress(object.getString("value"));
else if (object.getString("field_type_name").equals("inactive_job"))
model.setInavtiveText(object.getString("key"));
if(j+1==dataArray.length())
modelList.add(model);
}
}
// Log.d("Pointz",modelList.toString());
setupAdapter();
dialogManager.hideAlertDialog();
} catch (JSONException e) {
dialogManager.showCustom(e.getMessage());
dialogManager.hideAlertDialog();
e.printStackTrace();
} catch (IOException e) {
dialogManager.showCustom(e.getMessage());
dialogManager.hideAlertDialog();
e.printStackTrace();
}
}
else {
dialogManager.showCustom(responseObject.message());
dialogManager.hideAlertDialog();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
dialogManager.showCustom(t.getMessage());
dialogManager.hideAlertDialog();
}
});
}
private void setupAdapter() {
adapter = new Nokri_InactiveJobsAdapter(modelList, getContext(), new Nokri_InactiveJobsAdapter.OnItemClickListener() {
@Override
public void onItemClick(Nokri_InactiveJobsModel item) {
}
@Override
public void menuItemSelected(Nokri_InactiveJobsModel model, MenuItem item) {
switch (item.getItemId()){
case R.id.menu_resume_received:
listener.onCallback(model);
break;
case R.id.menu_delete:
id = model.getJobId();
popupManager.nokri_showDeletePopup();
break;
case R.id.menu_edit:
listener.onEditJobClick(model);
break;
case R.id.menu_view_job:
listener.onViewJobClick(model);
break;
default:
break;
}
}
@Override
public void onActive(Nokri_InactiveJobsModel model) {
nokri_activeJobs(model.getJobId());
}
@Override
public void onDeleteClick(Nokri_InactiveJobsModel model) {
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void nokri_activeJobs(String id){
JsonObject params = new JsonObject();
params.addProperty("job_id",id);
dialogManager = new Nokri_DialogManager();
dialogManager.showAlertDialog(getActivity());
RestService restService = Nokri_ServiceGenerator.createService(RestService.class, Nokri_SharedPrefManager.getEmail(getContext()), Nokri_SharedPrefManager.getPassword(getContext()),getContext());
Call<ResponseBody> myCall;
if(Nokri_SharedPrefManager.isSocialLogin(getContext())) {
myCall = restService.activeJob(params, Nokri_RequestHeaderManager.addSocialHeaders());
} else
{
myCall = restService.activeJob(params, Nokri_RequestHeaderManager.addHeaders());
}
// Call<ResponseBody> myCall = restService.getFollowedCompanies(Nokri_RequestHeaderManager.addHeaders());
myCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObject) {
if(responseObject.isSuccessful()){
try {
JSONObject response = new JSONObject(responseObject.body().string());
Nokri_ToastManager.showLongToast(getContext(),response.getString("message"));
nokri_getInactiveJobs();
dialogManager.hideAlertDialog();
} catch (JSONException e) {
dialogManager.showCustom(e.getMessage());
dialogManager.hideAlertDialog();
e.printStackTrace();
} catch (IOException e) {
dialogManager.showCustom(e.getMessage());
dialogManager.hideAlertDialog();
e.printStackTrace();
}
}
else {
dialogManager.showCustom(responseObject.message());
dialogManager.hideAlertDialog();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
dialogManager.showCustom(t.getMessage());
dialogManager.hideAlertDialog();
}
});
}
@Override
public void onConfirmClick(Dialog dialog) {
nokri_deleteJob();
dialog.dismiss();
}
public interface nokri_pagerCallback {
void onCallback(Nokri_InactiveJobsModel model);
void onViewJobClick(Nokri_InactiveJobsModel model);
void onEditJobClick(Nokri_InactiveJobsModel model);
}
public void nokri_setListener(nokri_pagerCallback listener){
this.listener = listener;
}
private void nokri_deleteJob(){
if(id!=null && !id.isEmpty()){
dialogManager = new Nokri_DialogManager();
dialogManager.showAlertDialog(getActivity());
JsonObject params = new JsonObject();
params.addProperty("job_id",id);
RestService restService = Nokri_ServiceGenerator.createService(RestService.class, Nokri_SharedPrefManager.getEmail(getContext()), Nokri_SharedPrefManager.getPassword(getContext()),getContext());
Call<ResponseBody> myCall;
if(Nokri_SharedPrefManager.isSocialLogin(getContext())) {
myCall = restService.postDeleteJob(params, Nokri_RequestHeaderManager.addSocialHeaders());
} else
{
myCall = restService.postDeleteJob(params, Nokri_RequestHeaderManager.addHeaders());
}
// Call<ResponseBody> myCall = restService.postDeleteResume(params, Nokri_RequestHeaderManager.addHeaders());
myCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObject) {
if(responseObject.isSuccessful()){
try {
JSONObject response = new JSONObject(responseObject.body().string());
if (response.getBoolean("success")) {
dialogManager.hideAlertDialog();
popupManager.nokri_showSuccessPopup(response.getString("message"));
nokri_getInactiveJobs();
} else {
dialogManager.showCustom(responseObject.message());
dialogManager.hideAlertDialog();
}
} catch (JSONException e) {
dialogManager.showCustom(e.getMessage());
dialogManager.hideAlertDialog();
e.printStackTrace();
} catch (IOException e) {
dialogManager.showCustom(e.getMessage());
dialogManager.hideAlertDialog();
e.printStackTrace();
}
}
else {
dialogManager.showCustom(responseObject.message());
dialogManager.hideAlertDialog();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
dialogManager.showCustom(t.getMessage());
dialogManager.hideAlertDialog();
}
});
}
}
}
|
andrewalexander/swoll
|
pkg/topology/topology.go
|
package topology
import (
"context"
"sync"
"github.com/criticalstack/swoll/pkg/types"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type OnEventCallback func(t EventType, container *types.Container)
// These are the two states in which an observer event can be in.
type EventType int
const (
EventTypeStart EventType = iota // container started
EventTypeStop // container stopped
)
// ErrNilEvent is the error returned to indicate the observer sent an empty
// message
var ErrNilEvent = errors.New("nil event")
// ErrNilContainer is the error returned to indicate the observer sent an empty
// container message
var ErrNilContainer = errors.New("nil container")
// ErrUnknownType is the error returned to indicate a malformed observer event
var ErrUnknownType = errors.New("unknown event-type")
// ErrBadNamespace is the error returned to indicate the observer was unable to
// resolve the PID-Namespace of the container
var ErrBadNamespace = errors.New("invalid kernel pid-namespace")
// ErrContainerNotFound is the error returned to indicate the container was
// unable to be resolved
var ErrContainerNotFound = errors.New("container not found")
type ObservationEvent struct {
Type EventType
Container *types.Container
}
type Observer interface {
Connect(ctx context.Context) error
Containers(ctx context.Context) ([]*types.Container, error)
Run(ctx context.Context, out chan<- *ObservationEvent)
Copy(opts ...interface{}) (Observer, error)
Close() error
}
type Topology struct {
sync.RWMutex
observer Observer
cache map[int]*types.Container
}
func NewTopology(obs Observer) *Topology {
return &Topology{
observer: obs,
cache: make(map[int]*types.Container),
}
}
func (t *Topology) Close() error {
if t != nil && t.observer != nil {
return t.observer.Close()
}
return nil
}
func (t *Topology) Connect(ctx context.Context) error {
return t.observer.Connect(ctx)
}
func (t *Topology) Containers(ctx context.Context) ([]*types.Container, error) {
return t.observer.Containers(ctx)
}
func (t *Topology) Run(ctx context.Context, cb OnEventCallback) {
ch := make(chan *ObservationEvent)
go t.observer.Run(ctx, ch)
for {
select {
case ev := <-ch:
t.Lock()
if err := t.processEvent(ctx, ev, cb); err != nil {
log.Warnf("error processing event: %v", err)
}
t.Unlock()
case <-ctx.Done():
return
}
}
}
func (t *Topology) LookupContainer(ctx context.Context, pidns int) (*types.Container, error) {
t.RLock()
defer t.RUnlock()
if container, ok := t.cache[pidns]; ok {
ret := container.Copy()
return ret, nil
}
return nil, ErrContainerNotFound
}
func (t *Topology) processEvent(ctx context.Context, ev *ObservationEvent, cb OnEventCallback) error {
if ev == nil {
return ErrNilEvent
}
container := ev.Container
if container == nil {
return ErrNilContainer
}
if container.PidNamespace <= 0 {
return ErrBadNamespace
}
switch ev.Type {
case EventTypeStart:
t.cache[container.PidNamespace] = container
if cb != nil {
t.Unlock()
cb(EventTypeStart, container)
t.Lock()
}
case EventTypeStop:
delete(t.cache, container.PidNamespace)
if cb != nil {
t.Unlock()
cb(EventTypeStop, container)
t.Lock()
}
default:
return ErrUnknownType
}
return nil
}
|
ggsdc/corn
|
libs/core/cornflow_core/authentication/decorators.py
|
"""
This file contains the decorator used for the authentication
"""
from functools import wraps
from .auth import BaseAuth
from cornflow_core.exceptions import InvalidCredentials
def authenticate(auth_class: BaseAuth):
"""
This is the decorator used for the authentication
:param auth_class: the class used for the authentication. It should be `BaseAuth` or a class that inherits from it
and that has a authenticate method.
:type auth_class: `BaseAuth`
:return: the wrapped function
"""
def decorator(func: callable):
"""
The decorator definition
:param callable func: the function that gets decorated
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""
The wrapper to the function that performs the authentication.
:param args: the original args sent to the decorated function
:param kwargs: the original kwargs sent to the decorated function
:return: the result of the call to the function
"""
if auth_class.authenticate():
return func(*args, **kwargs)
else:
raise InvalidCredentials("Unable to authenticate the user")
return wrapper
return decorator
|
onvif/oxfplayer
|
player/src/player/videoPlayback.h
|
/************************************************************************************
* Copyright (c) 2013 ONVIF.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of ONVIF nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ONVIF BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************************/
#ifndef VIDEOPLAYBACK_H
#define VIDEOPLAYBACK_H
#include "basePlayback.h"
#include "ffmpeg.h"
#include "types.h"
#include "videoContext.h"
#include "decoder.h"
#include "videoFrameWidget.h"
//! Main video system.
/*!
* \brief This class is responsible for video playback.
*/
class VideoPlayback : public BasePlayback
{
private:
Q_OBJECT
public:
VideoPlayback();
~VideoPlayback();
//! Set video context. VideoContext used to get delay from it.
void setVideoContext(VideoContext* video_context) { m_video_context = video_context; }
//! Set decoder to read from.
void setVideoDecoder(Decoder<VideoFrame>* video_decoder) { m_video_decoder = video_decoder; }
//! Set widget to draw on.
void setVideoWidget(VideoFrameWidget* video_widget);
virtual void start();
virtual void pause();
virtual void resume();
virtual void stop();
virtual void startAndPause();
virtual void clear();
virtual int getPlayingTime() const;
public slots:
//! Synchronize video to audio by audio timestamps.
void syncWithAudio(BasePlayback* playback);
protected:
//! Timer event to draw new frame.
virtual void timerEvent(QTimerEvent* event);
private:
//! Draw new frame.
void showFrame(bool single_frame = false);
private:
//! VideoContext.
VideoContext* m_video_context;
//! Decoder that provides data.
Decoder<VideoFrame>* m_video_decoder;
//! Widget to draw on.
VideoFrameWidget* m_video_widget;
//! Timer till next frame drawing.
int m_timer;
//! Currently drawing frame.
VideoFrame m_current_frame;
//! Current delay till next frame.
int m_current_delay;
};
#endif // VIDEOPLAYBACK_H
|
Ralireza/CTF
|
asis_2019_Andex/andex-jadx-reversed/sources/androidx/constraintlayout/solver/widgets/ConstraintWidgetContainer.java
|
package androidx.constraintlayout.solver.widgets;
import androidx.constraintlayout.solver.LinearSystem;
import androidx.constraintlayout.solver.Metrics;
import androidx.constraintlayout.solver.widgets.ConstraintAnchor.Type;
import androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConstraintWidgetContainer extends WidgetContainer {
private static final boolean DEBUG = false;
static final boolean DEBUG_GRAPH = false;
private static final boolean DEBUG_LAYOUT = false;
private static final int MAX_ITERATIONS = 8;
private static final boolean USE_SNAPSHOT = true;
int mDebugSolverPassCount = 0;
public boolean mGroupsWrapOptimized = false;
private boolean mHeightMeasuredTooSmall = false;
ChainHead[] mHorizontalChainsArray = new ChainHead[4];
int mHorizontalChainsSize = 0;
public boolean mHorizontalWrapOptimized = false;
private boolean mIsRtl = false;
private int mOptimizationLevel = 7;
int mPaddingBottom;
int mPaddingLeft;
int mPaddingRight;
int mPaddingTop;
public boolean mSkipSolver = false;
private Snapshot mSnapshot;
protected LinearSystem mSystem = new LinearSystem();
ChainHead[] mVerticalChainsArray = new ChainHead[4];
int mVerticalChainsSize = 0;
public boolean mVerticalWrapOptimized = false;
public List<ConstraintWidgetGroup> mWidgetGroups = new ArrayList();
private boolean mWidthMeasuredTooSmall = false;
public int mWrapFixedHeight = 0;
public int mWrapFixedWidth = 0;
public String getType() {
return "ConstraintLayout";
}
public boolean handlesInternalConstraints() {
return false;
}
public void fillMetrics(Metrics metrics) {
this.mSystem.fillMetrics(metrics);
}
public ConstraintWidgetContainer() {
}
public ConstraintWidgetContainer(int i, int i2, int i3, int i4) {
super(i, i2, i3, i4);
}
public ConstraintWidgetContainer(int i, int i2) {
super(i, i2);
}
public void setOptimizationLevel(int i) {
this.mOptimizationLevel = i;
}
public int getOptimizationLevel() {
return this.mOptimizationLevel;
}
public boolean optimizeFor(int i) {
if ((this.mOptimizationLevel & i) == i) {
return USE_SNAPSHOT;
}
return false;
}
public void reset() {
this.mSystem.reset();
this.mPaddingLeft = 0;
this.mPaddingRight = 0;
this.mPaddingTop = 0;
this.mPaddingBottom = 0;
this.mWidgetGroups.clear();
this.mSkipSolver = false;
super.reset();
}
public boolean isWidthMeasuredTooSmall() {
return this.mWidthMeasuredTooSmall;
}
public boolean isHeightMeasuredTooSmall() {
return this.mHeightMeasuredTooSmall;
}
public boolean addChildrenToSolver(LinearSystem linearSystem) {
addToSolver(linearSystem);
int size = this.mChildren.size();
for (int i = 0; i < size; i++) {
ConstraintWidget constraintWidget = (ConstraintWidget) this.mChildren.get(i);
if (constraintWidget instanceof ConstraintWidgetContainer) {
DimensionBehaviour dimensionBehaviour = constraintWidget.mListDimensionBehaviors[0];
DimensionBehaviour dimensionBehaviour2 = constraintWidget.mListDimensionBehaviors[1];
if (dimensionBehaviour == DimensionBehaviour.WRAP_CONTENT) {
constraintWidget.setHorizontalDimensionBehaviour(DimensionBehaviour.FIXED);
}
if (dimensionBehaviour2 == DimensionBehaviour.WRAP_CONTENT) {
constraintWidget.setVerticalDimensionBehaviour(DimensionBehaviour.FIXED);
}
constraintWidget.addToSolver(linearSystem);
if (dimensionBehaviour == DimensionBehaviour.WRAP_CONTENT) {
constraintWidget.setHorizontalDimensionBehaviour(dimensionBehaviour);
}
if (dimensionBehaviour2 == DimensionBehaviour.WRAP_CONTENT) {
constraintWidget.setVerticalDimensionBehaviour(dimensionBehaviour2);
}
} else {
Optimizer.checkMatchParent(this, linearSystem, constraintWidget);
constraintWidget.addToSolver(linearSystem);
}
}
if (this.mHorizontalChainsSize > 0) {
Chain.applyChainConstraints(this, linearSystem, 0);
}
if (this.mVerticalChainsSize > 0) {
Chain.applyChainConstraints(this, linearSystem, 1);
}
return USE_SNAPSHOT;
}
public void updateChildrenFromSolver(LinearSystem linearSystem, boolean[] zArr) {
zArr[2] = false;
updateFromSolver(linearSystem);
int size = this.mChildren.size();
for (int i = 0; i < size; i++) {
ConstraintWidget constraintWidget = (ConstraintWidget) this.mChildren.get(i);
constraintWidget.updateFromSolver(linearSystem);
if (constraintWidget.mListDimensionBehaviors[0] == DimensionBehaviour.MATCH_CONSTRAINT && constraintWidget.getWidth() < constraintWidget.getWrapWidth()) {
zArr[2] = USE_SNAPSHOT;
}
if (constraintWidget.mListDimensionBehaviors[1] == DimensionBehaviour.MATCH_CONSTRAINT && constraintWidget.getHeight() < constraintWidget.getWrapHeight()) {
zArr[2] = USE_SNAPSHOT;
}
}
}
public void setPadding(int i, int i2, int i3, int i4) {
this.mPaddingLeft = i;
this.mPaddingTop = i2;
this.mPaddingRight = i3;
this.mPaddingBottom = i4;
}
public void setRtl(boolean z) {
this.mIsRtl = z;
}
public boolean isRtl() {
return this.mIsRtl;
}
public void analyze(int i) {
super.analyze(i);
int size = this.mChildren.size();
for (int i2 = 0; i2 < size; i2++) {
((ConstraintWidget) this.mChildren.get(i2)).analyze(i);
}
}
/* JADX WARNING: type inference failed for: r8v15, types: [boolean] */
/* JADX WARNING: type inference failed for: r8v16 */
/* JADX WARNING: type inference failed for: r8v17 */
/* JADX WARNING: type inference failed for: r8v48 */
/* JADX WARNING: type inference failed for: r8v49 */
/* JADX WARNING: Multi-variable type inference failed. Error: jadx.core.utils.exceptions.JadxRuntimeException: No candidate types for var: r8v15, types: [boolean]
assigns: []
uses: [?[int, short, byte, char], boolean]
mth insns count: 345
at jadx.core.dex.visitors.typeinference.TypeSearch.fillTypeCandidates(TypeSearch.java:237)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at jadx.core.dex.visitors.typeinference.TypeSearch.run(TypeSearch.java:53)
at jadx.core.dex.visitors.typeinference.TypeInferenceVisitor.runMultiVariableSearch(TypeInferenceVisitor.java:99)
at jadx.core.dex.visitors.typeinference.TypeInferenceVisitor.visit(TypeInferenceVisitor.java:92)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:27)
at jadx.core.dex.visitors.DepthTraversal.lambda$visit$1(DepthTraversal.java:14)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:14)
at jadx.core.ProcessClass.process(ProcessClass.java:30)
at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:49)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:49)
at jadx.core.ProcessClass.process(ProcessClass.java:35)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:311)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:217)
*/
/* JADX WARNING: Removed duplicated region for block: B:107:0x0269 */
/* JADX WARNING: Removed duplicated region for block: B:110:0x0285 */
/* JADX WARNING: Removed duplicated region for block: B:111:0x0292 */
/* JADX WARNING: Removed duplicated region for block: B:113:0x0295 */
/* JADX WARNING: Removed duplicated region for block: B:69:0x0188 */
/* JADX WARNING: Removed duplicated region for block: B:71:0x0191 */
/* JADX WARNING: Removed duplicated region for block: B:85:0x01dc */
/* JADX WARNING: Unknown variable types count: 3 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public void layout() {
/*
r21 = this;
r1 = r21
int r2 = r1.mX
int r3 = r1.mY
int r0 = r21.getWidth()
r4 = 0
int r5 = java.lang.Math.max(r4, r0)
int r0 = r21.getHeight()
int r6 = java.lang.Math.max(r4, r0)
r1.mWidthMeasuredTooSmall = r4
r1.mHeightMeasuredTooSmall = r4
androidx.constraintlayout.solver.widgets.ConstraintWidget r0 = r1.mParent
if (r0 == 0) goto L_0x0046
androidx.constraintlayout.solver.widgets.Snapshot r0 = r1.mSnapshot
if (r0 != 0) goto L_0x002a
androidx.constraintlayout.solver.widgets.Snapshot r0 = new androidx.constraintlayout.solver.widgets.Snapshot
r0.<init>(r1)
r1.mSnapshot = r0
L_0x002a:
androidx.constraintlayout.solver.widgets.Snapshot r0 = r1.mSnapshot
r0.updateFrom(r1)
int r0 = r1.mPaddingLeft
r1.setX(r0)
int r0 = r1.mPaddingTop
r1.setY(r0)
r21.resetAnchors()
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem
androidx.constraintlayout.solver.Cache r0 = r0.getCache()
r1.resetSolverVariables(r0)
goto L_0x004a
L_0x0046:
r1.mX = r4
r1.mY = r4
L_0x004a:
int r0 = r1.mOptimizationLevel
r7 = 32
r8 = 8
r9 = 1
if (r0 == 0) goto L_0x006a
boolean r0 = r1.optimizeFor(r8)
if (r0 != 0) goto L_0x005c
r21.optimizeReset()
L_0x005c:
boolean r0 = r1.optimizeFor(r7)
if (r0 != 0) goto L_0x0065
r21.optimize()
L_0x0065:
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem
r0.graphOptimizer = r9
goto L_0x006e
L_0x006a:
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem
r0.graphOptimizer = r4
L_0x006e:
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
r10 = r0[r9]
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
r11 = r0[r4]
r21.resetChains()
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r0 = r1.mWidgetGroups
int r0 = r0.size()
if (r0 != 0) goto L_0x0092
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r0 = r1.mWidgetGroups
r0.clear()
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r0 = r1.mWidgetGroups
androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup r12 = new androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup
java.util.ArrayList r13 = r1.mChildren
r12.<init>(r13)
r0.add(r4, r12)
L_0x0092:
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r0 = r1.mWidgetGroups
int r12 = r0.size()
java.util.ArrayList r13 = r1.mChildren
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r0 = r21.getHorizontalDimensionBehaviour()
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r14 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
if (r0 == r14) goto L_0x00ad
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r0 = r21.getVerticalDimensionBehaviour()
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r14 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
if (r0 != r14) goto L_0x00ab
goto L_0x00ad
L_0x00ab:
r14 = 0
goto L_0x00ae
L_0x00ad:
r14 = 1
L_0x00ae:
r0 = 0
r15 = 0
L_0x00b0:
if (r15 >= r12) goto L_0x02f6
boolean r8 = r1.mSkipSolver
if (r8 != 0) goto L_0x02f6
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r8 = r1.mWidgetGroups
java.lang.Object r8 = r8.get(r15)
androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup r8 = (androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup) r8
boolean r8 = r8.mSkipSolver
if (r8 == 0) goto L_0x00c6
r19 = r12
goto L_0x02ea
L_0x00c6:
boolean r8 = r1.optimizeFor(r7)
if (r8 == 0) goto L_0x00fb
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r8 = r21.getHorizontalDimensionBehaviour()
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r7 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.FIXED
if (r8 != r7) goto L_0x00ed
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r7 = r21.getVerticalDimensionBehaviour()
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r8 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.FIXED
if (r7 != r8) goto L_0x00ed
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r7 = r1.mWidgetGroups
java.lang.Object r7 = r7.get(r15)
androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup r7 = (androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup) r7
java.util.List r7 = r7.getWidgetsToSolve()
java.util.ArrayList r7 = (java.util.ArrayList) r7
r1.mChildren = r7
goto L_0x00fb
L_0x00ed:
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r7 = r1.mWidgetGroups
java.lang.Object r7 = r7.get(r15)
androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup r7 = (androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup) r7
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidget> r7 = r7.mConstrainedGroup
java.util.ArrayList r7 = (java.util.ArrayList) r7
r1.mChildren = r7
L_0x00fb:
r21.resetChains()
java.util.ArrayList r7 = r1.mChildren
int r7 = r7.size()
r8 = 0
L_0x0105:
if (r8 >= r7) goto L_0x011d
java.util.ArrayList r4 = r1.mChildren
java.lang.Object r4 = r4.get(r8)
androidx.constraintlayout.solver.widgets.ConstraintWidget r4 = (androidx.constraintlayout.solver.widgets.ConstraintWidget) r4
boolean r9 = r4 instanceof androidx.constraintlayout.solver.widgets.WidgetContainer
if (r9 == 0) goto L_0x0118
androidx.constraintlayout.solver.widgets.WidgetContainer r4 = (androidx.constraintlayout.solver.widgets.WidgetContainer) r4
r4.layout()
L_0x0118:
int r8 = r8 + 1
r4 = 0
r9 = 1
goto L_0x0105
L_0x011d:
r9 = r0
r0 = 0
r4 = 1
L_0x0120:
if (r4 == 0) goto L_0x02d9
r17 = r4
r8 = 1
int r4 = r0 + 1
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem // Catch:{ Exception -> 0x0164 }
r0.reset() // Catch:{ Exception -> 0x0164 }
r21.resetChains() // Catch:{ Exception -> 0x0164 }
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem // Catch:{ Exception -> 0x0164 }
r1.createObjectVariables(r0) // Catch:{ Exception -> 0x0164 }
r0 = 0
L_0x0135:
if (r0 >= r7) goto L_0x014b
java.util.ArrayList r8 = r1.mChildren // Catch:{ Exception -> 0x0164 }
java.lang.Object r8 = r8.get(r0) // Catch:{ Exception -> 0x0164 }
androidx.constraintlayout.solver.widgets.ConstraintWidget r8 = (androidx.constraintlayout.solver.widgets.ConstraintWidget) r8 // Catch:{ Exception -> 0x0164 }
r18 = r9
androidx.constraintlayout.solver.LinearSystem r9 = r1.mSystem // Catch:{ Exception -> 0x0162 }
r8.createObjectVariables(r9) // Catch:{ Exception -> 0x0162 }
int r0 = r0 + 1
r9 = r18
goto L_0x0135
L_0x014b:
r18 = r9
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem // Catch:{ Exception -> 0x0162 }
boolean r8 = r1.addChildrenToSolver(r0) // Catch:{ Exception -> 0x0162 }
if (r8 == 0) goto L_0x015d
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem // Catch:{ Exception -> 0x015b }
r0.minimize() // Catch:{ Exception -> 0x015b }
goto L_0x015d
L_0x015b:
r0 = move-exception
goto L_0x0169
L_0x015d:
r17 = r8
r19 = r12
goto L_0x0186
L_0x0162:
r0 = move-exception
goto L_0x0167
L_0x0164:
r0 = move-exception
r18 = r9
L_0x0167:
r8 = r17
L_0x0169:
r0.printStackTrace()
java.io.PrintStream r9 = java.lang.System.out
r17 = r8
java.lang.StringBuilder r8 = new java.lang.StringBuilder
r8.<init>()
r19 = r12
java.lang.String r12 = "EXCEPTION : "
r8.append(r12)
r8.append(r0)
java.lang.String r0 = r8.toString()
r9.println(r0)
L_0x0186:
if (r17 == 0) goto L_0x0191
androidx.constraintlayout.solver.LinearSystem r8 = r1.mSystem
boolean[] r9 = androidx.constraintlayout.solver.widgets.Optimizer.flags
r1.updateChildrenFromSolver(r8, r9)
L_0x018f:
r9 = 2
goto L_0x01da
L_0x0191:
androidx.constraintlayout.solver.LinearSystem r8 = r1.mSystem
r1.updateFromSolver(r8)
r8 = 0
L_0x0197:
if (r8 >= r7) goto L_0x018f
java.util.ArrayList r9 = r1.mChildren
java.lang.Object r9 = r9.get(r8)
androidx.constraintlayout.solver.widgets.ConstraintWidget r9 = (androidx.constraintlayout.solver.widgets.ConstraintWidget) r9
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r12 = r9.mListDimensionBehaviors
r16 = 0
r12 = r12[r16]
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r0 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.MATCH_CONSTRAINT
if (r12 != r0) goto L_0x01bc
int r0 = r9.getWidth()
int r12 = r9.getWrapWidth()
if (r0 >= r12) goto L_0x01bc
boolean[] r0 = androidx.constraintlayout.solver.widgets.Optimizer.flags
r8 = 2
r12 = 1
r0[r8] = r12
goto L_0x018f
L_0x01bc:
r12 = 1
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r9.mListDimensionBehaviors
r0 = r0[r12]
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r12 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.MATCH_CONSTRAINT
if (r0 != r12) goto L_0x01d6
int r0 = r9.getHeight()
int r9 = r9.getWrapHeight()
if (r0 >= r9) goto L_0x01d6
boolean[] r0 = androidx.constraintlayout.solver.widgets.Optimizer.flags
r8 = 1
r9 = 2
r0[r9] = r8
goto L_0x01da
L_0x01d6:
r9 = 2
int r8 = r8 + 1
goto L_0x0197
L_0x01da:
if (r14 == 0) goto L_0x0254
r8 = 8
if (r4 >= r8) goto L_0x0254
boolean[] r0 = androidx.constraintlayout.solver.widgets.Optimizer.flags
boolean r0 = r0[r9]
if (r0 == 0) goto L_0x0254
r0 = 0
r9 = 0
r12 = 0
L_0x01e9:
if (r0 >= r7) goto L_0x0213
java.util.ArrayList r8 = r1.mChildren
java.lang.Object r8 = r8.get(r0)
androidx.constraintlayout.solver.widgets.ConstraintWidget r8 = (androidx.constraintlayout.solver.widgets.ConstraintWidget) r8
r17 = r4
int r4 = r8.mX
int r20 = r8.getWidth()
int r4 = r4 + r20
int r9 = java.lang.Math.max(r9, r4)
int r4 = r8.mY
int r8 = r8.getHeight()
int r4 = r4 + r8
int r12 = java.lang.Math.max(r12, r4)
int r0 = r0 + 1
r4 = r17
r8 = 8
goto L_0x01e9
L_0x0213:
r17 = r4
int r0 = r1.mMinWidth
int r0 = java.lang.Math.max(r0, r9)
int r4 = r1.mMinHeight
int r4 = java.lang.Math.max(r4, r12)
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r8 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
if (r11 != r8) goto L_0x0239
int r8 = r21.getWidth()
if (r8 >= r0) goto L_0x0239
r1.setWidth(r0)
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r8 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
r9 = 0
r0[r9] = r8
r0 = 1
r18 = 1
goto L_0x023a
L_0x0239:
r0 = 0
L_0x023a:
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r8 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
if (r10 != r8) goto L_0x0251
int r8 = r21.getHeight()
if (r8 >= r4) goto L_0x0251
r1.setHeight(r4)
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r4 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
r8 = 1
r0[r8] = r4
r0 = 1
r9 = 1
goto L_0x0259
L_0x0251:
r9 = r18
goto L_0x0259
L_0x0254:
r17 = r4
r9 = r18
r0 = 0
L_0x0259:
int r4 = r1.mMinWidth
int r8 = r21.getWidth()
int r4 = java.lang.Math.max(r4, r8)
int r8 = r21.getWidth()
if (r4 <= r8) goto L_0x0275
r1.setWidth(r4)
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r4 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.FIXED
r8 = 0
r0[r8] = r4
r0 = 1
r9 = 1
L_0x0275:
int r4 = r1.mMinHeight
int r8 = r21.getHeight()
int r4 = java.lang.Math.max(r4, r8)
int r8 = r21.getHeight()
if (r4 <= r8) goto L_0x0292
r1.setHeight(r4)
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r4 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.FIXED
r8 = 1
r0[r8] = r4
r0 = 1
r9 = 1
goto L_0x0293
L_0x0292:
r8 = 1
L_0x0293:
if (r9 != 0) goto L_0x02d2
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r4 = r1.mListDimensionBehaviors
r12 = 0
r4 = r4[r12]
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r12 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
if (r4 != r12) goto L_0x02b4
if (r5 <= 0) goto L_0x02b4
int r4 = r21.getWidth()
if (r4 <= r5) goto L_0x02b4
r1.mWidthMeasuredTooSmall = r8
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r4 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.FIXED
r9 = 0
r0[r9] = r4
r1.setWidth(r5)
r0 = 1
r9 = 1
L_0x02b4:
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r4 = r1.mListDimensionBehaviors
r4 = r4[r8]
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r12 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.WRAP_CONTENT
if (r4 != r12) goto L_0x02d2
if (r6 <= 0) goto L_0x02d2
int r4 = r21.getHeight()
if (r4 <= r6) goto L_0x02d2
r1.mHeightMeasuredTooSmall = r8
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour r4 = androidx.constraintlayout.solver.widgets.ConstraintWidget.DimensionBehaviour.FIXED
r0[r8] = r4
r1.setHeight(r6)
r4 = 1
r9 = 1
goto L_0x02d3
L_0x02d2:
r4 = r0
L_0x02d3:
r0 = r17
r12 = r19
goto L_0x0120
L_0x02d9:
r18 = r9
r19 = r12
java.util.List<androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup> r0 = r1.mWidgetGroups
java.lang.Object r0 = r0.get(r15)
androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup r0 = (androidx.constraintlayout.solver.widgets.ConstraintWidgetGroup) r0
r0.updateUnresolvedWidgets()
r0 = r18
L_0x02ea:
int r15 = r15 + 1
r12 = r19
r4 = 0
r7 = 32
r8 = 8
r9 = 1
goto L_0x00b0
L_0x02f6:
java.util.ArrayList r13 = (java.util.ArrayList) r13
r1.mChildren = r13
androidx.constraintlayout.solver.widgets.ConstraintWidget r4 = r1.mParent
if (r4 == 0) goto L_0x032a
int r2 = r1.mMinWidth
int r3 = r21.getWidth()
int r2 = java.lang.Math.max(r2, r3)
int r3 = r1.mMinHeight
int r4 = r21.getHeight()
int r3 = java.lang.Math.max(r3, r4)
androidx.constraintlayout.solver.widgets.Snapshot r4 = r1.mSnapshot
r4.applyTo(r1)
int r4 = r1.mPaddingLeft
int r2 = r2 + r4
int r4 = r1.mPaddingRight
int r2 = r2 + r4
r1.setWidth(r2)
int r2 = r1.mPaddingTop
int r3 = r3 + r2
int r2 = r1.mPaddingBottom
int r3 = r3 + r2
r1.setHeight(r3)
goto L_0x032e
L_0x032a:
r1.mX = r2
r1.mY = r3
L_0x032e:
if (r0 == 0) goto L_0x033a
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
r2 = 0
r0[r2] = r11
androidx.constraintlayout.solver.widgets.ConstraintWidget$DimensionBehaviour[] r0 = r1.mListDimensionBehaviors
r2 = 1
r0[r2] = r10
L_0x033a:
androidx.constraintlayout.solver.LinearSystem r0 = r1.mSystem
androidx.constraintlayout.solver.Cache r0 = r0.getCache()
r1.resetSolverVariables(r0)
androidx.constraintlayout.solver.widgets.ConstraintWidgetContainer r0 = r21.getRootConstraintContainer()
if (r1 != r0) goto L_0x034c
r21.updateDrawPosition()
L_0x034c:
return
*/
throw new UnsupportedOperationException("Method not decompiled: androidx.constraintlayout.solver.widgets.ConstraintWidgetContainer.layout():void");
}
public void preOptimize() {
optimizeReset();
analyze(this.mOptimizationLevel);
}
public void solveGraph() {
ResolutionAnchor resolutionNode = getAnchor(Type.LEFT).getResolutionNode();
ResolutionAnchor resolutionNode2 = getAnchor(Type.TOP).getResolutionNode();
resolutionNode.resolve(null, 0.0f);
resolutionNode2.resolve(null, 0.0f);
}
public void resetGraph() {
ResolutionAnchor resolutionNode = getAnchor(Type.LEFT).getResolutionNode();
ResolutionAnchor resolutionNode2 = getAnchor(Type.TOP).getResolutionNode();
resolutionNode.invalidateAnchors();
resolutionNode2.invalidateAnchors();
resolutionNode.resolve(null, 0.0f);
resolutionNode2.resolve(null, 0.0f);
}
public void optimizeForDimensions(int i, int i2) {
if (!(this.mListDimensionBehaviors[0] == DimensionBehaviour.WRAP_CONTENT || this.mResolutionWidth == null)) {
this.mResolutionWidth.resolve(i);
}
if (this.mListDimensionBehaviors[1] != DimensionBehaviour.WRAP_CONTENT && this.mResolutionHeight != null) {
this.mResolutionHeight.resolve(i2);
}
}
public void optimizeReset() {
int size = this.mChildren.size();
resetResolutionNodes();
for (int i = 0; i < size; i++) {
((ConstraintWidget) this.mChildren.get(i)).resetResolutionNodes();
}
}
public void optimize() {
if (!optimizeFor(8)) {
analyze(this.mOptimizationLevel);
}
solveGraph();
}
public ArrayList<Guideline> getVerticalGuidelines() {
ArrayList<Guideline> arrayList = new ArrayList<>();
int size = this.mChildren.size();
for (int i = 0; i < size; i++) {
ConstraintWidget constraintWidget = (ConstraintWidget) this.mChildren.get(i);
if (constraintWidget instanceof Guideline) {
Guideline guideline = (Guideline) constraintWidget;
if (guideline.getOrientation() == 1) {
arrayList.add(guideline);
}
}
}
return arrayList;
}
public ArrayList<Guideline> getHorizontalGuidelines() {
ArrayList<Guideline> arrayList = new ArrayList<>();
int size = this.mChildren.size();
for (int i = 0; i < size; i++) {
ConstraintWidget constraintWidget = (ConstraintWidget) this.mChildren.get(i);
if (constraintWidget instanceof Guideline) {
Guideline guideline = (Guideline) constraintWidget;
if (guideline.getOrientation() == 0) {
arrayList.add(guideline);
}
}
}
return arrayList;
}
public LinearSystem getSystem() {
return this.mSystem;
}
private void resetChains() {
this.mHorizontalChainsSize = 0;
this.mVerticalChainsSize = 0;
}
/* access modifiers changed from: 0000 */
public void addChain(ConstraintWidget constraintWidget, int i) {
if (i == 0) {
addHorizontalChain(constraintWidget);
} else if (i == 1) {
addVerticalChain(constraintWidget);
}
}
private void addHorizontalChain(ConstraintWidget constraintWidget) {
int i = this.mHorizontalChainsSize + 1;
ChainHead[] chainHeadArr = this.mHorizontalChainsArray;
if (i >= chainHeadArr.length) {
this.mHorizontalChainsArray = (ChainHead[]) Arrays.copyOf(chainHeadArr, chainHeadArr.length * 2);
}
this.mHorizontalChainsArray[this.mHorizontalChainsSize] = new ChainHead(constraintWidget, 0, isRtl());
this.mHorizontalChainsSize++;
}
private void addVerticalChain(ConstraintWidget constraintWidget) {
int i = this.mVerticalChainsSize + 1;
ChainHead[] chainHeadArr = this.mVerticalChainsArray;
if (i >= chainHeadArr.length) {
this.mVerticalChainsArray = (ChainHead[]) Arrays.copyOf(chainHeadArr, chainHeadArr.length * 2);
}
this.mVerticalChainsArray[this.mVerticalChainsSize] = new ChainHead(constraintWidget, 1, isRtl());
this.mVerticalChainsSize++;
}
public List<ConstraintWidgetGroup> getWidgetGroups() {
return this.mWidgetGroups;
}
}
|
zeroviscosity/veldt-js
|
scripts/layer/core/LivePair.js
|
'use strict';
const defaultTo = require('lodash/defaultTo');
const isNil = require('lodash/isNil');
const Group = require('./Group');
/**
* LivePair layer acts as an extension of the Group layer in which there are
* two layers, a parent and a child. Any temporary filters applied will be
* applied only to the child layer.
*/
class LivePair extends Group {
constructor(parent, child, options = {}) {
super(options);
if (isNil(parent) || isNil(parent.addFilter)) {
throw 'LivePair \'parent\' argument must be a Live layer';
}
if (isNil(child) || isNil(child.addFilter)) {
throw 'LivePair \'child\' argument must be a Live layer';
}
this.hideParentWhenFiltered = defaultTo(options.hideParentWhenFiltered, false);
this.parent = parent;
this.child = child;
this.layers.push(parent);
this.layers.push(child);
// Filters that only get applied to the child.
this.temporaryFilters = new Map();
}
enable() {
this.hidden = false;
this.muted = false;
if (this.temporaryFilters.size === 0 || !this.hideParentWhenFiltered) {
this.parent.show();
this.parent.unmute();
}
if (this.temporaryFilters.size > 0) {
this.child.show();
this.child.unmute();
}
return this;
}
disable() {
this.hidden = true;
this.muted = true;
this.parent.hide();
this.parent.mute();
this.child.hide();
this.child.mute();
return this;
}
addFilter(id, filter, isTemporary = false) {
if (!isTemporary) {
super.addFilter(id, filter);
return;
}
if (this.hideParentWhenFiltered) {
this.parent.disable();
}
this.temporaryFilters.set(id, filter);
this.child.addFilter(id, filter);
if (!this.isHidden()) {
this.child.enable();
}
}
removeFilter(id, isTemporary = false) {
if (!isTemporary) {
super.removeFilter(id);
return;
}
this.temporaryFilters.delete(id);
this.child.removeFilter(id);
// No filters applied? Then restore the parent and hide the child.
if (this.temporaryFilters.size === 0) {
this.child.disable();
if (this.hideParentWhenFiltered) {
if (!this.isHidden()) {
this.parent.enable();
}
}
}
}
isHidden() {
return this.parent.isHidden();
}
isMuted() {
return this.parent.isMuted();
}
isDisabled() {
return this.parent.isDisabled();
}
getZIndex() {
return this.parent.getZIndex();
}
getOpacity() {
return this.parent.getOpacity();
}
isFiltered() {
return this.parent.isFiltered() || this.child.isFiltered();
}
}
module.exports = LivePair;
|
workready/pythonbasic
|
sources/t09/t09ej07.py
|
class SpamException(Exception):
pass
def writer():
"""Simula escribir datos que se le pasan en un socket, fichero, etc"""
while True:
try:
w = (yield)
except SpamException:
print('***')
else:
print(w)
def writer_wrapper(coro):
coro.send(None) # Inicio la corrutina. Es equivalente a next(coro)
while True:
try:
x = (yield) # Capturo el valor que me envían
coro.send(x) # Y se lo paso al escritor
except StopIteration:
pass # Capturo la señal de finalización, cuando me dejan de mandar datos
# Comienza el juego
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # Inicio la corrutina
# Vamos a hacer saltar la excepción en el escritor
for i in [0, 1, 2, 'spam', 4]:
if i == 'spam':
wrap.throw(SpamException)
else:
wrap.send(i)
|
EladGabay/pulumi-oci
|
sdk/go/oci/getOptimizerResourceAction.go
|
<gh_stars>1-10
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package oci
import (
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// This data source provides details about a specific Resource Action resource in Oracle Cloud Infrastructure Optimizer service.
//
// Gets the resource action that corresponds to the specified OCID.
//
// ## Example Usage
//
// ```go
// package main
//
// import (
// "github.com/pulumi/pulumi-oci/sdk/go/oci"
// "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
// )
//
// func main() {
// pulumi.Run(func(ctx *pulumi.Context) error {
// _, err := oci.GetOptimizerResourceAction(ctx, &GetOptimizerResourceActionArgs{
// ResourceActionId: oci_optimizer_resource_action.Test_resource_action.Id,
// }, nil)
// if err != nil {
// return err
// }
// return nil
// })
// }
// ```
func LookupOptimizerResourceAction(ctx *pulumi.Context, args *LookupOptimizerResourceActionArgs, opts ...pulumi.InvokeOption) (*LookupOptimizerResourceActionResult, error) {
var rv LookupOptimizerResourceActionResult
err := ctx.Invoke("oci:index/getOptimizerResourceAction:GetOptimizerResourceAction", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
}
// A collection of arguments for invoking GetOptimizerResourceAction.
type LookupOptimizerResourceActionArgs struct {
// The unique OCID associated with the resource action.
ResourceActionId string `pulumi:"resourceActionId"`
}
// A collection of values returned by GetOptimizerResourceAction.
type LookupOptimizerResourceActionResult struct {
// Details about the recommended action.
Action GetOptimizerResourceActionAction `pulumi:"action"`
// The unique OCID associated with the category.
CategoryId string `pulumi:"categoryId"`
// The OCID of the compartment.
CompartmentId string `pulumi:"compartmentId"`
// The name associated with the compartment.
CompartmentName string `pulumi:"compartmentName"`
// The estimated cost savings, in dollars, for the resource action.
EstimatedCostSaving float64 `pulumi:"estimatedCostSaving"`
// Additional metadata key/value pairs that you provide. They serve the same purpose and functionality as fields in the `metadata` object.
ExtendedMetadata map[string]interface{} `pulumi:"extendedMetadata"`
// The unique OCID associated with the resource action.
Id string `pulumi:"id"`
// Custom metadata key/value pairs for the resource action.
Metadata map[string]interface{} `pulumi:"metadata"`
// The name assigned to the resource.
Name string `pulumi:"name"`
// The unique OCID associated with the recommendation.
RecommendationId string `pulumi:"recommendationId"`
ResourceActionId string `pulumi:"resourceActionId"`
// The unique OCID associated with the resource.
ResourceId string `pulumi:"resourceId"`
// The kind of resource.
ResourceType string `pulumi:"resourceType"`
// The resource action's current state.
State string `pulumi:"state"`
// The current status of the resource action.
Status string `pulumi:"status"`
// The date and time the resource action details were created, in the format defined by RFC3339.
TimeCreated string `pulumi:"timeCreated"`
// The date and time that the resource action entered its current status. The format is defined by RFC3339.
TimeStatusBegin string `pulumi:"timeStatusBegin"`
// The date and time the current status will change. The format is defined by RFC3339.
TimeStatusEnd string `pulumi:"timeStatusEnd"`
// The date and time the resource action details were last updated, in the format defined by RFC3339.
TimeUpdated string `pulumi:"timeUpdated"`
}
|
HemaHG/porta
|
config/initializers/active_record.rb
|
<filename>config/initializers/active_record.rb
# TODO: remove this hack?
class ActiveRecord::Base
# returns a human readable name of the class.
# It is here mainly to allow Cinstance to return "Application"
def human_name
self.to_s
end
end
|
a6dulaleem/pravega
|
controller/src/test/java/io/pravega/controller/server/eventProcessor/PravegaTablesRequestHandlersTest.java
|
<reponame>a6dulaleem/pravega
/**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.controller.server.eventProcessor;
import io.pravega.controller.mocks.SegmentHelperMock;
import io.pravega.controller.server.SegmentHelper;
import io.pravega.controller.server.security.auth.GrpcAuthHelper;
import io.pravega.controller.store.kvtable.KVTableMetadataStore;
import io.pravega.controller.store.kvtable.KVTableStoreFactory;
import io.pravega.controller.store.stream.StreamMetadataStore;
import io.pravega.controller.store.stream.StreamStoreFactory;
import io.pravega.controller.store.Version;
import lombok.Synchronized;
public class PravegaTablesRequestHandlersTest extends RequestHandlersTest {
private SegmentHelper segmentHelper;
@Override
@Synchronized
StreamMetadataStore getStore() {
if (segmentHelper == null) {
segmentHelper = SegmentHelperMock.getSegmentHelperMockForTables(executor);
}
return StreamStoreFactory.createPravegaTablesStore(segmentHelper, GrpcAuthHelper.getDisabledAuthHelper(), zkClient, executor);
}
@Override
KVTableMetadataStore getKvtStore() {
if (segmentHelper == null) {
segmentHelper = SegmentHelperMock.getSegmentHelperMockForTables(executor);
}
return KVTableStoreFactory.createPravegaTablesStore(segmentHelper, GrpcAuthHelper.getDisabledAuthHelper(), zkClient, executor);
}
@Override
int getVersionNumber(Version version) {
return (int) version.asLongVersion().getLongValue();
}
}
|
IAPark/PITherm
|
src/shared/utilities/__init__.py
|
<gh_stars>0
__author__ = 'Isaac'
|
getflywheel/sendgrid4r
|
lib/sendgrid4r/rest/settings/settings.rb
|
# -*- encoding: utf-8 -*-
module SendGrid4r
module REST
#
# SendGrid Web API v3 Settings
#
module Settings
Results = Struct.new(:result)
Result = Struct.new(:name, :title, :description, :enabled)
def self.create_results(resp)
return resp if resp.nil?
results = []
resp['result'].each do |result|
results.push(SendGrid4r::REST::Settings.create_result(result))
end
Results.new(results)
end
def self.create_result(resp)
return resp if resp.nil?
Result.new(
resp['name'], resp['title'], resp['description'], resp['enabled']
)
end
end
end
end
|
jasonsbarr/types
|
packages/iterable/lib/reverse.js
|
export const reverse = (iter) => iter.constructor(...[...iter].reverse());
|
iconara/aws-doc-sdk-examples
|
ruby/example_code/cloudwatch/tests/test_cw-ruby-example-show-alarms.rb
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX - License - Identifier: Apache - 2.0
require_relative '../cw-ruby-example-show-alarms'
describe '#describe_metric_alarms' do
let(:metric_namespace) { 'SITE/TRAFFIC' }
let(:metric_name) { 'UniqueVisitors' }
let(:dimension_name) { 'SiteName' }
let(:dimension_value) { 'example.com' }
let(:metric_value) { 5_885.0 }
let(:metric_unit) { 'Count' }
let(:cloudwatch_client) do
Aws::CloudWatch::Client.new(
stub_responses: {
describe_alarms: {
metric_alarms: [
{
alarm_name: 'ObjectsInBucket',
state_value: 'INSUFFICIENT_DATA',
state_reason: 'Unchecked: Initial alarm creation',
metric_name: 'NumberOfObjects',
namespace: 'AWS/S3',
statistic: 'Average',
period: 86_400,
unit: 'Count',
evaluation_periods: 1,
threshold: 1.0,
comparison_operator: 'GreaterThanThreshold',
ok_actions: [
'arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'
],
dimensions: [
{
name: 'BucketName',
value: 'doc-example-bucket'
},
{
name: 'StorageType',
value: 'AllStorageTypes'
}
]
}
]
}
}
)
end
it 'shows information about metric alarms' do
expect { describe_metric_alarms(cloudwatch_client) }.not_to raise_error
end
end
|
mrtyasar/PythonLearn
|
with mosh everybody python/typeConversion.py
|
birthYear = input('Birth year: ')
print(type(birthYear)) # değişkenin tipini öğrendik
age = 2020 - int(birthYear) # değişkeni int veri tipine çevirdik
print(type(age)) # değişkenin tipini öğrendik
print(age)
# Egzersiz
weightLbs = input('Weight (lbs): ')
weightKg = int(weightLbs) * 0.45
print(weightKg)
|
ystk/debian-net-snmp
|
agent/mibgroup/snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable.h
|
/*
* Note: this file originally auto-generated by mib2c using
* version : 1.48 $ of : mfd-top.m2c,v $
*
* $Id: usmDHUserKeyTable.h 14169 2006-01-25 16:28:12Z dts12 $
*/
#ifndef USMDHUSERKEYTABLE_H
#define USMDHUSERKEYTABLE_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup misc misc: Miscellaneous routines
*
* @{
*/
#include <net-snmp/library/asn1.h>
/*
* other required module components
*/
/* *INDENT-OFF* */
config_require(snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_interface)
config_require(snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_data_access)
config_require(snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_data_get)
config_require(snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_data_set)
/* *INDENT-ON* */
/*
* OID and column number definitions for usmDHUserKeyTable
*/
#include "usmDHUserKeyTable_oids.h"
/*
* enum definions
*/
#include "usmDHUserKeyTable_enums.h"
/*
*********************************************************************
* function declarations
*/
void init_usmDHUserKeyTable(void);
void shutdown_usmDHUserKeyTable(void);
/*
*********************************************************************
* Table declarations
*/
/**********************************************************************
**********************************************************************
***
*** Table usmDHUserKeyTable
***
**********************************************************************
**********************************************************************/
/*
* SNMP-USM-DH-OBJECTS-MIB::usmDHUserKeyTable is subid 2 of usmDHPublicObjects.
* Its status is Current.
* OID: .1.3.6.1.3.101.1.1.2, length: 9
*/
/*
*********************************************************************
* When you register your mib, you get to provide a generic
* pointer that will be passed back to you for most of the
* functions calls.
*
* TODO:100:r: Review all context structures
*/
/*
* TODO:101:o: |-> Review usmDHUserKeyTable registration context.
*/
typedef struct usmUser *usmDHUserKeyTable_registration;
/**********************************************************************/
/*
* TODO:110:r: |-> Review usmDHUserKeyTable data context structure.
* This structure is used to represent the data for usmDHUserKeyTable.
*/
typedef struct usmUser usmDHUserKeyTable_data;
/*
*********************************************************************
* TODO:115:o: |-> Review usmDHUserKeyTable undo context.
* We're just going to use the same data structure for our
* undo_context. If you want to do something more efficent,
* define your typedef here.
*/
typedef usmDHUserKeyTable_data usmDHUserKeyTable_undo_data;
/*
* TODO:120:r: |-> Review usmDHUserKeyTable mib index.
* This structure is used to represent the index for usmDHUserKeyTable.
*/
typedef struct usmDHUserKeyTable_mib_index_s {
/*
* usmUserEngineID(1)/SnmpEngineID/ASN_OCTET_STR/char(char)//L/a/w/e/R/d/h
*/
char usmUserEngineID[32];
size_t usmUserEngineID_len;
/*
* usmUserName(2)/SnmpAdminString/ASN_OCTET_STR/char(char)//L/a/w/e/R/d/H
*/
char usmUserName[32];
size_t usmUserName_len;
} usmDHUserKeyTable_mib_index;
/*
* TODO:121:r: | |-> Review usmDHUserKeyTable max index length.
* If you KNOW that your indexes will never exceed a certain
* length, update this macro to that length.
*
* BE VERY CAREFUL TO TAKE INTO ACCOUNT THE MAXIMUM
* POSSIBLE LENGHT FOR EVERY VARIABLE LENGTH INDEX!
* Guessing 128 - col/entry(2) - oid len(9)
*/
#define MAX_usmDHUserKeyTable_IDX_LEN 66
/*
*********************************************************************
* TODO:130:o: |-> Review usmDHUserKeyTable Row request (rowreq) context.
* When your functions are called, you will be passed a
* usmDHUserKeyTable_rowreq_ctx pointer.
*/
typedef struct usmDHUserKeyTable_rowreq_ctx_s {
/** this must be first for container compare to work */
netsnmp_index oid_idx;
oid oid_tmp[MAX_usmDHUserKeyTable_IDX_LEN];
usmDHUserKeyTable_mib_index tbl_idx;
usmDHUserKeyTable_data *data;
usmDHUserKeyTable_undo_data *undo;
unsigned int column_set_flags; /* flags for set columns */
/*
* flags per row. Currently, the first (lower) 8 bits are reserved
* for the user. See mfd.h for other flags.
*/
u_int rowreq_flags;
/*
* TODO:131:o: | |-> Add useful data to usmDHUserKeyTable rowreq context.
*/
/*
* storage for future expansion
*/
netsnmp_data_list *usmDHUserKeyTable_data_list;
} usmDHUserKeyTable_rowreq_ctx;
typedef struct usmDHUserKeyTable_ref_rowreq_ctx_s {
usmDHUserKeyTable_rowreq_ctx *rowreq_ctx;
} usmDHUserKeyTable_ref_rowreq_ctx;
/*
*********************************************************************
* function prototypes
*/
int
usmDHUserKeyTable_pre_request(usmDHUserKeyTable_registration *
user_context);
int
usmDHUserKeyTable_post_request(usmDHUserKeyTable_registration *
user_context, int rc);
int
usmDHUserKeyTable_rowreq_ctx_init(usmDHUserKeyTable_rowreq_ctx *
rowreq_ctx, void *user_init_ctx);
void
usmDHUserKeyTable_rowreq_ctx_cleanup(usmDHUserKeyTable_rowreq_ctx *
rowreq_ctx);
usmDHUserKeyTable_data *usmDHUserKeyTable_allocate_data(void);
void usmDHUserKeyTable_release_data(usmDHUserKeyTable_data *
data);
int
usmDHUserKeyTable_check_dependencies(usmDHUserKeyTable_rowreq_ctx *
rowreq_ctx);
int usmDHUserKeyTable_commit(usmDHUserKeyTable_rowreq_ctx *
rowreq_ctx);
int
usmDHUserKeyTable_irreversible_commit(usmDHUserKeyTable_rowreq_ctx
* rowreq_ctx);
usmDHUserKeyTable_rowreq_ctx
*usmDHUserKeyTable_row_find_by_mib_index
(usmDHUserKeyTable_mib_index * mib_idx);
extern oid usmDHUserKeyTable_oid[];
extern int usmDHUserKeyTable_oid_size;
#include "usmDHUserKeyTable_interface.h"
#include "usmDHUserKeyTable_data_access.h"
#include "usmDHUserKeyTable_data_get.h"
#include "usmDHUserKeyTable_data_set.h"
/*
* DUMMY markers, ignore
*
* TODO:099:x: *************************************************************
* TODO:199:x: *************************************************************
* TODO:299:x: *************************************************************
* TODO:399:x: *************************************************************
* TODO:499:x: *************************************************************
*/
#ifdef __cplusplus
}
#endif
#endif /* USMDHUSERKEYTABLE_H */
/** @} */
|
Open-EO/openeo-geopyspark-driver
|
tests/test_creo.py
|
<reponame>Open-EO/openeo-geopyspark-driver<filename>tests/test_creo.py<gh_stars>10-100
import unittest
import datetime
from openeogeotrellis.catalogs.creo import CreoCatalogClient
class TestCreo(unittest.TestCase):
def setUp(self):
self.l2a_catalog = CreoCatalogClient(mission="Sentinel2", level="LEVEL2A")
def test_creo_catalog(self):
date = datetime.date(2018, 4, 1)
results = self.l2a_catalog.query_product_paths(date, date, ulx=5, uly=51.1, brx=5.1, bry=51)
assert 'S2A_MSIL2A_20180401T105031_N0207_R051_T31UFS_20180401T144530.SAFE' in results[0]
|
lynx-json/jsua-lynx
|
src/util.js
|
import url from "url";
import * as jsua from "@lynx-json/jsua";
export function resolveSpecFromUrl(specUrl) {
return new Promise(function (resolve, reject) {
jsua.transferring.transfer({ url: specUrl })
.then(function (content) {
let reader = new FileReader();
reader.addEventListener("loadend", function () {
try {
resolve(JSON.parse(reader.result));
} catch (err) {
reject(err);
}
});
reader.readAsText(content.blob);
})
.catch(reject);
});
}
export function findNearestView(view, selector, predicate, origin) {
function query() {
var result = Array.from(view.querySelectorAll(selector));
if (view !== origin && view.matches(selector)) {
result.push(view);
}
return result;
}
if (!view || !selector || view.matches("[data-jsua-context~=app]")) return null;
origin = origin || view;
var matches = query();
if (matches.length === 0) return findNearestView(view.parentElement, selector, predicate, origin);
if (predicate) {
let matching = matches.find(predicate);
if (matching) return matching;
return findNearestView(view.parentElement, selector, predicate, origin);
}
return matches[0];
}
export function findNearestAncestorView(view, selector, predicate) {
if (!view || !selector || view.matches("[data-jsua-context~=app]")) return null;
var parent = view.parentElement;
if (parent && parent.matches(selector) && (!predicate || predicate(parent))) return parent;
return findNearestAncestorView(parent, selector, predicate);
}
export function buildFormData(submitView) {
var formView = exports.findNearestAncestorView(submitView, "[data-lynx-hints~=form]");
if (!formView) return null;
var formData;
if (submitView.getAttribute("data-lynx-submit-enctype") === "multipart/form-data") {
formData = new FormData();
} else {
formData = new URLSearchParams();
}
var inputViews = formView.querySelectorAll("[data-lynx-input]:not([data-lynx-hints~=container])");
Array.from(inputViews).forEach(function (inputView) {
var inputValues = inputView.lynxGetValue();
if (!Array.isArray(inputValues)) inputValues = [inputValues];
inputValues.forEach(function (inputValue) {
formData.append(inputView.getAttribute("data-lynx-input"), inputValue);
});
});
return formData;
}
export function scopeIncludesRealm(scope, realm) {
if (!scope || !realm) return false;
scope = url.parse(scope).href;
realm = url.parse(realm).href;
return realm.indexOf(scope) === 0;
}
export function resolveUrlForNode(node, relativeOrAbsoluteUrl) {
return url.resolve(node.base || '', relativeOrAbsoluteUrl);
}
|
fakeNetflix/mailchimp-repo-statistrano
|
lib/statistrano/deployment/strategy.rb
|
<gh_stars>10-100
module Statistrano
module Deployment
module Strategy
class << self
def registered
@_registered ||= {}
end
def register deployment, name
registered[name.to_sym] = deployment
end
def find name
registered.fetch(name.to_sym) do
raise UndefinedStrategy, "no strategies are registered as :#{name}"
end
end
end
class UndefinedStrategy < StandardError
end
end
end
end
# strategy utils
require_relative 'strategy/invoke_tasks'
require_relative 'strategy/check_git'
# strategies
require_relative 'strategy/base'
require_relative 'strategy/branches'
require_relative 'strategy/releases'
|
tucci-io/ref-dashboard
|
src/common/ShowMore/ShowMore.js
|
import React from 'react';
import { colors as Colors } from 'material-ui/styles/';
import { FlatButton } from 'material-ui';
const ShowMore = ({ style, label = 'SHOW MORE', visible = true, ...other }) => {
if (visible) {
return (
<div className="row align-center">
<FlatButton
{...other}
style={{ ...{ color: Colors.blue500 }, ...style }}
label={label}
/>
</div>
);
}
return <span />;
};
export default ShowMore;
|
tomasbrod/tbboinc
|
boinc_new/clientscr/screensaver.cpp
|
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2018 University of California
//
// BOINC 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 3 of the License, or (at your option) any later version.
//
// BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
// Screensaver coordinator.
// Alternates between a "default screensaver"
// and application graphics for running jobs.
// Periods are configurable via config file "ss_config.xml".
// See http://boinc.berkeley.edu/trac/wiki/ScreensaverEnhancements
#ifdef _WIN32
#include "boinc_win.h"
#endif
#ifdef __APPLE__
#include <Carbon/Carbon.h>
#include <sys/wait.h>
#include <app_ipc.h>
#include <malloc/malloc.h>
#include <pthread.h>
extern pthread_mutex_t saver_mutex;
#endif
// Common application includes
//
#include "diagnostics.h"
#include "common_defs.h"
#include "util.h"
#include "common_defs.h"
#include "filesys.h"
#include "error_numbers.h"
#include "gui_rpc_client.h"
#include "str_util.h"
#include "str_replace.h"
#include "screensaver.h"
// Platform specific application includes
//
#if defined(_WIN32)
#include "screensaver_win.h"
typedef HANDLE GFXAPP_ID;
#define DataMgmtProcType DWORD WINAPI
#elif defined(__APPLE__)
#include "Mac_Saver_Module.h"
typedef int GFXAPP_ID;
#define DataMgmtProcType void*
#endif
#ifdef _WIN32
// Allow for Unicode wide characters
#define PATH_SEPARATOR (_T("\\"))
#define THE_DEFAULT_SS_EXECUTABLE (_T(DEFAULT_SS_EXECUTABLE))
#define THE_SS_CONFIG_FILE (_T(SS_CONFIG_FILE))
#define DEFAULT_GFX_CANT_CONNECT ERR_CONNECT
#else
// Using (_T()) here causes compiler errors on Mac
#define PATH_SEPARATOR "/"
#define THE_DEFAULT_SS_EXECUTABLE DEFAULT_SS_EXECUTABLE
#define THE_SS_CONFIG_FILE SS_CONFIG_FILE
#define DEFAULT_GFX_CANT_CONNECT (ERR_CONNECT & 0xff)
#endif
// Flags for testing & debugging
#define SIMULATE_NO_GRAPHICS 0
bool CScreensaver::is_same_task(RESULT* taska, RESULT* taskb) {
if ((taska == NULL) || (taskb == NULL)) return false;
if (strcmp(taska->name, taskb->name)) return false;
if (strcmp(taska->project_url, taskb->project_url)) return false;
return true;
}
int CScreensaver::count_active_graphic_apps(RESULTS& res, RESULT* exclude) {
int i = 0;
unsigned int graphics_app_count = 0;
// Count the number of active graphics-capable apps excluding the specified result.
// If exclude is NULL, don't exclude any results.
//
for (i = res.results.size()-1; i >=0 ; i--) {
BOINCTRACE(_T("count_active_graphic_apps -- active task detected\n"));
BOINCTRACE(
_T("count_active_graphic_apps -- name = '%s', path = '%s'\n"),
res.results[i]->name, res.results[i]->graphics_exec_path
);
if (!strlen(res.results[i]->graphics_exec_path)) continue;
if (is_same_task(res.results[i], exclude)) continue;
#ifdef __APPLE__
// Remove it from the vector if incompatible with current version of OS X
if (isIncompatible(res.results[i]->graphics_exec_path)) {
BOINCTRACE(
_T("count_active_graphic_apps -- removing incompatible name = '%s', path = '%s'\n"),
res.results[i]->name, res.results[i]->graphics_exec_path
);
RESULT *rp = res.results[i];
res.results.erase(res.results.begin()+i);
delete rp;
continue;
}
#endif
BOINCTRACE(_T("count_active_graphic_apps -- active task detected w/graphics\n"));
graphics_app_count++;
}
return graphics_app_count;
}
// Choose a random graphics application out of the vector.
// Exclude the specified result unless it is the only candidate.
// If exclude is NULL or an empty string, don't exclude any results.
//
RESULT* CScreensaver::get_random_graphics_app(
RESULTS& res, RESULT* exclude
) {
RESULT* rp = NULL;
unsigned int i = 0;
unsigned int graphics_app_count = 0;
unsigned int random_selection = 0;
unsigned int current_counter = 0;
RESULT *avoid = exclude;
BOINCTRACE(_T("get_random_graphics_app -- Function Start\n"));
graphics_app_count = count_active_graphic_apps(res, avoid);
BOINCTRACE(_T("get_random_graphics_app -- graphics_app_count = '%d'\n"), graphics_app_count);
// If no graphics app found other than the one excluded, count again without excluding any
if ((0 == graphics_app_count) && (avoid != NULL)) {
avoid = NULL;
graphics_app_count = count_active_graphic_apps(res, avoid);
}
// If no graphics app was found, return NULL
if (0 == graphics_app_count) {
goto CLEANUP;
}
// Choose which application to display.
//
random_selection = (rand() % graphics_app_count) + 1;
BOINCTRACE(_T("get_random_graphics_app -- random_selection = '%d'\n"), random_selection);
// find the chosen graphics application.
//
for (i = 0; i < res.results.size(); i++) {
if (!strlen(res.results[i]->graphics_exec_path)) continue;
if (is_same_task(res.results[i], avoid)) continue;
current_counter++;
if (current_counter == random_selection) {
rp = res.results[i];
break;
}
}
CLEANUP:
BOINCTRACE(_T("get_random_graphics_app -- Function End\n"));
return rp;
}
#ifdef __APPLE__
void CScreensaver::markAsIncompatible(char *gfxAppPath) {
char *buf = (char *)malloc(strlen(gfxAppPath)+1);
if (buf) {
strlcpy(buf, gfxAppPath, malloc_size(buf));
m_vIncompatibleGfxApps.push_back(buf);
BOINCTRACE(_T("markAsIncompatible -- path = '%s'\n"), gfxAppPath);
}
}
bool CScreensaver::isIncompatible(char *appPath) {
unsigned int i = 0;
for (i = 0; i < m_vIncompatibleGfxApps.size(); i++) {
BOINCTRACE(
_T("isIncompatible -- comparing incompatible path '%s' to candidate path %s\n"),
m_vIncompatibleGfxApps[i], appPath
);
if (strcmp(m_vIncompatibleGfxApps[i], appPath) == 0) {
return true;
}
}
return false;
}
#endif
// Launch a project (science) graphics application
//
int CScreensaver::launch_screensaver(RESULT* rp, GFXAPP_ID& graphics_application) {
int retval = 0;
if (strlen(rp->graphics_exec_path)) {
// V6 Graphics
#ifdef __APPLE__
// For sandbox security, use gfx_switcher to launch gfx app
// as user boinc_project and group boinc_project.
//
// For unknown reasons, the graphics application exits with
// "RegisterProcess failed (error = -50)" unless we pass its
// full path twice in the argument list to execv.
char* argv[5];
argv[0] = "gfx_Switcher";
argv[1] = "-launch_gfx";
argv[2] = strrchr(rp->slot_path, '/');
if (*argv[2]) argv[2]++; // Point to the slot number in ascii
argv[3] = "--fullscreen";
argv[4] = 0;
retval = run_program(
rp->slot_path,
m_gfx_Switcher_Path,
4,
argv,
0,
graphics_application
);
if (graphics_application) {
launchedGfxApp(rp->graphics_exec_path, graphics_application, rp->slot);
}
#else
char* argv[3];
argv[0] = rp->graphics_exec_path;
argv[1] = "--fullscreen";
argv[2] = 0;
retval = run_program(
rp->slot_path,
rp->graphics_exec_path,
2,
argv,
0,
graphics_application
);
#endif
}
return retval;
}
// Terminate any screensaver graphics application
//
int CScreensaver::terminate_v6_screensaver(GFXAPP_ID& graphics_application) {
int retval = 0;
#ifdef __APPLE__
// Under sandbox security, use gfx_switcher to kill default gfx app
// as user boinc_master and group boinc_master. The man page for
// kill() says the user ID of the process sending the signal must
// match that of the target process, though in practice that seems
// not to be true on the Mac.
char current_dir[PATH_MAX];
char gfx_pid[16];
pid_t thePID;
int i;
if (graphics_application == 0) return 0;
// MUTEX may help prevent crashes when terminating an older gfx app which
// we were displaying using CGWindowListCreateImage under OS X >= 10.13
// Also prevents reentry when called from our other thread
pthread_mutex_lock(&saver_mutex);
sprintf(gfx_pid, "%d", graphics_application);
getcwd( current_dir, sizeof(current_dir));
char* argv[4];
argv[0] = "gfx_switcher";
argv[1] = "-kill_gfx";
argv[2] = gfx_pid;
argv[3] = 0;
retval = run_program(
current_dir,
m_gfx_Switcher_Path,
3,
argv,
0,
thePID
);
if (graphics_application) {
launchedGfxApp("", 0, -1);
}
for (i=0; i<200; i++) {
boinc_sleep(0.01); // Wait 2 seconds max
// Prevent gfx_switcher from becoming a zombie
if (waitpid(thePID, 0, WNOHANG) == thePID) {
break;
}
}
pthread_mutex_unlock(&saver_mutex);
#endif
#ifdef _WIN32
HWND hBOINCGraphicsWindow = FindWindow(BOINC_WINDOW_CLASS_NAME, NULL);
if (hBOINCGraphicsWindow) {
CloseWindow(hBOINCGraphicsWindow);
Sleep(1000);
hBOINCGraphicsWindow = FindWindow(BOINC_WINDOW_CLASS_NAME, NULL);
if (hBOINCGraphicsWindow) {
kill_program(graphics_application);
}
}
#endif
// For safety, call kill_program even under Apple sandbox security
kill_program(graphics_application);
return retval;
}
// Terminate the project (science) graphics application
// TODO: get rid of 2nd arg
//
int CScreensaver::terminate_screensaver(GFXAPP_ID& graphics_application, RESULT *) {
int retval = 0;
if (graphics_application) {
// V6 Graphics
if (m_bScience_gfx_running) {
terminate_v6_screensaver(graphics_application);
}
}
return retval;
}
// Launch the default graphics application
//
int CScreensaver::launch_default_screensaver(char *dir_path, GFXAPP_ID& graphics_application) {
int retval = 0;
int num_args;
#ifdef __APPLE__
// For sandbox security, use gfx_switcher to launch default
// gfx app as user boinc_master and group boinc_master.
char* argv[6];
argv[0] = "gfx_switcher";
argv[1] = "-default_gfx";
argv[2] = THE_DEFAULT_SS_EXECUTABLE; // Will be changed by gfx_switcher
argv[3] = "--fullscreen";
argv[4] = 0;
argv[5] = 0;
if (!m_bConnected) {
BOINCTRACE(_T("launch_default_screensaver using --retry_connect argument\n"));
argv[4] = "--retry_connect";
num_args = 5;
} else {
num_args = 4;
}
retval = run_program(
dir_path,
m_gfx_Switcher_Path,
num_args,
argv,
0,
graphics_application
);
if (graphics_application) {
launchedGfxApp("boincscr", graphics_application, -1);
}
BOINCTRACE(_T("launch_default_screensaver returned %d\n"), retval);
#else
char* argv[4];
char full_path[1024];
strlcpy(full_path, dir_path, sizeof(full_path));
strlcat(full_path, PATH_SEPARATOR, sizeof(full_path));
strlcat(full_path, THE_DEFAULT_SS_EXECUTABLE, sizeof(full_path));
argv[0] = full_path;
argv[1] = "--fullscreen";
argv[2] = 0;
argv[3] = 0;
if (!m_bConnected) {
BOINCTRACE(_T("launch_default_screensaver using --retry_connect argument\n"));
argv[2] = "--retry_connect";
num_args = 3;
} else {
num_args = 2;
}
retval = run_program(
dir_path,
full_path,
num_args,
argv,
0,
graphics_application
);
BOINCTRACE(_T("launch_default_screensaver %s returned %d\n"), full_path, retval);
#endif
return retval;
}
// Terminate the default graphics application
//
int CScreensaver::terminate_default_screensaver(GFXAPP_ID& graphics_application) {
int retval = 0;
if (! graphics_application) return 0;
retval = terminate_v6_screensaver(graphics_application);
return retval;
}
// If we cannot connect to the core client:
// - we retry connecting every 10 seconds
// - we launch the default graphics application with the argument --retry_connect, so
// it will continue running and will also retry connecting every 10 seconds.
//
// If we successfully connected to the core client, launch the default graphics application
// without the argument --retry_connect. If it can't connect, it will return immediately
// with the exit code ERR_CONNECT. In that case, we assume it was blocked by a firewall
// and so we run only project (science) graphics.
DataMgmtProcType CScreensaver::DataManagementProc() {
int retval = 0;
int suspend_reason = 0;
RESULT* theResult = NULL;
RESULT* graphics_app_result_ptr = NULL;
RESULT previous_result;
// previous_result_ptr = &previous_result when previous_result is valid, else NULL
RESULT* previous_result_ptr = NULL;
int iResultCount = 0;
int iIndex = 0;
double default_phase_start_time = 0.0;
double science_phase_start_time = 0.0;
double last_change_time = 0.0;
// If we run default screensaver during science phase because no science graphics
// are available, then shorten next default graphics phase by that much time.
double default_saver_start_time_in_science_phase = 0.0;
double default_saver_duration_in_science_phase = 0.0;
SS_PHASE ss_phase = DEFAULT_SS_PHASE;
bool switch_to_default_gfx = false;
bool killing_default_gfx = false;
int exit_status = 0;
char* default_ss_dir_path = NULL;
char full_path[1024];
BOINCTRACE(_T("CScreensaver::DataManagementProc - Display screen saver loading message\n"));
SetError(TRUE, SCRAPPERR_BOINCSCREENSAVERLOADING); // No GFX App is running: show moving BOINC logo
#ifdef _WIN32
m_tThreadCreateTime = time(0);
// Set the starting point for iterating through the results
m_iLastResultShown = 0;
m_tLastResultChangeTime = 0;
#endif
m_bDefault_ss_exists = false;
m_bScience_gfx_running = false;
m_bDefault_gfx_running = false;
m_bShow_default_ss_first = false;
#ifdef __APPLE__
m_vIncompatibleGfxApps.clear();
default_ss_dir_path = "/Library/Application Support/BOINC Data";
#else
default_ss_dir_path = (char*)m_strBOINCInstallDirectory.c_str();
#endif
strlcpy(full_path, default_ss_dir_path, sizeof(full_path));
strlcat(full_path, PATH_SEPARATOR, sizeof(full_path));
strlcat(full_path, THE_DEFAULT_SS_EXECUTABLE, sizeof(full_path));
if (boinc_file_exists(full_path)) {
m_bDefault_ss_exists = true;
} else {
SetError(TRUE, SCRAPPERR_CANTLAUNCHDEFAULTGFXAPP); // No GFX App is running: show moving BOINC logo
}
if (m_bDefault_ss_exists && m_bShow_default_ss_first) {
ss_phase = DEFAULT_SS_PHASE;
default_phase_start_time = dtime();
science_phase_start_time = 0;
switch_to_default_gfx = true;
} else {
ss_phase = SCIENCE_SS_PHASE;
default_phase_start_time = 0;
science_phase_start_time = dtime();
}
while (true) {
for (int i = 0; i < 4; i++) {
// ***
// *** Things that should be run frequently.
// *** 4 times per second.
// ***
// Are we supposed to exit the screensaver?
if (m_bQuitDataManagementProc) { // If main thread has requested we exit
BOINCTRACE(_T("CScreensaver::DataManagementProc - Thread told to stop\n"));
if (m_hGraphicsApplication || graphics_app_result_ptr) {
if (m_bDefault_gfx_running) {
BOINCTRACE(_T("CScreensaver::DataManagementProc - Terminating default screensaver\n"));
terminate_default_screensaver(m_hGraphicsApplication);
} else {
BOINCTRACE(_T("CScreensaver::DataManagementProc - Terminating screensaver\n"));
terminate_screensaver(m_hGraphicsApplication, graphics_app_result_ptr);
}
graphics_app_result_ptr = NULL;
previous_result_ptr = NULL;
m_hGraphicsApplication = 0;
}
BOINCTRACE(_T("CScreensaver::DataManagementProc - Stopping...\n"));
m_bDataManagementProcStopped = true; // Tell main thread that we exited
return 0; // Exit the thread
}
boinc_sleep(0.25);
}
// ***
// *** Things that should be run less frequently.
// *** 1 time per second.
// ***
// Blank screen saver?
if ((m_dwBlankScreen) && (time(0) > m_dwBlankTime) && (m_dwBlankTime > 0)) {
BOINCTRACE(_T("CScreensaver::DataManagementProc - Time to blank\n"));
SetError(FALSE, SCRAPPERR_SCREENSAVERBLANKED); // Blanked - hide moving BOINC logo
m_bQuitDataManagementProc = true;
continue; // Code above will exit the thread
}
BOINCTRACE(_T("CScreensaver::DataManagementProc - ErrorMode = '%d', ErrorCode = '%x'\n"), m_bErrorMode, m_hrError);
if (!m_bConnected) {
HandleRPCError();
}
if (m_bConnected) {
// Do we need to get the core client state?
if (m_bResetCoreState) {
// Try and get the current state of the CC
retval = rpc->get_state(state);
if (retval) {
// CC may not yet be running
HandleRPCError();
continue;
} else {
m_bResetCoreState = false;
}
}
// Update our task list
retval = rpc->get_screensaver_tasks(suspend_reason, results);
if (retval) {
// rpc call returned error
HandleRPCError();
m_bResetCoreState = true;
continue;
}
} else {
results.clear();
}
// Time to switch to default graphics phase?
if (m_bDefault_ss_exists && (ss_phase == SCIENCE_SS_PHASE) && (m_fGFXDefaultPeriod > 0)) {
if (science_phase_start_time && ((dtime() - science_phase_start_time) > m_fGFXSciencePeriod)) {
if (!m_bDefault_gfx_running) {
switch_to_default_gfx = true;
}
ss_phase = DEFAULT_SS_PHASE;
default_phase_start_time = dtime();
science_phase_start_time = 0;
if (m_bDefault_gfx_running && default_saver_start_time_in_science_phase) {
// Remember how long default graphics ran during science phase
default_saver_duration_in_science_phase += (dtime() - default_saver_start_time_in_science_phase);
}
default_saver_start_time_in_science_phase = 0;
}
}
// Time to switch to science graphics phase?
if ((ss_phase == DEFAULT_SS_PHASE) && m_bConnected && (m_fGFXSciencePeriod > 0)) {
if (default_phase_start_time &&
((dtime() - default_phase_start_time + default_saver_duration_in_science_phase)
> m_fGFXDefaultPeriod)) {
// BOINCTRACE(_T("CScreensaver::Ending Default phase: now=%f, default_phase_start_time=%f, default_saver_duration_in_science_phase=%f\n"),
// dtime(), default_phase_start_time, default_saver_duration_in_science_phase);
ss_phase = SCIENCE_SS_PHASE;
default_phase_start_time = 0;
default_saver_duration_in_science_phase = 0;
science_phase_start_time = dtime();
if (m_bDefault_gfx_running) {
default_saver_start_time_in_science_phase = science_phase_start_time;
}
switch_to_default_gfx = false;
}
}
// Core client suspended?
// We ignore SUSPEND_REASON_CPU_USAGE in SS coordinator, so it won't kill graphics apps for
// short-term CPU usage spikes (such as anti-virus.) Added 9 April 2010
if (suspend_reason && !(suspend_reason & (SUSPEND_REASON_CPU_THROTTLE | SUSPEND_REASON_CPU_USAGE))) {
if (!m_bDefault_gfx_running) {
SetError(TRUE, m_hrError); // No GFX App is running: show moving BOINC logo
if (m_bDefault_ss_exists) {
switch_to_default_gfx = true;
}
}
}
if (switch_to_default_gfx) {
if (m_bScience_gfx_running) {
if (m_hGraphicsApplication || previous_result_ptr) {
// use previous_result_ptr because graphics_app_result_ptr may no longer be valid
terminate_screensaver(m_hGraphicsApplication, previous_result_ptr);
if (m_hGraphicsApplication == 0) {
graphics_app_result_ptr = NULL;
m_bScience_gfx_running = false;
} else {
// HasProcessExited() test will clear m_hGraphicsApplication and graphics_app_result_ptr
}
previous_result_ptr = NULL;
}
} else {
if (!m_bDefault_gfx_running) {
switch_to_default_gfx = false;
retval = launch_default_screensaver(default_ss_dir_path, m_hGraphicsApplication);
if (retval) {
m_hGraphicsApplication = 0;
previous_result_ptr = NULL;
graphics_app_result_ptr = NULL;
m_bDefault_gfx_running = false;
SetError(TRUE, SCRAPPERR_CANTLAUNCHDEFAULTGFXAPP); // No GFX App is running: show moving BOINC logo
} else {
m_bDefault_gfx_running = true;
if (ss_phase == SCIENCE_SS_PHASE) {
default_saver_start_time_in_science_phase = dtime();
}
SetError(FALSE, SCRAPPERR_BOINCSCREENSAVERLOADING); // A GFX App is running: hide moving BOINC logo
}
}
}
}
if ((ss_phase == SCIENCE_SS_PHASE) && !switch_to_default_gfx) {
#if SIMULATE_NO_GRAPHICS /* FOR TESTING */
if (!m_bDefault_gfx_running) {
SetError(TRUE, m_hrError); // No GFX App is running: show moving BOINC logo
if (m_bDefault_ss_exists) {
switch_to_default_gfx = true;
}
}
#else /* NORMAL OPERATION */
if (m_bScience_gfx_running) {
// Is the current graphics app's associated task still running?
if ((m_hGraphicsApplication) || (graphics_app_result_ptr)) {
iResultCount = (int)results.results.size();
graphics_app_result_ptr = NULL;
// Find the current task in the new results vector (if it still exists)
for (iIndex = 0; iIndex < iResultCount; iIndex++) {
theResult = results.results.at(iIndex);
if (is_same_task(theResult, previous_result_ptr)) {
graphics_app_result_ptr = theResult;
previous_result = *theResult;
previous_result_ptr = &previous_result;
break;
}
}
// V6 graphics only: if worker application has stopped running, terminate_screensaver
if ((graphics_app_result_ptr == NULL) && (m_hGraphicsApplication != 0)) {
if (previous_result_ptr) {
BOINCTRACE(_T("CScreensaver::DataManagementProc - %s finished\n"),
previous_result.graphics_exec_path
);
}
terminate_screensaver(m_hGraphicsApplication, previous_result_ptr);
previous_result_ptr = NULL;
if (m_hGraphicsApplication == 0) {
graphics_app_result_ptr = NULL;
m_bScience_gfx_running = false;
// Save previous_result and previous_result_ptr for get_random_graphics_app() call
} else {
// HasProcessExited() test will clear m_hGraphicsApplication and graphics_app_result_ptr
}
}
if (last_change_time && (m_fGFXChangePeriod > 0) && ((dtime() - last_change_time) > m_fGFXChangePeriod) ) {
if (count_active_graphic_apps(results, previous_result_ptr) > 0) {
if (previous_result_ptr) {
BOINCTRACE(_T("CScreensaver::DataManagementProc - time to change: %s / %s\n"),
previous_result.name, previous_result.graphics_exec_path
);
}
terminate_screensaver(m_hGraphicsApplication, graphics_app_result_ptr);
if (m_hGraphicsApplication == 0) {
graphics_app_result_ptr = NULL;
m_bScience_gfx_running = false;
// Save previous_result and previous_result_ptr for get_random_graphics_app() call
} else {
// HasProcessExited() test will clear m_hGraphicsApplication and graphics_app_result_ptr
}
}
last_change_time = dtime();
}
}
} // End if (m_bScience_gfx_running)
// If no current graphics app, pick an active task at random
// and launch its graphics app
//
if ((m_bDefault_gfx_running || (m_hGraphicsApplication == 0)) && (graphics_app_result_ptr == NULL)) {
if (suspend_reason && !(suspend_reason & (SUSPEND_REASON_CPU_THROTTLE | SUSPEND_REASON_CPU_USAGE))) {
graphics_app_result_ptr = NULL;
} else {
graphics_app_result_ptr = get_random_graphics_app(results, previous_result_ptr);
previous_result_ptr = NULL;
}
if (graphics_app_result_ptr) {
if (m_bDefault_gfx_running) {
terminate_default_screensaver(m_hGraphicsApplication);
killing_default_gfx = true;
// Remember how long default graphics ran during science phase
if (default_saver_start_time_in_science_phase) {
default_saver_duration_in_science_phase += (dtime() - default_saver_start_time_in_science_phase);
//BOINCTRACE(_T("CScreensaver::During Science phase: now=%f, default_saver_start_time=%f, default_saver_duration=%f\n"),
// dtime(), default_saver_start_time_in_science_phase, default_saver_duration_in_science_phase);
}
default_saver_start_time_in_science_phase = 0;
// HasProcessExited() test will clear
// m_hGraphicsApplication and graphics_app_result_ptr
} else {
retval = launch_screensaver(graphics_app_result_ptr, m_hGraphicsApplication);
if (retval) {
m_hGraphicsApplication = 0;
previous_result_ptr = NULL;
graphics_app_result_ptr = NULL;
m_bScience_gfx_running = false;
} else {
// A GFX App is running: hide moving BOINC logo
//
SetError(FALSE, SCRAPPERR_BOINCSCREENSAVERLOADING);
last_change_time = dtime();
m_bScience_gfx_running = true;
// Make a local copy of current result, since original pointer
// may have been freed by the time we perform later tests
previous_result = *graphics_app_result_ptr;
previous_result_ptr = &previous_result;
if (previous_result_ptr) {
BOINCTRACE(_T("CScreensaver::DataManagementProc - launching %s\n"),
previous_result.graphics_exec_path
);
}
}
}
} else {
if (!m_bDefault_gfx_running) {
// We can't run a science graphics app, so run the default graphics if available
SetError(TRUE, m_hrError);
if (m_bDefault_ss_exists) {
switch_to_default_gfx = true;
}
}
} // End if no science graphics available
} // End if no current science graphics app is running
#endif // ! SIMULATE_NO_GRAPHICS
if (switch_to_default_gfx) {
switch_to_default_gfx = false;
if (!m_bDefault_gfx_running) {
retval = launch_default_screensaver(default_ss_dir_path, m_hGraphicsApplication);
if (retval) {
m_hGraphicsApplication = 0;
previous_result_ptr = NULL;
graphics_app_result_ptr = NULL;
m_bDefault_gfx_running = false;
SetError(TRUE, SCRAPPERR_CANTLAUNCHDEFAULTGFXAPP);
// No GFX App is running: show BOINC logo
} else {
m_bDefault_gfx_running = true;
default_saver_start_time_in_science_phase = dtime();
SetError(FALSE, SCRAPPERR_BOINCSCREENSAVERLOADING);
// Default GFX App is running: hide moving BOINC logo
}
}
}
} // End if ((ss_phase == SCIENCE_SS_PHASE) && !switch_to_default_gfx)
// Is the graphics app still running?
if (m_hGraphicsApplication) {
if (HasProcessExited(m_hGraphicsApplication, exit_status)) {
// Something has happened to the previously selected screensaver
// application. Start a different one.
BOINCTRACE(_T("CScreensaver::DataManagementProc - Graphics application isn't running, start a new one.\n"));
if (m_bDefault_gfx_running) {
// If we were able to connect to core client
// but gfx app can't, don't use it.
//
BOINCTRACE(_T("CScreensaver::DataManagementProc - Default graphics application exited with code %d.\n"), exit_status);
if (!killing_default_gfx) { // If this is an unexpected exit
if (exit_status == DEFAULT_GFX_CANT_CONNECT) {
SetError(TRUE, SCRAPPERR_DEFAULTGFXAPPCANTCONNECT);
// No GFX App is running: show moving BOINC logo
} else {
SetError(TRUE, SCRAPPERR_DEFAULTGFXAPPCRASHED);
// No GFX App is running: show moving BOINC logo
}
m_bDefault_ss_exists = false;
ss_phase = SCIENCE_SS_PHASE;
}
killing_default_gfx = false;
}
SetError(TRUE, SCRAPPERR_BOINCNOGRAPHICSAPPSEXECUTING);
// No GFX App is running: show moving BOINC logo
m_hGraphicsApplication = 0;
graphics_app_result_ptr = NULL;
m_bDefault_gfx_running = false;
m_bScience_gfx_running = false;
#ifdef __APPLE__
launchedGfxApp("", 0, -1);
#endif
continue;
}
}
} // end while(true)
}
#ifdef _WIN32
BOOL CScreensaver::HasProcessExited(HANDLE pid_handle, int &exitCode) {
unsigned long status = 1;
if (GetExitCodeProcess(pid_handle, &status)) {
if (status == STILL_ACTIVE) {
exitCode = 0;
return false;
}
}
exitCode = (int)status;
return true;
}
#else
bool CScreensaver::HasProcessExited(pid_t pid, int &exitCode) {
int status;
pid_t p;
p = waitpid(pid, &status, WNOHANG);
exitCode = WEXITSTATUS(status);
if (p == pid) return true; // process has exited
if (p == -1) return true; // PID doesn't exist
exitCode = 0;
return false;
}
#endif
void CScreensaver::GetDefaultDisplayPeriods(struct ss_periods &periods) {
char* default_data_dir_path = NULL;
char buf[1024];
FILE* f;
MIOFILE mf;
periods.GFXDefaultPeriod = GFX_DEFAULT_PERIOD;
periods.GFXSciencePeriod = GFX_SCIENCE_PERIOD;
periods.GFXChangePeriod = GFX_CHANGE_PERIOD;
periods.Show_default_ss_first = false;
#ifdef __APPLE__
default_data_dir_path = "/Library/Application Support/BOINC Data";
#else
default_data_dir_path = (char*)m_strBOINCDataDirectory.c_str();
#endif
strlcpy(buf, default_data_dir_path, sizeof(buf));
strlcat(buf, PATH_SEPARATOR, sizeof(buf));
strlcat(buf, THE_SS_CONFIG_FILE, sizeof(buf));
f = boinc_fopen(buf, "r");
if (!f) return;
mf.init_file(f);
XML_PARSER xp(&mf);
while (!xp.get_tag()) {
if (xp.parse_bool("default_ss_first", periods.Show_default_ss_first)) continue;
if (xp.parse_double("default_gfx_duration", periods.GFXDefaultPeriod)) continue;
if (xp.parse_double("science_gfx_duration", periods.GFXSciencePeriod)) continue;
if (xp.parse_double("science_gfx_change_interval", periods.GFXChangePeriod)) continue;
}
fclose(f);
BOINCTRACE(
_T("CScreensaver::GetDefaultDisplayPeriods: m_bShow_default_ss_first=%d, m_fGFXDefaultPeriod=%f, m_fGFXSciencePeriod=%f, m_fGFXChangePeriod=%f\n"),
(int)periods.Show_default_ss_first,
periods.GFXDefaultPeriod,
periods.GFXSciencePeriod,
periods.GFXChangePeriod
);
}
|
isandesh1986/mrchecker
|
example/src/main/java/com/capgemini/mrchecker/selenium/pages/projectY/NotificationMessagesPage.java
|
<filename>example/src/main/java/com/capgemini/mrchecker/selenium/pages/projectY/NotificationMessagesPage.java
package com.capgemini.mrchecker.selenium.pages.projectY;
import com.capgemini.mrchecker.selenium.core.BasePage;
import com.capgemini.mrchecker.selenium.pages.environment.GetEnvironmentParam;
import com.capgemini.mrchecker.selenium.pages.environment.PageSubURLsProjectYEnum;
import com.capgemini.mrchecker.test.core.logger.BFLogger;
public class NotificationMessagesPage extends BasePage {
@Override
public boolean isLoaded() {
getDriver().waitForPageLoaded();
return getDriver().getCurrentUrl()
.contains(PageSubURLsProjectYEnum.NOTIFICATION_MESSAGE.getValue());
}
@Override
public void load() {
BFLogger.logDebug("Load 'Notification Message' page.");
getDriver().get(GetEnvironmentParam.THE_INTERNET_MAIN_PAGE.getValue() + PageSubURLsProjectYEnum.NOTIFICATION_MESSAGE.getValue());
getDriver().waitForPageLoaded();
}
@Override
public String pageTitle() {
return getActualPageTitle();
}
}
|
CavalryXD/APN6_Repo
|
net-next/arch/openrisc/include/asm/pgtable.h
|
<filename>net-next/arch/openrisc/include/asm/pgtable.h
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* OpenRISC Linux
*
* Linux architectural port borrowing liberally from similar works of
* others. All original copyrights apply as per the original source
* declaration.
*
* OpenRISC implementation:
* Copyright (C) 2003 <NAME> <<EMAIL>>
* Copyright (C) 2010-2011 <NAME> <<EMAIL>>
* et al.
*/
/* or32 pgtable.h - macros and functions to manipulate page tables
*
* Based on:
* include/asm-cris/pgtable.h
*/
#ifndef __ASM_OPENRISC_PGTABLE_H
#define __ASM_OPENRISC_PGTABLE_H
#define __ARCH_USE_5LEVEL_HACK
#include <asm-generic/pgtable-nopmd.h>
#ifndef __ASSEMBLY__
#include <asm/mmu.h>
#include <asm/fixmap.h>
/*
* The Linux memory management assumes a three-level page table setup. On
* or32, we use that, but "fold" the mid level into the top-level page
* table. Since the MMU TLB is software loaded through an interrupt, it
* supports any page table structure, so we could have used a three-level
* setup, but for the amounts of memory we normally use, a two-level is
* probably more efficient.
*
* This file contains the functions and defines necessary to modify and use
* the or32 page table tree.
*/
extern void paging_init(void);
/* Certain architectures need to do special things when pte's
* within a page table are directly modified. Thus, the following
* hook is made available.
*/
#define set_pte(pteptr, pteval) ((*(pteptr)) = (pteval))
#define set_pte_at(mm, addr, ptep, pteval) set_pte(ptep, pteval)
/*
* (pmds are folded into pgds so this doesn't get actually called,
* but the define is needed for a generic inline function.)
*/
#define set_pmd(pmdptr, pmdval) (*(pmdptr) = pmdval)
#define PGDIR_SHIFT (PAGE_SHIFT + (PAGE_SHIFT-2))
#define PGDIR_SIZE (1UL << PGDIR_SHIFT)
#define PGDIR_MASK (~(PGDIR_SIZE-1))
/*
* entries per page directory level: we use a two-level, so
* we don't really have any PMD directory physically.
* pointers are 4 bytes so we can use the page size and
* divide it by 4 (shift by 2).
*/
#define PTRS_PER_PTE (1UL << (PAGE_SHIFT-2))
#define PTRS_PER_PGD (1UL << (32-PGDIR_SHIFT))
/* calculate how many PGD entries a user-level program can use
* the first mappable virtual address is 0
* (TASK_SIZE is the maximum virtual address space)
*/
#define USER_PTRS_PER_PGD (TASK_SIZE/PGDIR_SIZE)
#define FIRST_USER_ADDRESS 0UL
/*
* Kernels own virtual memory area.
*/
/*
* The size and location of the vmalloc area are chosen so that modules
* placed in this area aren't more than a 28-bit signed offset from any
* kernel functions that they may need. This greatly simplifies handling
* of the relocations for l.j and l.jal instructions as we don't need to
* introduce any trampolines for reaching "distant" code.
*
* 64 MB of vmalloc area is comparable to what's available on other arches.
*/
#define VMALLOC_START (PAGE_OFFSET-0x04000000UL)
#define VMALLOC_END (PAGE_OFFSET)
#define VMALLOC_VMADDR(x) ((unsigned long)(x))
/* Define some higher level generic page attributes.
*
* If you change _PAGE_CI definition be sure to change it in
* io.h for ioremap() too.
*/
/*
* An OR32 PTE looks like this:
*
* | 31 ... 10 | 9 | 8 ... 6 | 5 | 4 | 3 | 2 | 1 | 0 |
* Phys pg.num L PP Index D A WOM WBC CI CC
*
* L : link
* PPI: Page protection index
* D : Dirty
* A : Accessed
* WOM: Weakly ordered memory
* WBC: Write-back cache
* CI : Cache inhibit
* CC : Cache coherent
*
* The protection bits below should correspond to the layout of the actual
* PTE as per above
*/
#define _PAGE_CC 0x001 /* software: pte contains a translation */
#define _PAGE_CI 0x002 /* cache inhibit */
#define _PAGE_WBC 0x004 /* write back cache */
#define _PAGE_WOM 0x008 /* weakly ordered memory */
#define _PAGE_A 0x010 /* accessed */
#define _PAGE_D 0x020 /* dirty */
#define _PAGE_URE 0x040 /* user read enable */
#define _PAGE_UWE 0x080 /* user write enable */
#define _PAGE_SRE 0x100 /* superuser read enable */
#define _PAGE_SWE 0x200 /* superuser write enable */
#define _PAGE_EXEC 0x400 /* software: page is executable */
#define _PAGE_U_SHARED 0x800 /* software: page is shared in user space */
/* 0x001 is cache coherency bit, which should always be set to
* 1 - for SMP (when we support it)
* 0 - otherwise
*
* we just reuse this bit in software for _PAGE_PRESENT and
* force it to 0 when loading it into TLB.
*/
#define _PAGE_PRESENT _PAGE_CC
#define _PAGE_USER _PAGE_URE
#define _PAGE_WRITE (_PAGE_UWE | _PAGE_SWE)
#define _PAGE_DIRTY _PAGE_D
#define _PAGE_ACCESSED _PAGE_A
#define _PAGE_NO_CACHE _PAGE_CI
#define _PAGE_SHARED _PAGE_U_SHARED
#define _PAGE_READ (_PAGE_URE | _PAGE_SRE)
#define _PAGE_CHG_MASK (PAGE_MASK | _PAGE_ACCESSED | _PAGE_DIRTY)
#define _PAGE_BASE (_PAGE_PRESENT | _PAGE_ACCESSED)
#define _PAGE_ALL (_PAGE_PRESENT | _PAGE_ACCESSED)
#define _KERNPG_TABLE \
(_PAGE_BASE | _PAGE_SRE | _PAGE_SWE | _PAGE_ACCESSED | _PAGE_DIRTY)
#define PAGE_NONE __pgprot(_PAGE_ALL)
#define PAGE_READONLY __pgprot(_PAGE_ALL | _PAGE_URE | _PAGE_SRE)
#define PAGE_READONLY_X __pgprot(_PAGE_ALL | _PAGE_URE | _PAGE_SRE | _PAGE_EXEC)
#define PAGE_SHARED \
__pgprot(_PAGE_ALL | _PAGE_URE | _PAGE_SRE | _PAGE_UWE | _PAGE_SWE \
| _PAGE_SHARED)
#define PAGE_SHARED_X \
__pgprot(_PAGE_ALL | _PAGE_URE | _PAGE_SRE | _PAGE_UWE | _PAGE_SWE \
| _PAGE_SHARED | _PAGE_EXEC)
#define PAGE_COPY __pgprot(_PAGE_ALL | _PAGE_URE | _PAGE_SRE)
#define PAGE_COPY_X __pgprot(_PAGE_ALL | _PAGE_URE | _PAGE_SRE | _PAGE_EXEC)
#define PAGE_KERNEL \
__pgprot(_PAGE_ALL | _PAGE_SRE | _PAGE_SWE \
| _PAGE_SHARED | _PAGE_DIRTY | _PAGE_EXEC)
#define PAGE_KERNEL_RO \
__pgprot(_PAGE_ALL | _PAGE_SRE \
| _PAGE_SHARED | _PAGE_DIRTY | _PAGE_EXEC)
#define PAGE_KERNEL_NOCACHE \
__pgprot(_PAGE_ALL | _PAGE_SRE | _PAGE_SWE \
| _PAGE_SHARED | _PAGE_DIRTY | _PAGE_EXEC | _PAGE_CI)
#define __P000 PAGE_NONE
#define __P001 PAGE_READONLY_X
#define __P010 PAGE_COPY
#define __P011 PAGE_COPY_X
#define __P100 PAGE_READONLY
#define __P101 PAGE_READONLY_X
#define __P110 PAGE_COPY
#define __P111 PAGE_COPY_X
#define __S000 PAGE_NONE
#define __S001 PAGE_READONLY_X
#define __S010 PAGE_SHARED
#define __S011 PAGE_SHARED_X
#define __S100 PAGE_READONLY
#define __S101 PAGE_READONLY_X
#define __S110 PAGE_SHARED
#define __S111 PAGE_SHARED_X
/* zero page used for uninitialized stuff */
extern unsigned long empty_zero_page[2048];
#define ZERO_PAGE(vaddr) (virt_to_page(empty_zero_page))
/* number of bits that fit into a memory pointer */
#define BITS_PER_PTR (8*sizeof(unsigned long))
/* to align the pointer to a pointer address */
#define PTR_MASK (~(sizeof(void *)-1))
/* sizeof(void*)==1<<SIZEOF_PTR_LOG2 */
/* 64-bit machines, beware! SRB. */
#define SIZEOF_PTR_LOG2 2
/* to find an entry in a page-table */
#define PAGE_PTR(address) \
((unsigned long)(address)>>(PAGE_SHIFT-SIZEOF_PTR_LOG2)&PTR_MASK&~PAGE_MASK)
/* to set the page-dir */
#define SET_PAGE_DIR(tsk, pgdir)
#define pte_none(x) (!pte_val(x))
#define pte_present(x) (pte_val(x) & _PAGE_PRESENT)
#define pte_clear(mm, addr, xp) do { pte_val(*(xp)) = 0; } while (0)
#define pmd_none(x) (!pmd_val(x))
#define pmd_bad(x) ((pmd_val(x) & (~PAGE_MASK)) != _KERNPG_TABLE)
#define pmd_present(x) (pmd_val(x) & _PAGE_PRESENT)
#define pmd_clear(xp) do { pmd_val(*(xp)) = 0; } while (0)
/*
* The following only work if pte_present() is true.
* Undefined behaviour if not..
*/
static inline int pte_read(pte_t pte) { return pte_val(pte) & _PAGE_READ; }
static inline int pte_write(pte_t pte) { return pte_val(pte) & _PAGE_WRITE; }
static inline int pte_exec(pte_t pte) { return pte_val(pte) & _PAGE_EXEC; }
static inline int pte_dirty(pte_t pte) { return pte_val(pte) & _PAGE_DIRTY; }
static inline int pte_young(pte_t pte) { return pte_val(pte) & _PAGE_ACCESSED; }
static inline pte_t pte_wrprotect(pte_t pte)
{
pte_val(pte) &= ~(_PAGE_WRITE);
return pte;
}
static inline pte_t pte_rdprotect(pte_t pte)
{
pte_val(pte) &= ~(_PAGE_READ);
return pte;
}
static inline pte_t pte_exprotect(pte_t pte)
{
pte_val(pte) &= ~(_PAGE_EXEC);
return pte;
}
static inline pte_t pte_mkclean(pte_t pte)
{
pte_val(pte) &= ~(_PAGE_DIRTY);
return pte;
}
static inline pte_t pte_mkold(pte_t pte)
{
pte_val(pte) &= ~(_PAGE_ACCESSED);
return pte;
}
static inline pte_t pte_mkwrite(pte_t pte)
{
pte_val(pte) |= _PAGE_WRITE;
return pte;
}
static inline pte_t pte_mkread(pte_t pte)
{
pte_val(pte) |= _PAGE_READ;
return pte;
}
static inline pte_t pte_mkexec(pte_t pte)
{
pte_val(pte) |= _PAGE_EXEC;
return pte;
}
static inline pte_t pte_mkdirty(pte_t pte)
{
pte_val(pte) |= _PAGE_DIRTY;
return pte;
}
static inline pte_t pte_mkyoung(pte_t pte)
{
pte_val(pte) |= _PAGE_ACCESSED;
return pte;
}
/*
* Conversion functions: convert a page and protection to a page entry,
* and a page entry and page directory to the page they refer to.
*/
/* What actually goes as arguments to the various functions is less than
* obvious, but a rule of thumb is that struct page's goes as struct page *,
* really physical DRAM addresses are unsigned long's, and DRAM "virtual"
* addresses (the 0xc0xxxxxx's) goes as void *'s.
*/
static inline pte_t __mk_pte(void *page, pgprot_t pgprot)
{
pte_t pte;
/* the PTE needs a physical address */
pte_val(pte) = __pa(page) | pgprot_val(pgprot);
return pte;
}
#define mk_pte(page, pgprot) __mk_pte(page_address(page), (pgprot))
#define mk_pte_phys(physpage, pgprot) \
({ \
pte_t __pte; \
\
pte_val(__pte) = (physpage) + pgprot_val(pgprot); \
__pte; \
})
static inline pte_t pte_modify(pte_t pte, pgprot_t newprot)
{
pte_val(pte) = (pte_val(pte) & _PAGE_CHG_MASK) | pgprot_val(newprot);
return pte;
}
/*
* pte_val refers to a page in the 0x0xxxxxxx physical DRAM interval
* __pte_page(pte_val) refers to the "virtual" DRAM interval
* pte_pagenr refers to the page-number counted starting from the virtual
* DRAM start
*/
static inline unsigned long __pte_page(pte_t pte)
{
/* the PTE contains a physical address */
return (unsigned long)__va(pte_val(pte) & PAGE_MASK);
}
#define pte_pagenr(pte) ((__pte_page(pte) - PAGE_OFFSET) >> PAGE_SHIFT)
/* permanent address of a page */
#define __page_address(page) (PAGE_OFFSET + (((page) - mem_map) << PAGE_SHIFT))
#define pte_page(pte) (mem_map+pte_pagenr(pte))
/*
* only the pte's themselves need to point to physical DRAM (see above)
* the pagetable links are purely handled within the kernel SW and thus
* don't need the __pa and __va transformations.
*/
static inline void pmd_set(pmd_t *pmdp, pte_t *ptep)
{
pmd_val(*pmdp) = _KERNPG_TABLE | (unsigned long) ptep;
}
#define pmd_page(pmd) (pfn_to_page(pmd_val(pmd) >> PAGE_SHIFT))
#define pmd_page_kernel(pmd) ((unsigned long) __va(pmd_val(pmd) & PAGE_MASK))
/* to find an entry in a page-table-directory. */
#define pgd_index(address) ((address >> PGDIR_SHIFT) & (PTRS_PER_PGD-1))
#define __pgd_offset(address) pgd_index(address)
#define pgd_offset(mm, address) ((mm)->pgd+pgd_index(address))
/* to find an entry in a kernel page-table-directory */
#define pgd_offset_k(address) pgd_offset(&init_mm, address)
#define __pmd_offset(address) \
(((address) >> PMD_SHIFT) & (PTRS_PER_PMD-1))
/*
* the pte page can be thought of an array like this: pte_t[PTRS_PER_PTE]
*
* this macro returns the index of the entry in the pte page which would
* control the given virtual address
*/
#define __pte_offset(address) \
(((address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1))
#define pte_offset_kernel(dir, address) \
((pte_t *) pmd_page_kernel(*(dir)) + __pte_offset(address))
#define pte_offset_map(dir, address) \
((pte_t *)page_address(pmd_page(*(dir))) + __pte_offset(address))
#define pte_offset_map_nested(dir, address) \
pte_offset_map(dir, address)
#define pte_unmap(pte) do { } while (0)
#define pte_unmap_nested(pte) do { } while (0)
#define pte_pfn(x) ((unsigned long)(((x).pte)) >> PAGE_SHIFT)
#define pfn_pte(pfn, prot) __pte((((pfn) << PAGE_SHIFT)) | pgprot_val(prot))
#define pte_ERROR(e) \
printk(KERN_ERR "%s:%d: bad pte %p(%08lx).\n", \
__FILE__, __LINE__, &(e), pte_val(e))
#define pgd_ERROR(e) \
printk(KERN_ERR "%s:%d: bad pgd %p(%08lx).\n", \
__FILE__, __LINE__, &(e), pgd_val(e))
extern pgd_t swapper_pg_dir[PTRS_PER_PGD]; /* defined in head.S */
struct vm_area_struct;
static inline void update_tlb(struct vm_area_struct *vma,
unsigned long address, pte_t *pte)
{
}
extern void update_cache(struct vm_area_struct *vma,
unsigned long address, pte_t *pte);
static inline void update_mmu_cache(struct vm_area_struct *vma,
unsigned long address, pte_t *pte)
{
update_tlb(vma, address, pte);
update_cache(vma, address, pte);
}
/* __PHX__ FIXME, SWAP, this probably doesn't work */
/* Encode and de-code a swap entry (must be !pte_none(e) && !pte_present(e)) */
/* Since the PAGE_PRESENT bit is bit 4, we can use the bits above */
#define __swp_type(x) (((x).val >> 5) & 0x7f)
#define __swp_offset(x) ((x).val >> 12)
#define __swp_entry(type, offset) \
((swp_entry_t) { ((type) << 5) | ((offset) << 12) })
#define __pte_to_swp_entry(pte) ((swp_entry_t) { pte_val(pte) })
#define __swp_entry_to_pte(x) ((pte_t) { (x).val })
#define kern_addr_valid(addr) (1)
#include <asm-generic/pgtable.h>
typedef pte_t *pte_addr_t;
#endif /* __ASSEMBLY__ */
#endif /* __ASM_OPENRISC_PGTABLE_H */
|
teodutu/POO
|
Laburi/Lab9/src/exceptions/MainErrors.java
|
package exceptions;
public class MainErrors {
private static void outOfMemory() {
int[] v = new int[2000000000];
}
private static void stackOverflow() {
stackOverflow();
}
private static String showcaseFinally() {
try {
return "Still returned ok";
} catch (Exception e) {
System.out.println(e.getCause().toString());
System.out.println(e.getMessage());
e.printStackTrace();
return "Caught exception";
} finally {
System.out.println("Finally");
}
}
public static void main(String[] args) {
// outOfMemory();
// stackOverflow();
Calculator calc = new Calculator();
// System.out.println(calc.add(2000000000, 1000000000));
System.out.println(calc.divide(1, 0));
// System.out.println(calc.add(-2000000000, -1000000000));
System.out.println(showcaseFinally());
}
}
|
stigger/AppleScript-IDEA
|
src/main/java/com/intellij/plugin/applescript/lang/sdef/parser/SDEF_Parser.java
|
<gh_stars>10-100
package com.intellij.plugin.applescript.lang.sdef.parser;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.plugin.applescript.lang.ide.sdef.AppleScriptSystemDictionaryRegistryService;
import com.intellij.plugin.applescript.lang.ide.sdef.DictionaryInfo;
import com.intellij.plugin.applescript.lang.sdef.*;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.*;
import com.intellij.xml.util.IncludedXmlTag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class SDEF_Parser {
private static final Logger LOG = Logger.getInstance("#" + SDEF_Parser.class.getName());
public static void parse(@NotNull XmlFile file, @NotNull ApplicationDictionary parsedDictionary) {
System.out.println("Start parsing xml file --- " + file.toString() + " ---");
LOG.debug("Start parsing xml file --- " + file.toString() + " ---");
if (parsedDictionary.getRootTag() == null) {
parsedDictionary.setRootTag(file.getRootTag());
}
final XmlDocument document = file.getDocument();
if (document != null) {
final XmlTag rootTag = document.getRootTag();
if (rootTag != null) {
XmlAttribute attr = rootTag.getAttribute("title");
if ("dictionary".equals(rootTag.getName()) && attr != null) {
String dicTitle = attr.getValue();
if (!StringUtil.isEmpty(dicTitle)) {
parsedDictionary.setName(dicTitle);
}
}
parseRootTag(parsedDictionary, rootTag);
}
}
System.out.println("parsing completed for file.");
LOG.debug("parsing completed for file.");
}
public static void parseRootTag(@NotNull ApplicationDictionary parsedDictionary, @NotNull XmlTag rootTag) {
String xInclNs = rootTag.getAttributeValue("xmlns:xi");
XmlTag[] includes = getIncludes(rootTag, xInclNs);
processIncludes(parsedDictionary, includes);
XmlTag[] rootSubTags = rootTag.getSubTags();
for (XmlTag suiteTag : rootSubTags) {
includes = getIncludes(suiteTag, xInclNs);
processIncludes(parsedDictionary, includes);
}
for (XmlTag suiteTag : rootSubTags) {
if ("dictionary".equals(suiteTag.getName()) && suiteTag instanceof IncludedXmlTag) {
XmlFile xmlFile = getDictionaryFileFromInclude(parsedDictionary.getProject(), (IncludedXmlTag) suiteTag);
if (xmlFile != null) {
parsedDictionary.processInclude(xmlFile);
}
} else if (!"suite".equals(suiteTag.getName())) continue;
rootTag.getSubTags()[0].getName();
Suite suite = parseSuiteTag(suiteTag, parsedDictionary);
XmlTag[] suiteCommands = suiteTag.findSubTags("command");
for (XmlTag commandTag : suiteCommands) {
AppleScriptCommand command = parseCommandTag(commandTag, suite);
parsedDictionary.addCommand(command);
suite.addCommand(command);
}
XmlTag[] suiteClasses = suiteTag.findSubTags("class");
for (XmlTag classTag : suiteClasses) {
AppleScriptClass appleScriptClass = parseClassTag(classTag, suite);
parsedDictionary.addClass(appleScriptClass);
suite.addClass(appleScriptClass);
}
XmlTag[] suiteValueTypes = suiteTag.findSubTags("value-type");
for (XmlTag valueTypeTag : suiteValueTypes) {
AppleScriptClass simpleClass = parseClassTag(valueTypeTag, suite);
parsedDictionary.addClass(simpleClass);
suite.addClass(simpleClass);
}
XmlTag[] suiteClassExtensions = suiteTag.findSubTags("class-extension");
for (XmlTag classExtensionTag : suiteClassExtensions) {
AppleScriptClass appleScriptClass = parseClassExtensionTag(classExtensionTag, parsedDictionary, suite);
if (appleScriptClass != null) {
parsedDictionary.addClass(appleScriptClass);
suite.addClass(appleScriptClass);
}
}
XmlTag[] recordTypeTags = suiteTag.findSubTags("record-type");
for (XmlTag recordTag : recordTypeTags) {
DictionaryRecord record = parseRecordTag(recordTag, suite);
parsedDictionary.addRecord(record);
suite.addRecord(record);
}
XmlTag[] enumerationTags = suiteTag.findSubTags("enumeration");
for (XmlTag enumerationTag : enumerationTags) {
DictionaryEnumeration enumeration = parseEnumerationTag(enumerationTag, suite);
parsedDictionary.addEnumeration(enumeration);
suite.addEnumeration(enumeration);
}
parsedDictionary.addSuite(suite);//todo remove adding the components directly to dictionary (see above)
}
}
@Nullable
private static XmlFile getDictionaryFileFromInclude(@NotNull Project project, IncludedXmlTag xmlIncludeTag) {
XmlFile xmlFile = null;
XmlElement origXmlElement = xmlIncludeTag.getOriginal();
PsiFile origPsiFile = origXmlElement != null ? origXmlElement.getContainingFile() : null;
if (origPsiFile instanceof XmlFile) {
xmlFile = (XmlFile) origPsiFile;
AppleScriptSystemDictionaryRegistryService dictionaryService = ServiceManager.getService(AppleScriptSystemDictionaryRegistryService
.class);
VirtualFile vFile = origPsiFile.getVirtualFile();
DictionaryInfo dInfo = dictionaryService.getDictionaryInfoByApplicationPath(vFile.getPath());
if (dInfo != null) {
File ioFile = dInfo.getDictionaryFile();
if (ioFile.exists()) {
vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile);
if (vFile == null || !vFile.isValid()) return null;
PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
xmlFile = (XmlFile) psiFile;
}
}
}
return xmlFile;
}
private static XmlTag[] getIncludes(@NotNull XmlTag rootTag, String xInclNs) {
if (xInclNs == null) return null;
return rootTag.findSubTags("include", xInclNs);
}
private static void processIncludes(@NotNull ApplicationDictionary parsedDictionary, @Nullable XmlTag[] includes) {
if (includes == null) return;
for (XmlTag include : includes) {
String hrefIncl = include.getAttributeValue("href");
if (!StringUtil.isEmpty(hrefIncl)) {
hrefIncl = hrefIncl.replace("file://localhost", "");
File includedFile = new File(hrefIncl);
// ((IncludedXmlTag) suiteTag).getOriginal().getContainingFile();
//as there is assertion error (java.lang.AssertionError: File accessed outside allowed roots),
// we are trying to find if the dictionary file for this included dictionary was already generated
AppleScriptSystemDictionaryRegistryService dictionarySystemRegistry = ServiceManager
.getService(AppleScriptSystemDictionaryRegistryService.class);
VirtualFile vFile;
File ioFile = null;
DictionaryInfo dInfo = dictionarySystemRegistry.getDictionaryInfoByApplicationPath(includedFile.getPath());
if (dInfo != null) {
ioFile = dInfo.getDictionaryFile();
} else if (includedFile.isFile()) {
String fName = includedFile.getName();
int index = fName.lastIndexOf('.');
fName = index < 0 ? fName : fName.substring(0, index);
ioFile = dictionarySystemRegistry.getDictionaryFile(fName);
}
if (ioFile == null || !ioFile.exists()) ioFile = includedFile;
if (ioFile.exists()) {
vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile);
if (vFile == null || !vFile.isValid()) continue;
PsiFile psiFile = PsiManager.getInstance(parsedDictionary.getProject()).findFile(vFile);
XmlFile xmlFile = (XmlFile) psiFile;
if (xmlFile != null) {
parsedDictionary.processInclude(xmlFile);
}
}
}
}
}
private static Suite parseSuiteTag(XmlTag suiteTag, ApplicationDictionary dictionary) {
//todo add all subtags to the suite here
Suite result = null;
String name = suiteTag.getAttributeValue("name");
String code = suiteTag.getAttributeValue("code");
String description = suiteTag.getAttributeValue("description");
String hiddenVal = suiteTag.getAttributeValue("hidden");
if (name != null && code != null) {
result = new SuiteImpl(dictionary, code, name, "yes".equals(hiddenVal), description, suiteTag);
}
return result;
}
private static AppleScriptClass parseClassExtensionTag(XmlTag classExtensionTag, ApplicationDictionary dictionary,
Suite suite) {
String parentClassName = classExtensionTag.getAttributeValue("extends");
AppleScriptClass parentClass = dictionary.findClass(parentClassName);
String parentClassCode = parentClass != null ? parentClass.getCode() : null;
String pluralName = classExtensionTag.getAttributeValue("plural");
//todo parent class code could be NULL!! need to parse included dictionary in this case looks like...
if (parentClassCode == null && parentClassName != null) {
int l = parentClassName.length();
parentClassCode = parentClassName.substring(l >= 4 ? 4 : l - 1);
}
if (parentClassName == null || parentClassCode == null) return null;
List<String> elementNames = initClassElements(classExtensionTag);
List<String> respondingCommands = initClassRespondingMessages(classExtensionTag);
final AppleScriptClass classExtension = new DictionaryClass(suite, parentClassName, parentClassCode,
classExtensionTag, null, elementNames, respondingCommands, pluralName);
String description = classExtensionTag.getAttributeValue("description");
classExtension.setDescription(description);
XmlTag[] propertyTags = classExtensionTag.findSubTags("property");
List<AppleScriptPropertyDefinition> properties = getPropertiesFromTags(classExtension, propertyTags);
classExtension.setProperties(properties);
return classExtension;
}
@NotNull
private static List<AppleScriptPropertyDefinition> getPropertiesFromTags(@NotNull DictionaryComponent classOrRecord,
@NotNull XmlTag[] propertyTags) {
if (!(classOrRecord instanceof AppleScriptClass) && !(classOrRecord instanceof DictionaryRecord))
return new ArrayList<>(0);
List<AppleScriptPropertyDefinition> properties = new ArrayList<>(propertyTags.length);
for (XmlTag propTag : propertyTags) {
AppleScriptPropertyDefinition property;
String pName = propTag.getAttributeValue("name");
String pCode = propTag.getAttributeValue("code");
String pDescription = propTag.getAttributeValue("description");
String pType = propTag.getAttributeValue("type");
if (StringUtil.isEmpty(pType)) {
XmlTag tType = propTag.findFirstSubTag("type");
pType = tType != null ? tType.getAttributeValue("type") : null;
}
String pAccessType = propTag.getAttributeValue("access");
AccessType accessType = "r".equals(pAccessType) ? AccessType.R : AccessType.RW;
if (pName != null && pCode != null && pType != null) {
property = new DictionaryPropertyImpl(classOrRecord, pName, pCode, pType, pDescription, propTag, accessType);
properties.add(property);
}
}
return properties;
}
private static DictionaryEnumeration parseEnumerationTag(XmlTag enumerationTag, Suite suite) {
String name = enumerationTag.getAttributeValue("name");
String code = enumerationTag.getAttributeValue("code");
if (name == null || code == null) return null;
String description = enumerationTag.getAttributeValue("description");
final List<DictionaryEnumerator> enumConstants = new ArrayList<>();
XmlTag[] enumTags = enumerationTag.findSubTags("enumerator");
final DictionaryEnumeration enumeration = new DictionaryEnumerationImpl(suite, name, code, description,
enumerationTag);
for (XmlTag enumTag : enumTags) {
DictionaryEnumerator enumConst;
String eName = enumTag.getAttributeValue("name");
String eCode = enumTag.getAttributeValue("code");
String eDescription = enumTag.getAttributeValue("description");
if (eName != null && eCode != null) {
enumConst = new DictionaryEnumeratorImpl(enumeration, eName, eCode, eDescription, enumTag);
enumConstants.add(enumConst);
}
}
enumeration.setEnumerators(enumConstants);
return enumeration;
}
private static DictionaryRecord parseRecordTag(XmlTag recordTag, Suite suite) {
String name = recordTag.getAttributeValue("name");
String code = recordTag.getAttributeValue("code");
if (name == null || code == null) return null;
String description = recordTag.getAttributeValue("description");
XmlTag[] propertyTags = recordTag.findSubTags("property");
final DictionaryRecord record = new DictionaryRecordDefinition(suite, name, code, description, recordTag);
final List<AppleScriptPropertyDefinition> properties = getPropertiesFromTags(record, propertyTags);
record.setProperties(properties);//could be zero??
return record;
}
private static AppleScriptClass parseClassTag(XmlTag classTag, Suite suite) {
String name = classTag.getAttributeValue("name");
String code = classTag.getAttributeValue("code");
String pluralName = classTag.getAttributeValue("plural");
if (name == null || code == null) return null;
String parentClassName = classTag.getAttributeValue("inherits");
List<String> elementNames = initClassElements(classTag);
List<String> respondingCommands = initClassRespondingMessages(classTag);
final AppleScriptClass aClass = new DictionaryClass(suite, name, code, classTag, parentClassName, elementNames,
respondingCommands, pluralName);
String description = classTag.getAttributeValue("description");
aClass.setDescription(description);
XmlTag[] propertyTags = classTag.findSubTags("property");
final List<AppleScriptPropertyDefinition> properties = new ArrayList<>();
for (XmlTag propTag : propertyTags) {
String pName = propTag.getAttributeValue("name");
String pCode = propTag.getAttributeValue("code");
String pDescription = propTag.getAttributeValue("description");
String pType = propTag.getAttributeValue("type");
if (StringUtil.isEmpty(pType)) {
XmlTag tType = propTag.findFirstSubTag("type");
pType = tType != null ? tType.getAttributeValue("type") : null;
}
String pAccessType = propTag.getAttributeValue("access");
AccessType accessType = "r".equals(pAccessType) ? AccessType.R : AccessType.RW;
if (pName != null && pCode != null && pType != null) {
final AppleScriptPropertyDefinition property = new DictionaryPropertyImpl(aClass, pName, pCode, pType,
pDescription, propTag, accessType);
properties.add(property);
}
}
aClass.setProperties(properties);
return aClass;
}
private static List<String> initClassRespondingMessages(XmlTag classTag) {
XmlTag[] elementNameTags = classTag.findSubTags("responds-to");
List<String> commandNames = new ArrayList<>();
for (XmlTag elemTag : elementNameTags) {
String val = elemTag.getAttributeValue("command");
if (val != null) {
commandNames.add(val);
}
}
return commandNames;
}
private static List<String> initClassElements(XmlTag classTag) {
XmlTag[] elementNameTags = classTag.findSubTags("element");
List<String> elementNames = new ArrayList<>();
for (XmlTag elemTag : elementNameTags) {
String val = elemTag.getAttributeValue("type");
if (val != null) {
elementNames.add(val);
}
}
return elementNames;
}
private static AppleScriptCommand parseCommandTag(XmlTag commandTag, Suite suite) {
String name = commandTag.getAttributeValue("name");
String code = commandTag.getAttributeValue("code");
String description = commandTag.getAttributeValue("description");
String documentation = commandTag.getSubTagText("documentation");
if (name == null || code == null) return null;
final AppleScriptCommand command = new AppleScriptCommandImpl(suite, name, code, commandTag);
command.setDescription(description);
command.setDictionaryDoc(documentation);
XmlTag resultTag = commandTag.findFirstSubTag("result");
if (resultTag != null) {
String rType = resultTag.getAttributeValue("type");
String rDesc = resultTag.getAttributeValue("description");
if (rType != null) {
CommandResult commandResult = new CommandResult(rType, rDesc);
command.setResult(commandResult);
}
}
XmlTag directParam = commandTag.findFirstSubTag("direct-parameter");
CommandDirectParameter directParameter = null;
if (directParam != null) {
XmlAttribute type = directParam.getAttribute("type");
XmlAttribute requiresAccess = directParam.getAttribute("requires-access");
XmlAttribute paramDescription = directParam.getAttribute("description");
XmlAttribute isOptionalAttr = directParam.getAttribute("optional");
String typeVal = null;
if (type != null) {
typeVal = type.getValue();
} else {//could be sub-tag
XmlTag typeTag = directParam.findFirstSubTag("type");
if (typeTag != null) {
XmlAttribute typeAttr = typeTag.getAttribute("type");
if (typeAttr == null) {
XmlTag typeSubTag = typeTag.findFirstSubTag("type");
typeAttr = typeSubTag != null ? typeSubTag.getAttribute("type") : null;
}
typeVal = typeAttr != null ? typeAttr.getValue() : null;
}
}
boolean isOptional = isOptionalAttr != null && "yes".equals(isOptionalAttr.getValue());
if (typeVal != null) {
if (paramDescription != null) {
directParameter = new CommandDirectParameter(command, typeVal, paramDescription.getValue(), isOptional);
} else {
directParameter = new CommandDirectParameter(command, typeVal, null, isOptional);
}
}
}
XmlTag[] parameters = commandTag.findSubTags("parameter");
List<CommandParameter> commandParameters = new ArrayList<>();
CommandParameter commandParameter = null;
for (XmlTag paramTag : parameters) {
String pName = paramTag.getAttributeValue("name");
String pCode = paramTag.getAttributeValue("code");
String pDescription = paramTag.getAttributeValue("description");
String pType = paramTag.getAttributeValue("type");
if (pType == null) {
XmlTag typeSubTag = paramTag.findFirstSubTag("type");
if (typeSubTag != null) {
pType = typeSubTag.getAttributeValue("type");
}
}
String pOptional = paramTag.getAttributeValue("optional");
if (pName != null && pCode != null && pType != null) {
boolean bOptional = false;
if ("yes".equals(pOptional)) {
bOptional = true;
}
commandParameter = new CommandParameterImpl(command, pName, pCode, bOptional, pType, pDescription, paramTag);
}
if (commandParameter != null) {
commandParameters.add(commandParameter);
}
}
command.setDirectParameter(directParameter);
command.setParameters(commandParameters);
// result = new AppleScriptCommandImpl(suite, name, code, commandParameters, directParameter, null, description);
return command;
}
}
|
kiarashmhn/DocumentTranslation-FrontEnd
|
src/components/order/form/AfghanDrivingLicence.js
|
<reponame>kiarashmhn/DocumentTranslation-FrontEnd
export const afghanDrivingLicenceForm = {
title: "afghanDrivingLicence",
steps: 7,
content: [
{
title: "uploadAfghanDrivingLicence",
content: [
{
key: "files",
type: "fileHandler",
fileType: "documents"
}
]
},
{
title: "personalInfo",
content: [
{
key: "aName1",
type: "text"
},
{
key: "aLastName",
type: "text",
notRequired: true
},
{
key: "valad",
type: "text"
},
{
key: "tazkaraInformation1",
type: "tazkaraInfo"
},
{
key: "aBirthDate",
type: "complexDate",
required: true
}
]
},
{
title: "birthLocation",
content: [
{
key: "provinceDistrict",
provinceKey: "province",
districtKey: "district",
villageKey: "village",
type: "provinceDistrict",
name: "aBirthLocation",
required: true
}
]
},
{
title: "homeAddress",
content: [
{
key: "provinceDistrict1",
provinceKey: "province",
districtKey: "district",
villageKey: "village",
type: "provinceDistrict",
name: "homeAddress",
required: true
}
]
},
{
title: "cardInfo",
content: [
{
key: "bloodType",
type: "select",
options: [
{ value: "Oplus", key: "Oplus" },
{ value: "Ominus", key: "Ominus" },
{ value: "Aplus", key: "Aplus" },
{ value: "Aminus", key: "Aminus" },
{ value: "Bplus", key: "Bplus" },
{ value: "Bminus", key: "Bminus" },
{ value: "ABplus", key: "ABplus" },
{ value: "ABminus", key: "ABminus" }
],
required: true
},
{
key: "serialNumber2",
type: "text"
},
{
key: "directorProvince",
type: "select",
options: [
{ value: "kaboul", key: "kaboul" },
{ value: "herat", key: "herat" },
{ value: "nangarhar", key: "nangarhar" },
{ value: "balkh", key: "balkh" },
{ value: "kandahar", key: "kandahar" },
{ value: "ghor", key: "ghor" },
{ value: "laghman", key: "laghman" },
{ value: "kunduz", key: "kunduz" },
{ value: "paktiya", key: "paktiya" },
{ value: "zabol", key: "zabol" },
{ value: "baghlan", key: "baghlan" },
{ value: "badakhchan", key: "badakhchan" },
{ value: "bamiyan", key: "bamiyan" },
{ value: "badghis", key: "badghis" },
{ value: "maydanWardak", key: "maydanWardak" },
{ value: "logar", key: "logar" },
{ value: "samangan", key: "samangan" },
{ value: "takhar", key: "takhar" },
{ value: "nouristan", key: "nouristan" },
{ value: "faryab", key: "faryab" },
{ value: "sarpol", key: "sarpol" },
{ value: "paktika", key: "paktika" },
{ value: "farah", key: "farah" },
{ value: "helmand", key: "helmand" },
{ value: "nimroz", key: "nimroz" },
{ value: "ghazni", key: "ghazni" },
{ value: "orozgan", key: "orozgan" },
{ value: "kapissa", key: "kapissa" },
{ value: "parwan", key: "parwan" },
{ value: "pandjchir", key: "pandjchir" },
{ value: "djozdjan", key: "djozdjan" },
{ value: "khost", key: "khost" },
{ value: "kounar", key: "kounar" },
{ value: "deykandi", key: "deykandi" }
],
required: true
},
{
key: "dateofIssue1",
type: "date"
},
{
key: "validationDate1",
type: "date"
},
{
key: "aGrade",
type: "check",
grid: 5
},
{
key: "bGrade",
type: "check",
grid: 5
},
{
key: "cGrade",
type: "check",
grid: 5
},
{
key: "dGrade",
type: "check",
grid: 5
},
{
key: "eGrade",
type: "check",
grid: 12
},
{
key: "licenseNumber",
type: "multi",
notRequired: true,
fields: [
{
key: "licensePage"
},
{
key: "licenseRegistration"
}
]
},
{
key: "ticket",
type: "select",
options: [
{ value: "yes", key: "yes" },
{ value: "no", key: "no" }
],
required: true
}
]
},
{
title: "description",
content: [
{
key: "additionalFiles",
type: "additionalFileHandler",
fileType: "additional",
tooltipKey: "description"
},
{
key: "description",
type: "text",
grid: 12,
notRequired: true
}
]
},
{
title: "addr",
content: [
{
key: "address",
type: "address"
}
]
}
]
};
|
onezens/QQTweak
|
qqtw/qqheaders7.2/QQAIOShortVideoMsgModel.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "QQAIOMsgModel.h"
@interface QQAIOShortVideoMsgModel : QQAIOMsgModel
{
_Bool _isReported;
_Bool _animatedInsertCellFlag;
}
@property(nonatomic) _Bool animatedInsertCellFlag; // @synthesize animatedInsertCellFlag=_animatedInsertCellFlag;
- (id)cellClassName;
- (double)cellHeight;
- (id)cellViewClassName;
- (id)eventHandleClassName;
- (id)initWithMessageModel:(id)arg1;
@property(nonatomic) _Bool isReported; // @synthesize isReported=_isReported;
- (_Bool)shouldDisplaySelfNick;
@end
|
MichealWayne/Moo-CSS
|
demo/mobile/webpack.config.js
|
<gh_stars>100-1000
/**
* webpack config
*/
const fs = require('fs');
const glob = require('glob');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LessFunc = require('less-plugin-functions');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const getTimeStr = require('ijijin_builder/nodebuild/lib/util/util').getTimeStr;
const PurifyCssPlugin = require('purifycss-webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const CONFIG = require('./package.json');
// top banner
const MY_BANNER = `
${CONFIG.name}
@version: ${CONFIG.version}
@description: ${CONFIG.description}
@author: ${CONFIG.author}
@task: ${CONFIG.task || ''}
@build time: ${getTimeStr()}
`;
const BROWSERS_VERSION_SET = { // for autoprefixer
browsers: [
'last 2 versions',
'android 4',
'ios 8'
]
// pc: ['ie 6-8', 'Firefox > 20', 'cover 99.5%']
};
const IMAGE_LIMIT = 5000; // base64 limit
module.exports = (options = {}) => {
const entries = glob.sync('./src/**/enter.js');
const entryJSList = {};
const entryHtmlList = [];
for (const path of entries) {
const chunkName = path.slice('./src/js/'.length, -'/enter.js'.length);
entryJSList[chunkName] = path;
entryHtmlList.push(new HtmlWebpackPlugin({
template: './src/' + chunkName + '.html',
filename: chunkName + '.html',
chunks: ['manifest', 'vendor', chunkName, 'commons'],
minify: {
removeAttributeQuotes: false
}
}));
}
let plugins = [
...entryHtmlList,
new webpack.optimize.SplitChunksPlugin({
names: "commons"
}),
new VueLoaderPlugin(),
new PurifyCssPlugin({
styleExtensions: [path.join(__dirname, 'src/less/*')],
paths: glob.sync(path.join(__dirname, 'src/*.(html|vue)'))
}),
new MiniCssExtractPlugin({
filename: `css/[name]${options.dev ? '' : '.[chunkhash:8]'}.css`,
chunkFilename: `[id].css`
})
];
if (!options.dev) plugins.push(new webpack.IgnorePlugin(/mock\/*/)); // ignore mock
if (options.prod) { // add banner description
plugins.push(new webpack.BannerPlugin(MY_BANNER));
}
return {
entry: entryJSList,
resolve: {
extensions: ['.js', '.css', 'less'],
alias: {
'~': path.resolve(__dirname, '../Moo-CSS/'),
'@': path.resolve(__dirname, 'src'),
'mock': path.resolve(__dirname, 'src/mock'),
'lib': path.resolve(__dirname, 'src/js/lib'),
'css': path.resolve(__dirname, 'src/css'),
'less': path.resolve(__dirname, 'src/less'),
'sass': path.resolve(__dirname, 'src/sass')
}
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: options.dev ? '[name].js' :
//'js/[name].js',
'js/[name].[chunkhash:8].js',
chunkFilename: '[id].js?[chunkhash:8]'
},
devtool: options.dev && 'cheap-module-source-map' || (options.prod ? false : 'source-map'),
module: {
rules: [
// js
{
test: /\.js$/,
exclude: /ijijin_builder/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
,'eslint-loader'
]
},
// html
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
root: path.resolve(__dirname, 'src'),
attrs: ['img:src']
}
}
},
// css
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]_[hash:base64:8]'
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')(BROWSERS_VERSION_SET)
],
localIdentName: 'm-[hash:base64:5]',
modules: true
}
}
]
},
// less
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: 'm-[hash:base64:4]'
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')(BROWSERS_VERSION_SET)
],
localIdentName: 'purify_[hash:base64:5]',
modules: true
}
},
{
loader: 'less-loader',
options: {
strictMath: true,
plugins: [new LessFunc()],
localIdentName: 'purify_[hash:base64:5]',
modules: true
}
}
]
},
// sass
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')(BROWSERS_VERSION_SET)
],
localIdentName: 'purify_[hash:base64:5]',
modules: true
}
},
{
loader: 'sass-loader',
options: {
strictMath: true,
plugins: [new LessFunc()],
localIdentName: 'purify_[hash:base64:5]',
modules: true
}
}
]
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'less': [
'vue-style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: 'm-[hash:base64:4]'
}
},
'less-loader'
]
}
}
},
// image or font
{
test: /\.(png|jpg|jpeg|gif)(\?.+)?$/,
use: [{
loader: 'url-loader',
options: {
limit: IMAGE_LIMIT,
name: 'images/[hash].[ext]'
}
}]
},
{
test: /\.(eot|svg|ttf|woff|woff2)\w*/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
publicPath: '../assets/font/',
outputPath: 'assets/font/'
}
}]
}
]
},
optimization: {
splitChunks: {
name: true,
chunks: "async",
minSize: 2000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
cacheGroups: {
commons: {
test: /less/,
name: 'commons',
chunks: 'initial',
minChunks: 2,
minSize: 2000
}
}
}
},
plugins: plugins,
devServer: {
port: 3000,
hot: true,
contentBase: path.join(__dirname, 'src'),
overlay: true,
historyApiFallback: {
index: '/assets/',
disableDotRule: true
},
inline: true
},
performance: {
hints: options.dev ? false : 'warning'
}
}
};
|
standardgaussian/Titania
|
lib/game/entities/magnetBootsPickup.js
|
ig.module('game.entities.magnetBootsPickup')
.requires('impact.entity',
'game.entities.pickup'
)
.defines(function() {
EntityMagnetBootsPickup = EntityPickup.extend({
animSheet : new ig.AnimationSheet('media/pickups/magBootsPickup.png', 16, 16),
offset: {x:0, y:0},
propertyValue: 'magnetBoots',
});
});
|
timroes/elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/index/engine/FrozenIndexTests.java
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.index.engine;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardTestCase;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchService;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.internal.AliasFilter;
import org.elasticsearch.search.internal.ShardSearchLocalRequest;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.xpack.core.XPackClient;
import org.elasticsearch.xpack.core.XPackPlugin;
import org.elasticsearch.xpack.core.action.TransportFreezeIndexAction;
import org.hamcrest.Matchers;
import java.io.IOException;
import java.util.Collection;
import java.util.EnumSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
public class FrozenIndexTests extends ESSingleNodeTestCase {
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return pluginList(XPackPlugin.class);
}
public void testCloseFreezeAndOpen() throws ExecutionException, InterruptedException {
createIndex("index", Settings.builder().put("index.number_of_shards", 2).build());
client().prepareIndex("index", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
client().prepareIndex("index", "_doc", "2").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
client().prepareIndex("index", "_doc", "3").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("index")));
expectThrows(ClusterBlockException.class, () -> client().prepareIndex("index", "_doc", "4").setSource("field", "value")
.setRefreshPolicy(IMMEDIATE).get());
IndicesService indexServices = getInstanceFromNode(IndicesService.class);
Index index = resolveIndex("index");
IndexService indexService = indexServices.indexServiceSafe(index);
IndexShard shard = indexService.getShard(0);
Engine engine = IndexShardTestCase.getEngine(shard);
assertEquals(0, shard.refreshStats().getTotal());
boolean useDFS = randomBoolean();
assertHitCount(client().prepareSearch().setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED)
.setSearchType(useDFS ? SearchType.DFS_QUERY_THEN_FETCH : SearchType.QUERY_THEN_FETCH).get(), 3);
assertThat(engine, Matchers.instanceOf(FrozenEngine.class));
assertEquals(useDFS ? 3 : 2, shard.refreshStats().getTotal());
assertFalse(((FrozenEngine)engine).isReaderOpen());
assertTrue(indexService.getIndexSettings().isSearchThrottled());
try (Engine.Searcher searcher = shard.acquireSearcher("test")) {
assertNotNull(FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()));
}
// now scroll
SearchResponse searchResponse = client().prepareSearch().setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED)
.setScroll(TimeValue.timeValueMinutes(1)).setSize(1).get();
do {
assertHitCount(searchResponse, 3);
assertEquals(1, searchResponse.getHits().getHits().length);
SearchService searchService = getInstanceFromNode(SearchService.class);
assertThat(searchService.getActiveContexts(), Matchers.greaterThanOrEqualTo(1));
for (int i = 0; i < 2; i++) {
shard = indexService.getShard(i);
engine = IndexShardTestCase.getEngine(shard);
assertFalse(((FrozenEngine) engine).isReaderOpen());
}
searchResponse = client().prepareSearchScroll(searchResponse.getScrollId()).setScroll(TimeValue.timeValueMinutes(1)).get();
} while (searchResponse.getHits().getHits().length > 0);
}
public void testSearchAndGetAPIsAreThrottled() throws InterruptedException, IOException, ExecutionException {
XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
.startObject("properties").startObject("field").field("type", "text").field("term_vector", "with_positions_offsets_payloads")
.endObject().endObject()
.endObject().endObject();
createIndex("index", Settings.builder().put("index.number_of_shards", 2).build(), "_doc", mapping);
for (int i = 0; i < 10; i++) {
client().prepareIndex("index", "_doc", "" + i).setSource("field", "foo bar baz").get();
}
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("index")));
int numRequests = randomIntBetween(20, 50);
CountDownLatch latch = new CountDownLatch(numRequests);
ActionListener listener = ActionListener.wrap(latch::countDown);
int numRefreshes = 0;
for (int i = 0; i < numRequests; i++) {
numRefreshes++;
switch (randomIntBetween(0, 3)) {
case 0:
client().prepareGet("index", "_doc", "" + randomIntBetween(0, 9)).execute(listener);
break;
case 1:
client().prepareSearch("index").setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.execute(listener);
// in total 4 refreshes 1x query & 1x fetch per shard (we have 2)
numRefreshes += 3;
break;
case 2:
client().prepareTermVectors("index", "_doc", "" + randomIntBetween(0, 9)).execute(listener);
break;
case 3:
client().prepareExplain("index", "_doc", "" + randomIntBetween(0, 9)).setQuery(new MatchAllQueryBuilder())
.execute(listener);
break;
default:
assert false;
}
}
latch.await();
IndicesStatsResponse index = client().admin().indices().prepareStats("index").clear().setRefresh(true).get();
assertEquals(numRefreshes, index.getTotal().refresh.getTotal());
}
public void testFreezeAndUnfreeze() throws InterruptedException, ExecutionException {
createIndex("index", Settings.builder().put("index.number_of_shards", 2).build());
client().prepareIndex("index", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
client().prepareIndex("index", "_doc", "2").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
client().prepareIndex("index", "_doc", "3").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
if (randomBoolean()) {
// sometimes close it
assertAcked(client().admin().indices().prepareClose("index").get());
}
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("index")));
{
IndicesService indexServices = getInstanceFromNode(IndicesService.class);
Index index = resolveIndex("index");
IndexService indexService = indexServices.indexServiceSafe(index);
assertTrue(indexService.getIndexSettings().isSearchThrottled());
IndexShard shard = indexService.getShard(0);
assertEquals(0, shard.refreshStats().getTotal());
}
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("index").setFreeze(false)));
{
IndicesService indexServices = getInstanceFromNode(IndicesService.class);
Index index = resolveIndex("index");
IndexService indexService = indexServices.indexServiceSafe(index);
assertFalse(indexService.getIndexSettings().isSearchThrottled());
IndexShard shard = indexService.getShard(0);
Engine engine = IndexShardTestCase.getEngine(shard);
assertThat(engine, Matchers.instanceOf(InternalEngine.class));
}
client().prepareIndex("index", "_doc", "4").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
}
private void assertIndexFrozen(String idx) {
IndicesService indexServices = getInstanceFromNode(IndicesService.class);
Index index = resolveIndex(idx);
IndexService indexService = indexServices.indexServiceSafe(index);
assertTrue(indexService.getIndexSettings().isSearchThrottled());
assertTrue(FrozenEngine.INDEX_FROZEN.get(indexService.getIndexSettings().getSettings()));
}
public void testDoubleFreeze() throws ExecutionException, InterruptedException {
createIndex("test-idx", Settings.builder().put("index.number_of_shards", 2).build());
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("test-idx")));
ExecutionException executionException = expectThrows(ExecutionException.class,
() -> xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("test-idx")
.indicesOptions(new IndicesOptions(EnumSet.noneOf(IndicesOptions.Option.class),
EnumSet.of(IndicesOptions.WildcardStates.OPEN)))));
assertEquals("no index found to freeze", executionException.getCause().getMessage());
}
public void testUnfreezeClosedIndices() throws ExecutionException, InterruptedException {
createIndex("idx", Settings.builder().put("index.number_of_shards", 1).build());
client().prepareIndex("idx", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
createIndex("idx-closed", Settings.builder().put("index.number_of_shards", 1).build());
client().prepareIndex("idx-closed", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("idx")));
assertAcked(client().admin().indices().prepareClose("idx-closed").get());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("idx*").setFreeze(false)
.indicesOptions(IndicesOptions.strictExpand())));
ClusterStateResponse stateResponse = client().admin().cluster().prepareState().get();
assertEquals(IndexMetaData.State.CLOSE, stateResponse.getState().getMetaData().index("idx-closed").getState());
assertEquals(IndexMetaData.State.OPEN, stateResponse.getState().getMetaData().index("idx").getState());
assertHitCount(client().prepareSearch().get(), 1L);
}
public void testFreezePattern() throws ExecutionException, InterruptedException {
createIndex("test-idx", Settings.builder().put("index.number_of_shards", 1).build());
client().prepareIndex("test-idx", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
createIndex("test-idx-1", Settings.builder().put("index.number_of_shards", 1).build());
client().prepareIndex("test-idx-1", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("test-idx")));
assertIndexFrozen("test-idx");
IndicesStatsResponse index = client().admin().indices().prepareStats("test-idx").clear().setRefresh(true).get();
assertEquals(0, index.getTotal().refresh.getTotal());
assertHitCount(client().prepareSearch("test-idx").setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED).get(), 1);
index = client().admin().indices().prepareStats("test-idx").clear().setRefresh(true).get();
assertEquals(1, index.getTotal().refresh.getTotal());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("test*")));
assertIndexFrozen("test-idx");
assertIndexFrozen("test-idx-1");
index = client().admin().indices().prepareStats("test-idx").clear().setRefresh(true).get();
assertEquals(1, index.getTotal().refresh.getTotal());
index = client().admin().indices().prepareStats("test-idx-1").clear().setRefresh(true).get();
assertEquals(0, index.getTotal().refresh.getTotal());
}
public void testCanMatch() throws ExecutionException, InterruptedException, IOException {
createIndex("index");
client().prepareIndex("index", "_doc", "1").setSource("field", "2010-01-05T02:00").setRefreshPolicy(IMMEDIATE).execute()
.actionGet();
client().prepareIndex("index", "_doc", "2").setSource("field", "2010-01-06T02:00").setRefreshPolicy(IMMEDIATE).execute()
.actionGet();
{
IndicesService indexServices = getInstanceFromNode(IndicesService.class);
Index index = resolveIndex("index");
IndexService indexService = indexServices.indexServiceSafe(index);
IndexShard shard = indexService.getShard(0);
assertFalse(indexService.getIndexSettings().isSearchThrottled());
SearchService searchService = getInstanceFromNode(SearchService.class);
assertTrue(searchService.canMatch(new ShardSearchLocalRequest(shard.shardId(), 1, SearchType.QUERY_THEN_FETCH, null,
Strings.EMPTY_ARRAY, false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, true, null, null)));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.rangeQuery("field").gte("2010-01-03||+2d").lte("2010-01-04||+2d/d"));
assertTrue(searchService.canMatch(new ShardSearchLocalRequest(shard.shardId(), 1, SearchType.QUERY_THEN_FETCH, sourceBuilder,
Strings.EMPTY_ARRAY, false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, true, null, null)));
sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.rangeQuery("field").gt("2010-01-06T02:00").lt("2010-01-07T02:00"));
assertFalse(searchService.canMatch(new ShardSearchLocalRequest(shard.shardId(), 1, SearchType.QUERY_THEN_FETCH, sourceBuilder,
Strings.EMPTY_ARRAY, false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, true, null, null)));
}
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("index")));
{
IndicesService indexServices = getInstanceFromNode(IndicesService.class);
Index index = resolveIndex("index");
IndexService indexService = indexServices.indexServiceSafe(index);
IndexShard shard = indexService.getShard(0);
assertTrue(indexService.getIndexSettings().isSearchThrottled());
SearchService searchService = getInstanceFromNode(SearchService.class);
assertTrue(searchService.canMatch(new ShardSearchLocalRequest(shard.shardId(), 1, SearchType.QUERY_THEN_FETCH, null,
Strings.EMPTY_ARRAY, false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, true, null, null)));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.rangeQuery("field").gte("2010-01-03||+2d").lte("2010-01-04||+2d/d"));
assertTrue(searchService.canMatch(new ShardSearchLocalRequest(shard.shardId(), 1, SearchType.QUERY_THEN_FETCH, sourceBuilder,
Strings.EMPTY_ARRAY, false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, true, null, null)));
sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.rangeQuery("field").gt("2010-01-06T02:00").lt("2010-01-07T02:00"));
assertFalse(searchService.canMatch(new ShardSearchLocalRequest(shard.shardId(), 1, SearchType.QUERY_THEN_FETCH, sourceBuilder,
Strings.EMPTY_ARRAY, false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, true, null, null)));
IndicesStatsResponse response = client().admin().indices().prepareStats("index").clear().setRefresh(true).get();
assertEquals(0, response.getTotal().refresh.getTotal()); // never opened a reader
}
}
public void testWriteToFrozenIndex() throws ExecutionException, InterruptedException {
createIndex("idx", Settings.builder().put("index.number_of_shards", 1).build());
client().prepareIndex("idx", "_doc", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("idx")));
assertIndexFrozen("idx");
expectThrows(ClusterBlockException.class, () ->
client().prepareIndex("idx", "_doc", "2").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get());
}
public void testIgnoreUnavailable() throws ExecutionException, InterruptedException {
createIndex("idx", Settings.builder().put("index.number_of_shards", 1).build());
createIndex("idx-close", Settings.builder().put("index.number_of_shards", 1).build());
assertAcked(client().admin().indices().prepareClose("idx-close"));
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("idx*", "not_available")
.indicesOptions(IndicesOptions.fromParameters(null, "true", null, null, IndicesOptions.strictExpandOpen()))));
assertIndexFrozen("idx");
assertEquals(IndexMetaData.State.CLOSE,
client().admin().cluster().prepareState().get().getState().metaData().index("idx-close").getState());
}
public void testUnfreezeClosedIndex() throws ExecutionException, InterruptedException {
createIndex("idx", Settings.builder().put("index.number_of_shards", 1).build());
XPackClient xPackClient = new XPackClient(client());
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("idx")));
assertAcked(client().admin().indices().prepareClose("idx"));
assertEquals(IndexMetaData.State.CLOSE,
client().admin().cluster().prepareState().get().getState().metaData().index("idx").getState());
expectThrows(ExecutionException.class,
() -> xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("id*").setFreeze(false)
.indicesOptions(new IndicesOptions(EnumSet.noneOf(IndicesOptions.Option.class),
EnumSet.of(IndicesOptions.WildcardStates.OPEN)))));
// we don't resolve to closed indices
assertAcked(xPackClient.freeze(new TransportFreezeIndexAction.FreezeRequest("idx").setFreeze(false)));
assertEquals(IndexMetaData.State.OPEN,
client().admin().cluster().prepareState().get().getState().metaData().index("idx").getState());
}
}
|
snoopdave/incubator-usergrid
|
stack/services/src/main/java/org/apache/usergrid/management/OrganizationConfigProps.java
|
<filename>stack/services/src/main/java/org/apache/usergrid/management/OrganizationConfigProps.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.usergrid.management;
import org.apache.usergrid.system.ServerEnvironmentProps;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public interface OrganizationConfigProps {
String ORGPROPERTIES_API_URL_BASE = ServerEnvironmentProps.API_URL_BASE;
String ORGPROPERTIES_DEFAULT_CONNECTION_PARAM = "usergrid.rest.default-connection-param";
String ORGPROPERTIES_ADMIN_SYSADMIN_EMAIL = AccountCreationProps.PROPERTIES_ADMIN_SYSADMIN_EMAIL;
// these can not currently be set as org config items, but they select
// the full URL to be created from the org-specific API URL base and the
// hardcoded paths
//
// use these specifiers with getFullUrl() to select the URL to be built
enum WorkflowUrl {
ORGANIZATION_ACTIVATION_URL,
ADMIN_ACTIVATION_URL,
ADMIN_CONFIRMATION_URL,
ADMIN_RESETPW_URL,
USER_ACTIVATION_URL,
USER_CONFIRMATION_URL,
USER_RESETPW_URL
}
Set<String> getOrgPropertyNames();
Properties getPropertiesMap();
Map<String, String> getDefaultPropertiesMap();
Map<String, String> getOrgPropertiesMap();
String getOrgPropertyNameRegex();
String getProperty(String name);
String getProperty(String name, String defaultValue);
boolean boolProperty(String name, boolean defaultValue);
int intProperty(String name, int defaultValue);
long longProperty(String name, long defaultValue);
void setProperty(String name, String value);
String getFullUrlTemplate(WorkflowUrl urlType);
String getFullUrl(WorkflowUrl urlType, Object ... arguments);
boolean orgPropertyNameValid(String name);
}
|
hey-frnk/thevfdcollective
|
FluorescenceApp/src/fl_app_colors.h
|
/**
******************************************************************************
* @file vfdco_led.h
* @author The VFD Collective, Frank from The VFD Collective (<NAME>)
* @version V1.0
* @date 20-November-2019
* @brief This is the dummy driver to test the functionality of the LED libs
******************************************************************************
* @toc Table of contents, enter to navigate:
******************************************************************************
**/
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _VFDCO_LED_DRIVER
#define _VFDCO_LED_DRIVER
#include <stdint.h>
#include "../FluorescenceV3/Commons/vfdco_config.h"
// Array of color values of size n um_bytes to be written in the next write cycle
// to the physical WS2812B/SK6812 LEDs
// extern uint8_t rgb_arr[4 * CONFIG_NUM_PIXELS];
// Initialize SW/HW of num_pixels * SK6812 LEDs
void vfdco_clr_init(uint8_t initial_dim_factor);
// You might never ever make use of it but hey... in case
void vfdco_clr_deInit(void);
void vfdco_clr_set_dim_factor(uint8_t dim_factor);
// Some simple access functions. Add some more if u feel creative
void vfdco_clr_set_RGB(uint8_t index, uint8_t r, uint8_t g, uint8_t b);
void vfdco_clr_set_RGBW(uint8_t index, uint8_t r, uint8_t g, uint8_t b, uint8_t w);
void vfdco_clr_set_all_RGB(uint8_t r, uint8_t g, uint8_t b);
void vfdco_clr_set_all_RGBW(uint8_t r, uint8_t g, uint8_t b, uint8_t w);
// Colors all written? Shuttle the data bit by bit into the LEDs
void vfdco_clr_render();
//
void vfdco_clr_target_RGB(uint8_t *tp, uint8_t r, uint8_t g, uint8_t b);
void vfdco_clr_target_RGBW(uint8_t *tp, uint8_t r, uint8_t g, uint8_t b, uint8_t w);
void vfdco_clr_target_all_RGB(uint8_t *tp, uint8_t r, uint8_t g, uint8_t b);
void vfdco_clr_target_all_RGBW(uint8_t *tp, uint8_t r, uint8_t g, uint8_t b, uint8_t w);
void vfdco_clr_minimize_difference(uint8_t *target_arr);
#endif
#ifdef __cplusplus
}
#endif
|
lakeweb/spur-gear-gen
|
project/sgv.cpp
|
#include "stdafx.h"
#include "Geometry.h"
#include "objects.h"
#include "shared.h"
#include "Drawing.h"
#include "sgv.h"
#include <sstream>
// ......................................................................
void svg_stream( std::ostream& os, const SP_BaseItem& in )
{
typecase( *in,
[ & ]( PointItem& pa ) {
os << " " << pa.get_bg_point( ).get_x( ) << " " << pa.get_bg_point( ).get_y( );
},
[ & ]( LineItem& pa ) {
os << " " << pa.get_bg_line( ).first.get_x( ) << " "
<< pa.get_bg_line( ).first.get_y( ) << " "
<< pa.get_bg_line( ).second.get_x( ) << " "
<< pa.get_bg_line( ).second.get_y( )
;
},
[ & ]( const ArcItem& pa ) {
double rad= bg::distance( pa.get_o( ), pa.get_a( ) );
os << "M"
<< " " << pa.get_a( ).get_x( )
<< " " << pa.get_a( ).get_y( )
<< " A "
<< " " << rad
<< " " << rad
<< " 0 0 1"// <-- TODO!!!
<< " " << pa.get_b( ).get_x( )
<< " " << pa.get_b( ).get_y( )
<< " M "
;
},
[ & ]( const RectItem& pa ) {
},
[ & ]( const EllipesItem& pa ) {
},
[ & ]( const BezierCubeItem& pa ) {
},
[ & ]( const PolyItem& pa ) {
for( auto l : pa )
os << " " << l.get_x( ) << " " << l.get_y( ) << " ";
});
}
// ......................................................................
void SVG_WriteFile( bfs::path& path, DrawingObects& draw )
{
CXML xml;
xml.Open( path.wstring( ).c_str( ), "svg", CXML::modeProgFile );
xml.Clear( );
xml.CreateEmptyDoc( "svg" );
xml.SetDOCTYPE( L"!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"" );
XMLNODE svg= xml.GetCurrentNode( );
svg.SetElementValue( "metadata", L"spur_gear_gen Copyright: Highlands Electronics 1996-2017" );
svg.SetAttribute( "width", L"40cm" );
svg.SetAttribute( "height", L"40cm" );
svg.SetAttribute( "viewBox", L"-1 -1 2 2" );
svg.SetAttribute( "xmlns", L"http://www.w3.org/2000/svg" );
svg.SetAttribute( "version", L"1.1" );
svg.SetElementValue( "title", L"spur gear gen" );
std::ostringstream os;
os << "M ";
for( auto it : draw )
for( auto im : it )
os << svg_obj( im ) << " ";
std::wstring buf( utf8_to_uni( ( os.str( ).c_str( ) ) ) );
XMLNODE node= svg.AddChild( "path" );
node.SetAttribute( "stroke-width", L".01" );
node.SetAttribute( "stroke", L"black" );
node.SetAttribute( "fill", L"none" );
node.SetAttribute( "d", buf.c_str( ) );
//os.str("");
//os.clear( );
//node= svg.AddChild( "circle" );
////<circle cx="10" cy="10" r="2" fill="red"/>
//node.SetAttribute( "cx", L".0" );
//node.SetAttribute( "cy", L".0" );
//node.SetAttribute( "r", L".1" );
//node.SetAttribute( "fill", L"blue" );
// node.SetAttribute( "fill", L"none" );
xml.Close( );
}
|
vizee/misc
|
go/gorpool/gorpool_test.go
|
<filename>go/gorpool/gorpool_test.go
package gorpool
import (
"fmt"
"runtime"
"sync"
"testing"
)
func TestPool(t *testing.T) {
p := Pool{}
wg := sync.WaitGroup{}
for i := 0; i < 1000; i++ {
wg.Add(1)
p.Go(func() {
fmt.Println("do", runtime.NumGoroutine())
wg.Done()
})
}
wg.Wait()
}
|
FeizNouri/logisland
|
logisland-components/logisland-connectors/logisland-connector-opc/src/main/java/com/hurence/logisland/connect/opc/da/OpcDaSourceConnector.java
|
<reponame>FeizNouri/logisland
/**
* Copyright (C) 2016 Hurence (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hurence.logisland.connect.opc.da;
import com.hurence.logisland.connect.opc.CommonDefinitions;
import com.hurence.logisland.connect.opc.CommonUtils;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigValue;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.source.SourceConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* OPC-DA Connector.
*
* @author amarziali
*/
public class OpcDaSourceConnector extends SourceConnector {
private static final Logger logger = LoggerFactory.getLogger(OpcDaSourceConnector.class);
private Map<String, ConfigValue> configValues;
public static final String PROPERTY_SERVER_CLSID = "server.clsId";
public static final String PROPERTY_SERVER_PROGID = "server.progId";
public static final String PROPERTY_AUTH_NTLM_USER = "auth.ntlm.user";
public static final String PROPERTY_AUTH_NTLM_PASSWORD = "<PASSWORD>";
public static final String PROPERTY_AUTH_NTLM_DOMAIN = "auth.ntlm.domain";
public static final String PROPERTY_SESSION_REFRESH_PERIOD = "session.refreshPeriodMillis";
public static final String PROPERTY_SESSION_DIRECT_READ = "session.directReadFromDevice";
public static final String PROPERTY_TAGS_DATA_TYPE_OVERRIDE = "tags.type.override";
/**
* The configuration.
*/
private static final ConfigDef CONFIG = CommonDefinitions.addCommonProperties(new ConfigDef())
.define(PROPERTY_AUTH_NTLM_DOMAIN, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH,
"The logon domain")
.define(PROPERTY_AUTH_NTLM_USER, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH,
"The logon user")
.define(PROPERTY_AUTH_NTLM_PASSWORD, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH,
"The logon password")
.define(PROPERTY_SERVER_CLSID, ConfigDef.Type.STRING, ConfigDef.Importance.MEDIUM,
"The CLSID of the OPC server COM component")
.define(PROPERTY_SERVER_PROGID, ConfigDef.Type.STRING, ConfigDef.Importance.MEDIUM,
"The Program ID of the OPC server COM component")
.define(PROPERTY_SESSION_REFRESH_PERIOD, ConfigDef.Type.LONG, 10_000, ConfigDef.Importance.LOW,
"The opc group data refresh period in milliseconds")
.define(PROPERTY_SESSION_DIRECT_READ, ConfigDef.Type.BOOLEAN, false, ConfigDef.Importance.LOW,
"Use server cache or read directly from device")
.define(PROPERTY_TAGS_DATA_TYPE_OVERRIDE, ConfigDef.Type.LIST, ConfigDef.Importance.LOW,
"If present will ask the opc server to override the data type with the one provided. " +
"Should be a short value supported by Variant");
@Override
public String version() {
return getClass().getPackage().getImplementationVersion();
}
@Override
public void start(Map<String, String> props) {
//shallow copy
configValues = config().validate(props).stream().collect(Collectors.toMap(ConfigValue::name, Function.identity()));
List<String> tags = (List<String>) configValues.get(CommonDefinitions.PROPERTY_TAGS_ID).value();
List<String> freqs = (List<String>) configValues.get(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE).value();
List<String> modes = (List<String>) configValues.get(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE).value();
//validate the configs
CommonUtils.validateTagConfig(tags, freqs, modes);
if (configValues.get(PROPERTY_TAGS_DATA_TYPE_OVERRIDE).value() != null) {
try {
if (tags.size() != ((List<String>) configValues.get(PROPERTY_TAGS_DATA_TYPE_OVERRIDE).value()).stream()
.map(Short::parseShort).count()) {
throw new IllegalArgumentException("Provided list of data type override must match the length of provided tags");
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Provided list of data type override must contains only short values");
}
}
//all right.. let's start
logger.info("Starting OPC-DA connector (version {}) on server {} reading tags {}", version(),
configValues.get(CommonDefinitions.PROPERTY_SERVER_URI).value(),
configValues.get(CommonDefinitions.PROPERTY_TAGS_ID).value());
}
@Override
public Class<? extends Task> taskClass() {
return OpcDaSourceTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
Map<String, String> ret = configValues.entrySet().stream()
.filter(a -> a.getValue().value() != null)
.collect(Collectors.toMap(a -> a.getKey(), a -> a.getValue().value().toString()));
ret.put(CommonDefinitions.PROPERTY_TAGS_ID, ((List<String>) configValues.get(CommonDefinitions.PROPERTY_TAGS_ID).value()).stream().collect(Collectors.joining(",")));
ret.put(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE, ((List<String>) configValues.get(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE).value()).stream().collect(Collectors.joining(",")));
ret.put(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE, ((List<String>) configValues.get(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE).value()).stream().collect(Collectors.joining(",")));
if (configValues.get(PROPERTY_TAGS_DATA_TYPE_OVERRIDE).value() != null) {
ret.put(PROPERTY_TAGS_DATA_TYPE_OVERRIDE, ((List<String>) configValues.get(PROPERTY_TAGS_DATA_TYPE_OVERRIDE).value()).stream().collect(Collectors.joining(",")));
}
return Collections.singletonList(ret);
}
@Override
public void stop() {
logger.info("Stopping OPC-DA connector (version {}) on server {}", version(), configValues.get(CommonDefinitions.PROPERTY_SERVER_URI).value());
}
@Override
public ConfigDef config() {
return CONFIG;
}
}
|
chs6558/chs6558.github.io
|
node_modules/styled-icons/fa-solid/FontAwesomeLogoFull/FontAwesomeLogoFull.esm.js
|
export * from '@styled-icons/fa-solid/FontAwesomeLogoFull';
|
PRkudupu/Algo-python
|
array_strings/py/two_dimensional.py
|
<reponame>PRkudupu/Algo-python<filename>array_strings/py/two_dimensional.py<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# ### Processing and printing
# In[36]:
#Processing and printing
a =[[1,2,3,],[4,5,6]]
print('a:',a,'\na[0]:',a[0],'\na[1]:',a[1])
# In[15]:
#Print specific element in an list
print('a[0][1] :',a[0][1])
# In[24]:
# Process 2 dimensional array
for i in range(len(a)):
for j in range(len(a[i])):
print('a[i],[j]',a[i][j])
# In[41]:
### Handy feature to print
for i in a:
for elem in i:
print(elem)
# ### Sum of all elements in an array
# In[27]:
# sum of all the elements in the list
sum=0
for i in a:
for elem in i:
sum += elem
print('sum',sum)
# ### Create new 2 dimensional array
# In[35]:
# Create 2 dimensional list based on m *n with 0
# Create an empty list and append new elements
n =3
m =4
a =[]
for i in range(n):
print('[0]',[0])
print('m',m)
a.append([0] * m )
print(a)
# ### Using generators
# #### Python provides generator functions as a convenient shortcut to building iterators
# In[43]:
n=3
m=4
a =[[0]* m for i in range(n)]
print(a)
# ### Find max in 2 dimensional aray
# In[40]:
m=0
a= [[10,20,40],[20,400,200]]
for i in a:
for elem in i:
if elem > m:
m=elem
print(elem)
print('maximum',m)
#
|
nryotaro/at_c
|
src/abc153/b.cc
|
#ifdef _debug
#define _GLIBCXX_DEBUG
#endif
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#ifndef _debug
int main() {
ll h, n;
cin >> h >> n;
for(int i = 0; i < n; i++) {
ll temp;
cin >> temp;
h -= temp;
}
if(h <= 0)
cout << "Yes";
else
cout << "No";
return 0;
}
#endif
|
murrcha/kkaysheva
|
chapter_006/src/main/java/ru/job4j/tracker/ConsoleInput.java
|
package ru.job4j.tracker;
import java.util.Scanner;
/**
* ConsoleInput - запрос данных от пользователя через консоль
*
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ConsoleInput implements Input {
/**
* Объект для считывания стандартного потока ввода
*/
private Scanner scanner = new Scanner(System.in);
/**
* Method ask - запрашивает данные у пользователя через консоль
* @param question - запрос данных
* @return ответ пользователя
*/
@Override
public String ask(String question) {
System.out.print(question);
return scanner.nextLine();
}
/**
* Method ask - запрашивает данные у пользователя через консоль
* @param question - запрос
* @param range - диапазон
* @return -
*/
@Override
public int ask(String question, int[] range) {
int key = Integer.valueOf(ask(question));
boolean exist = false;
for (int value : range) {
if (value == key) {
exist = true;
break;
}
}
if (!exist) {
throw new MenuOutException("Номер пункта меню вне диапазона");
}
return key;
}
}
|
nop-os/nop
|
kernel/include/nop/idt.h
|
#ifndef __NOP_IDT_H__
#define __NOP_IDT_H__
#include <arch/i586.h>
#include <nop/type.h>
#define IDT_ERR_BASE 0x00
#define IDT_PIC_BASE 0x20
#define IDT_NOP_BASE 0x30
#define IDT_CLK (IDT_PIC_BASE + 0x00)
#define IDT_KEYB (IDT_PIC_BASE + 0x01)
#define IDT_MOUSE (IDT_PIC_BASE + 0x0C)
#define IDT_RTC (IDT_PIC_BASE + 0x08)
#define IDT_NOP (IDT_NOP_BASE + 0x00)
typedef struct idt_entry_t idt_entry_t;
typedef struct idt_hand_t idt_hand_t;
struct idt_entry_t {
uint16_t addr_lo;
uint16_t sgmt;
uint8_t zero;
uint8_t attr;
uint16_t addr_hi;
} __attribute__((packed));
struct idt_hand_t {
void (*func)(i586_regs_t *regs);
int id;
};
extern idt_entry_t idt_table[];
extern uint32_t idt_list[];
extern idt_hand_t *idt_hand;
extern int idt_count;
extern int idt_level;
void idt_pic_on(void);
void idt_pic_off(void);
void idt_init(void);
int idt_add(void (*func)(i586_regs_t *regs), int id);
void idt_remove(int index);
void idt_call(i586_regs_t *regs, int id);
#endif
|
inclusive-design/coop-map-directory-index
|
mdi/admin.py
|
from django.contrib.gis import admin
from django.contrib.gis.admin import ModelAdmin, OSMGeoAdmin, TabularInline
from accounts.models import SocialNetwork
from .models import \
Category, Challenge, LegalStatus, Organization, OrganizationSocialNetwork, Stage, Type, Tool, License, \
Pricing, Niche, Relationship, EntitiesEntities, Service
from django.db.models.functions import Lower
# Window dressing
admin.site.site_header = 'Platform Coop : Map / Directory / Index'
admin.site.site_title = 'Admin'
admin.site.index_title = 'Map / Directory / Index'
# Create Admin-related classes
@admin.register(Category)
class CategoryAdmin(ModelAdmin):
list_display = ('name', 'order', 'type', 'description')
@admin.register(Challenge)
class LegalStatusAdmin(ModelAdmin):
list_display = ('name', 'order', 'description', )
@admin.register(LegalStatus)
class LegalStatusAdmin(ModelAdmin):
list_display = ('name', 'order', 'description', )
@admin.register(Service)
class ServiceAdmin(ModelAdmin):
list_display = ('name', 'order', 'description', )
@admin.register(Type)
class TypeAdmin(ModelAdmin):
list_display = ('name', 'description')
class OrganizationSocialNetworkInline(TabularInline):
model = OrganizationSocialNetwork
extra = 3
@admin.register(Organization)
class OrganizationAdmin(OSMGeoAdmin):
list_display = ('name', 'city', 'country',)
list_filter = ('source', 'categories', 'type', 'sectors', 'country',)
search_fields = ['name', 'description', ]
inlines = [OrganizationSocialNetworkInline]
ordering = [Lower('name'), ]
@admin.register(SocialNetwork)
class SocialNetworkAdmin(admin.ModelAdmin):
list_filter = ('name', 'format', )
search_fields = ['name', 'description', ]
@admin.register(Relationship)
class RelationshipAdmin(admin.ModelAdmin):
list_display = ('name', )
@admin.register(EntitiesEntities)
class EntitiesEntitiesAdmin(admin.ModelAdmin):
list_display = ('from_ind', 'from_org', 'relationship', 'to_ind', 'to_org', )
@admin.register(Stage)
class ToolAdmin(ModelAdmin):
list_display = ('name', 'description', )
@admin.register(Niche)
class NicheAdmin(ModelAdmin):
list_display = ('name', 'description', )
@admin.register(Tool)
class ToolAdmin(admin.ModelAdmin):
list_display = ('name', 'license', )
list_filter = ('niches', 'license', 'pricing') # 'languages_supported',)
search_fields = ['name', 'description', ]
@admin.register(License)
class LicenseAdmin(admin.ModelAdmin):
fields = ('spdx', 'name', 'url', )
list_display = ('spdx', 'name', 'url', )
list_filter = ('spdx', )
search_fields = ['spdx', 'name', ]
@admin.register(Pricing)
class PricingAdmin(admin.ModelAdmin):
fields = ('name', )
|
Ybalrid/orbiter
|
Extern/mssdk_dx7/samples/Multimedia/DMusic/src/MusicLines/mllocalplayer.h
|
<gh_stars>1000+
//
// MLLocalPlayer.h
//
// Local player implementation
//
// Copyright (c) 1998-1999 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef _MLLocalPlayer_
#define _MLLocalPlayer_
// LocalPlayer is a Player controlled by a local controller.
//
class LocalPlayer : public Player
{
public:
LocalPlayer(int PlayerNo, Game *pGame) :
m_PlayerNo(PlayerNo), Player(PlayerNo, pGame)
{}
void Reset(ArenaPt pt);
Move ComputeMove();
private:
int m_PlayerNo; // For class Input mapping of controls -> player
};
#endif // _MLLocalPlayer_
|
WorldofJARcraft/craco
|
src/test/java/org/cryptimeleon/craco/sig/hashthensign/HashThenSignTest.java
|
package org.cryptimeleon.craco.sig.hashthensign;
import org.cryptimeleon.craco.common.ByteArrayImplementation;
import org.cryptimeleon.craco.sig.*;
import org.cryptimeleon.craco.sig.hashthensign.params.BBSHTSParams;
import org.cryptimeleon.craco.sig.hashthensign.params.HashThenSignParams;
import org.cryptimeleon.craco.sig.hashthensign.params.PSHTSParams;
import org.cryptimeleon.math.hash.HashFunction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Collection;
/**
* Test for the {@link HashThenSign} construction. Each combination of {@link SignatureScheme} and {@link HashFunction}
* to be tested need to be specified using {@link HashThenSignParams}.
*/
@RunWith(value = Parameterized.class)
public class HashThenSignTest {
private SignatureScheme hashThenSign;
private SignatureKeyPair<? extends VerificationKey, ? extends SigningKey> keyPair1;
private SignatureKeyPair<? extends VerificationKey, ? extends SigningKey> keyPair2;
private ByteArrayImplementation message1;
private ByteArrayImplementation message2;
public HashThenSignTest(HashThenSignParams params) {
this.hashThenSign = new HashThenSign(params.getHashFunction(), params.getSignatureScheme());
this.keyPair1 = params.getKeyPair1();
this.keyPair2 = params.getKeyPair2();
this.message1 = (ByteArrayImplementation) params.getMessage1();
this.message2 = (ByteArrayImplementation) params.getMessage2();
}
/**
* Each scheme to be tested needs to be added to the list output by this method.
*
* @return list of {@link HashThenSignParams} specifying schemes to be tested
*/
@Parameterized.Parameters(name = "{index}: {0}")
public static Collection<HashThenSignParams> data() {
ArrayList<HashThenSignParams> schemesToTest = new ArrayList<>();
schemesToTest.addAll(PSHTSParams.getParams());
schemesToTest.addAll(BBSHTSParams.getParams());
return schemesToTest;
}
@Test
public void testSignAndVerify() {
// assert correction of the signature scheme
SignatureSchemeTester.testSignatureSchemeSignAndVerify(hashThenSign, message1, keyPair1.getVerificationKey(),
keyPair1.getSigningKey());
}
@Test
public void testNegativeSignAndVerifyWrongMesssage() {
// negative test: verifying a signature on the correct verification key, but wrong message -> verify fails?
SignatureSchemeTester.testNegativeWrongMessageSignatureSchemeSignAndVerify(hashThenSign, message1, message2,
keyPair1.getVerificationKey(), keyPair1.getSigningKey());
}
@Test
public void testNegativeSignAndVerifyWrongKeys() {
// negative test: verifying a signature with the wrong verification key -> verify fails?
SignatureSchemeTester.testNegativeWrongKeysSignatureSchemeSignAndVerify(hashThenSign, message1,
keyPair1.getVerificationKey(), keyPair1.getSigningKey(), keyPair2.getVerificationKey(),
keyPair2.getSigningKey());
}
@Test
public void testRepresentations() {
// Test the standard representation of a signature scheme
SignatureSchemeTester.testRepresentationSignatureScheme(hashThenSign, message1, keyPair1.getVerificationKey(),
keyPair1.getSigningKey());
}
}
|
mmicek/kaacore
|
demos/polygon_tester.cpp
|
#include <cstdlib>
#include <iostream>
#include <vector>
#include <glm/glm.hpp>
#include "kaacore/engine.h"
#include "kaacore/geometry.h"
#include "kaacore/log.h"
#include "kaacore/nodes.h"
#include "kaacore/scenes.h"
struct PolygonTesterDemoScene : kaacore::Scene {
std::vector<glm::dvec2> points;
kaacore::NodePtr shape_repr;
kaacore::Engine* engine;
PolygonTesterDemoScene()
{
this->engine = kaacore::get_engine();
this->camera().position({0., 0.});
auto shape_repr = kaacore::make_node();
shape_repr->position({0, 0});
shape_repr->shape(kaacore::Shape::Box({3, 3}));
this->shape_repr = this->root_node.add_child(shape_repr);
}
void add_point(const glm::dvec2 p)
{
if (not this->points.empty() and this->points.back() == p) {
return;
}
kaacore::NodeOwnerPtr point_node = kaacore::make_node();
point_node->position(p);
point_node->shape(kaacore::Shape::Circle(1.));
this->root_node.add_child(point_node);
if (this->points.size()) {
this->add_segment(p, this->points.back());
}
this->points.push_back(p);
}
void add_segment(const glm::dvec2 a, const glm::dvec2 b)
{
kaacore::NodeOwnerPtr segment_node = kaacore::make_node();
segment_node->position(a);
segment_node->shape(kaacore::Shape::Segment({0, 0}, b - a));
this->root_node.add_child(segment_node);
}
void finalize_polygon()
{
this->add_segment(this->points.back(), this->points.front());
auto center = kaacore::find_points_center(this->points);
for (auto& pt : this->points) {
pt -= center;
}
auto polygon_type = kaacore::classify_polygon(this->points);
KAACORE_APP_LOG_INFO(
"Polygon type: {}", static_cast<int>(polygon_type));
if (polygon_type != kaacore::PolygonType::not_convex) {
this->shape_repr->shape(kaacore::Shape::Polygon(this->points));
} else {
KAACORE_APP_LOG_ERROR("Polygon not convex!");
}
this->points.clear();
}
void update(const kaacore::Duration dt) override
{
for (auto const& event : this->get_events()) {
if (auto mouse_button = event.mouse_button()) {
auto pos = mouse_button->position();
if (mouse_button->button() == kaacore::MouseButton::left) {
pos = this->camera().unproject_position(pos);
KAACORE_APP_LOG_INFO(
"Adding point: ({}, {})", pos.x, pos.y);
this->add_point(pos);
} else if (
mouse_button->button() == kaacore::MouseButton::left) {
pos = this->camera().unproject_position(pos);
KAACORE_APP_LOG_INFO(
"Adding point: ({}, {})", pos.x, pos.y);
this->add_point(pos);
}
}
if (auto keyboard_key = event.keyboard_key()) {
if (keyboard_key->key() == kaacore::Keycode::q) {
kaacore::get_engine()->quit();
break;
} else if (keyboard_key->key() == kaacore::Keycode::f) {
KAACORE_APP_LOG_INFO("Finalizing polygon");
this->finalize_polygon();
} else if (keyboard_key->key() == kaacore::Keycode::w) {
this->camera().position(
this->camera().position() + glm::dvec2(0., -2.5));
} else if (keyboard_key->key() == kaacore::Keycode::a) {
this->camera().position(
this->camera().position() + glm::dvec2(-2.5, 0.));
} else if (keyboard_key->key() == kaacore::Keycode::s) {
this->camera().position(
this->camera().position() + glm::dvec2(0., 2.5));
} else if (keyboard_key->key() == kaacore::Keycode::d) {
this->camera().position(
this->camera().position() + glm::dvec2(2.5, 0.));
} else if (keyboard_key->key() == kaacore::Keycode::i) {
this->camera().scale(
this->camera().scale() + glm::dvec2(0.1, 0.1));
} else if (keyboard_key->key() == kaacore::Keycode::o) {
this->camera().scale(
this->camera().scale() - glm::dvec2(0.1, 0.1));
} else if (keyboard_key->key() == kaacore::Keycode::r) {
this->camera().rotation(this->camera().rotation() + 0.3);
}
}
}
}
};
extern "C" int
main(int argc, char* argv[])
{
kaacore::Engine eng(
{800, 600}, kaacore::VirtualResolutionMode::aggresive_stretch);
PolygonTesterDemoScene scene;
eng.run(&scene);
return 0;
}
|
castle-games/castle-client
|
core/src/behaviors/text.h
|
<reponame>castle-games/castle-client
#pragma once
#include "precomp.h"
#include "behaviors/base.h"
#include "props.h"
struct TextFontResource {
love::StrongRef<love::Data> data;
struct Entry {
int pixelSize;
std::unique_ptr<love::Font> font;
};
std::vector<Entry> entries;
};
struct TextComponent : BaseComponent {
struct Props {
PROP(
std::string, content,
.label("Content")
.rulesGet(false)
) = "";
PROP(
bool, visible,
.label("Visible")
.rulesSet(false)
.rulesGet(false)
) = true;
PROP(int, order) = -1;
PROP(
std::string, fontName,
.label("Font")
.rulesGet(false)
.rulesSet(false)
.allowedValues(
"DMSans",
"CourierPrime",
"Glacier",
"HelicoCentrica",
"Piazzolla",
"YatraOne",
"Bore",
"Synco",
"Tektur"
)
)
= "DMSans";
PROP(float, fontSize,
.label("Font size")
.rulesGet(false)
.rulesSet(false)
) = 10;
PROP(float, fontSizeScale,
.label("Font size scale")
.rulesGet(false)
.rulesSet(false)
) = 1;
PROP(float, emsPerLine,
.label("Number of 'm's that fit per line")
.rulesGet(false)
.rulesSet(false)
) = 1;
PROP(std::string, alignment,
.label("Alignment")
.rulesGet(false)
.rulesSet(false)
.allowedValues("left", "right", "center", "justify")
) = "center";
PROP(love::Color, color,
.label("Color")
.rulesGet(false)
.rulesSet(false)
) = { 0x24, 0x22, 0x34, 0xff };
} props;
struct TouchRectangle {
love::Vector2 min { 0, 0 };
love::Vector2 max { 0, 0 };
};
mutable std::optional<TouchRectangle> touchRectangle;
mutable TouchId lastTouchId = nullTouch;
mutable bool touching = false;
TextFontResource *fontResource = nullptr;
};
class TextBehavior : public BaseBehavior<TextBehavior, TextComponent> {
public:
static constexpr auto name = "Text";
static constexpr auto behaviorId = 19;
static constexpr auto displayName = "Text";
static constexpr auto allowsDisableWithoutRemoval = false;
using BaseBehavior::BaseBehavior;
void handleReadComponent(ActorId actorId, TextComponent &component, Reader &reader);
void handlePrePerform();
bool handleDrawComponent(ActorId actorId, const TextComponent &component,
std::optional<SceneDrawingOptions> options) const;
void handleDrawOverlay() const;
std::optional<std::string> handleDrawBase64PreviewPng(
ActorId actorId, const TextComponent &component);
void handleSetProperty(
ActorId actorId, TextComponent &component, PropId propId, const ExpressionValue &value);
bool hasTapTrigger(ActorId actorId);
inline static const TouchToken overlayTouchToken;
inline static const TouchToken leaderboardTouchToken;
struct OverlayStyle {
PROP(love::Colorf, regularBackgroundColor) = { 227 / 255.0, 230 / 255.0, 255 / 255.0, 1 };
PROP(love::Colorf, regularForegroundColor) = { 36 / 255.0, 34 / 255.0, 52 / 255.0, 1 };
PROP(love::Colorf, tappableBackgroundColor) = { 36 / 255.0, 34 / 255.0, 52 / 255.0, 1 };
PROP(love::Colorf, tappingBackgroundColor) = { 64 / 255.0, 51 / 255.0, 83 / 255.0, 1 };
PROP(love::Colorf, tappableForegroundColor) = { 227 / 255.0, 230 / 255.0, 255 / 255.0, 1 };
PROP(float, fontSize) = 20;
PROP(float, horizontalPadding) = 4;
PROP(float, topPadding) = 2.75;
PROP(float, bottomPadding) = 2;
PROP(float, horizontalMargin) = 4;
PROP(float, betweenMargin) = 2;
PROP(float, bottomMargin) = 4;
};
static OverlayStyle overlayStyle;
static void loadFontResources(Lv &lv);
static void unloadFontResources();
static TextFontResource *getFontResource(const std::string &name);
static love::Font *getFont(TextFontResource *fontResource, float pixelSize);
void updateEmsPerLine(ActorId actorId, TextComponent &component);
private:
friend struct ShowResponse;
friend struct HideResponse;
friend struct HideTextResponse;
friend class Editor; // for sending text actors data to JS while editing
Lv &lv { Lv::getInstance() };
inline static std::unordered_map<std::string, TextFontResource> fontResources;
mutable love::Font *overlayFont = nullptr;
love::Font *getOverlayFont() const;
std::unique_ptr<love::Canvas> previewCanvas;
void updateFont(ActorId actorId, TextComponent &component);
std::string formatContent(ActorId actorId, const std::string &content) const;
void asciifyContent(std::string &content);
};
inline TextBehavior::OverlayStyle TextBehavior::overlayStyle;
inline TextFontResource *TextBehavior::getFontResource(const std::string &name) {
return &fontResources[name];
}
|
freundlich/fcppt
|
libs/core/include/fcppt/mpl/map/object_concept.hpp
|
<gh_stars>10-100
// Copyright <NAME> 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MPL_MAP_OBJECT_CONCEPT_HPP_INCLUDED
#define FCPPT_MPL_MAP_OBJECT_CONCEPT_HPP_INCLUDED
#include <fcppt/mpl/map/is_object.hpp>
namespace fcppt::mpl::map
{
/**
\brief Concept for maps.
\ingroup fcpptmpl
\see fcppt::mpl::map::is_object
*/
template<typename T>
concept object_concept = fcppt::mpl::map::is_object<T>::value;
}
#endif
|
VVmartseniuk/zafira-ui
|
client/app/_auth/bg-instance/bg-instance.directive.js
|
(function () {
'use strict';
angular.module('app.bgInstance').directive('bgInstance', function () {
return {
template: require('./bg-instance.html'),
restrict: 'E',
replace: true,
};
});
})();
|
delay-tolerant-networking/DTN2
|
servlib/security/Ciphersuite_BA9.h
|
/*
* Copyright 2006 SPARTA 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.
*/
#ifndef _CIPHERSUITE_BA9_H_
#define _CIPHERSUITE_BA9_H_
#ifdef BSP_ENABLED
#include "bundling/BlockProcessor.h"
#include "BA_BlockProcessor.h"
#include "Ciphersuite_BA.h"
namespace dtn {
/**
* Block processor implementation for the Bundle Authentication Block
*/
class Ciphersuite_BA9 : public Ciphersuite_BA {
public:
const static int CSNUM_BA = 9;
virtual u_int16_t cs_num() {
return CSNUM_BA;
};
const static int RESULT_LEN = 48;
virtual size_t result_len() {
return RESULT_LEN;
}
private:
};
} // namespace dtn
#endif /* BSP_ENABLED */
#endif /* _CIPHERSUITE_BA9_H_ */
|
dushmis/linux-pam
|
modules/pam_warn/pam_warn.c
|
/* pam_warn module */
/*
* $Id$
*
* Written by <NAME> <<EMAIL>> 1996/3/11
*/
#include "config.h"
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
#include <stdarg.h>
/*
* here, we make a definition for the externally accessible function
* in this file (this definition is required for static a module
* but strongly encouraged generally) it is used to instruct the
* modules include file to define the function prototypes.
*/
#define PAM_SM_AUTH
#define PAM_SM_PASSWORD
#include <security/pam_modules.h>
#include <security/pam_ext.h>
/* some syslogging */
#define OBTAIN(item, value, default_value) do { \
(void) pam_get_item(pamh, item, &value); \
value = value ? value : default_value ; \
} while (0)
static void log_items(pam_handle_t *pamh, const char *function, int flags)
{
const void *service=NULL, *user=NULL, *terminal=NULL,
*rhost=NULL, *ruser=NULL;
OBTAIN(PAM_SERVICE, service, "<unknown>");
OBTAIN(PAM_TTY, terminal, "<unknown>");
OBTAIN(PAM_USER, user, "<unknown>");
OBTAIN(PAM_RUSER, ruser, "<unknown>");
OBTAIN(PAM_RHOST, rhost, "<unknown>");
pam_syslog(pamh, LOG_NOTICE,
"function=[%s] flags=%#x service=[%s] terminal=[%s] user=[%s]"
" ruser=[%s] rhost=[%s]\n", function, flags,
(const char *) service, (const char *) terminal,
(const char *) user, (const char *) ruser,
(const char *) rhost);
}
/* --- authentication management functions (only) --- */
int pam_sm_authenticate(pam_handle_t *pamh, int flags,
int argc UNUSED, const char **argv UNUSED)
{
log_items(pamh, __FUNCTION__, flags);
return PAM_IGNORE;
}
int pam_sm_setcred(pam_handle_t *pamh, int flags,
int argc UNUSED, const char **argv UNUSED)
{
log_items(pamh, __FUNCTION__, flags);
return PAM_IGNORE;
}
/* password updating functions */
int pam_sm_chauthtok(pam_handle_t *pamh, int flags,
int argc UNUSED, const char **argv UNUSED)
{
log_items(pamh, __FUNCTION__, flags);
return PAM_IGNORE;
}
int
pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
int argc UNUSED, const char **argv UNUSED)
{
log_items(pamh, __FUNCTION__, flags);
return PAM_IGNORE;
}
int
pam_sm_open_session(pam_handle_t *pamh, int flags,
int argc UNUSED, const char **argv UNUSED)
{
log_items(pamh, __FUNCTION__, flags);
return PAM_IGNORE;
}
int
pam_sm_close_session(pam_handle_t *pamh, int flags,
int argc UNUSED, const char **argv UNUSED)
{
log_items(pamh, __FUNCTION__, flags);
return PAM_IGNORE;
}
/* end of module definition */
|
lukehb/137-roi
|
src/main/java/onethreeseven/roi/model/RoIGrid.java
|
<reponame>lukehb/137-roi
package onethreeseven.roi.model;
import onethreeseven.common.util.Maths;
import onethreeseven.common.util.NDUtil;
import onethreeseven.roi.algorithm.AbstractRoIMining;
import onethreeseven.trajsuitePlugin.model.BoundingCoordinates;
import onethreeseven.trajsuitePlugin.util.BoundsUtil;
import java.util.*;
import java.util.stream.Collectors;
/**
* A grid which can have the density of its grid cells tracked.
* This is a requirement for RoI mining.
* @see AbstractRoIMining
* @author <NAME>
*/
public class RoIGrid extends Grid implements RoIMiningSpace {
private final Map<Integer, RoIGridCell> gridCells;
/**
* Creates a new roi grid using a specified n-d grid
* This constructor is typically called by {@link MiningSpaceFactory}.
*
* @param grid the n-d grid
* @see MiningSpaceFactory
*/
RoIGrid(Grid grid) {
super(grid.nCellsPerDimension, grid.getBounds());
this.gridCells = new HashMap<>();
}
private int getIdx(int[] indices) {
return NDUtil.flattenIndices(indices, this.nCellsPerDimension);
}
/**
* Increment the density of the cell at the position specified by the indices.
* If no cell exists, makes one and sets the density to one.
*
* @param entityId the entity that was in this cell
* @param index the index of the cell in question
*/
public void incrementCellDensity(String entityId, int index) {
RoIGridCell cell = gridCells.get(index);
if (cell == null) {
//make grid cell
RoIGridCell roIGridCell = new RoIGridCell(index, NDUtil.inflateIndex(index, this.nCellsPerDimension));
roIGridCell.incrementTally(entityId);
putCell(roIGridCell);
} else {
//already exists just increment
cell.incrementTally(entityId);
}
}
/**
* Add a grid cell, overrides any existing entry for this cell
*
* @param roIGridCell the grid cell to add
*/
private void putCell(RoIGridCell roIGridCell) {
this.gridCells.put(roIGridCell.getIndex(), roIGridCell);
}
public RoIGridCell moveToCell(int[] startIndices, int[] offset) {
int[] moved = new int[startIndices.length];
for (int i = 0; i < startIndices.length; i++) {
moved[i] = startIndices[i] + offset[i];
if (moved[i] > nCellsPerDimension[i] - 1 || moved[i] < 0) {
//out of bounds
return null;
}
}
return getCell(moved);
}
@Override
public RoIGridCell getCell(int[] indices) {
return gridCells.get(getIdx(indices));
}
@Override
public void unprocessAll() {
for (RoIGridCell cell : gridCells.values()) {
cell.markUnprocessed();
}
}
@Override
public Collection<? extends MiningCell> getDenseCells() {
//get the dense cells (but only unprocessed ones)
List<? extends MiningCell> unprocessedCells = gridCells.values().stream()
.filter(miningCell -> !miningCell.isProcessed()).sorted((o1, o2) -> o2.getDensity() - o1.getDensity()).collect(Collectors.toList());
return unprocessedCells;
}
/**
* Given a collection of 1d indices inflate them all into n-d indices
*
* @param indices the 1d indices
* @return the n-d indices
*/
public int[][] getNdIndices(Collection<Integer> indices) {
int[][] ndIndices = new int[indices.size()][nDimensions()];
int i = 0;
for (Integer index1d : indices) {
ndIndices[i] = NDUtil.inflateIndex(index1d, nCellsPerDimension);
i++;
}
return ndIndices;
}
@Override
public Collection<MiningCell> getNeighbourCells(MiningCell queryCell) {
RoIGridCell start = (RoIGridCell) queryCell;
int nDimensions = nDimensions();
Collection<MiningCell> neighbourCells = new ArrayList<>(nDimensions * 2);
//check up and down in each dimension
for (int n = 0; n < nDimensions; n++) {
int[] up = new int[nDimensions];
up[n] = 1;
int[] down = new int[nDimensions];
down[n] = -1;
RoIGridCell movedUp = moveToCell(start.getIndices(), up);
RoIGridCell movedDown = moveToCell(start.getIndices(), down);
if (movedUp != null) {
neighbourCells.add(movedUp);
}
if (movedDown != null) {
neighbourCells.add(movedDown);
}
}
return neighbourCells;
}
@Override
public RoI removeSparsity(RoI roi) {
//remove sparsity by getting the index bounds of the RoI
//then filling in the all cells in between
int[][] cellIndices = getNdIndices(roi.getCells());
int[][] indexBounds = BoundsUtil.calculateBounds(cellIndices);
int nDimensions = indexBounds.length;
//get extreme indices based on bounds
int[] min = new int[nDimensions];
int[] max = new int[nDimensions];
int[] shape = new int[nDimensions];
for (int n = 0; n < nDimensions; n++) {
min[n] = indexBounds[n][0];
max[n] = indexBounds[n][1];
shape[n] = max[n] - min[n] + 1;
}
int[] indices = fitIndicesIntoDimensions(shape, min, max);
//make the new roi with all indices filled in
RoI denseRoI = new RoI(roi.getId());
for (int index1d : indices) {
MiningCell cell = getCell(index1d);
//if no cell available here, because this is method
//must remove sparsity it may require a cell to be made
if (cell == null) {
cell = new RoIGridCell(index1d, super.toNdIdx(index1d));
//have to add it in the grid (with zero density) for processing reasons
this.putCell((RoIGridCell) cell);
}
denseRoI.add(cell);
}
return denseRoI;
}
/**
* Get the centroid coordinate from an roi using its cells (assuming the roi is from this grid).
* @param roi The roi the get the centroid coordinates of.
* @return The centroid coordinates of the RoI.
*/
public double[] getCentroid(RoI roi){
int nRois = roi.size();
double[][] allCentroids = new double[nRois][2];
int i = 0;
for (Integer cellId : roi.getCells()) {
BoundingCoordinates cellBounds = this.getCellBounds(cellId);
if(cellBounds != null){
allCentroids[i] = BoundsUtil.getCenter(cellBounds.getBounds());
}
i++;
}
return Maths.medoid(allCentroids);
}
@Override
public MiningCell getCell(int idx) {
return gridCells.get(idx);
}
/**
* Once the grid has been populated with dense cells we want to know the maximum possible cell density
*
* @return maximum possible cell density
*/
public int getMaxPossibleDensity() {
HashSet<String> possibleEntityIds = new HashSet<>();
for (RoIGridCell cell : gridCells.values()) {
possibleEntityIds.addAll(cell.getKeys());
}
return possibleEntityIds.size();
}
@Override
public String toString(){
StringBuilder str = new StringBuilder("RoI Grid(");
for (int i = 0; i < nCellsPerDimension.length; i++) {
str.append(String.valueOf(nCellsPerDimension[i]));
if(i != nCellsPerDimension.length - 1){
str.append("x");
}
}
str.append(")");
return str.toString();
}
}
|
UKGovernmentBEIS/beis-psd
|
spec/factories/location.rb
|
FactoryBot.define do
factory :location do
association :business
name { "Registered office" }
address_line_1 { Faker::Address.street_address }
address_line_2 { Faker::Address.community }
city { Faker::Address.city }
country { Faker::Address.country }
county { Faker::Address.state }
phone_number { Faker::PhoneNumber.phone_number }
postal_code { Faker::Address.postcode }
end
end
|
miguel-kjh/ReID-in-Sport-competitions
|
img2pose/train.py
|
<reponame>miguel-kjh/ReID-in-Sport-competitions
import argparse
import random
from os import path
import numpy as np
import torch
from torch import optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.tensorboard import SummaryWriter
from config import Config
from data_loader_lmdb import LMDBDataLoader
from data_loader_lmdb_augmenter import LMDBDataLoaderAugmenter
from early_stop import EarlyStop
from img2pose import img2poseModel
from model_loader import load_model, save_model
from train_logger import TrainLogger
from utils.dist import init_distributed_mode, reduce_dict
class Train:
def __init__(self, config):
self.config = config
# start tensorboard summary writer
self.writer = SummaryWriter(config.log_path)
# load training dataset generator
if self.config.random_flip or self.config.random_crop:
self.train_loader = LMDBDataLoaderAugmenter(
self.config, self.config.train_source
)
else:
self.train_loader = LMDBDataLoader(self.config, self.config.train_source)
print(f"Training with {len(self.train_loader.dataset)} images.")
# loads validation dataset generator if a validation dataset is given
if self.config.val_source is not None:
self.val_loader = LMDBDataLoader(self.config, self.config.val_source, False)
# creates model
self.img2pose_model = img2poseModel(
depth=self.config.depth,
min_size=self.config.min_size,
max_size=self.config.max_size,
device=self.config.device,
pose_mean=self.config.pose_mean,
pose_stddev=self.config.pose_stddev,
distributed=self.config.distributed,
gpu=self.config.gpu,
threed_68_points=np.load(self.config.threed_68_points),
threed_5_points=np.load(self.config.threed_5_points),
)
# optimizer for the backbone and heads
if args.optimizer == "Adam":
self.optimizer = optim.Adam(
self.img2pose_model.fpn_model.parameters(),
lr=self.config.lr,
weight_decay=self.config.weight_decay,
)
elif args.optimizer == "SGD":
self.optimizer = optim.SGD(
self.img2pose_model.fpn_model.parameters(),
lr=self.config.lr,
weight_decay=self.config.weight_decay,
momentum=self.config.momentum,
)
else:
raise Exception("No optimizer founded, please select between SGD or Adam.")
# loads a model with optimizer so that it can continue training where it stopped
if self.config.resume_path:
print(f"Resuming training from {self.config.resume_path}")
load_model(
self.img2pose_model.fpn_model,
self.config.resume_path,
model_only=False,
optimizer=self.optimizer,
cpu_mode=str(self.config.device) == "cpu",
)
# loads a pretrained model without loading the optimizer
if self.config.pretrained_path:
print(f"Loading pretrained weights from {self.config.pretrained_path}")
load_model(
self.img2pose_model.fpn_model,
self.config.pretrained_path,
model_only=True,
cpu_mode=str(self.config.device) == "cpu",
)
# saves configuration to file for easier retrival later
print(self.config)
self.save_file(self.config, "config.txt")
# saves optimizer config to file for easier retrival later
print(self.optimizer)
self.save_file(self.optimizer, "optimizer.txt")
self.tensorboard_loss_every = max(len(self.train_loader) // 100, 1)
# self.evaluate_every = max(len(self.train_loader) // 1, 1)
# reduce learning rate when the validation loss stops to decrease
if self.config.lr_plateau:
self.scheduler = ReduceLROnPlateau(
self.optimizer,
mode="min",
factor=0.1,
patience=3,
verbose=True,
threshold=0.001,
cooldown=1,
min_lr=0.00001,
)
# stops training before the defined epochs if validation loss stops to decrease
if self.config.early_stop:
self.early_stop = EarlyStop(mode="min", patience=5)
def run(self):
self.img2pose_model.train()
# accumulate running loss to log into tensorboard
running_losses = {}
running_losses["loss"] = 0
step = 0
# prints the best step and loss every time it does a validation
self.best_step = 0
self.best_val_loss = float("Inf")
for epoch in range(self.config.epochs):
train_logger = TrainLogger(
self.config.batch_size, self.config.frequency_log
)
idx = 0
for idx, data in enumerate(self.train_loader):
imgs, targets = data
imgs = [image.to(self.config.device) for image in imgs]
targets = [
{k: v.to(self.config.device) for k, v in t.items()} for t in targets
]
self.optimizer.zero_grad()
# forward pass
losses = self.img2pose_model.forward(imgs, targets)
loss = sum(loss for loss in losses.values())
# does a backward propagation through the network
loss.backward()
torch.nn.utils.clip_grad_norm_(
self.img2pose_model.fpn_model.parameters(), 10
)
self.optimizer.step()
if self.config.distributed:
losses = reduce_dict(losses)
loss = sum(loss for loss in losses.values())
for loss_name in losses.keys():
if loss_name in running_losses:
running_losses[loss_name] += losses[loss_name].item()
else:
running_losses[loss_name] = losses[loss_name].item()
running_losses["loss"] += loss.item()
# saves loss into tensorboard
if step % self.tensorboard_loss_every == 0 and step != 0:
for loss_name in running_losses.keys():
self.writer.add_scalar(
f"train_{loss_name}",
running_losses[loss_name] / self.tensorboard_loss_every,
step,
)
running_losses[loss_name] = 0
train_logger(
epoch, self.config.epochs, idx, len(self.train_loader), loss.item()
)
step += 1
# evaluate model using validation set (if set)
if self.config.val_source is not None:
val_loss = self.evaluate(step)
else:
# otherwise just save the model
save_model(
self.img2pose_model.fpn_model_without_ddp,
self.optimizer,
self.config,
step=step,
)
# if validation loss stops decreasing, decrease lr
if self.config.lr_plateau and self.config.val_source is not None:
self.scheduler.step(val_loss)
# early stop model to prevent overfitting
if self.config.early_stop and self.config.val_source is not None:
self.early_stop(val_loss)
if self.early_stop.stop:
print("Early stopping model...")
break
if self.config.val_source is not None:
val_loss = self.evaluate(step)
def checkpoint(self, val_loss, step):
if val_loss < self.best_val_loss:
self.best_val_loss = val_loss
self.best_step = step
save_model(
self.img2pose_model.fpn_model_without_ddp,
self.optimizer,
self.config,
val_loss,
step,
)
def reduce_lr(self):
for params in self.optimizer.param_groups:
params["lr"] /= 10
print("Reducing learning rate...")
print(self.optimizer)
def evaluate(self, step):
val_losses = {}
val_losses["loss"] = 0
print("Evaluating model...")
with torch.no_grad():
for data in iter(self.val_loader):
imgs, targets = data
imgs = [image.to(self.config.device) for image in imgs]
targets = [
{k: v.to(self.config.device) for k, v in t.items()} for t in targets
]
if self.config.distributed:
torch.cuda.synchronize()
losses = self.img2pose_model.forward(imgs, targets)
if self.config.distributed:
losses = reduce_dict(losses)
loss = sum(loss for loss in losses.values())
for loss_name in losses.keys():
if loss_name in val_losses:
val_losses[loss_name] += losses[loss_name].item()
else:
val_losses[loss_name] = losses[loss_name].item()
val_losses["loss"] += loss.item()
for loss_name in val_losses.keys():
self.writer.add_scalar(
f"val_{loss_name}",
round(val_losses[loss_name] / len(self.val_loader), 6),
step,
)
val_loss = round(val_losses["loss"] / len(self.val_loader), 6)
self.checkpoint(val_loss, step)
print(
"Current validation loss: "
+ f"{val_loss:.6f} at step {step}"
+ " - Best validation loss: "
+ f"{self.best_val_loss:.6f} at step {self.best_step}"
)
self.img2pose_model.train()
return val_loss
def save_file(self, string, file_name):
with open(path.join(self.config.work_path, file_name), "w") as file:
file.write(str(string))
file.close()
def parse_args():
parser = argparse.ArgumentParser(
description="Train a deep network to predict 3D expression and 6DOF pose."
)
# network and training parameters
parser.add_argument(
"--min_size", help="Min size", default=(640, 672, 704, 736, 768, 800), type=int
)
parser.add_argument("--max_size", help="Max size", default=1400, type=int)
parser.add_argument("--epochs", help="Number of epochs.", default=100, type=int)
parser.add_argument(
"--depth", help="Number of layers [18, 50 or 101].", default=18, type=int
)
parser.add_argument("--lr", help="Learning rate.", default=0.001, type=float)
parser.add_argument(
"--optimizer", help="Optimizer (SGD or Adam).", default="SGD", type=str
)
parser.add_argument("--batch_size", help="Batch size.", default=2, type=int)
parser.add_argument(
"--lr_plateau", help="Reduce lr on plateau.", action="store_true"
)
parser.add_argument("--early_stop", help="Use early stop.", action="store_true")
parser.add_argument("--workers", help="Workers number.", default=4, type=int)
parser.add_argument(
"--pose_mean", help="Pose mean file path.", type=str, required=True
)
parser.add_argument(
"--pose_stddev", help="Pose stddev file path.", type=str, required=True
)
# training/validation configuration
parser.add_argument(
"--workspace", help="Worskspace path to save models and logs.", required=True
)
parser.add_argument(
"--train_source", help="Path to the dataset train LMDB file.", required=True
)
parser.add_argument(
"--val_source", help="Path to the dataset validation LMDB file."
)
parser.add_argument(
"--prefix", help="Prefix to save the model.", type=str, required=True
)
# resume from or load pretrained weights
parser.add_argument(
"--pretrained_path", help="Path to pretrained weights.", type=str
)
parser.add_argument(
"--resume_path", help="Path to load model to resume training.", type=str
)
# online augmentation
parser.add_argument("--noise_augmentation", action="store_true")
parser.add_argument("--contrast_augmentation", action="store_true")
parser.add_argument("--random_flip", action="store_true")
parser.add_argument("--random_crop", action="store_true")
# distributed training parameters
parser.add_argument(
"--world-size", default=1, type=int, help="number of distributed processes"
)
parser.add_argument(
"--dist-url", default="env://", help="url used to set up distributed training"
)
parser.add_argument(
"--distributed", help="Use distributed training", action="store_true"
)
# reference points to create pose labels
parser.add_argument(
"--threed_5_points",
type=str,
help="Reference 3D points to compute pose.",
default="./pose_references/reference_3d_5_points_trans.npy",
)
parser.add_argument(
"--threed_68_points",
type=str,
help="Reference 3D points to compute pose.",
default="./pose_references/reference_3d_68_points_trans.npy",
)
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
if args.distributed:
init_distributed_mode(args)
config = Config(args)
torch.manual_seed(42)
np.random.seed(42)
random.seed(42)
train = Train(config)
train.run()
|
Grundkurs/LTBL2
|
docs/search/pages_0.js
|
<reponame>Grundkurs/LTBL2<filename>docs/search/pages_0.js<gh_stars>1-10
var searchData=
[
['ltbl2',['LTBL2',['../md__d_1__c_09_09__v_s__l_t_b_l2__l_t_b_l2__l_i_c_e_n_s_e.html',1,'']]],
['let_20there_20be_20light_202',['Let There Be Light 2',['../md__d_1__c_09_09__v_s__l_t_b_l2__l_t_b_l2__r_e_a_d_m_e.html',1,'']]]
];
|
fergy/aplit_linux-5
|
drivers/regulator/pv88080-regulator.c
|
<filename>drivers/regulator/pv88080-regulator.c
/*
* pv88080-regulator.c - Regulator device driver for PV88080
* Copyright (C) 2016 Powerventure Semiconductor Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/regmap.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/regulator/of_regulator.h>
#include "pv88080-regulator.h"
#define PV88080_MAX_REGULATORS 4
/* PV88080 REGULATOR IDs */
enum {
/* BUCKs */
PV88080_ID_BUCK1,
PV88080_ID_BUCK2,
PV88080_ID_BUCK3,
PV88080_ID_HVBUCK,
};
enum pv88080_types {
TYPE_PV88080_AA,
TYPE_PV88080_BA,
};
struct pv88080_regulator {
struct regulator_desc desc;
unsigned int mode_reg;
unsigned int conf2;
unsigned int conf5;
};
struct pv88080 {
struct device *dev;
struct regmap *regmap;
struct regulator_dev *rdev[PV88080_MAX_REGULATORS];
unsigned long type;
const struct pv88080_compatible_regmap *regmap_config;
};
struct pv88080_buck_voltage {
int min_uV;
int max_uV;
int uV_step;
};
struct pv88080_buck_regmap {
/* REGS */
int buck_enable_reg;
int buck_vsel_reg;
int buck_mode_reg;
int buck_limit_reg;
int buck_vdac_range_reg;
int buck_vrange_gain_reg;
/* MASKS */
int buck_enable_mask;
int buck_vsel_mask;
int buck_limit_mask;
};
struct pv88080_compatible_regmap {
/* BUCK1, 2, 3 */
struct pv88080_buck_regmap buck_regmap[PV88080_MAX_REGULATORS-1];
/* HVBUCK */
int hvbuck_enable_reg;
int hvbuck_vsel_reg;
int hvbuck_enable_mask;
int hvbuck_vsel_mask;
};
static const struct regmap_config pv88080_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
};
/* Current limits array (in uA) for BUCK1, BUCK2, BUCK3.
* Entry indexes corresponds to register values.
*/
static const unsigned int pv88080_buck1_limits[] = {
3230000, 5130000, 6960000, 8790000
};
static const unsigned int pv88080_buck23_limits[] = {
1496000, 2393000, 3291000, 4189000
};
static const struct pv88080_buck_voltage pv88080_buck_vol[2] = {
{
.min_uV = 600000,
.max_uV = 1393750,
.uV_step = 6250,
},
{
.min_uV = 1400000,
.max_uV = 2193750,
.uV_step = 6250,
},
};
static const struct pv88080_compatible_regmap pv88080_aa_regs = {
/* BUCK1 */
.buck_regmap[0] = {
.buck_enable_reg = PV88080AA_REG_BUCK1_CONF0,
.buck_vsel_reg = PV88080AA_REG_BUCK1_CONF0,
.buck_mode_reg = PV88080AA_REG_BUCK1_CONF1,
.buck_limit_reg = PV88080AA_REG_BUCK1_CONF1,
.buck_vdac_range_reg = PV88080AA_REG_BUCK1_CONF2,
.buck_vrange_gain_reg = PV88080AA_REG_BUCK1_CONF5,
.buck_enable_mask = PV88080_BUCK1_EN,
.buck_vsel_mask = PV88080_VBUCK1_MASK,
.buck_limit_mask = PV88080_BUCK1_ILIM_MASK,
},
/* BUCK2 */
.buck_regmap[1] = {
.buck_enable_reg = PV88080AA_REG_BUCK2_CONF0,
.buck_vsel_reg = PV88080AA_REG_BUCK2_CONF0,
.buck_mode_reg = PV88080AA_REG_BUCK2_CONF1,
.buck_limit_reg = PV88080AA_REG_BUCK2_CONF1,
.buck_vdac_range_reg = PV88080AA_REG_BUCK2_CONF2,
.buck_vrange_gain_reg = PV88080AA_REG_BUCK2_CONF5,
.buck_enable_mask = PV88080_BUCK2_EN,
.buck_vsel_mask = PV88080_VBUCK2_MASK,
.buck_limit_mask = PV88080_BUCK2_ILIM_MASK,
},
/* BUCK3 */
.buck_regmap[2] = {
.buck_enable_reg = PV88080AA_REG_BUCK3_CONF0,
.buck_vsel_reg = PV88080AA_REG_BUCK3_CONF0,
.buck_mode_reg = PV88080AA_REG_BUCK3_CONF1,
.buck_limit_reg = PV88080AA_REG_BUCK3_CONF1,
.buck_vdac_range_reg = PV88080AA_REG_BUCK3_CONF2,
.buck_vrange_gain_reg = PV88080AA_REG_BUCK3_CONF5,
.buck_enable_mask = PV88080_BUCK3_EN,
.buck_vsel_mask = PV88080_VBUCK3_MASK,
.buck_limit_mask = PV88080_BUCK3_ILIM_MASK,
},
/* HVBUCK */
.hvbuck_enable_reg = PV88080AA_REG_HVBUCK_CONF2,
.hvbuck_vsel_reg = PV88080AA_REG_HVBUCK_CONF1,
.hvbuck_enable_mask = PV88080_HVBUCK_EN,
.hvbuck_vsel_mask = PV88080_VHVBUCK_MASK,
};
static const struct pv88080_compatible_regmap pv88080_ba_regs = {
/* BUCK1 */
.buck_regmap[0] = {
.buck_enable_reg = PV88080BA_REG_BUCK1_CONF0,
.buck_vsel_reg = PV88080BA_REG_BUCK1_CONF0,
.buck_mode_reg = PV88080BA_REG_BUCK1_CONF1,
.buck_limit_reg = PV88080BA_REG_BUCK1_CONF1,
.buck_vdac_range_reg = PV88080BA_REG_BUCK1_CONF2,
.buck_vrange_gain_reg = PV88080BA_REG_BUCK1_CONF5,
.buck_enable_mask = PV88080_BUCK1_EN,
.buck_vsel_mask = PV88080_VBUCK1_MASK,
.buck_limit_mask = PV88080_BUCK1_ILIM_MASK,
},
/* BUCK2 */
.buck_regmap[1] = {
.buck_enable_reg = PV88080BA_REG_BUCK2_CONF0,
.buck_vsel_reg = PV88080BA_REG_BUCK2_CONF0,
.buck_mode_reg = PV88080BA_REG_BUCK2_CONF1,
.buck_limit_reg = PV88080BA_REG_BUCK2_CONF1,
.buck_vdac_range_reg = PV88080BA_REG_BUCK2_CONF2,
.buck_vrange_gain_reg = PV88080BA_REG_BUCK2_CONF5,
.buck_enable_mask = PV88080_BUCK2_EN,
.buck_vsel_mask = PV88080_VBUCK2_MASK,
.buck_limit_mask = PV88080_BUCK2_ILIM_MASK,
},
/* BUCK3 */
.buck_regmap[2] = {
.buck_enable_reg = PV88080BA_REG_BUCK3_CONF0,
.buck_vsel_reg = PV88080BA_REG_BUCK3_CONF0,
.buck_mode_reg = PV88080BA_REG_BUCK3_CONF1,
.buck_limit_reg = PV88080BA_REG_BUCK3_CONF1,
.buck_vdac_range_reg = PV88080BA_REG_BUCK3_CONF2,
.buck_vrange_gain_reg = PV88080BA_REG_BUCK3_CONF5,
.buck_enable_mask = PV88080_BUCK3_EN,
.buck_vsel_mask = PV88080_VBUCK3_MASK,
.buck_limit_mask = PV88080_BUCK3_ILIM_MASK,
},
/* HVBUCK */
.hvbuck_enable_reg = PV88080BA_REG_HVBUCK_CONF2,
.hvbuck_vsel_reg = PV88080BA_REG_HVBUCK_CONF1,
.hvbuck_enable_mask = PV88080_HVBUCK_EN,
.hvbuck_vsel_mask = PV88080_VHVBUCK_MASK,
};
#ifdef CONFIG_OF
static const struct of_device_id pv88080_dt_ids[] = {
{ .compatible = "pvs,pv88080", .data = (void *)TYPE_PV88080_AA },
{ .compatible = "pvs,pv88080-aa", .data = (void *)TYPE_PV88080_AA },
{ .compatible = "pvs,pv88080-ba", .data = (void *)TYPE_PV88080_BA },
{},
};
MODULE_DEVICE_TABLE(of, pv88080_dt_ids);
#endif
static unsigned int pv88080_buck_get_mode(struct regulator_dev *rdev)
{
struct pv88080_regulator *info = rdev_get_drvdata(rdev);
unsigned int data;
int ret, mode = 0;
ret = regmap_read(rdev->regmap, info->mode_reg, &data);
if (ret < 0)
return ret;
switch (data & PV88080_BUCK1_MODE_MASK) {
case PV88080_BUCK_MODE_SYNC:
mode = REGULATOR_MODE_FAST;
break;
case PV88080_BUCK_MODE_AUTO:
mode = REGULATOR_MODE_NORMAL;
break;
case PV88080_BUCK_MODE_SLEEP:
mode = REGULATOR_MODE_STANDBY;
break;
default:
return -EINVAL;
}
return mode;
}
static int pv88080_buck_set_mode(struct regulator_dev *rdev,
unsigned int mode)
{
struct pv88080_regulator *info = rdev_get_drvdata(rdev);
int val = 0;
switch (mode) {
case REGULATOR_MODE_FAST:
val = PV88080_BUCK_MODE_SYNC;
break;
case REGULATOR_MODE_NORMAL:
val = PV88080_BUCK_MODE_AUTO;
break;
case REGULATOR_MODE_STANDBY:
val = PV88080_BUCK_MODE_SLEEP;
break;
default:
return -EINVAL;
}
return regmap_update_bits(rdev->regmap, info->mode_reg,
PV88080_BUCK1_MODE_MASK, val);
}
static const struct regulator_ops pv88080_buck_ops = {
.get_mode = pv88080_buck_get_mode,
.set_mode = pv88080_buck_set_mode,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
.is_enabled = regulator_is_enabled_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.list_voltage = regulator_list_voltage_linear,
.set_current_limit = regulator_set_current_limit_regmap,
.get_current_limit = regulator_get_current_limit_regmap,
};
static const struct regulator_ops pv88080_hvbuck_ops = {
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
.is_enabled = regulator_is_enabled_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.list_voltage = regulator_list_voltage_linear,
};
#define PV88080_BUCK(chip, regl_name, min, step, max, limits_array) \
{\
.desc = {\
.id = chip##_ID_##regl_name,\
.name = __stringify(chip##_##regl_name),\
.of_match = of_match_ptr(#regl_name),\
.regulators_node = of_match_ptr("regulators"),\
.type = REGULATOR_VOLTAGE,\
.owner = THIS_MODULE,\
.ops = &pv88080_buck_ops,\
.min_uV = min, \
.uV_step = step, \
.n_voltages = ((max) - (min))/(step) + 1, \
.curr_table = limits_array, \
.n_current_limits = ARRAY_SIZE(limits_array), \
},\
}
#define PV88080_HVBUCK(chip, regl_name, min, step, max) \
{\
.desc = {\
.id = chip##_ID_##regl_name,\
.name = __stringify(chip##_##regl_name),\
.of_match = of_match_ptr(#regl_name),\
.regulators_node = of_match_ptr("regulators"),\
.type = REGULATOR_VOLTAGE,\
.owner = THIS_MODULE,\
.ops = &pv88080_hvbuck_ops,\
.min_uV = min, \
.uV_step = step, \
.n_voltages = ((max) - (min))/(step) + 1, \
},\
}
static struct pv88080_regulator pv88080_regulator_info[] = {
PV88080_BUCK(PV88080, BUCK1, 600000, 6250, 1393750,
pv88080_buck1_limits),
PV88080_BUCK(PV88080, BUCK2, 600000, 6250, 1393750,
pv88080_buck23_limits),
PV88080_BUCK(PV88080, BUCK3, 600000, 6250, 1393750,
pv88080_buck23_limits),
PV88080_HVBUCK(PV88080, HVBUCK, 0, 5000, 1275000),
};
static irqreturn_t pv88080_irq_handler(int irq, void *data)
{
struct pv88080 *chip = data;
int i, reg_val, err, ret = IRQ_NONE;
err = regmap_read(chip->regmap, PV88080_REG_EVENT_A, ®_val);
if (err < 0)
goto error_i2c;
if (reg_val & PV88080_E_VDD_FLT) {
for (i = 0; i < PV88080_MAX_REGULATORS; i++) {
if (chip->rdev[i] != NULL) {
regulator_notifier_call_chain(chip->rdev[i],
REGULATOR_EVENT_UNDER_VOLTAGE,
NULL);
}
}
err = regmap_write(chip->regmap, PV88080_REG_EVENT_A,
PV88080_E_VDD_FLT);
if (err < 0)
goto error_i2c;
ret = IRQ_HANDLED;
}
if (reg_val & PV88080_E_OVER_TEMP) {
for (i = 0; i < PV88080_MAX_REGULATORS; i++) {
if (chip->rdev[i] != NULL) {
regulator_notifier_call_chain(chip->rdev[i],
REGULATOR_EVENT_OVER_TEMP,
NULL);
}
}
err = regmap_write(chip->regmap, PV88080_REG_EVENT_A,
PV88080_E_OVER_TEMP);
if (err < 0)
goto error_i2c;
ret = IRQ_HANDLED;
}
return ret;
error_i2c:
dev_err(chip->dev, "I2C error : %d\n", err);
return IRQ_NONE;
}
/*
* I2C driver interface functions
*/
static int pv88080_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct regulator_init_data *init_data = dev_get_platdata(&i2c->dev);
struct pv88080 *chip;
const struct pv88080_compatible_regmap *regmap_config;
const struct of_device_id *match;
struct regulator_config config = { };
int i, error, ret;
unsigned int conf2, conf5;
chip = devm_kzalloc(&i2c->dev, sizeof(struct pv88080), GFP_KERNEL);
if (!chip)
return -ENOMEM;
chip->dev = &i2c->dev;
chip->regmap = devm_regmap_init_i2c(i2c, &pv88080_regmap_config);
if (IS_ERR(chip->regmap)) {
error = PTR_ERR(chip->regmap);
dev_err(chip->dev, "Failed to allocate register map: %d\n",
error);
return error;
}
if (i2c->dev.of_node) {
match = of_match_node(pv88080_dt_ids, i2c->dev.of_node);
if (!match) {
dev_err(chip->dev, "Failed to get of_match_node\n");
return -EINVAL;
}
chip->type = (unsigned long)match->data;
} else {
chip->type = id->driver_data;
}
i2c_set_clientdata(i2c, chip);
if (i2c->irq != 0) {
ret = regmap_write(chip->regmap, PV88080_REG_MASK_A, 0xFF);
if (ret < 0) {
dev_err(chip->dev,
"Failed to mask A reg: %d\n", ret);
return ret;
}
ret = regmap_write(chip->regmap, PV88080_REG_MASK_B, 0xFF);
if (ret < 0) {
dev_err(chip->dev,
"Failed to mask B reg: %d\n", ret);
return ret;
}
ret = regmap_write(chip->regmap, PV88080_REG_MASK_C, 0xFF);
if (ret < 0) {
dev_err(chip->dev,
"Failed to mask C reg: %d\n", ret);
return ret;
}
ret = devm_request_threaded_irq(&i2c->dev, i2c->irq, NULL,
pv88080_irq_handler,
IRQF_TRIGGER_LOW|IRQF_ONESHOT,
"pv88080", chip);
if (ret != 0) {
dev_err(chip->dev, "Failed to request IRQ: %d\n",
i2c->irq);
return ret;
}
ret = regmap_update_bits(chip->regmap, PV88080_REG_MASK_A,
PV88080_M_VDD_FLT | PV88080_M_OVER_TEMP, 0);
if (ret < 0) {
dev_err(chip->dev,
"Failed to update mask reg: %d\n", ret);
return ret;
}
} else {
dev_warn(chip->dev, "No IRQ configured\n");
}
switch (chip->type) {
case TYPE_PV88080_AA:
chip->regmap_config = &pv88080_aa_regs;
break;
case TYPE_PV88080_BA:
chip->regmap_config = &pv88080_ba_regs;
break;
}
regmap_config = chip->regmap_config;
config.dev = chip->dev;
config.regmap = chip->regmap;
/* Registeration for BUCK1, 2, 3 */
for (i = 0; i < PV88080_MAX_REGULATORS-1; i++) {
if (init_data)
config.init_data = &init_data[i];
pv88080_regulator_info[i].desc.csel_reg
= regmap_config->buck_regmap[i].buck_limit_reg;
pv88080_regulator_info[i].desc.csel_mask
= regmap_config->buck_regmap[i].buck_limit_mask;
pv88080_regulator_info[i].mode_reg
= regmap_config->buck_regmap[i].buck_mode_reg;
pv88080_regulator_info[i].conf2
= regmap_config->buck_regmap[i].buck_vdac_range_reg;
pv88080_regulator_info[i].conf5
= regmap_config->buck_regmap[i].buck_vrange_gain_reg;
pv88080_regulator_info[i].desc.enable_reg
= regmap_config->buck_regmap[i].buck_enable_reg;
pv88080_regulator_info[i].desc.enable_mask
= regmap_config->buck_regmap[i].buck_enable_mask;
pv88080_regulator_info[i].desc.vsel_reg
= regmap_config->buck_regmap[i].buck_vsel_reg;
pv88080_regulator_info[i].desc.vsel_mask
= regmap_config->buck_regmap[i].buck_vsel_mask;
ret = regmap_read(chip->regmap,
pv88080_regulator_info[i].conf2, &conf2);
if (ret < 0)
return ret;
conf2 = ((conf2 >> PV88080_BUCK_VDAC_RANGE_SHIFT) &
PV88080_BUCK_VDAC_RANGE_MASK);
ret = regmap_read(chip->regmap,
pv88080_regulator_info[i].conf5, &conf5);
if (ret < 0)
return ret;
conf5 = ((conf5 >> PV88080_BUCK_VRANGE_GAIN_SHIFT) &
PV88080_BUCK_VRANGE_GAIN_MASK);
pv88080_regulator_info[i].desc.min_uV =
pv88080_buck_vol[conf2].min_uV * (conf5+1);
pv88080_regulator_info[i].desc.uV_step =
pv88080_buck_vol[conf2].uV_step * (conf5+1);
pv88080_regulator_info[i].desc.n_voltages =
((pv88080_buck_vol[conf2].max_uV * (conf5+1))
- (pv88080_regulator_info[i].desc.min_uV))
/(pv88080_regulator_info[i].desc.uV_step) + 1;
config.driver_data = (void *)&pv88080_regulator_info[i];
chip->rdev[i] = devm_regulator_register(chip->dev,
&pv88080_regulator_info[i].desc, &config);
if (IS_ERR(chip->rdev[i])) {
dev_err(chip->dev,
"Failed to register PV88080 regulator\n");
return PTR_ERR(chip->rdev[i]);
}
}
pv88080_regulator_info[PV88080_ID_HVBUCK].desc.enable_reg
= regmap_config->hvbuck_enable_reg;
pv88080_regulator_info[PV88080_ID_HVBUCK].desc.enable_mask
= regmap_config->hvbuck_enable_mask;
pv88080_regulator_info[PV88080_ID_HVBUCK].desc.vsel_reg
= regmap_config->hvbuck_vsel_reg;
pv88080_regulator_info[PV88080_ID_HVBUCK].desc.vsel_mask
= regmap_config->hvbuck_vsel_mask;
/* Registeration for HVBUCK */
if (init_data)
config.init_data = &init_data[PV88080_ID_HVBUCK];
config.driver_data = (void *)&pv88080_regulator_info[PV88080_ID_HVBUCK];
chip->rdev[PV88080_ID_HVBUCK] = devm_regulator_register(chip->dev,
&pv88080_regulator_info[PV88080_ID_HVBUCK].desc, &config);
if (IS_ERR(chip->rdev[PV88080_ID_HVBUCK])) {
dev_err(chip->dev, "Failed to register PV88080 regulator\n");
return PTR_ERR(chip->rdev[PV88080_ID_HVBUCK]);
}
return 0;
}
static const struct i2c_device_id pv88080_i2c_id[] = {
{ "pv88080", TYPE_PV88080_AA },
{ "pv88080-aa", TYPE_PV88080_AA },
{ "pv88080-ba", TYPE_PV88080_BA },
{},
};
MODULE_DEVICE_TABLE(i2c, pv88080_i2c_id);
static struct i2c_driver pv88080_regulator_driver = {
.driver = {
.name = "pv88080",
.of_match_table = of_match_ptr(pv88080_dt_ids),
},
.probe = pv88080_i2c_probe,
.id_table = pv88080_i2c_id,
};
module_i2c_driver(pv88080_regulator_driver);
MODULE_AUTHOR("<NAME> <<EMAIL>>");
MODULE_DESCRIPTION("Regulator device driver for Powerventure PV88080");
MODULE_LICENSE("GPL");
|
ajb85/stinkfoot-FE
|
src/Badger/index.js
|
<reponame>ajb85/stinkfoot-FE
import $ from './Badger.js';
export default $;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.