repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
rapid7/raptor-io
|
spec/raptor-io/protocol/http/response_spec.rb
|
<gh_stars>1-10
#coding: utf-8
require 'spec_helper'
describe RaptorIO::Protocol::HTTP::Response do
it_should_behave_like 'RaptorIO::Protocol::HTTP::Message'
let(:url) { 'http://test.com' }
let(:response) do
"HTTP/1.1 404 Not Found\r\n" +
"Content-Type: text/html;charset=utf-8\r\n" +
"Content-Length: 27\r\n\r\n" +
"<!DOCTYPE html>\n" +
"More stuff\n".force_encoding( 'ASCII-8BIT')
end
let(:response_cr) do
"HTTP/1.1 404 Not Found\n" +
"Content-Type: text/html;charset=utf-8\n" +
"Content-Length: 27\n\n" +
"<!DOCTYPE html>\n" +
"More stuff\n".force_encoding( 'ASCII-8BIT')
end
it 'forces the body to UTF-8' do
described_class.parse( response ).body.encoding.to_s.should == 'UTF-8'
described_class.new( body: "stuff τεστblah" ).body.should == 'stuff τεστblah'
end
describe '#text?' do
context 'when the content-type is' do
context 'text/*' do
it 'returns true' do
h = {
headers: { 'Content-Type' => 'text/stuff' },
body: "stuff"
}
described_class.new( h ).text?.should be_true
end
end
context 'application/*' do
context 'and the response body is' do
context 'binary' do
it 'returns false' do
h = {
headers: { 'Content-Type' => 'application/stuff' },
body: "\00\00\00"
}
described_class.new( h ).text?.should be_false
end
end
context 'text' do
it 'returns true' do
h = {
headers: { 'Content-Type' => 'application/stuff' },
body: "stuff"
}
described_class.new( h ).text?.should be_true
end
end
end
end
context 'other' do
it 'returns false' do
h = {
headers: { 'Content-Type' => 'blah/stuff' },
body: "stuff"
}
described_class.new( h ).text?.should be_false
end
end
context nil do
context 'and the response body is' do
context 'binary' do
it 'returns false' do
h = { body: "\00\00\00" }
described_class.new( h ).text?.should be_false
end
end
context 'text' do
it 'returns true' do
h = { body: "stuff" }
described_class.new( h ).text?.should be_true
end
end
end
end
end
end
describe '#code' do
it 'returns the HTTP status code' do
described_class.new( url: url, code: 200 ).code.should == 200
end
it 'defaults to 0' do
described_class.new( url: url ).code.should == 0
end
end
describe '#body' do
it 'returns the HTTP response body' do
described_class.parse( response ).body.should == "<!DOCTYPE html>\nMore stuff\n"
end
it 'is forced to UTF8' do
described_class.parse( response ).body.encoding.to_s.should == 'UTF-8'
end
end
describe '#redirect?' do
context 'when the code is in the 3xx family' do
context 'and there is a Location in the headers' do
it 'returns true' do
300.upto( 399 ) do |code|
described_class.new(
url: url,
code: code,
headers: { 'Location' => url }
).redirect?.should be_true
end
end
end
context 'and there is no Location in the headers' do
it 'returns false' do
300.upto( 399 ) do |code|
described_class.new(
url: url,
code: code
).redirect?.should be_false
end
end
end
end
context 'when the code is not in the 3xx family' do
it 'returns false' do
described_class.new(
url: url,
code: 200
).redirect?.should be_false
end
context 'and there is a Location in the headers' do
it 'returns true' do
described_class.new(
url: url,
code: 200,
headers: { 'Location' => url }
).redirect?.should be_false
end
end
end
end
describe '#modified?' do
context 'when the code is 304' do
it 'returns false' do
described_class.new( url: url, code: 304 ).modified?.should be_false
end
end
context 'when the code is not 304' do
it 'returns true' do
described_class.new( url: url, code: 301 ).modified?.should be_true
end
end
end
describe '#request' do
it 'returns the assigned request' do
r = RaptorIO::Protocol::HTTP::Request.new( url: url )
described_class.new( url: url, request: r ).request.should == r
end
end
describe '.parse' do
it 'supports CRLF terminators' do
r = described_class.parse( response )
r.version.should == '1.1'
r.code.should == 404
r.message.should == 'Not Found'
r.body.should == "<!DOCTYPE html>\nMore stuff\n"
r.headers.should == {
'Content-Type' => 'text/html;charset=utf-8',
'Content-Length' => '27'
}
r.to_s.should == response
end
it 'supports CR terminators' do
r = described_class.parse( response_cr )
r.version.should == '1.1'
r.code.should == 404
r.message.should == 'Not Found'
r.body.should == "<!DOCTYPE html>\nMore stuff\n"
r.headers.should == {
'Content-Type' => 'text/html;charset=utf-8',
'Content-Length' => '27'
}
r.to_s.should == response
end
context 'when passed an empty string' do
it 'returns an empty response' do
r = described_class.parse( '' )
r.version.should == '1.1'
r.code.should == 0
r.message.should be_nil
r.body.should be_nil
r.headers.should == {}
end
end
end
describe '#to_s' do
it 'returns a String representation of the response' do
r = described_class.new(
version: '1.1',
code: 404,
message: 'Not Found',
body: "<!DOCTYPE html>\nMore stuff\n",
headers: {
'Content-Type' => 'text/html;charset=utf-8',
'Content-Length' => '431'
}
)
r.to_s.should == response
end
end
end
|
AchoArnold/cracking-the-coding-interview
|
chapter2/singly_linked_list_test.go
|
<gh_stars>1-10
package chapter2
import (
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSlice(t *testing.T) {
list := makeListForRange(4)
assert.Equal(t, []int{0, 1, 2, 3}, list.Slice())
}
func TestReverse(t *testing.T) {
list := makeListForRange(4)
assert.Equal(t, []int{3, 2, 1, 0}, list.Reverse().Slice())
}
func TestString(t *testing.T) {
list := makeListForRange(4)
assert.Equal(t, "0->1->2->3->nil", list.String())
}
func TestMakeFromSlice(t *testing.T) {
slices := [][]int{
{1, 2, 3, 5},
{1, 2, 4},
}
for _, slice := range slices {
t.Run(strconv.Itoa(len(slice))+" items slice", func(t *testing.T) {
assert.Equal(t, makeFromSlice(slice).Slice(), slice)
})
}
}
func TestCount(t *testing.T) {
slices := [][]int{
{1, 2, 3, 5},
{1, 2, 4},
}
for _, slice := range slices {
t.Run(strconv.Itoa(len(slice))+" items slice", func(t *testing.T) {
assert.Equal(t, makeFromSlice(slice).Count(), len(slice))
})
}
t.Run("Testing Empty List", func(t *testing.T) {
var list SinglyLinkedList
assert.Equal(t, list.Count(), 0)
})
}
func TestDeleteNode(t *testing.T) {
testData := []struct {
name string
listData []int
dataToDelete int
expectedList []int
}{
{
"Deleting head",
[]int{1, 2, 3},
1,
[]int{2, 3},
},
{
"Deleting middle",
[]int{1, 2, 3},
2,
[]int{1, 3},
},
{
"Deleting tail",
[]int{1, 2},
3,
[]int{1, 2},
},
}
for _, data := range testData {
t.Run(data.name, func(t *testing.T) {
assert.Equal(t, data.expectedList, makeFromSlice(data.listData).deleteNode(data.dataToDelete).Slice())
})
}
}
|
coderbydesign/kudo-o-matic
|
app/jobs/fcm/transaction_job.rb
|
Fcm::TransactionJob = Struct.new(:transaction) do
def perform
return if transaction.receiver.nil? || transaction.receiver.deactivated?
registration_ids = transaction.receiver.fcm_tokens.collect(&:token).flatten.uniq
return if registration_ids.blank?
title = '₭udos received!'
body = "You just received #{transaction.amount} ₭ from #{transaction.sender.name}!"
event = 'transaction'
options = {
notification: {
title: title,
body: body,
event: event,
sound: 'default',
badge: '1'
},
data: {
title: title,
body: body,
event: event,
},
priority: 'high'
}
FCM_SERVICE.send_notification(registration_ids, options)
end
def queue_name
'fcm'
end
end
|
AuroScholar/TeacherSdk
|
auro_scholar_lib/src/main/java/com/auro/scholr/home/presentation/viewmodel/InviteFriendViewModel.java
|
package com.auro.scholr.home.presentation.viewmodel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.auro.scholr.core.common.ResponseApi;
import com.auro.scholr.home.domain.usecase.HomeDbUseCase;
import com.auro.scholr.home.domain.usecase.HomeRemoteUseCase;
import com.auro.scholr.home.domain.usecase.HomeUseCase;
import io.reactivex.disposables.CompositeDisposable;
public class InviteFriendViewModel extends ViewModel {
CompositeDisposable compositeDisposable;
public MutableLiveData<ResponseApi> serviceLiveData = new MutableLiveData<>();
public MutableLiveData<String> mobileNumber = new MutableLiveData<>();
public HomeUseCase homeUseCase;
public HomeDbUseCase homeDbUseCase;
public HomeRemoteUseCase homeRemoteUseCase;
public InviteFriendViewModel(HomeUseCase homeUseCase, HomeDbUseCase homeDbUseCase, HomeRemoteUseCase homeRemoteUseCase) {
this.homeUseCase = homeUseCase;
this.homeDbUseCase=homeDbUseCase;
this.homeRemoteUseCase=homeRemoteUseCase;
}
private CompositeDisposable getCompositeDisposable() {
if (compositeDisposable == null) {
compositeDisposable = new CompositeDisposable();
}
return compositeDisposable;
}
}
|
qianfen2021/conan
|
conan-agent/src/main/java/com/tal/wangxiao/conan/agent/service/ReplayService.java
|
<reponame>qianfen2021/conan<filename>conan-agent/src/main/java/com/tal/wangxiao/conan/agent/service/ReplayService.java
package com.tal.wangxiao.conan.agent.service;
/**
* 流量回放管理服务
* @author conan
*/
public interface ReplayService {
/**
* 流量回放
* @param taskExecutionId 任务执行ID
* @param recordId 任务录制ID
* @param replayId 任务回放ID
* @throws Exception
*/
void replay(Integer taskExecutionId, Integer recordId, Integer replayId) throws Exception;
}
|
rsn8887/mame2003-plus-libretro
|
src/includes/skydiver.h
|
/*************************************************************************
Atari Skydiver hardware
*************************************************************************/
/*----------- defined in vidhrdw/skydiver.c -----------*/
extern data8_t *skydiver_videoram;
MACHINE_INIT( skydiver );
WRITE_HANDLER( skydiver_videoram_w );
WRITE_HANDLER( skydiver_wram_w ); /* the signal is WRAM, presumably Work RAM */
READ_HANDLER( skydiver_wram_r );
WRITE_HANDLER( skydiver_start_lamp_1_w );
WRITE_HANDLER( skydiver_start_lamp_2_w );
WRITE_HANDLER( skydiver_lamp_s_w );
WRITE_HANDLER( skydiver_lamp_k_w );
WRITE_HANDLER( skydiver_lamp_y_w );
WRITE_HANDLER( skydiver_lamp_d_w );
WRITE_HANDLER( skydiver_lamp_i_w );
WRITE_HANDLER( skydiver_lamp_v_w );
WRITE_HANDLER( skydiver_lamp_e_w );
WRITE_HANDLER( skydiver_lamp_r_w );
WRITE_HANDLER( skydiver_width_w );
WRITE_HANDLER( skydiver_coin_lockout_w );
VIDEO_START( skydiver );
VIDEO_UPDATE( skydiver );
|
DirectProject/direct-msg-monitor
|
src/test/java/org/nhindirect/monitor/SpringBaseTest.java
|
package org.nhindirect.monitor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.reactive.function.client.WebClient;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@DirtiesContext
@TestPropertySource("classpath:bootstrap.properties")
public abstract class SpringBaseTest
{
protected WebClient webClient;
@BeforeEach
public void setUp()
{
webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
}
}
|
badetitou/VerveineJ
|
test_src/jws_basic/store/client/Main.java
|
package store.client;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.Stub;
/**
* This is a simple standalone client application that invokes the the
* <code>echoString</code> and <code>myoperation</code> operations of the
* SimpleEjbService Web service.
*
*/
public class Main {
public static void main(String[] args) throws ServiceException,
RemoteException {
String url = args[0];
String supplier = args[1];
String partName = args[2];
String partID = args[3];
long amount = new Long(args[4]).longValue();
String notes = args[5];
OrderService service = new OrderService_Impl();
MyPortType port = service.getHelloPort();
Stub stub = (Stub) port;
stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]);
OrderStruct in = new OrderStruct();
in.setSupplier(supplier);
in.setPartName(partName);
in.setPartID(partID);
in.setAmount(amount);
in.setNotes(notes);
String orderRating = port.processOrderApp(in);
System.out.println("Order Rating Response: " + orderRating);
}
}
|
ashishjayamohan/competitive-programming
|
Practice/moves.py
|
t = int(input())
answer = []
for a in range(t):
n = int(input())
ans = int(8*(((n)*(n+1)*(2*n+1))/6))
answer.append(ans)
for b in answer:
print(str(b))
|
AlexShkarin/pyLabLib-v0
|
pylablib/core/dataproc/interpolate.py
|
from builtins import range
import numpy as np
import scipy.interpolate
from . import waveforms
from ..datatable import wrapping
def _data_range(data):
return (np.min(data),np.max(data))
def interpolate1D_func(x, y, kind="linear", axis=-1, copy=True, bounds_error=True, fill_values=np.nan, assume_sorted=False):
"""
1D interpolation.
Simply a wrapper around :class:`scipy.interpolate.interp1d`.
Args:
x: 1D arrays of x coordinates for the points at which to find the values.
y: array of values corresponding to x points (can have more than 1 dimension, in which case the output values are (N-1)-dimensional)
kind: Interpolation method.
axis: axis in y-data over which to interpolate.
copy: if ``True``, make internal copies of `x` and `y`.
bounds_error: if ``True``, raise error if interpolation function arguments are outside of `x` bounds.
fill_values: values to fill the outside-bounds regions if ``bounds_error==False``.
assume_sorted: if ``True``, assume that `data` is sorted.
Returns:
A 1D array with interpolated data.
"""
if fill_values=="bounds":
fill_values=tuple(np.take(y,[x.argmin(),x.argmax()],axis=axis))
bounds_error=False
return scipy.interpolate.interp1d(x,y,kind=kind,axis=axis,copy=copy,bounds_error=bounds_error,fill_value=fill_values,assume_sorted=assume_sorted)
def interpolate1D(data, x, kind="linear", bounds_error=True, fill_values=np.nan, assume_sorted=False):
"""
1D interpolation.
Args:
data: 2-column array [(x,y)], where ``y`` is a function of ``x``.
x: Arrays of x coordinates for the points at which to find the values.
kind: Interpolation method.
bounds_error: if ``True``, raise error if `x` values are outside of `data` bounds.
fill_values: values to fill the outside-bounds regions if ``bounds_error==False``
assume_sorted: if ``True``, assume that `data` is sorted.
Returns:
A 1D array with interpolated data.
"""
return interpolate1D_func(data[:,0],data[:,1],kind=kind,bounds_error=bounds_error,fill_values=fill_values,assume_sorted=assume_sorted)(x)
def interpolate2D(data, x, y, method="linear", fill_value=np.nan):
"""
Interpolate data in 2D.
Simply a wrapper around :func:`scipy.interpolate.griddata`.
Args:
data: 3-column array [(x,y,z)], where ``z`` is a function of ``x`` and ``y``.
x/y: Arrays of x and y coordinates for the points at which to find the values.
method: Interpolation method.
Returns:
A 2D array with interpolated data.
"""
interp_data=scipy.interpolate.griddata((data[:,0],data[:,1]),data[:,2],(x,y),method=method,fill_value=fill_value)
return interp_data
def interpolateND(data, xs, method="linear"):
"""
Interpolate data in N dimensions.
Simply a wrapper around :func:`scipy.interpolate.griddata`.
Args:
data: ``(N+1)``-column array ``[(x_1,..,x_N,y)]``, where ``y`` is a function of ``x_1, ... ,x_N``.
xs: ``N``-tuple of arrays of coordinates for the points at which to find the values.
method: Interpolation method.
Returns:
An ND array with interpolated data.
"""
coords=tuple([data[:,n] for n in range(data.shape[1]-1)])
interp_data=scipy.interpolate.griddata(coords,data[:,-1],xs,method=method)
return interp_data
def regular_grid_from_scatter(data, x_points, y_points, x_range=None, y_range=None, method="nearest"):
"""
Turn irregular scatter-points data into a regular 2D grid function.
Args:
data: 3-column array ``[(x,y,z)]``, where ``z`` is a function of ``x`` and ``y``.
x_points/y_points: Number of points along x/y axes.
x_range/y_range: If not ``None``, a tuple specifying the desired range of the data (all points in `data` outside the range are excluded).
method: Interpolation method (see :func:`scipy.interpolate.griddata` for options).
Returns:
A nested tuple ``(data, (x_grid, y_grid))``, where all entries are 2D arrays (either with data or with gridpoint locations).
"""
if x_range is not None:
data=waveforms.cut_to_range(data,x_range,0)
else:
x_range=_data_range(data[:,0])
if y_range is not None:
data=waveforms.cut_to_range(data,y_range,1)
else:
y_range=_data_range(data[:,1])
x_grid=np.linspace(x_range[0],x_range[1],x_points)
y_grid=np.linspace(y_range[0],y_range[1],y_points)
xi,yi=np.meshgrid(x_grid,y_grid)
interp_data=scipy.interpolate.griddata((data[:,0],data[:,1]),data[:,2],(xi,yi),method=method)
return interp_data,(x_grid,y_grid)
def interpolate_trace(trace, step, rng=None, x_column=0, select_columns=None, kind="linear", assume_sorted=False,):
"""
Interpolate trace data over a regular grid with the given step.
`rng` specifies interpolation range (by default, whole data range).
`x_column` specifies column index for x-data.
`select_column` specifies which columns to interpolate and keep at the output (by default, all data).
If ``assume_sorted==True``, assume that x-data is sorted.
`kind` specifies interpolation method.
"""
wtrace=wrapping.wrap(trace)
src_column=waveforms.get_x_column(trace,x_column=x_column)
select_columns=select_columns or range(wtrace.shape()[1])
rng_min,rng_max=rng or (None,None)
rng_min=src_column.min() if (rng_min is None) else rng_min
rng_max=src_column.max() if (rng_max is None) else rng_max
start=(rng_min//step)*step
stop=(rng_max//step)*step
pts=np.arange(start,stop+step/2.,step)
xidx=wtrace.c.get_index(x_column)
columns=[ pts if wtrace.c.get_index(c)==xidx else
interpolate1D_func(src_column,wtrace[:,c],kind=kind,bounds_error=False,fill_values="bounds",assume_sorted=assume_sorted)(pts)
for c in select_columns]
return wtrace.subtable((slice(None),select_columns)).columns_replaced(columns,wrapped=False)
def average_interpolate_1D(data, step, rng=None, avg_kernel=1, min_weight=0, kind="linear"):
"""
1D interpolation combined with pre-averaging.
Args:
data: 2-column array [(x,y)], where ``y`` is a function of ``x``.
step: distance between the points in the interpolated data (all resulting x-coordinates are multiples of `step`).
rng: if not ``None``, specifies interpolation range (by default, whole data range).
avg_kernel: kernel used for initial averaging. Can be either a 1D array, where each point corresponds to the relative bin weight,
or an integer, which specifies simple rectangular kernel of the given width.
min_weight: minimal accumulated weight in the bin to consider it 'valid'
(if the bin is invalid, its accumulated value is ignored, and its value is obtained by the interpolation step).
`min_weight` of 0 implies any non-zero weight; otherwise, weight ``>=min_weight``.
kind: Interpolation method.
Returns:
A 2-column array with the interpolated data.
"""
if isinstance(avg_kernel,(int,float)):
avg_kernel=max(int(avg_kernel)//2,0)*2+1
avg_kernel=np.ones(avg_kernel)
rng_min,rng_max=rng or (None,None)
rng_min=data[:,0].min() if (rng_min is None) else rng_min
rng_max=data[:,0].max() if (rng_max is None) else rng_max
rng=(rng_min,rng_max)
rng=[(l//step)*step for l in rng]
bins=np.linspace(rng[0],rng[1],int((rng[1]-rng[0])/step)+1)
locs=bins.searchsorted(data[:,0])
locs[locs==len(bins)]-=1
bindiffs=data[:,0]-bins[locs]
locs[(locs>0)&(bindiffs<-step/2.)]-=1
sums=np.zeros((len(bins)))
np.add.at(sums,locs,data[:,1])
weights=np.zeros((len(bins)))
np.add.at(weights,locs,1)
sums=np.convolve(sums,avg_kernel,mode="same")
weights=np.convolve(weights,avg_kernel,mode="same")
filled=weights>min_weight if min_weight==0 else weights>=min_weight
intx=bins[filled]
inty=sums[filled]/weights[filled]
data=interpolate1D_func(intx,inty,kind=kind,bounds_error=False,fill_values="bounds",assume_sorted=True)(bins)
return np.column_stack((bins,data))
|
techoopsie/oopsie-sdk-java
|
src/main/java/io/oopsie/sdk/PartitionKey.java
|
<reponame>techoopsie/oopsie-sdk-java<filename>src/main/java/io/oopsie/sdk/PartitionKey.java
package io.oopsie.sdk;
import java.util.UUID;
public class PartitionKey extends Attribute {
PartitionKey(UUID id, String name, DataType type, Validation validation) {
super(id, name, type, null, validation);
}
}
|
calce/sgo
|
sgo_test.go
|
package sgo
import (
"time"
"testing"
"net/http"
"github.com/calce/sgo/mocks"
. "github.com/smartystreets/goconvey/convey"
)
func TestBackend(t *testing.T) {
Convey("General", t, func(){
// live client
Convey("should be able to create http client when not supplied", func(){
liveend, e := NewBackend("", "", "", 0, nil)
So(e, ShouldBeNil)
So(liveend.client, ShouldNotBeNil)
})
mock := mocks.New("mocks")
backend, e := NewBackend("yay", "http://connect.squareup.com/v1", "me", time.Second * 30, mock.Client)
Convey("should create new backend properly", func(){
So(e, ShouldBeNil)
Convey("baseURL should not be blank", func(){
So(backend.GetBaseURL(), ShouldNotBeBlank)
})
query := Query{
Method: GET,
URL: backend.GetBaseURL() + "payments",
Params: "?",
IsList: true,
GetObject: getListObject,
GetList: getList,
}
req, e := backend.makeRequest(&query);
Convey("should create proper request", func(){
So(e, ShouldBeNil)
So(req, ShouldNotBeNil)
res, e := backend.client.Do(req);
Convey("should return a good response after calling an endpoint", func(){
So(e, ShouldBeNil)
So(res, ShouldNotBeNil)
list, err := backend.parseResponse(res, &query)
Convey("should be able to parse a good response", func(){
ESo(err)
So(list, ShouldHaveSameTypeAs, &[]Payment{})
var iter *Iter = backend.createIterator(list, res, &query)
Convey("should be able to create iterators out of requested lists", func(){
So(iter, ShouldNotBeNil)
So(iter.backend, ShouldEqual, backend)
})
})
})
})
})
})
}
func TestCall(t *testing.T) {
mock := mocks.New("mocks")
backend, _ := NewBackend("yay", "http://connect.squareup.com/v1", "me", time.Second * 30, mock.Client)
Convey("Calling", t, func(){
Convey("Listing", func(){
query := Query{
Method: GET,
URL: backend.GetBaseURL() + "payments",
Params: "?",
IsList: true,
GetObject: getListObject,
GetList: getList,
}
v, err := backend.Call(&query)
Convey("should be able to call properly", func(){
So(err, ShouldBeNil)
iter := v.(*Iter)
err = backend.loadNextPage(iter)
Convey("should be able to load an iterator's next page", func(){
So(err, ShouldBeNil)
So(iter.list, ShouldNotBeNil)
So(iter.currentPage, ShouldEqual, 2)
})
})
})
Convey("Retrieving", func(){
Convey("should retrieve existing object", func(){
query := Query{
Method: GET,
URL: backend.GetBaseURL() + "payments/yes",
Params: "?",
IsList: false,
GetObject: getObject,
GetList: getList,
}
_, err := backend.Call(&query)
So(err, ShouldBeNil)
})
Convey("should return 404 on non-existing object", func(){
query := Query{
Method: GET,
URL: backend.GetBaseURL() + "payments/YAY",
Params: "?",
IsList: false,
GetObject: getObject,
GetList: getList,
}
_, err := backend.Call(&query)
So(err, ShouldNotBeNil)
So(err.ApiError.ErrorCode, ShouldEqual, http.StatusNotFound)
})
})
})
}
func TestDefaultBackend(t *testing.T) {
Convey("Default backend", t, func(){
Convey("should be able to get/set default backend", func(){
backend, _ := GetDefaultBackend()
So(backend, ShouldNotBeNil)
newBackend := Backend{}
SetDefaultBackend(&newBackend)
newDefaultBackend, _ := GetDefaultBackend()
So(newDefaultBackend, ShouldPointTo, &newBackend)
})
})
}
func TestQuery(t *testing.T) {
query := Query{}
Convey("Query", t, func(){
So(query.CreateNextPageQuery(""), ShouldNotBeNil)
})
}
func getObject() interface{} {
return &Payment{}
}
func getListObject() interface{} {
return &[]Payment{}
}
func getList(l interface{}) *[]interface{} {
pl := l.(*[]Payment)
size := len(*pl)
il := make([]interface{}, size, cap(*pl))
for i:=0; i<size; i++ {
il[i] = &(*pl)[i]
}
return &il
}
func ESo(err *Error) {
if err != nil {
if err.ParseError != nil { Print("( Parse: ", err) }
if err.ApiError != nil { Print("(", err.ApiError.ErrorCode, " - ", err.ApiError.Message, ") ") }
}
So(err, ShouldBeNil)
}
|
thehyve/platform-etl-backend
|
src/main/scala/io/opentargets/etl/backend/drug/MechanismOfAction.scala
|
<filename>src/main/scala/io/opentargets/etl/backend/drug/MechanismOfAction.scala<gh_stars>1-10
package io.opentargets.etl.backend.drug
import com.typesafe.scalalogging.LazyLogging
import io.opentargets.etl.backend.spark.Helpers.validateDF
import org.apache.spark.sql.functions._
import org.apache.spark.sql.{DataFrame, SparkSession}
/**
* Object for preparing mechanism of action section of the drug object.
*
* Output structure:
*
* id
* mechanismsOfAction
* -- rows
* ---- mechanismOfAction
* ---- references
* ------ source
* ------ ids
* ------ urls
* ---- targets
* ---- targetName
* -- uniqueActiontype
* -- unqueTargetType
*
*
*/
object MechanismOfAction extends LazyLogging {
/**
*
* @param mechanismDf: raw data from Chembl
* @param targetDf: raw data from Chembl
* @param geneDf: gene parquet file listed under target in configuration
* @param sparkSession implicit
*/
def apply(mechanismDf: DataFrame, targetDf: DataFrame, geneDf: DataFrame)(
implicit sparkSession: SparkSession): DataFrame = {
logger.info("Processing mechanisms of action")
val mechanism = mechanismDf
.withColumnRenamed("molecule_chembl_id", "id")
.withColumnRenamed("mechanism_of_action", "mechanismOfAction")
.withColumnRenamed("action_type", "actionType")
.withColumn("chemblIds", col("_metadata.all_molecule_chembl_ids"))
.drop("_metadata", "parent_molecule_chembl_id")
val references = chemblMechanismReferences(mechanism)
val target = chemblTarget(targetDf, geneDf)
mechanism
.join(references, Seq("id"), "outer")
.join(target, Seq("target_chembl_id"), "outer")
.drop("mechanism_refs", "record_id", "target_chembl_id")
// filter to remove rows which don't require further processing. Including them results in a bug in the API.
.filter(
"""
|mechanismOfAction is not null
|or references is not null
|or targetName is not null
|or targets is not null
|""".stripMargin
)
.drop("id")
.filter("chemblIds is not null")
.distinct
.transform(consolidateDuplicateReferences)
}
private def consolidateDuplicateReferences(df: DataFrame): DataFrame = {
val cols = df.columns.filter(_ != "references")
df.groupBy(cols.head, cols.tail: _*)
.agg(collect_set("references").as("r"))
.withColumn("references", flatten(col("r")))
.drop("r")
}
private def chemblMechanismReferences(dataFrame: DataFrame): DataFrame = {
val requiredColumns = Set("id", "mechanism_refs")
validateDF(requiredColumns, dataFrame)
dataFrame
.select(col("id"), explode(col("mechanism_refs")))
.groupBy("id", "col.ref_type")
.agg(collect_list("col.ref_id").as("ref_id"), collect_list("col.ref_url").as("ref_url"))
.withColumn(
"references",
struct(col("ref_type").as("source"), col("ref_id").as("ids"), col("ref_url").as("urls")))
.groupBy("id")
.agg(collect_list("references").as("references"))
}
private def chemblTarget(target: DataFrame, gene: DataFrame): DataFrame = {
val targetCols = Set("target_components", "pref_name", "target_type", "target_chembl_id")
val geneCols = List(col("id").as("geneId"), explode(col("proteinIds.id")).as("uniprot_id"))
// validate incoming dataframes
validateDF(targetCols, target)
// get rid of entries where target components is none
val targetDf = target
.withColumn("target_components", explode(col("target_components")))
.filter(col("target_components.accession").isNotNull)
.select(
col("pref_name").as("targetName"),
col("target_components.accession").as("uniprot_id"),
lower(col("target_type")).as("targetType"),
col("target_chembl_id")
)
val genes = gene.select(geneCols: _*)
targetDf
.join(genes, Seq("uniprot_id"), "left_outer")
.groupBy("target_chembl_id", "targetName", "targetType")
.agg(array_distinct(collect_list("geneId")).as("targets"))
}
}
|
Dbevan/SunderingShadows
|
d/islands/elf/guard1.c
|
<reponame>Dbevan/SunderingShadows
//guard house based off shadow one
/* trying eval for making stations for guards so
they can return crims to jail
eval return
"/daemon/destinations_d.c"->query_waystations("/d/islands/elf/guard1")
* // eval return
"/daemon/destinations_d.c"->clear_waystations("/d/islands/elf/guard1")
* // eval return
"/daemon/destinations_d.c"->generate_waystations("/d/islands/elf/guard1", 5, 3)
* eval return
"/daemon/destinations_d.c"->generate_waystations("/d/islands/elf/guard1", 5, 4)
*/
#include <std.h>
#include "elf.h"
#define GROVE "/d/islands/elf/grove2"
#define CELL "/d/islands/elf/cell"
inherit "/std/jail_main.c";
void create(){
::create();
set_jail_location("Ashta'Rathai");
set_cell(CELL);
set_terrain(STONE_BUILDING);
set_travel(PAVED_ROAD);
set_name("Ashta'Rathai jail");
set_short("The Ashta'Rathai jail tree");
set_long("%^BOLD%^%^GREEN%^Jailer's Office \n\n%^RESET%^"+
"%^GREEN%^This is a rather large tree with several"+
" cages hanging from the branches where criminals are checked"+
" in before being caged while their fate is decided. "+
"There is a simple desk in one corner and several chairs"+
" in the room. The tree sprawls up around fifty feet into"+
" the air with many little resting places built onto it. "+
" There is a list posted on the base of the tree. "+
" Guards often gather here to meet." );
set_items(([
"grate" : "Perhaps the guard won't mind if you peer through the "
"grate to see who is in the cage.",
(({"cage","cell"})) : "This is a bronze cage with a "+
"grate on it to peer through",
"list" : "Type <list> to see how to use this room.",
]));
set_listen("default","You can hear a chill wind blow.");
set_smell("default","It smells of plants and water.");
set_exits(([
"northeast" : GROVE,
"cage" : CELL,
"up" : ROOMS"office",
"grate" : CELL,//invis exit
]));
add_invis_exit("grate");
add_pre_exit_function("grate", "GoThroughDoor");
set_door("cage door",CELL,"cage","Ashta'Rathai jail key","lock");
set_open("cage door",0);
set_locked("cage door", 1, "lock");
lock_difficulty("cage door",-90, "lock");
set_lock_description("cage door", "lock",
"This lock is sandwiched between two very heavy "
"metal plates to prevent tampering. The mechanism appears to be "
"not only complex but require a very sturdy key to get the pieces "
"to even move.");
set_door_description("cell door", "This is a brass grate with a lock on it. "+
"It is placed at the bottom of the cage.");
set_string("cage door","open","The cell door creaks loudly as it "
"swings open.");
set_string("cage door","close","An ominous thud echoes off the cage "
"as the door latches shut solidly.");
}
void init() {
::init();
add_action("peer_out", "peer");
}
void reset() {
::reset();
if(!present("jailer"))
new(MON"jailer")->move(TO);
if(!present("mage guard"))
new(MON"guard")->move(TO);
if(!present("mirror warrior"))
new(MON"guard2")->move(TO);
}
int GoThroughDoor() {
if(query_verb() == "grate") {
write("You won't fit through there silly.");
return 0;
}
// need this to allow normal GoThroughDoor for the regular door exits
return ::GoThroughDoor();
}
int peer_out(string str) {
if(!str) {
tell_object(TP,"Peer where?");
return 1;
}
if(str == "cell" || str == "through grate" || str == "cage"){
tell_object(TP,"You step up to the cage and peer into the cell.\n");
tell_room(ETP,TPQCN+
" steps up to the cage and peers inside.\n",TP);
tell_room(CELL,"You hear footsteps and catch "
"a glimpse of movement through the grate in the door.\n",TP);
TP->force_me("peer grate 1");
return 1;
}
}
|
Lothrazar/SamsPowerups
|
Commands/src/main/java/com/lothrazar/samscommands/command/CommandSearchSpawner.java
|
<reponame>Lothrazar/SamsPowerups
package com.lothrazar.samscommands.command;
import java.util.ArrayList;
import java.util.List;
import com.lothrazar.samscommands.ModCommands;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentTranslation;
public class CommandSearchSpawner implements ICommand
{
public static boolean REQUIRES_OP;
public CommandSearchSpawner()
{
aliases.add("SEARCHSPAWNER");
aliases.add("searchdungeon");
aliases.add("SEARCHDUNGEON");
aliases.add("searchs");
aliases.add("searchd");
}
@Override
public int compareTo(Object arg0)
{
return 0;
}
@Override
public String getName()
{
return "searchspawner";
}
@Override
public String getCommandUsage(ICommandSender sender)
{
return "/" + getName() + " [radius]";
}
private ArrayList<String> aliases = new ArrayList<String>();
@Override
public List getAliases()
{
return aliases;
}
public static final int MAXRADIUS = 128;// TODO: config file for these? yes no?
public static final int DEFAULTRADIUS = 64;
@Override
public void execute(ICommandSender sender, String[] args) throws CommandException
{
EntityPlayer player = (EntityPlayer)sender;
int radius = 0;
if(args.length > 0)
{
radius = Integer.parseInt(args[0]);
}
if(radius > MAXRADIUS) { radius = MAXRADIUS; }
if(radius <= 0 ) { radius = DEFAULTRADIUS; }
//BlockPos found = Util.findClosestBlock(player, Blocks.mob_spawner, radius);
ArrayList<BlockPos> founds = ModCommands.findBlocks(player, Blocks.mob_spawner, radius);
if(founds.size() == 0)
{
//TODO: lang file for this string
player.addChatMessage(new ChatComponentTranslation( "None Found with radius "+radius ));
}
else
{
String m;
for(BlockPos found : founds) //if(found != null)
{
//"Found at : "+
m = ModCommands.getCoordsOrReduced(player, found);//TODO: lang file?
player.addChatMessage(new ChatComponentTranslation( m ));
}
}
}
@Override
public boolean canCommandSenderUse(ICommandSender ic)
{
return (REQUIRES_OP) ? ic.canUseCommand(2, this.getName()) : true;
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args,BlockPos pos)
{
return null;
}
@Override
public boolean isUsernameIndex(String[] args, int index)
{
return false;
}
}
|
shugo/thinreports-generator
|
test/features/feature_test.rb
|
# frozen_string_literal: true
require 'minitest/autorun'
require 'minitest/unit'
require 'pathname'
require 'thinreports'
class FeatureTest < Minitest::Test
class << self
attr_reader :name, :desc
def feature(name, desc = nil, &block)
@name = name
@desc = desc
define_method(:test_feature, &block)
end
end
def dir
@dir ||= Pathname.new(__dir__).join(feature_name.to_s)
end
def path_of(filename)
dir.join(filename).to_path
end
def assert_pdf(actual)
actual_pdf.binwrite(actual)
if expect_pdf.exist?
assert match_expect_pdf?, 'Does not match expect.pdf. Check diff.pdf for details.'
else
flunk 'expect.pdf does not exist.'
end
end
def template_path(filename = 'template.tlf')
dir.join(filename).to_path
end
private
def feature_name
self.class.name
end
def match_expect_pdf?
system("diff-pdf --output-diff=#{path_of('diff.pdf')} #{expect_pdf} #{actual_pdf}")
end
def actual_pdf
dir.join('actual.pdf')
end
def expect_pdf
dir.join('expect.pdf')
end
end
|
MattiasLiljeson/denLilleOstPojken
|
CoreLib/src/Pill.h
|
#ifndef PILL_H
#define PILL_H
#include "Tile.h"
#include "Collectable.h"
#include "IODevice.h"
class PillEatenState;
class Pill: public Collectable
{
private:
Tile* m_tile;
PillEatenState* m_eatenState;
float flotyAnimTick;
float flotyAnimOffset;
TransformInfo m_origin;
public:
Pill(SpriteInfo* p_spriteInfo, SoundInfo* p_soundInfo, Tile* p_tile, GameStats* p_gameStats);
virtual ~Pill();
void update(float p_deltaTime, InputInfo p_inputInfo);
virtual bool isConsumed();
void consume();
};
#endif
|
dxCarl/LeetCode
|
src/main/java/com/xiao/deng/leetcode/compress/Solution.java
|
package com.xiao.deng.leetcode.compress;
public class Solution {
/**
* 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。
* 若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)
* <p>
* 输入:"aabcccccaaa"
* 输出:"a2b1c5a3"
* <p>
* 输入:"abbccd"
* 输出:"abbccd"
* 解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
*
* @param S
* @return
*/
public String compressString(String S) {
char[] chars = S.toCharArray();
if (chars.length == 0) {
return "";
}
int i = 0;
StringBuilder sb = new StringBuilder();
while (i < chars.length) {
int count = 1;
char cur = chars[i];
int j = i+1;
if (j == chars.length) {
sb.append(cur);
sb.append(1);
break;
}
for (; j < chars.length; j++) {
char comp = chars[j];
if (cur == comp) {
count++;
if (j == chars.length - 1) {
sb.append(cur);
sb.append(count);
i = chars.length;
break;
}
}
else {
sb.append(cur);
sb.append(count);
i = j;
break;
}
}
}
String compressStr = sb.toString();
int len = compressStr.length();
return len < S.length() ? compressStr : S;
}
public static void main(String[] args) {
String s = "aabcccccaaa";
String ans = new Solution().compressString(s);
System.out.println(ans);
}
}
|
odoo-mastercore/odoo-argentina
|
l10n_ar_account_withholding/models/afip.py
|
from odoo import models, fields
class AfipTablagananciasEscala(models.Model):
_name = 'afip.tabla_ganancias.escala'
_description = 'afip.tabla_ganancias.escala'
_rec_name = 'importe_desde'
importe_desde = fields.Float(
'Mas de $',
)
importe_hasta = fields.Float(
'A $',
)
importe_fijo = fields.Float(
'$',
)
porcentaje = fields.Float(
'Más el %'
)
importe_excedente = fields.Float(
'S/ Exced. de $'
)
class AfipTablagananciasAlicuotasymontos(models.Model):
_name = 'afip.tabla_ganancias.alicuotasymontos'
_description = 'afip.tabla_ganancias.alicuotasymontos'
_rec_name = 'codigo_de_regimen'
codigo_de_regimen = fields.Char(
'Codigo de regimen',
size=6,
required=True,
help='Codigo de regimen de inscripcion en impuesto a las ganancias.'
)
anexo_referencia = fields.Char(
required=True,
)
concepto_referencia = fields.Text(
required=True,
)
porcentaje_inscripto = fields.Float(
'% Inscripto',
help='Elija -1 si se debe calcular s/escala'
)
porcentaje_no_inscripto = fields.Float(
'% No Inscripto'
)
montos_no_sujetos_a_retencion = fields.Float(
)
|
jon-greer-ixd/searchlight
|
app/personalDetail.js
|
function PersonalDetail(
name,
value,
show
) {
this.name = name,
this.value = value,
this.show = show
}
PersonalDetail.prototype.print = function () {
console.log( "Name " + this.name + ". Value " + this.value + ". Show " + this.show );
}
function createPersonalDetail() {
return new PersonalDetail();
}
module.exports.createPersonalDetail = createPersonalDetail;
|
LasTshaMAN/politeia
|
politeiad/backend/gitbe/decred.go
|
// Copyright (c) 2017-2019 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package gitbe
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrec/secp256k1/v3/ecdsa"
"github.com/decred/dcrd/dcrutil/v3"
"github.com/decred/dcrd/wire"
dcrdataapi "github.com/decred/dcrdata/api/types/v4"
"github.com/decred/politeia/decredplugin"
"github.com/decred/politeia/politeiad/api/v1/identity"
"github.com/decred/politeia/politeiad/backend"
"github.com/decred/politeia/util"
)
// XXX plugins really need to become an interface. Run with this for now.
const (
decredPluginIdentity = "fullidentity"
decredPluginJournals = "journals"
defaultCommentIDFilename = "commentid.txt"
defaultCommentFilename = "comments.journal"
defaultCommentsFlushed = "comments.flushed"
defaultBallotFilename = "ballot.journal"
defaultBallotFlushed = "ballot.flushed"
journalVersion = "1" // Version 1 of the comment journal
journalActionAdd = "add" // Add entry
journalActionDel = "del" // Delete entry
journalActionAddLike = "addlike" // Add comment like
flushRecordVersion = "1" // Version 1 of the flush journal
// Following are what should be well-known interface hooks
PluginPostHookEdit = "postedit" // Hook Post Edit
)
var (
// errDuplicateVote is emitted when a cast vote is a duplicate.
errDuplicateVote = errors.New("duplicate vote")
)
// FlushRecord is a structure that is stored on disk when a journal has been
// flushed.
type FlushRecord struct {
Version string `json:"version"` // Version
Timestamp string `json:"timestamp"` // Timestamp
}
// JournalAction prefixes and determines what the next structure is in
// the JSON journal.
// Version is used to determine what version of the comment journal structure
// follows.
// journalActionAdd -> Add entry
// journalActionDel -> Delete entry
// journalActionAddLike -> Add comment like structure (comments only)
type JournalAction struct {
Version string `json:"version"` // Version
Action string `json:"action"` // Add/Del
}
var (
decredPluginSettings map[string]string // [key]setting
decredPluginHooks map[string]func(string) error // [key]func(token) error
// Pregenerated journal actions
journalAdd []byte
journalDel []byte
journalAddLike []byte
// Plugin specific data that CANNOT be treated as metadata
pluginDataDir = filepath.Join("plugins", "decred")
decredPluginCommentsCache = make(map[string]map[string]decredplugin.Comment) // [token][commentid]comment
journalsReplayed bool = false
)
// init is used to pregenerate the JSON journal actions.
func init() {
var err error
journalAdd, err = json.Marshal(JournalAction{
Version: journalVersion,
Action: journalActionAdd,
})
if err != nil {
panic(err.Error())
}
journalDel, err = json.Marshal(JournalAction{
Version: journalVersion,
Action: journalActionDel,
})
if err != nil {
panic(err.Error())
}
journalAddLike, err = json.Marshal(JournalAction{
Version: journalVersion,
Action: journalActionAddLike,
})
if err != nil {
panic(err.Error())
}
}
func getDecredPlugin(dcrdataHost string) backend.Plugin {
decredPlugin := backend.Plugin{
ID: decredplugin.ID,
Version: decredplugin.Version,
Settings: []backend.PluginSetting{},
}
decredPlugin.Settings = append(decredPlugin.Settings,
backend.PluginSetting{
Key: "dcrdata",
Value: dcrdataHost,
},
)
// Initialize hooks
decredPluginHooks = make(map[string]func(string) error)
// Initialize settings map
decredPluginSettings = make(map[string]string)
for _, v := range decredPlugin.Settings {
decredPluginSettings[v.Key] = v.Value
}
return decredPlugin
}
// initDecredPlugin is called externally to run initial procedures
// such as replaying journals
func (g *gitBackEnd) initDecredPluginJournals() error {
log.Infof("initDecredPlugin")
// check if backend journal is initialized
if g.journal == nil {
return fmt.Errorf("initDecredPlugin backend journal isn't initialized")
}
err := g.replayAllJournals()
if err != nil {
log.Infof("initDecredPlugin replay all journals %v", err)
}
return nil
}
// replayAllJournals replays ballot and comment journals for every stored proposal
// this function can be called without the lock held
func (g *gitBackEnd) replayAllJournals() error {
log.Infof("replayAllJournals")
files, err := ioutil.ReadDir(g.journals)
if err != nil {
return fmt.Errorf("Read dir journals: %v", err)
}
for _, f := range files {
name := f.Name()
// replay comments for all props
_, err = g.replayComments(name)
if err != nil {
return fmt.Errorf("replayAllJournals replayComments %s %v", name, err)
}
}
journalsReplayed = true
return nil
}
//SetDecredPluginSetting removes a setting if the value is "" and adds a setting otherwise.
func setDecredPluginSetting(key, value string) {
if value == "" {
delete(decredPluginSettings, key)
return
}
decredPluginSettings[key] = value
}
func setDecredPluginHook(name string, f func(string) error) {
decredPluginHooks[name] = f
}
func (g *gitBackEnd) vettedPropExists(token string) bool {
tokenb, err := util.ConvertStringToken(token)
if err != nil {
return false
}
return g.VettedExists(tokenb)
}
func (g *gitBackEnd) getNewCid(token string) (string, error) {
dir := pijoin(g.journals, token)
err := os.MkdirAll(dir, 0774)
if err != nil {
return "", err
}
filename := pijoin(dir, defaultCommentIDFilename)
g.Lock()
defer g.Unlock()
fh, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0664)
if err != nil {
return "", err
}
defer fh.Close()
// Determine if file is empty
fi, err := fh.Stat()
if err != nil {
return "", err
}
if fi.Size() == 0 {
// First comment id
_, err := fmt.Fprintf(fh, "1\n")
if err != nil {
return "", err
}
return "1", nil
}
// Only allow one line
var cid string
s := bufio.NewScanner(fh)
for i := 0; s.Scan(); i++ {
if i != 0 {
return "", fmt.Errorf("comment id file corrupt")
}
c, err := strconv.ParseUint(s.Text(), 10, 64)
if err != nil {
return "", err
}
// Increment comment id
c++
cid = strconv.FormatUint(c, 10)
// Write back new comment id
_, err = fh.Seek(0, io.SeekStart)
if err != nil {
return "", err
}
_, err = fmt.Fprintf(fh, "%v\n", c)
if err != nil {
return "", err
}
}
if err := s.Err(); err != nil {
return "", err
}
return cid, nil
}
// verifyMessage verifies a message is properly signed.
// Copied from https://github.com/decred/dcrd/blob/0fc55252f912756c23e641839b1001c21442c38a/rpcserver.go#L5605
func (g *gitBackEnd) verifyMessage(address, message, signature string) (bool, error) {
// Decode the provided address.
addr, err := dcrutil.DecodeAddress(address, g.activeNetParams)
if err != nil {
return false, fmt.Errorf("Could not decode address: %v",
err)
}
// Only P2PKH addresses are valid for signing.
if _, ok := addr.(*dcrutil.AddressPubKeyHash); !ok {
return false, fmt.Errorf("Address is not a pay-to-pubkey-hash "+
"address: %v", address)
}
// Decode base64 signature.
sig, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return false, fmt.Errorf("Malformed base64 encoding: %v", err)
}
// Validate the signature - this just shows that it was valid at all.
// we will compare it with the key next.
var buf bytes.Buffer
wire.WriteVarString(&buf, 0, "Decred Signed Message:\n")
wire.WriteVarString(&buf, 0, message)
expectedMessageHash := chainhash.HashB(buf.Bytes())
pk, wasCompressed, err := ecdsa.RecoverCompact(sig,
expectedMessageHash)
if err != nil {
// Mirror Bitcoin Core behavior, which treats error in
// RecoverCompact as invalid signature.
return false, nil
}
// Reconstruct the pubkey hash.
dcrPK := pk
var serializedPK []byte
if wasCompressed {
serializedPK = dcrPK.SerializeCompressed()
} else {
serializedPK = dcrPK.SerializeUncompressed()
}
a, err := dcrutil.NewAddressSecpPubKey(serializedPK, g.activeNetParams)
if err != nil {
// Again mirror Bitcoin Core behavior, which treats error in
// public key reconstruction as invalid signature.
return false, nil
}
// Return boolean if addresses match.
return a.Address() == address, nil
}
func bestBlock() (*dcrdataapi.BlockDataBasic, error) {
url := decredPluginSettings["dcrdata"] + "/api/block/best"
log.Debugf("connecting to %v", url)
// XXX this http command needs a reasonable timeout.
r, err := http.Get(url)
log.Debugf("http connecting to %v", url)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("dcrdata error: %v %v %v",
r.StatusCode, url, err)
}
return nil, fmt.Errorf("dcrdata error: %v %v %s",
r.StatusCode, url, body)
}
var bdb dcrdataapi.BlockDataBasic
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&bdb); err != nil {
return nil, err
}
return &bdb, nil
}
func block(block uint32) (*dcrdataapi.BlockDataBasic, error) {
h := strconv.FormatUint(uint64(block), 10)
url := decredPluginSettings["dcrdata"] + "/api/block/" + h
log.Debugf("connecting to %v", url)
r, err := http.Get(url)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("dcrdata error: %v %v %v",
r.StatusCode, url, err)
}
return nil, fmt.Errorf("dcrdata error: %v %v %s",
r.StatusCode, url, body)
}
var bdb dcrdataapi.BlockDataBasic
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&bdb); err != nil {
return nil, err
}
return &bdb, nil
}
func batchTransactions(hashes []string) ([]dcrdataapi.TrimmedTx, error) {
// Request body is dcrdataapi.Txns marshalled to JSON
reqBody, err := json.Marshal(dcrdataapi.Txns{
Transactions: hashes,
})
if err != nil {
return nil, err
}
// Make the POST request
url := decredPluginSettings["dcrdata"] + "/api/txs/trimmed"
log.Debugf("connecting to %v", url)
r, err := http.Post(url, "application/json; charset=utf-8",
bytes.NewReader(reqBody))
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("dcrdata error: %v %v %v",
r.StatusCode, url, err)
}
return nil, fmt.Errorf("dcrdata error: %v %v %s",
r.StatusCode, url, body)
}
// Unmarshal the response
var ttx []dcrdataapi.TrimmedTx
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&ttx); err != nil {
return nil, err
}
return ttx, nil
}
// pluginBestBlock returns current best block height from wallet.
func (g *gitBackEnd) pluginBestBlock() (string, error) {
bb, err := bestBlock()
if err != nil {
return "", err
}
return strconv.FormatUint(uint64(bb.Height), 10), nil
}
// decredPluginPostEdit called after and edit is complete but before commit.
func (g *gitBackEnd) decredPluginPostEdit(token string) error {
log.Tracef("decredPluginPostEdit: %v", token)
// The post edit hook gets called on both unvetted and vetted
// proposals, but comments can only be made on vetted proposals.
var destination string
var err error
if g.vettedPropExists(token) {
destination, err = g.flushComments(token)
if err != nil {
return err
}
}
// When destination is empty there was nothing to do
if destination == "" {
log.Tracef("decredPluginPostEdit: nothing to do %v", token)
return nil
}
// Add comments to git
return g.gitAdd(g.unvetted, destination)
}
// createFlushFile creates a file that indicates that the a journal was flused.
//
// Must be called WITH the mutex held.
func createFlushFile(filename string) error {
// Mark directory as flushed
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
// Stuff timestamp in flushfile
j := json.NewEncoder(f)
err = j.Encode(FlushRecord{
Version: flushRecordVersion,
Timestamp: strconv.FormatInt(time.Now().Unix(), 10),
})
return err
}
// flushJournalsUnwind unwinds all the flushing action if something goes wrong.
//
// Must be called WITH the mutex held.
func (g *gitBackEnd) flushJournalsUnwind(id string) error {
// git stash, can fail if there are no uncommitted failures
err := g.gitStash(g.unvetted)
if err == nil {
// git stash drop, allowed to fail
_ = g.gitStashDrop(g.unvetted)
}
// git checkout master
err = g.gitCheckout(g.unvetted, "master")
if err != nil {
return err
}
// delete branch
err = g.gitBranchDelete(g.unvetted, id)
if err != nil {
return err
}
// git clean -xdf
return g.gitClean(g.unvetted)
}
// flushCommentflushes comments journal to decred plugin directory in
// git. It returns the filename that was coppied into git repo.
//
// Must be called WITH the mutex held.
func (g *gitBackEnd) flushComments(token string) (string, error) {
if !g.vettedPropExists(token) {
return "", fmt.Errorf("unknown proposal: %v", token)
}
// Setup source filenames and verify they actually exist
srcDir := pijoin(g.journals, token)
srcComments := pijoin(srcDir, defaultCommentFilename)
if !util.FileExists(srcComments) {
return "", nil
}
// Setup destination filenames
version, err := getLatest(pijoin(g.unvetted, token))
if err != nil {
return "", err
}
dir := pijoin(g.unvetted, token, version, pluginDataDir)
comments := pijoin(dir, defaultCommentFilename)
// Create the destination container dir
_ = os.MkdirAll(dir, 0764)
// Move journal and comment id into place
err = g.journal.Copy(srcComments, comments)
if err != nil {
return "", err
}
// Return filename that is relative to git dir.
return pijoin(token, version, pluginDataDir, defaultCommentFilename),
nil
}
// flushCommentJournal flushes an individual comment journal.
//
// Must be called WITH the mutex held.
func (g *gitBackEnd) flushCommentJournal(token string) (string, error) {
// We simply copy the journal into git
destination, err := g.flushComments(token)
if err != nil {
return "", fmt.Errorf("Could not flush %v: %v", token, err)
}
// Create flush record
filename := pijoin(g.journals, token, defaultCommentsFlushed)
err = createFlushFile(filename)
if err != nil {
return "", fmt.Errorf("Could not mark flushed %v: %v", token,
err)
}
return destination, nil
}
// _flushCommentJournals walks all comment journal directories and copies
// modified journals into the unvetted repo. It returns an array of filenames
// that need to be added to the git repo and subsequently rebased into the
// vetted repo .
//
// Must be called WITH the mutex held.
func (g *gitBackEnd) _flushCommentJournals() ([]string, error) {
dirs, err := ioutil.ReadDir(g.journals)
if err != nil {
return nil, err
}
files := make([]string, 0, len(dirs))
for _, v := range dirs {
filename := pijoin(g.journals, v.Name(),
defaultCommentsFlushed)
log.Tracef("Checking: %v", v.Name())
if util.FileExists(filename) {
continue
}
log.Infof("Flushing comments: %v", v.Name())
// Add filename to work
destination, err := g.flushCommentJournal(v.Name())
if err != nil {
log.Error(err)
continue
}
files = append(files, destination)
}
return files, nil
}
// flushCommentJournals wraps _flushCommentJournals in git magic to revert
// flush in case of errors.
//
// Must be called WITHOUT the mutex held.
func (g *gitBackEnd) flushCommentJournals() error {
log.Tracef("flushCommentJournals")
// We may have to make this more granular
g.Lock()
defer g.Unlock()
// git checkout master
err := g.gitCheckout(g.unvetted, "master")
if err != nil {
return err
}
// git pull --ff-only --rebase
err = g.gitPull(g.unvetted, true)
if err != nil {
return err
}
// git checkout -b timestamp_flushcomments
branch := strconv.FormatInt(time.Now().Unix(), 10) + "_flushcomments"
_ = g.gitBranchDelete(g.unvetted, branch) // Just in case
err = g.gitNewBranch(g.unvetted, branch)
if err != nil {
return err
}
// closure to handle unwind if needed
var errUnwind error
defer func() {
if errUnwind == nil {
return
}
err := g.flushJournalsUnwind(branch)
if err != nil {
log.Errorf("flushJournalsUnwind: %v", err)
}
}()
// Flush journals
files, err := g._flushCommentJournals()
if err != nil {
errUnwind = err
return err
}
if len(files) == 0 {
log.Info("flushCommentJournals: nothing to do")
err = g.flushJournalsUnwind(branch)
if err != nil {
log.Errorf("flushJournalsUnwind: %v", err)
}
return nil
}
// git add journals
commitMessage := "Flush comment journals.\n\n"
for _, v := range files {
err = g.gitAdd(g.unvetted, v)
if err != nil {
errUnwind = err
return err
}
s := strings.Split(v, string(os.PathSeparator))
if len(s) == 0 {
commitMessage += "ERROR: " + v + "\n"
} else {
commitMessage += s[0] + "\n"
}
}
// git commit
err = g.gitCommit(g.unvetted, commitMessage)
if err != nil {
errUnwind = err
return err
}
// git rebase master
err = g.rebasePR(branch)
if err != nil {
errUnwind = err
return err
}
return nil
}
// flushVotes flushes votes journal to decred plugin directory in git. It
// returns the filename that was coppied into git repo.
//
// Must be called WITH the mutex held.
func (g *gitBackEnd) flushVotes(token string) (string, error) {
if !g.vettedPropExists(token) {
return "", fmt.Errorf("unknown proposal: %v", token)
}
// Setup source filenames and verify they actually exist
srcDir := pijoin(g.journals, token)
srcVotes := pijoin(srcDir, defaultBallotFilename)
if !util.FileExists(srcVotes) {
return "", nil
}
// Setup destination filenames
version, err := getLatest(pijoin(g.unvetted, token))
if err != nil {
return "", err
}
dir := pijoin(g.unvetted, token, version, pluginDataDir)
votes := pijoin(dir, defaultBallotFilename)
// Create the destination container dir
_ = os.MkdirAll(dir, 0764)
// Move journal into place
err = g.journal.Copy(srcVotes, votes)
if err != nil {
return "", err
}
// Return filename that is relative to git dir.
return pijoin(token, version, pluginDataDir, defaultBallotFilename), nil
}
// _flushVotesJournals walks all votes journal directories and copies
// modified journals into the unvetted repo. It returns an array of filenames
// that need to be added to the git repo and subsequently rebased into the
// vetted repo .
//
// Must be called WITH the mutex held.
func (g *gitBackEnd) _flushVotesJournals() ([]string, error) {
dirs, err := ioutil.ReadDir(g.journals)
if err != nil {
return nil, err
}
files := make([]string, 0, len(dirs))
for _, v := range dirs {
filename := pijoin(g.journals, v.Name(),
defaultBallotFlushed)
log.Tracef("Checking: %v", v.Name())
if util.FileExists(filename) {
continue
}
log.Infof("Flushing votes: %v", v.Name())
// We simply copy the journal into git
destination, err := g.flushVotes(v.Name())
if err != nil {
log.Errorf("Could not flush %v: %v", v.Name(), err)
continue
}
// Create flush record
err = createFlushFile(filename)
if err != nil {
log.Errorf("Could not mark flushed %v: %v", v.Name(),
err)
continue
}
// Add filename to work
files = append(files, destination)
}
return files, nil
}
// flushVoteJournals wraps _flushVoteJournals in git magic to revert
// flush in case of errors.
//
// Must be called WITHOUT the mutex held.
func (g *gitBackEnd) flushVoteJournals() error {
log.Tracef("flushVoteJournals")
// We may have to make this more granular
g.Lock()
defer g.Unlock()
// git checkout master
err := g.gitCheckout(g.unvetted, "master")
if err != nil {
return err
}
// git pull --ff-only --rebase
err = g.gitPull(g.unvetted, true)
if err != nil {
return err
}
// git checkout -b timestamp_flushvotes
branch := strconv.FormatInt(time.Now().Unix(), 10) + "_flushvotes"
_ = g.gitBranchDelete(g.unvetted, branch) // Just in case
err = g.gitNewBranch(g.unvetted, branch)
if err != nil {
return err
}
// closure to handle unwind if needed
var errUnwind error
defer func() {
if errUnwind == nil {
return
}
err := g.flushJournalsUnwind(branch)
if err != nil {
log.Errorf("flushJournalsUnwind: %v", err)
}
}()
// Flush journals
files, err := g._flushVotesJournals()
if err != nil {
errUnwind = err
return err
}
if len(files) == 0 {
log.Info("flushVotesJournals: nothing to do")
err = g.flushJournalsUnwind(branch)
if err != nil {
log.Errorf("flushJournalsUnwind: %v", err)
}
return nil
}
// git add journals
commitMessage := "Flush vote journals.\n\n"
for _, v := range files {
err = g.gitAdd(g.unvetted, v)
if err != nil {
errUnwind = err
return err
}
s := strings.Split(v, string(os.PathSeparator))
if len(s) == 0 {
commitMessage += "ERROR: " + v + "\n"
} else {
commitMessage += s[0] + "\n"
}
}
// git commit
err = g.gitCommit(g.unvetted, commitMessage)
if err != nil {
errUnwind = err
return err
}
// git rebase master
err = g.rebasePR(branch)
if err != nil {
errUnwind = err
return err
}
return nil
}
func (g *gitBackEnd) decredPluginJournalFlusher() {
// XXX make this a single PR instead of 2 to save some git time
err := g.flushCommentJournals()
if err != nil {
log.Errorf("decredPluginJournalFlusher: %v", err)
}
err = g.flushVoteJournals()
if err != nil {
log.Errorf("decredPluginVoteFlusher: %v", err)
}
}
func (g *gitBackEnd) pluginNewComment(payload string) (string, error) {
// XXX this should become part of some sort of context
fiJSON, ok := decredPluginSettings[decredPluginIdentity]
if !ok {
return "", fmt.Errorf("full identity not set")
}
fi, err := identity.UnmarshalFullIdentity([]byte(fiJSON))
if err != nil {
return "", err
}
// Decode comment
comment, err := decredplugin.DecodeNewComment([]byte(payload))
if err != nil {
return "", fmt.Errorf("DecodeNewComment: %v", err)
}
// Verify proposal exists, we can run this lockless
if !g.vettedPropExists(comment.Token) {
return "", fmt.Errorf("unknown proposal: %v", comment.Token)
}
// Do some cheap things before expensive calls
cfilename := pijoin(g.journals, comment.Token,
defaultCommentFilename)
if comment.ParentID == "" {
// Empty ParentID means comment 0
comment.ParentID = "0"
}
// Sign signature
r := fi.SignMessage([]byte(comment.Signature))
receipt := hex.EncodeToString(r[:])
// Create new comment id
cid, err := g.getNewCid(comment.Token)
if err != nil {
return "", fmt.Errorf("could not generate new comment id: %v",
err)
}
// Create Journal entry
c := decredplugin.Comment{
Token: comment.Token,
ParentID: comment.ParentID,
Comment: comment.Comment,
Signature: comment.Signature,
PublicKey: comment.PublicKey,
CommentID: cid,
Receipt: receipt,
Timestamp: time.Now().Unix(),
}
blob, err := decredplugin.EncodeComment(c)
if err != nil {
return "", fmt.Errorf("EncodeComment: %v", err)
}
// Add comment to journal
err = g.journal.Journal(cfilename, string(journalAdd)+
string(blob))
if err != nil {
return "", fmt.Errorf("could not journal %v: %v", c.Token, err)
}
// Comment journal filename
flushFilename := pijoin(g.journals, comment.Token,
defaultCommentsFlushed)
// Cache comment
g.Lock()
// Mark comment journal dirty
_ = os.Remove(flushFilename)
// Remove from cash.
if _, ok := decredPluginCommentsCache[c.Token]; !ok {
decredPluginCommentsCache[c.Token] =
make(map[string]decredplugin.Comment)
}
_, ok = decredPluginCommentsCache[c.Token][c.CommentID]
if ok {
// Sanity
log.Errorf("comment should not have existed.")
}
decredPluginCommentsCache[c.Token][c.CommentID] = c
g.Unlock()
// Encode reply
ncr := decredplugin.NewCommentReply{
CommentID: c.CommentID,
Receipt: c.Receipt,
Timestamp: c.Timestamp,
}
ncrb, err := decredplugin.EncodeNewCommentReply(ncr)
if err != nil {
return "", fmt.Errorf("EncodeNewCommentReply: %v", err)
}
// return success and encoded answer
return string(ncrb), nil
}
func (g *gitBackEnd) pluginCensorComment(payload string) (string, error) {
log.Tracef("pluginCensorComment")
// Check if journals were replayed
if !journalsReplayed {
return "", backend.ErrJournalsNotReplayed
}
// XXX this should become part of some sort of context
fiJSON, ok := decredPluginSettings[decredPluginIdentity]
if !ok {
return "", fmt.Errorf("full identity not set")
}
fi, err := identity.UnmarshalFullIdentity([]byte(fiJSON))
if err != nil {
return "", fmt.Errorf("UnmarshalFullIdentity: %v", err)
}
// Decode censor comment
censor, err := decredplugin.DecodeCensorComment([]byte(payload))
if err != nil {
return "", fmt.Errorf("DecodeCensorComment: %v", err)
}
// Verify proposal exists, we can run this lockless
if !g.vettedPropExists(censor.Token) {
return "", fmt.Errorf("unknown proposal: %v", censor.Token)
}
// Sign signature
r := fi.SignMessage([]byte(censor.Signature))
receipt := hex.EncodeToString(r[:])
// Comment journal filename
flushFilename := pijoin(g.journals, censor.Token,
defaultCommentsFlushed)
// Ensure proposal exists in comments cache
g.Lock()
// Mark comment journal dirty
_ = os.Remove(flushFilename)
// Verify cache
_, ok = decredPluginCommentsCache[censor.Token]
if !ok {
g.Unlock()
return "", fmt.Errorf("proposal not found %v", censor.Token)
}
// Ensure comment exists in comments cache and has not
// already been censored
c, ok := decredPluginCommentsCache[censor.Token][censor.CommentID]
if !ok {
g.Unlock()
return "", fmt.Errorf("comment not found %v:%v",
censor.Token, censor.CommentID)
}
if c.Censored {
g.Unlock()
return "", fmt.Errorf("comment already censored %v: %v",
censor.Token, censor.CommentID)
}
// Update comments cache
oc := c
c.Comment = ""
c.Censored = true
decredPluginCommentsCache[censor.Token][censor.CommentID] = c
g.Unlock()
// We create an unwind function that MUST be called from all error
// paths. If everything works ok it is a no-op.
unwind := func() {
g.Lock()
decredPluginCommentsCache[censor.Token][censor.CommentID] = oc
g.Unlock()
}
// Create Journal entry
cc := decredplugin.CensorComment{
Token: censor.Token,
CommentID: censor.CommentID,
Reason: censor.Reason,
Signature: censor.Signature,
PublicKey: censor.PublicKey,
Receipt: receipt,
Timestamp: time.Now().Unix(),
}
blob, err := decredplugin.EncodeCensorComment(cc)
if err != nil {
unwind()
return "", fmt.Errorf("EncodeCensorComment: %v", err)
}
// Add censor comment to journal
cfilename := pijoin(g.journals, censor.Token,
defaultCommentFilename)
err = g.journal.Journal(cfilename, string(journalDel)+string(blob))
if err != nil {
unwind()
return "", fmt.Errorf("could not journal %v: %v", cc.Token, err)
}
// Encode reply
ccr := decredplugin.CensorCommentReply{
Receipt: cc.Receipt,
}
ccrb, err := decredplugin.EncodeCensorCommentReply(ccr)
if err != nil {
unwind()
return "", fmt.Errorf("EncodeCensorCommentReply: %v", err)
}
return string(ccrb), nil
}
// encodeGetCommentsReply converts a comment map into a JSON string that can be
// returned as a decredplugin reply. If the comment map is nil it returns a
// valid empty reply structure.
func encodeGetCommentsReply(cm map[string]decredplugin.Comment) (string, error) {
if cm == nil {
cm = make(map[string]decredplugin.Comment)
}
// Encode reply
gcr := decredplugin.GetCommentsReply{
Comments: make([]decredplugin.Comment, 0, len(cm)),
}
for _, v := range cm {
gcr.Comments = append(gcr.Comments, v)
}
gcrb, err := decredplugin.EncodeGetCommentsReply(gcr)
if err != nil {
return "", fmt.Errorf("encodeGetCommentsReply: %v", err)
}
return string(gcrb), nil
}
// replayComments replay the comments for a given proposal
// the proposal is matched by the provided token
// this function can be called WITHOUT the lock held
func (g *gitBackEnd) replayComments(token string) (map[string]decredplugin.Comment, error) {
log.Debugf("replayComments %s", token)
// Verify proposal exists, we can run this lockless
if !g.vettedPropExists(token) {
return nil, nil
}
// Do some cheap things before expensive calls
cfilename := pijoin(g.journals, token,
defaultCommentFilename)
// Replay journal
err := g.journal.Open(cfilename)
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("journal.Open: %v", err)
}
return nil, nil
}
defer func() {
err = g.journal.Close(cfilename)
if err != nil {
log.Errorf("journal.Close: %v", err)
}
}()
comments := make(map[string]decredplugin.Comment)
for {
err = g.journal.Replay(cfilename, func(s string) error {
ss := bytes.NewReader([]byte(s))
d := json.NewDecoder(ss)
// Decode action
var action JournalAction
err = d.Decode(&action)
if err != nil {
return fmt.Errorf("journal action: %v", err)
}
switch action.Action {
case journalActionAdd:
var c decredplugin.Comment
err = d.Decode(&c)
if err != nil {
return fmt.Errorf("journal add: %v",
err)
}
// Sanity
if _, ok := comments[c.CommentID]; ok {
log.Errorf("duplicate comment id %v",
c.CommentID)
}
comments[c.CommentID] = c
case journalActionDel:
var cc decredplugin.CensorComment
err = d.Decode(&cc)
if err != nil {
return fmt.Errorf("journal censor: %v",
err)
}
// Ensure comment has been added
c, ok := comments[cc.CommentID]
if !ok {
// Complain but we can't do anything
// about it. Can't return error or we'd
// abort journal loop.
log.Errorf("comment not found: %v",
cc.CommentID)
return nil
}
// Delete comment
c.Comment = ""
c.Censored = true
comments[cc.CommentID] = c
default:
return fmt.Errorf("invalid action: %v",
action.Action)
}
return nil
})
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
}
g.Lock()
decredPluginCommentsCache[token] = comments
g.Unlock()
return comments, nil
}
func (g *gitBackEnd) pluginGetComments(payload string) (string, error) {
log.Tracef("pluginGetComments")
// Check if journals were replayed
if !journalsReplayed {
return "", backend.ErrJournalsNotReplayed
}
// Decode comment
gc, err := decredplugin.DecodeGetComments([]byte(payload))
if err != nil {
return "", fmt.Errorf("DecodeGetComments: %v", err)
}
g.Lock()
comments := decredPluginCommentsCache[gc.Token]
g.Unlock()
return encodeGetCommentsReply(comments)
}
|
sigopt/sigopt-java
|
src/test/java/com/sigopt/net/ParamsBuilderTest.java
|
package com.sigopt.net;
import com.sigopt.model.APIResource;
import com.sigopt.model.MockResource;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ParamsBuilderTest {
HashMap<String, Object> params;
@BeforeClass
public static void setUp() {
}
@Before
public void setUpMockData() {
params = new HashMap<String, Object>();
}
@Test
public void buildSimple() throws Exception {
params.put("age", 100);
params.put("name", "sigopt");
params.put("is_cool", true);
params.put("null_key", null);
Map<String, Object> actual = ParamsBuilder.build(params);
assertEquals("100", actual.get("age"));
assertEquals("sigopt", actual.get("name"));
assertEquals("true", actual.get("is_cool"));
assertFalse(actual.containsKey("null_key"));
}
@Test
public void buildWithData() throws Exception {
MockResource mockResource = new MockResource("id-10", "some-name-here");
params.put("data", mockResource);
Map<String, Object> actual = ParamsBuilder.build(params);
assertEquals(mockResource.toJson(), actual.get("data"));
}
@Test
public void buildWithJson() throws Exception {
MockResource mockResource = new MockResource("id-10", "some-name-here");
params.put("data", mockResource);
Map<String, Object> actual = ParamsBuilder.build(params);
String dataString = ((String) actual.get("data"));
assertTrue("superAwesomeName serialized as underscore case", dataString.indexOf("super_awesome_name") >= 0);
}
}
|
humaniq/react-native-android-library-humaniq-api
|
android/src/main/java/com/humaniq/apilib/network/models/response/profile/ExchangeModelUsd.java
|
<gh_stars>1-10
package com.humaniq.apilib.network.models.response.profile;
/**
* Created by gritsay on 7/31/17.
*/
public class ExchangeModelUsd {
private double USD;
public double getUSD() {
return USD;
}
public void setUSD(double USD) {
this.USD = USD;
}
}
|
jwilger/racing_on_rails
|
app/controllers/pages_controller.rb
|
# frozen_string_literal: true
# Any way to not require render_page?
# Should provide sensible default if page is missing? Or just a 404?
# Thinking we have a catch-all controller that uses render inline,
# but could use a template handler with a comple method that queries DB?
# Template-finding seems to assume a file, though
class PagesController < ApplicationController
def show
@page = Page.find_by_normalized_path!(params[:path])
render inline: @page.body, layout: "application"
end
end
|
gazer2kanlin/uia.message4j
|
uia.message/src/main/java/uia/message/codec/FloatCodec.java
|
/*******************************************************************************
* Copyright 2017 UIA
*
* 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 uia.message.codec;
import java.nio.ByteBuffer;
/**
* Convert data between float and byte array. <br>
*
* @author Kyle
*/
public class FloatCodec implements BlockCodec<Float> {
@Override
public Float zeroValue() {
return 0.0f;
}
@Override
public Float decode(byte[] data, int bitLength) throws BlockCodecException {
try {
return Float.valueOf(ByteBuffer.wrap(data).getFloat());
}
catch (Exception ex) {
throw new BlockCodecException("float codec failure. " + ex.getMessage(), ex);
}
}
@Override
public byte[] encode(Float data, int bitLength) throws BlockCodecException {
try {
float value = data.floatValue();
return ByteBuffer.allocate(4).putFloat(value).array();
}
catch (Exception ex) {
throw new BlockCodecException("float encode failure. " + ex.getMessage(), ex);
}
}
@Override
public void reset() {
}
@Override
public String getValueType() {
return "float";
}
}
|
craynafinal/cs553_design_pattern_assignments
|
visitor/pattpack/expr_vis1/Variable.java
|
package pattpack.expr_vis1;
import java.io.*;
/**
* This class represents a variable in an expression.
* A variable holds its current value under the assumption
* (Flyweight pattern) that all occurrences of a same
* variable are shared. This is a crucial assumption for
* interpreting the statements that host a variable.
*/
public class Variable implements Expr {
private String name;
private int value;
/**
* Construct a variable.
* @param name The identifier of this variable.
*/
public Variable (String name) { this (name, 0); }
/**
* Construct a variable.
* @param name The identifier of this variable.
* @param value The initializer of this variable.
*/
public Variable (String name, int value) {
this.name = name;
this.value = value;
}
/**
* Print this expression.
* @param out The stream where the expression is printed.
*/
public void print (PrintStream out) { out.print (name); }
/**
* Set the value of this variable.
* @param value The value to set this variable to.
*/
public void setValue (int value) { this.value = value; }
/**
* Return the value of this variable.
* @return The value of this variable.
*/
public int eval () { return value; }
}
|
alexa/alexa-apis-for-java
|
ask-smapi-model/src/com/amazon/ask/smapi/model/v1/skill/betaTest/BetaTest.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
* except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.amazon.ask.smapi.model.v1.skill.betaTest;
import java.util.Objects;
import java.time.OffsetDateTime;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Beta test for an Alexa skill.
*/
@JsonDeserialize(builder = BetaTest.Builder.class)
public final class BetaTest {
@JsonProperty("expiryDate")
private OffsetDateTime expiryDate = null;
@JsonProperty("status")
private String status = null;
@JsonProperty("feedbackEmail")
private String feedbackEmail = null;
@JsonProperty("invitationUrl")
private String invitationUrl = null;
@JsonProperty("invitesRemaining")
private Integer invitesRemaining = null;
public static Builder builder() {
return new Builder();
}
private BetaTest(Builder builder) {
if (builder.expiryDate != null) {
this.expiryDate = builder.expiryDate;
}
if (builder.status != null) {
this.status = builder.status;
}
if (builder.feedbackEmail != null) {
this.feedbackEmail = builder.feedbackEmail;
}
if (builder.invitationUrl != null) {
this.invitationUrl = builder.invitationUrl;
}
if (builder.invitesRemaining != null) {
this.invitesRemaining = builder.invitesRemaining;
}
}
/**
* Expiry date of the beta test.
* @return expiryDate
**/
@JsonProperty("expiryDate")
public OffsetDateTime getExpiryDate() {
return expiryDate;
}
/**
* Get status
*
* For this enum type, if a value unknown to the SDK is returned the UNKNOWN_TO_SDK_VERSION
* enumeration value will be returned. To directly return the raw String value, use getStatusAsString().
*
* @return status
**/
public com.amazon.ask.smapi.model.v1.skill.betaTest.Status getStatus() {
return com.amazon.ask.smapi.model.v1.skill.betaTest.Status.fromValue(status);
}
/**
* Get the underlying String value for status.
*
* Using this accessor will retrieve the raw underlying value, even if it is not
* present in the corresponding enumeration. For forward compatibility, it is recommended
* to use this approach over the enumeration.
*
* @return status as a String value
**/
@JsonProperty("status")
public String getStatusAsString() {
return status;
}
/**
* Email address for providing feedback
* @return feedbackEmail
**/
@JsonProperty("feedbackEmail")
public String getFeedbackEmail() {
return feedbackEmail;
}
/**
* Deeplinking for getting authorized to the beta test.
* @return invitationUrl
**/
@JsonProperty("invitationUrl")
public String getInvitationUrl() {
return invitationUrl;
}
/**
* Remaining invite count for the beta test.
* @return invitesRemaining
**/
@JsonProperty("invitesRemaining")
public Integer getInvitesRemaining() {
return invitesRemaining;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BetaTest v1SkillBetaTestBetaTest = (BetaTest) o;
return Objects.equals(this.expiryDate, v1SkillBetaTestBetaTest.expiryDate) &&
Objects.equals(this.status, v1SkillBetaTestBetaTest.status) &&
Objects.equals(this.feedbackEmail, v1SkillBetaTestBetaTest.feedbackEmail) &&
Objects.equals(this.invitationUrl, v1SkillBetaTestBetaTest.invitationUrl) &&
Objects.equals(this.invitesRemaining, v1SkillBetaTestBetaTest.invitesRemaining);
}
@Override
public int hashCode() {
return Objects.hash(expiryDate, status, feedbackEmail, invitationUrl, invitesRemaining);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class BetaTest {\n");
sb.append(" expiryDate: ").append(toIndentedString(expiryDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" feedbackEmail: ").append(toIndentedString(feedbackEmail)).append("\n");
sb.append(" invitationUrl: ").append(toIndentedString(invitationUrl)).append("\n");
sb.append(" invitesRemaining: ").append(toIndentedString(invitesRemaining)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static class Builder {
private OffsetDateTime expiryDate;
private String status;
private String feedbackEmail;
private String invitationUrl;
private Integer invitesRemaining;
private Builder() {}
@JsonProperty("expiryDate")
public Builder withExpiryDate(OffsetDateTime expiryDate) {
this.expiryDate = expiryDate;
return this;
}
@JsonProperty("status")
public Builder withStatus(String status) {
this.status = status;
return this;
}
public Builder withStatus(com.amazon.ask.smapi.model.v1.skill.betaTest.Status status) {
this.status = status != null ? status.toString() : null;
return this;
}
@JsonProperty("feedbackEmail")
public Builder withFeedbackEmail(String feedbackEmail) {
this.feedbackEmail = feedbackEmail;
return this;
}
@JsonProperty("invitationUrl")
public Builder withInvitationUrl(String invitationUrl) {
this.invitationUrl = invitationUrl;
return this;
}
@JsonProperty("invitesRemaining")
public Builder withInvitesRemaining(Integer invitesRemaining) {
this.invitesRemaining = invitesRemaining;
return this;
}
public BetaTest build() {
return new BetaTest(this);
}
}
}
|
Leonard2/alive_reversing
|
Source/Tools/relive_api/BaseProperty.cpp
|
#include "BaseProperty.hpp"
#include <jsonxx/jsonxx.h>
#include <string>
BaseProperty::BaseProperty(const std::string& name, const std::string& typeName, bool isVisibleToEditor)
: m_name(name)
, m_typeName(typeName)
, m_isVisibleToEditor(isVisibleToEditor)
{
}
BaseProperty::~BaseProperty() = default;
[[nodiscard]] const std::string& BaseProperty::Name() const
{
return m_name;
}
[[nodiscard]] const std::string& BaseProperty::TypeName() const
{
return m_typeName;
}
[[nodiscard]] bool BaseProperty::IsVisibleToEditor() const
{
return m_isVisibleToEditor;
}
|
chromium/chromium
|
cc/raster/gpu_raster_buffer_provider.h
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_RASTER_GPU_RASTER_BUFFER_PROVIDER_H_
#define CC_RASTER_GPU_RASTER_BUFFER_PROVIDER_H_
#include <stdint.h>
#include <memory>
#include <random>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "cc/raster/raster_buffer_provider.h"
#include "cc/raster/raster_query_queue.h"
#include "gpu/command_buffer/common/sync_token.h"
namespace gpu {
namespace raster {
class RasterInterface;
} // namespace raster
} // namespace gpu
namespace viz {
class ContextProvider;
class RasterContextProvider;
} // namespace viz
namespace cc {
class CC_EXPORT GpuRasterBufferProvider : public RasterBufferProvider {
public:
static constexpr float kRasterMetricProbability = 0.01;
GpuRasterBufferProvider(
viz::ContextProvider* compositor_context_provider,
viz::RasterContextProvider* worker_context_provider,
bool use_gpu_memory_buffer_resources,
viz::ResourceFormat tile_format,
const gfx::Size& max_tile_size,
bool unpremultiply_and_dither_low_bit_depth_tiles,
bool enable_oop_rasterization,
RasterQueryQueue* const pending_raster_queries,
float raster_metric_probability = kRasterMetricProbability);
GpuRasterBufferProvider(const GpuRasterBufferProvider&) = delete;
~GpuRasterBufferProvider() override;
GpuRasterBufferProvider& operator=(const GpuRasterBufferProvider&) = delete;
// Overridden from RasterBufferProvider:
std::unique_ptr<RasterBuffer> AcquireBufferForRaster(
const ResourcePool::InUsePoolResource& resource,
uint64_t resource_content_id,
uint64_t previous_content_id,
bool depends_on_at_raster_decodes,
bool depends_on_hardware_accelerated_jpeg_candidates,
bool depends_on_hardware_accelerated_webp_candidates) override;
void Flush() override;
viz::ResourceFormat GetResourceFormat() const override;
bool IsResourcePremultiplied() const override;
bool CanPartialRasterIntoProvidedResource() const override;
bool IsResourceReadyToDraw(
const ResourcePool::InUsePoolResource& resource) const override;
uint64_t SetReadyToDrawCallback(
const std::vector<const ResourcePool::InUsePoolResource*>& resources,
base::OnceClosure callback,
uint64_t pending_callback_id) const override;
void Shutdown() override;
gpu::SyncToken PlaybackOnWorkerThread(
gpu::Mailbox* mailbox,
GLenum texture_target,
bool texture_is_overlay_candidate,
const gpu::SyncToken& sync_token,
const gfx::Size& resource_size,
viz::ResourceFormat resource_format,
const gfx::ColorSpace& color_space,
bool resource_has_previous_content,
const RasterSource* raster_source,
const gfx::Rect& raster_full_rect,
const gfx::Rect& raster_dirty_rect,
uint64_t new_content_id,
const gfx::AxisTransform2d& transform,
const RasterSource::PlaybackSettings& playback_settings,
const GURL& url,
base::TimeTicks raster_buffer_creation_time,
bool depends_on_at_raster_decodes,
bool depends_on_hardware_accelerated_jpeg_candidates,
bool depends_on_hardware_accelerated_webp_candidates);
private:
class GpuRasterBacking;
class RasterBufferImpl : public RasterBuffer {
public:
RasterBufferImpl(GpuRasterBufferProvider* client,
const ResourcePool::InUsePoolResource& in_use_resource,
GpuRasterBacking* backing,
bool resource_has_previous_content,
bool depends_on_at_raster_decodes,
bool depends_on_hardware_accelerated_jpeg_candidates,
bool depends_on_hardware_accelerated_webp_candidates);
RasterBufferImpl(const RasterBufferImpl&) = delete;
~RasterBufferImpl() override;
RasterBufferImpl& operator=(const RasterBufferImpl&) = delete;
// Overridden from RasterBuffer:
void Playback(const RasterSource* raster_source,
const gfx::Rect& raster_full_rect,
const gfx::Rect& raster_dirty_rect,
uint64_t new_content_id,
const gfx::AxisTransform2d& transform,
const RasterSource::PlaybackSettings& playback_settings,
const GURL& url) override;
bool SupportsBackgroundThreadPriority() const override;
private:
// These fields may only be used on the compositor thread.
const raw_ptr<GpuRasterBufferProvider> client_;
raw_ptr<GpuRasterBacking> backing_;
// These fields are for use on the worker thread.
const gfx::Size resource_size_;
const viz::ResourceFormat resource_format_;
const gfx::ColorSpace color_space_;
const bool resource_has_previous_content_;
const bool depends_on_at_raster_decodes_;
const bool depends_on_hardware_accelerated_jpeg_candidates_;
const bool depends_on_hardware_accelerated_webp_candidates_;
const gpu::SyncToken before_raster_sync_token_;
const GLenum texture_target_;
const bool texture_is_overlay_candidate_;
gpu::Mailbox mailbox_;
// A SyncToken to be returned from the worker thread, and waited on before
// using the rastered resource.
gpu::SyncToken after_raster_sync_token_;
base::TimeTicks creation_time_;
};
bool ShouldUnpremultiplyAndDitherResource(viz::ResourceFormat format) const;
gpu::SyncToken PlaybackOnWorkerThreadInternal(
gpu::Mailbox* mailbox,
GLenum texture_target,
bool texture_is_overlay_candidate,
const gpu::SyncToken& sync_token,
const gfx::Size& resource_size,
viz::ResourceFormat resource_format,
const gfx::ColorSpace& color_space,
bool resource_has_previous_content,
const RasterSource* raster_source,
const gfx::Rect& raster_full_rect,
const gfx::Rect& raster_dirty_rect,
uint64_t new_content_id,
const gfx::AxisTransform2d& transform,
const RasterSource::PlaybackSettings& playback_settings,
const GURL& url,
bool depends_on_at_raster_decodes,
RasterQuery* query);
const raw_ptr<viz::ContextProvider> compositor_context_provider_;
const raw_ptr<viz::RasterContextProvider> worker_context_provider_;
const bool use_gpu_memory_buffer_resources_;
const viz::ResourceFormat tile_format_;
const gfx::Size max_tile_size_;
const bool enable_oop_rasterization_;
const raw_ptr<RasterQueryQueue> pending_raster_queries_;
// Accessed with the worker context lock acquired.
std::mt19937 random_generator_;
std::bernoulli_distribution bernoulli_distribution_;
const bool is_using_raw_draw_;
};
} // namespace cc
#endif // CC_RASTER_GPU_RASTER_BUFFER_PROVIDER_H_
|
tianyl1984/androidApp
|
src/org/orman/dbms/sqlite/generic/SQLiteGrammar.java
|
package org.orman.dbms.sqlite.generic;
import java.util.EnumMap;
import java.util.Map;
import org.orman.sql.IndexType;
import org.orman.sql.QueryType;
import org.orman.sql.SQLGrammarProvider;
import org.orman.sql.TableConstraintType;
import org.orman.sql.exception.QueryTypeNotImplementedException;
/**
* MySQL grammar for SQL language. Update accordingly {@link SQLGrammarProvider}
*
* @see SQLGrammarProvider
*
* @author <NAME> <<EMAIL>>
*/
@SuppressWarnings("serial")
public class SQLiteGrammar implements SQLGrammarProvider {
private Map<QueryType, String> queryGrammar = new EnumMap<QueryType, String>(QueryType.class){{
// put statements into map;
put(QueryType.USE_DATABASE, "USE DATABASE {DATABASE}");
put(QueryType.CREATE_TABLE, "CREATE TABLE {TABLE_LIST} ({COLUMN_OR_CONSTRAINT_DESCRIPTION_LIST})");
put(QueryType.CREATE_TABLE_IF_NOT_EXSISTS, "CREATE TABLE IF NOT EXISTS {TABLE_LIST} ({COLUMN_OR_CONSTRAINT_DESCRIPTION_LIST})");
put(QueryType.DROP_TABLE, "DROP TABLE {TABLE_LIST}");
put(QueryType.DROP_TABLE_IF_EXISTS, "DROP TABLE IF EXISTS {TABLE_LIST}");
put(QueryType.SELECT, "SELECT {SELECT_COLUMN_LIST} FROM {TABLE_LIST} {JOIN}{WHERE}{GROUP_BY}{HAVING}{ORDER_BY}{LIMIT}");
put(QueryType.SELECT_DISTINCT, "SELECT DISTINCT {SELECT_COLUMN_LIST} FROM {TABLE_LIST} {JOIN}{WHERE}{GROUP_BY}{HAVING}{ORDER_BY}{LIMIT}");
put(QueryType.INSERT, "INSERT INTO {TABLE_LIST} ({COLUMN_LIST}) VALUES ({VALUE_LIST})");
put(QueryType.UPDATE, "UPDATE {TABLE_LIST} SET {COLUMN_VALUE_LIST} {WHERE}");
put(QueryType.DELETE, "DELETE FROM {TABLE_LIST} {WHERE}");
put(QueryType.CREATE_INDEX, "CREATE INDEX {INDEX_NAME} ON {TABLE_LIST} ({SELECT_COLUMN_LIST})"); // highly depends on DBMS
put(QueryType.CREATE_UNIQUE_INDEX, "CREATE UNIQUE INDEX {INDEX_NAME} ON {TABLE_LIST} ({SELECT_COLUMN_LIST})"); // highly depends on DBMS
put(QueryType.CREATE_INDEX_IF_NOT_EXISTS, "CREATE INDEX IF NOT EXISTS {INDEX_NAME} ON {TABLE_LIST} ({SELECT_COLUMN_LIST})"); // highly depends on DBMS
put(QueryType.CREATE_UNIQUE_INDEX_IF_NOT_EXISTS, "CREATE UNIQUE INDEX IF NOT EXISTS {INDEX_NAME} ON {TABLE_LIST} ({SELECT_COLUMN_LIST})"); // highly depends on DBMS
put(QueryType.DROP_INDEX, "DROP INDEX {INDEX_NAME}");
put(QueryType.DROP_INDEX_IF_EXISTS, "DROP INDEX IF EXISTS {INDEX_NAME} ");
put(QueryType.BEGIN_TRANSACTION, "BEGIN TRANSACTION");
put(QueryType.COMMIT_TRANSACTION, "COMMIT");
put(QueryType.ROLLBACK_TRANSACTION, "ROLLBACK");
}};
private Map<TableConstraintType, String> constraintGrammar = new EnumMap<TableConstraintType, String>(TableConstraintType.class){{
put(TableConstraintType.FOREIGN_KEY, "FOREIGN KEY (%s) REFERENCES %s (%s)");
put(TableConstraintType.UNIQUE, "UNIQUE (%s)");
put(TableConstraintType.PRIMARY_KEY ,"PRIMARY KEY (%s)");
put(TableConstraintType.AUTO_INCREMENT, "PRIMARY KEY AUTOINCREMENT");
put(TableConstraintType.USING, "USING (%s)");
put(TableConstraintType.NOT_NULL, "NOT NULL");
}};
private Map<IndexType, String> indexTypeGrammar = new EnumMap<IndexType, String>(IndexType.class){{
put(IndexType.BTREE, "BTREE");
put(IndexType.HASH, "HASH");
}};
private static final String[] reservedKeywords = {
"ABORT","ACTION","ADD","AFTER",
"ALTER","ANALYZE","AND","AS",
"ATTACH","AUTOINCREMENT","BEFORE","BEGIN",
"BY","CASCADE","CASE","CAST",
"COLLATE","COLUMN","COMMIT","CONFLICT",
"CREATE","CROSS","CURRENT_DATE","CURRENT_TIME",
"DATABASE","DEFAULT","DEFERRABLE","DEFERRED",
"DESC","DETACH","DISTINCT","DROP",
"ELSE","END","ESCAPE","EXCEPT",
"EXISTS","EXPLAIN","FAIL","FOR",
"FROM","FULL","GLOB","GROUP",
"IF","IGNORE","IMMEDIATE","IN",
"INDEXED","INITIALLY","INNER","INSERT",
"INTERSECT","INTO","IS","ISNULL",
"KEY","LEFT","LIKE","LIMIT",
"NATURAL","NO","NOT","NOTNULL",
"OF","OFFSET","ON","OR",
"OUTER","PLAN","PRAGMA","PRIMARY",
"RAISE","REFERENCES","REGEXP","REINDEX",
"RENAME","REPLACE","RESTRICT","RIGHT",
"ROW","SAVEPOINT","SELECT","SET",
"TEMP","TEMPORARY","THEN","TO",
"TRIGGER","UNION","UNIQUE","UPDATE",
"VACUUM","VALUES","VIEW","VIRTUAL", "WHERE"
};
@Override
public String getTemplate(QueryType type) {
String tpl = queryGrammar.get(type);
if (tpl == null)
throw new QueryTypeNotImplementedException(type.toString());
return tpl;
}
@Override
public String getConstraint(TableConstraintType type) {
String tpl = constraintGrammar.get(type);
if (tpl == null)
throw new QueryTypeNotImplementedException(type.toString());
return tpl;
}
@Override
public String getIndexType(IndexType indexType) {
String tpl = indexTypeGrammar.get(indexType);
if (tpl == null)
throw new QueryTypeNotImplementedException(indexType.toString());
return tpl;
}
@Override
public String[] getReservedKeywords() {
return reservedKeywords;
}
}
|
FuTlanyu/StudyBOSLiveBroadcast
|
app/src/main/java/studybos/com/studybos2/data/ChatMessage.java
|
<reponame>FuTlanyu/StudyBOSLiveBroadcast
package studybos.com.studybos2.data;
import java.io.Serializable;
/**
* Created by 机械革命 on 2018/10/17.
*/
public class ChatMessage implements Serializable {
private String sender;
private String getter;
private String mess;
private String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getGetter() {
return getter;
}
public void setGetter(String getter) {
this.getter = getter;
}
public String getMess() {
return mess;
}
public void setMess(String mess) {
this.mess = mess;
}
}
|
appotry/blog_demos
|
dubbo_service_provider/src/main/java/com/bolingcavalry/service/PlatformService.java
|
<reponame>appotry/blog_demos<filename>dubbo_service_provider/src/main/java/com/bolingcavalry/service/PlatformService.java
package com.bolingcavalry.service;
/**
* @author willzhao
* @version V1.0
* @Description: 执行平台层次的服务
* @email <EMAIL>
* @Date 17/5/15 下午2:51
*/
public interface PlatformService {
/**
* 返回rpc来源的身份信息
* @return
*/
String getRpcFrom();
}
|
Mario-Kart-Felix/django-cms
|
cms/test_utils/project/sampleapp/urls_extra.py
|
<filename>cms/test_utils/project/sampleapp/urls_extra.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'extra_2/$', views.extra_view, {'message': 'test included urlconf'}, name='extra_second'),
]
|
Testiduk/gitlabhq
|
spec/features/security/dashboard_access_spec.rb
|
<gh_stars>1000+
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe "Dashboard access" do
include AccessMatchers
describe "GET /dashboard" do
subject { dashboard_projects_path }
it { is_expected.to be_allowed_for :admin }
it { is_expected.to be_allowed_for :user }
it { is_expected.to be_denied_for :visitor }
end
describe "GET /dashboard/issues" do
subject { issues_dashboard_path }
it { is_expected.to be_allowed_for :admin }
it { is_expected.to be_allowed_for :user }
it { is_expected.to be_denied_for :visitor }
end
describe "GET /dashboard/merge_requests" do
subject { merge_requests_dashboard_path }
it { is_expected.to be_allowed_for :admin }
it { is_expected.to be_allowed_for :user }
it { is_expected.to be_denied_for :visitor }
end
describe "GET /dashboard/projects/starred" do
subject { starred_dashboard_projects_path }
it { is_expected.to be_allowed_for :admin }
it { is_expected.to be_allowed_for :user }
it { is_expected.to be_denied_for :visitor }
end
describe "GET /help" do
subject { help_path }
it { is_expected.to be_allowed_for :admin }
it { is_expected.to be_allowed_for :user }
it { is_expected.to be_allowed_for :visitor }
end
describe "GET /projects/new" do
it { expect(new_project_path).to be_allowed_for :admin }
it { expect(new_project_path).to be_allowed_for :user }
it { expect(new_project_path).to be_denied_for :visitor }
end
describe "GET /groups/new" do
it { expect(new_group_path).to be_allowed_for :admin }
it { expect(new_group_path).to be_allowed_for :user }
it { expect(new_group_path).to be_denied_for :visitor }
end
describe "GET /dashboard/groups" do
subject { dashboard_groups_path }
it { is_expected.to be_allowed_for :admin }
it { is_expected.to be_allowed_for :user }
it { is_expected.to be_denied_for :visitor }
end
end
|
AnnaFilinova/project1
|
venv/Lib/site-packages/bokeh/server/static/js/lib/version.js
|
<reponame>AnnaFilinova/project1<filename>venv/Lib/site-packages/bokeh/server/static/js/lib/version.js
export const version = "2.3.1";
|
bekuno/oc-server3
|
htdocs/resource2/tinymce/plugins/table/langs/ca_dlg.js
|
tinyMCE.addI18n('ca.table_dlg',{
general_tab:"General",
advanced_tab:"Avan\u00E7at",
general_props:"Propietats generals",
advanced_props:"Propietats avan\u00E7ades",
rowtype:"Fila",
title:"Insereix/Modifica taula",
width:"Amplada",
height:"Al\u00E7ada",
cols:"Columnes",
rows:"Files",
cellspacing:"Espaiat de cel\u00B7la",
cellpadding:"Separaci\u00F3 de cel\u00B7la",
border:"Vora",
align:"Alineaci\u00F3",
align_default:"Per defecte",
align_left:"Esquerra",
align_right:"Dreta",
align_middle:"Centre",
row_title:"Propietats de fila",
cell_title:"Propietats de cel\u00B7la",
cell_type:"Tipus de cel\u00B7la",
valign:"Alineaci\u00F3 vertical",
align_top:"A dalt",
align_bottom:"A baix",
bordercolor:"Color de vora",
bgcolor:"Color de fons",
merge_cells_title:"Fusiona cel\u00B7les",
id:"Id",
style:"Estil",
langdir:"Direcci\u00F3 de l\'idioma",
langcode:"Codi de l\'idioma",
mime:"Tipus MIME",
ltr:"D\'esquerra a dreta",
rtl:"De dreta a esquerra",
bgimage:"Imatge de fons",
summary:"Resum",
td:"Dades",
th:"Cap\u00E7alera",
cell_cell:"Actualitza la cel\u00B7la",
cell_row:"Actualitza totes les cel\u00B7les de la fila",
cell_all:"Actualitza totes les cel\u00B7les de la taula",
row_row:"Actualitza la fila",
row_odd:"Actualitza les files senars",
row_even:"Actualitza les files parells",
row_all:"Actualitza totes les files",
thead:"Cap\u00E7alera de la taula",
tbody:"Cos de la taula",
tfoot:"Peu de la taula",
scope:"Abast",
rowgroup:"Grup de files",
colgroup:"Grup de columnes",
col_limit:"Heu superat el nombre m\u00E0xim de columnes de {$cols}.",
row_limit:"Heu superat el nombre m\u00E0xim de files de {$rows}.",
cell_limit:"Heu superat el nombre m\u00E0xim de cel\u00B7les de {$cells}..",
missing_scope:"Esteu segur que voleu continuar sense indicar un abast per a aquesta cel\u00B7la de cap\u00E7alera. Pot ser dif\u00EDcil per a alguns usuaris amb discapacitats entendre el contingut o les dades mostrades a la taula.",
caption:"T\u00EDtol de la taula",
frame:"Marc",
frame_none:"cap",
frame_groups:"grups",
frame_rows:"files",
frame_cols:"columnes",
frame_all:"tot",
rules:"Regles",
rules_void:"buit",
rules_above:"per damunt de",
rules_below:"per sota de",
rules_hsides:"hsides",
rules_lhs:"lhs",
rules_rhs:"rhs",
rules_vsides:"vsides",
rules_box:"quadre",
rules_border:"vora"
});
|
vladbotlevskyi/website
|
CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js
|
class NoiseLoop {
constructor(diameter, min, max) {
this.diameter = diameter;
this.min = min;
this.max = max;
this.cx = random(1000);
this.cy = random(1000);
}
value(a) {
let xoff = map(cos(a), -1, 1, this.cx, this.cx + this.diameter);
let yoff = map(sin(a), -1, 1, this.cy, this.cy + this.diameter);
let r = noise(xoff, yoff);
return map(r, 0, 1, this.min, this.max);
}
}
|
lab-of-living-matter/freqent
|
freqent/tests/brusselator/plots/make_epTrajFitPlot.py
|
<reponame>lab-of-living-matter/freqent
import os
import sys
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import h5py
import matplotlib as mpl
from datetime import datetime
from scipy import stats
# plt.close('all')
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['font.size'] = 12
mpl.rcParams['axes.linewidth'] = 2
mpl.rcParams['xtick.major.width'] = 2
mpl.rcParams['xtick.minor.width'] = 2
mpl.rcParams['ytick.major.width'] = 2
mpl.rcParams['ytick.minor.width'] = 2
if sys.platform == 'linux':
datapath = '/mnt/llmStorage203/Danny/brusselatorSims/reactionsOnly/191026/'
savepath = '/media/daniel/storage11/Dropbox/LLM_Danny/freqent/brusselator/stochastic_simulations/'
elif sys.platform == 'darwin':
datapath = '/Volumes/Storage/Danny/brusselatorSims/reactionsOnly/191026/'
savepath = '/Users/Danny/Dropbox/LLM_Danny/freqent/brusselator/stochastic_simulations/'
file = 'alpha90.01713130052228_nSim50'
with h5py.File(os.path.join(datapath, file, 'data.hdf5')) as d:
ep_blind_traj = d['data']['ep_blinds'][:, ::10]
epr_blind = d['data']['epr_blind'][()]
t_points = d['data']['t_points'][::10]
mu = np.log((d['params']['B'][()] * d['params']['rates'][2] * d['params']['rates'][4] /
(d['params']['C'][()] * d['params']['rates'][3] * d['params']['rates'][5])))
r = stats.linregress(t_points[len(t_points) // 2:],
ep_blind_traj[:, len(t_points) // 2:].mean(axis=0))
fig, ax = plt.subplots()
ax.plot(t_points, ep_blind_traj.T, 'k', alpha=0.1, lw=0.5)
ax.plot(t_points, ep_blind_traj.mean(axis=0), 'k')
ax.plot(t_points[len(t_points) // 2:],
t_points[len(t_points) // 2:] * r.slope + r.intercept,
'r--', lw=2)
ax.tick_params(which='both', direction='in')
ax.set(xlabel='t', ylabel=r'$\Delta S_{blind}$', title=r'$\Delta \mu = {m:0.2f}$'.format(m=mu))
ax.set_aspect(np.diff(ax.get_xlim())[0] / np.diff(ax.get_ylim())[0])
legend_handles = [mpl.lines.Line2D([0], [0], color='k', alpha=0.1, lw=0.5, label='trajectories'),
mpl.lines.Line2D([0], [0], color='k', label='mean'),
mpl.lines.Line2D([0], [0], linestyle='--', color='r', lw=2, label='linear fit')]
ax.legend(handles=legend_handles, loc='best')
fig.savefig(os.path.join(savepath, datetime.now().strftime('%y%m%d') + '_epBlind_fit_mu{m:0.2f}.pdf'.format(m=mu)), format='pdf')
plt.show()
|
Shemplo/Study-courses
|
Software design/SD - 7. Clock/src/main/java/ru/shemplo/estat/gen/TimeBasedEventGenerator.java
|
<gh_stars>1-10
package ru.shemplo.estat.gen;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import ru.shemplo.estat.EventStatistics;
import ru.shemplo.estat.clock.TimeProvider;
import ru.shemplo.snowball.annot.Cooler;
import ru.shemplo.snowball.annot.Init;
import ru.shemplo.snowball.annot.Snowflake;
@Snowflake
public class TimeBasedEventGenerator implements EventGenerator {
@Cooler
public static TimeBasedEventGenerator getInstance () {
return new TimeBasedEventGenerator ();
}
@Init private EventStatistics statistics;
@Init private TimeProvider provider;
@Init private Random random;
private Thread thread;
private final Runnable THREAD_TASK = () -> {
final long tmp = provider.getCurrentTime ();
AtomicLong previousTime = new AtomicLong (tmp);
while (true) {
long time = provider.getCurrentTime (),
delta = time - previousTime.get ();
final int id = 1 + random.nextInt (10);
if (random.nextDouble () < 1.0 * delta / 20000) {
statistics.registerEvent ("Event " + id);
previousTime.set (time);
/*
System.out.println (String.format ("Event `%s` ocurred\n%s (total %-3d)",
"Event " + id, new Date (time).toString (),
statistics.getEventStatisticsByName ("Event "+ id)));
*/
} else {
try { Thread.sleep (10); }
catch (InterruptedException ie) {
return;
}
}
}
};
@Override
public void startGenerator () {
if (thread == null) {
thread = new Thread (THREAD_TASK);
}
thread.start ();
}
}
|
iorrah/salve-a-quebrada
|
app/components/Modal/index.js
|
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import Button from 'components/Button';
import Cross from 'images/cross.svg';
function Modal(props) {
const inputName = useRef(null);
const inputAddress = useRef(null);
useEffect(() => {
inputName.current.focus();
}, []);
const getIsNameValid = () => {
if (props.name === '') {
inputName.current.focus();
return false;
}
return true;
};
const getIsAddressValid = () => {
if (props.address === '') {
inputAddress.current.focus();
return false;
}
return true;
};
const handleFormSubmit = event => {
event.preventDefault();
if (!getIsNameValid()) {
return false;
}
if (!getIsAddressValid()) {
return false;
}
props.handleSubmit();
return true;
};
return (
<div className="modal__overlay">
<div className="modal__aligner">
<div className="modal__card">
<div className="modal__header">
<h1 className="modal__title">Adicione um novo local</h1>
<button
onClick={props.handleClose}
type="button"
className="modal__close-button"
>
<img
src={Cross}
className="modal__close-image"
alt="Fechar"
title="Fechar"
/>
</button>
</div>
<form onSubmit={handleFormSubmit}>
<div className="modal__body">
<div>
<input
ref={inputName}
name="name"
className="modal__input"
type="text"
placeholder="Nome do local *"
value={props.name}
onChange={props.handleChange}
/>
</div>
<div>
<input
ref={inputAddress}
name="address"
className="modal__input"
type="text"
placeholder="Endereço completo *"
value={props.address}
onChange={props.handleChange}
/>
</div>
<div>
<input
name="link"
className="modal__input"
type="text"
placeholder="Link para doação"
value={props.link}
onChange={props.handleChange}
/>
</div>
<div className="modal_input-container">
<input
name="image-text"
className="modal__input modal__input--file"
type="text"
placeholder="URL para uma foto da faixada"
value={props.imageText}
onChange={props.handleChange}
/>
{/* <input
name="image-file"
id="image-file"
className="modal__input-file"
type="file"
/> */}
{/* <label
htmlFor="image-file"
className="modal__input-file-trigger"
title="Adicionar imagem"
>
Upload
</label> */}
</div>
</div>
<div className="modal__footer">
<Button type="submit">Adicionar Local</Button>
</div>
</form>
</div>
</div>
</div>
);
}
Modal.propTypes = {
handleSubmit: PropTypes.func,
handleClose: PropTypes.func,
handleChange: PropTypes.func,
name: PropTypes.string,
address: PropTypes.string,
link: PropTypes.string,
imageText: PropTypes.string,
};
export default Modal;
|
ezdayo/vpp
|
src/vpp/engine/clustering.cpp
|
/**
*
* @file vpp/engine/clustering.cpp
*
* @brief This is a generic clustering engine
*
* This file is part of the VPP framework (see link).
*
* @author <NAME> <<EMAIL>>
*
* @copyright (c) 2019-2020 <NAME>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/ezdayo/vpp
*
**/
#include "vpp/log.hpp"
#include "vpp/engine/clustering.hpp"
namespace VPP {
namespace Engine {
Clustering::Clustering() noexcept
: dnj(Util::Task::Core::Mode::Sync)
#ifdef VPP_HAS_SIMILARITY_CLUSTERING_SUPPORT
, similarity(Util::Task::Core::Mode::Sync)
#endif
{
#ifdef VPP_HAS_SIMILARITY_CLUSTERING_SUPPORT
similarity.denominate("similarity");
expose(similarity);
similarity.filter = ([](const Zone &){ return false; });
similarity.threshold = 1.0f;
#endif
dnj.denominate("dnj");
expose(dnj);
dnj.filter = ([](const Zone &){ return false; });
dnj.ratio = 0.33f;
dnj.cross = true;
}
Error::Type Clustering::process(Scene &scene) noexcept {
#ifdef VPP_HAS_SIMILARITY_CLUSTERING_SUPPORT
auto err_sim = similarity.start(scene);
if (err_sim != Error::NONE) return err_sim;
err_sim = similarity.wait();
if (err_sim != Error::NONE) return err_sim;
#endif
auto err_dnj = dnj.start(scene);
if (err_dnj != Error::NONE) return err_dnj;
err_dnj = dnj.wait();
return err_dnj;
}
} // namespace Engine
} // namespace VPP
|
dkatashev/adyen-web
|
packages/lib/src/components/internal/Address/components/CountryField.test.js
|
<gh_stars>0
import { mount } from 'enzyme';
import { h } from 'preact';
import CountryField from './CountryField';
import getDataset from '~/utils/fetch-json-data';
jest.mock('~/utils/fetch-json-data');
const countriesMock = [
{
id: 'BR',
name: 'Brazil'
},
{
id: 'NL',
name: 'Netherlands'
},
{
id: 'SG',
name: 'Singapore'
},
{
id: 'US',
name: 'United States'
}
];
getDataset.mockImplementation(jest.fn(() => Promise.resolve(countriesMock)));
describe('CountryField', () => {
const getWrapper = props => mount(<CountryField {...props} />);
test('calls getDataset', () => {
const wrapper = getWrapper();
expect(getDataset).toHaveBeenCalled();
});
test('loads countries', async () => {
const wrapper = await getWrapper();
wrapper.update();
expect(wrapper.find('li[data-value]')).toHaveLength(4);
});
test('only loads the allowed countries ', async () => {
const allowedCountries = ['US', 'NL'];
const wrapper = await getWrapper({ allowedCountries });
wrapper.update();
expect(wrapper.find('li[data-value]')).toHaveLength(2);
});
test('preselects the passed country', async () => {
const value = 'NL';
const wrapper = await getWrapper({ value });
wrapper.update();
expect(wrapper.find('Select').prop('selected')).toBe(value);
});
test('should be read only if there is only one item', async () => {
const allowedCountries = ['NL'];
const value = 'NL';
const wrapper = await getWrapper({ value, allowedCountries });
wrapper.update();
expect(wrapper.find('Select').prop('readonly')).toBe(true);
});
});
|
wtwhite/xmp
|
src/maxmin.h
|
<filename>src/maxmin.h<gh_stars>0
#ifndef __MAXMIN_H
#define __MAXMIN_H
// An external configuration process should #define INLINE to be either "inline" (if it is supported)
// or blank (in the increasingly unlikely event that it is not). But if it doesn't:
#ifndef INLINE
// Assume we do have "inline" ability -- that way if we do, everything works happily and quickly; if we
// don't, we get compilation errors which should point out what we need to do. Would be nice if we
// could warn on this, but there's no portable equivalent of #error for warnings.
#define INLINE inline
#define __MAXMIN_H_WE_DEFINED_INLINE
#endif // not INLINE
// Believe it or not, MSVC++'s C compiler does not recognise the inline keyword, even though its C++
// compiler does! Actually it makes no attempt to be C99 compliant at all, and "inline" is a C99-ism.
// But all's not lost, since empirically on either /O1 or /O2 the MSVC++ 2008 will inline these routines anyway.
static INLINE int iMax(int x, int y) {
return x > y ? x : y;
}
static INLINE int iMin(int x, int y) {
return x < y ? x : y;
}
static INLINE unsigned uMax(unsigned x, unsigned y) {
return x > y ? x : y;
}
static INLINE unsigned uMin(unsigned x, unsigned y) {
return x < y ? x : y;
}
static INLINE long lMax(long x, long y) {
return x > y ? x : y;
}
static INLINE long lMin(long x, long y) {
return x < y ? x : y;
}
static INLINE unsigned long ulMax(unsigned long x, unsigned long y) {
return x > y ? x : y;
}
static INLINE unsigned long ulMin(unsigned long x, unsigned long y) {
return x < y ? x : y;
}
// Don't bother with separate routines for float, since floats are promoted to doubles
// and can implicitly convert back anyway.
static INLINE double dblMax(double x, double y) {
return x > y ? x : y;
}
static INLINE double dblMin(double x, double y) {
return x < y ? x : y;
}
// Clean up after ourselves if necessary...
#ifdef __MAXMIN_H_WE_DEFINED_INLINE
#undef INLINE
#endif // not __MAXMIN_H_WE_DEFINED_INLINE
#endif // #include guard
|
Oliver-makes-code/apoli
|
src/main/java/io/github/apace100/apoli/power/Power.java
|
<filename>src/main/java/io/github/apace100/apoli/power/Power.java
package io.github.apace100.apoli.power;
import net.minecraft.entity.LivingEntity;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;
public class Power {
protected LivingEntity entity;
protected PowerType<?> type;
private boolean shouldTick = false;
private boolean shouldTickWhenInactive = false;
private List<Predicate<LivingEntity>> conditions;
public Power(PowerType<?> type, LivingEntity entity) {
this.type = type;
this.entity = entity;
this.conditions = new LinkedList<>();
}
public Power addCondition(Predicate<LivingEntity> condition) {
this.conditions.add(condition);
return this;
}
protected void setTicking() {
this.setTicking(false);
}
protected void setTicking(boolean evenWhenInactive) {
this.shouldTick = true;
this.shouldTickWhenInactive = evenWhenInactive;
}
public boolean shouldTick() {
return shouldTick;
}
public boolean shouldTickWhenInactive() {
return shouldTickWhenInactive;
}
public void tick() {
}
public void onGained() {
}
public void onLost() {
}
public void onAdded() {
}
public void onRemoved() {
}
public void onRespawn() {
}
public boolean isActive() {
return conditions.stream().allMatch(condition -> condition.test(entity));
}
public NbtElement toTag() {
return new NbtCompound();
}
public void fromTag(NbtElement tag) {
}
public PowerType<?> getType() {
return type;
}
}
|
lveay2/algorithm-solutions
|
src/main/java/lintcode/system_design/_479_Second_Max_of_Array.java
|
<reponame>lveay2/algorithm-solutions<gh_stars>0
package lintcode.system_design;
public class _479_Second_Max_of_Array {
public static int secondMax(int[] nums) {
if (nums.length == 2) {
return Math.min(nums[0], nums[1]);
}
int firstMax = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int num : nums) {
if (num > firstMax) {
secondMax = firstMax;
firstMax = num;
} else if (num > secondMax) {
secondMax = num;
}
}
return secondMax;
}
public static void main(String[] args) {
System.out.println(secondMax(new int[]{1, 3, 2, 4}));
System.out.println(secondMax(new int[]{1, -1, -2}));
System.out.println(secondMax(new int[]{1, 1, 2, 2}));
}
}
|
pguillory/MinecraftAdmin
|
deps/cinch/lib/narcissus.js
|
<filename>deps/cinch/lib/narcissus.js<gh_stars>1-10
var fs = require('fs');
var path = require('path');
function read(basename) {
var filename = path.join(__dirname, '../deps/narcissus/lib', basename + '.js');
return fs.readFileSync(filename, 'utf8');
};
(function() {
var Narcissus;
eval(read('jsdefs'));
eval(read('jslex'));
eval(read('jsparse'));
eval(read('jsdecomp'));
exports.definitions = Narcissus.definitions;
exports.lexer = Narcissus.lexer;
exports.parser = Narcissus.parser;
exports.decompiler = Narcissus.decompiler;
})();
|
pedrohd21/Cursos-Feitos
|
Curso-Em-Video-Python/2Exercicios/103_ficha_de_jogador.py
|
<reponame>pedrohd21/Cursos-Feitos
def jogador(nome='Desconhecido', gols=0):
print(f'O jogador {nome} fez {gols} gols(s) no campeonato.')
#Programa principal
nome = str(input('Nome do jogador: '))
gols = str(input('Quantos gols marcou: '))
if len(nome) > 0:
if gols.isnumeric() > 0:
jogador(nome, int(gols))
else:
jogador(nome=nome)
if gols.isnumeric() > 0:
if len(nome) == 0:
if gols.isnumeric() > 0:
jogador(gols=int(gols))
else:
jogador()
|
bowhan/kent
|
src/hg/encode/docId/docIdView/docIdView.c
|
/* docIdView - cgi to show metadata from docId table. */
#include "common.h"
#include "linefile.h"
#include "hash.h"
#include "options.h"
#include "jksql.h"
#include "htmshell.h"
#include "web.h"
#include "cheapcgi.h"
#include "cart.h"
#include "hui.h"
#include "docId.h"
#include "mdb.h"
#include "portable.h"
#include "trashDir.h"
#include "dystring.h"
/* Global Variables */
struct cart *cart; /* CGI and other variables */
struct hash *oldVars = NULL;
char *database = "encpipeline_prod";
char *docIdTable = DEFAULT_DOCID_TABLE;
//char *docIdDir = "/hive/groups/encode/dcc/pipeline/downloads/docId";
char *docIdDir = "http://hgdownload-test.cse.ucsc.edu/goldenPath/docId";
char *docIdDirBeta = "http://hgdownload-test.cse.ucsc.edu/goldenPath/betaDocId";
void addValue(struct dyString *str, char *value)
{
if ((value != NULL) && !sameString(value, "None"))
{
dyStringPrintf(str, "%s, ", value);
}
}
void doStandard(struct cart *theCart)
{
cart = theCart;
cartWebStart(cart, database, "ENCODE DCC Submissions");
struct sqlConnection *conn = sqlConnect(database);
struct docIdSub *docIdSub;
char query[10 * 1024];
struct sqlResult *sr;
char **row;
struct tempName tn;
trashDirFile(&tn, "docId", "meta", ".txt");
char *tempFile = tn.forCgi;
//printf("tempFile is %s\n<BR>", tempFile);
// <Data type> <Cell Type> <Key Metadata> <View>
printf("<table border=1><tr>");
printf("<th>date submitted</th>");
printf("<th>dataType</th>");
printf("<th>cell type</th>");
printf("<th>metadata</th>");
// printf("<th>view</th>");
printf("<th>fileType</th>");
printf("<th>file</th>");
printf("<th>lab</th>");
printf("<th>assembly</th>");
printf("<th>subId</th>");
printf("<th>val-report</th>");
printf("</tr>\n");
sqlSafef(query, sizeof query, "select * from %s", docIdTable);
sr = sqlGetResult(conn, query);
while ((row = sqlNextRow(sr)) != NULL)
{
docIdSub = docIdSubLoad(row);
verbose(2, "ix %d\n", docIdSub->ix);
verbose(2, "submitDate %s\n", docIdSub->submitDate);
verbose(2, "md5sum %s\n", docIdSub->md5sum);
verbose(2, "valReport %s\n", docIdSub->valReport);
verbose(2, "metaData %s\n", docIdSub->metaData);
verbose(2, "submitPath %s\n", docIdSub->submitPath);
verbose(2, "submitter %s\n", docIdSub->submitter);
cgiDecode(docIdSub->metaData, docIdSub->metaData, strlen(docIdSub->metaData));
//printf("tempFile %s\n", tempFile);
FILE *f = mustOpen(tempFile, "w");
fwrite(docIdSub->metaData, strlen(docIdSub->metaData), 1, f);
fclose(f);
//boolean validated = FALSE;
struct mdbObj *mdbObj = mdbObjsLoadFromFormattedFile(tempFile, NULL);
unlink(tempFile);
// <Data type> <Cell Type> <Key Metadata> <View>
char *docIdType = mdbObjFindValue(mdbObj, "type");
char *docIdComposite = mdbObjFindValue(mdbObj, "composite");
char buffer[10 * 1024];
char *cellFromMetaData = mdbObjFindValue(mdbObj, "cell");
safef(buffer, sizeof buffer, "%d", docIdSub->ix);
if (sameString(database, "encpipeline_beta"))
docIdDir = docIdDirBeta;
printf("<tr>");
printf("<td>%s</td> ", docIdSub->submitDate);
printf("<td>%s</td> ", mdbObjFindValue(mdbObj, "dataType"));
printf("<td>%s</td> ", cellFromMetaData);
struct dyString *str = newDyString(100);
addValue(str, mdbObjFindValue(mdbObj, "antibody"));
addValue(str, mdbObjFindValue(mdbObj, "treatment"));
addValue(str, mdbObjFindValue(mdbObj, "rnaExtract"));
addValue(str, mdbObjFindValue(mdbObj, "localization"));
printf("<td>%s<a href=docIdView?docId=%s&db=%s&meta=\"\"> ...</a></td>", str->string,buffer, database);
freeDyString(&str);
// printf("<td>%s</td> ", mdbObjFindValue(mdbObj, "view"));
printf("<td>%s</td> ", mdbObjFindValue(mdbObj, "type"));
printf("<td><a href=%s> %s</a></td>",
docIdGetPath(buffer, docIdDir, docIdType, NULL) ,
docIdDecorate(docIdComposite, cellFromMetaData, docIdSub->ix));
char *lab = mdbObjFindValue(mdbObj, "lab");
char *subId = mdbObjFindValue(mdbObj, "subId");
printf("<td><a href=docIdView?docId=%s&db=%s&lab=\"%s\"> %s</a></td>",buffer, database, subId, lab);
printf("<td>%s</td> ", mdbObjFindValue(mdbObj, "assembly"));
printf("<td>%s</td> ", subId);
printf("<td><a href=docIdView?docId=%s&db=%s&report=\"\"> report</a></td>", buffer, database);
printf("</tr>\n");
}
printf("</table>");
sqlFreeResult(&sr);
sqlDisconnect(&conn);
cartWebEnd();
}
void doDocIdMeta(struct cart *theCart)
{
char *docId = cartString(theCart, "docId");
cartWebStart(cart, database, "ENCODE DCC: Metadata for docId %s",docId);
struct sqlConnection *conn = sqlConnect(database);
char query[10 * 1024];
struct sqlResult *sr;
char **row;
struct tempName tn;
trashDirFile(&tn, "docId", "meta", ".txt");
char *tempFile = tn.forCgi;
boolean beenHere = FALSE;
printf("<a href=docIdView?db=%s> Return </a><BR>", database);
sqlSafef(query, sizeof query, "select * from %s where ix=%s", docIdTable,docId);
sr = sqlGetResult(conn, query);
while ((row = sqlNextRow(sr)) != NULL)
{
if (beenHere)
errAbort("found more than one record with ix value %s in table %s",
docId, docIdTable);
beenHere = TRUE;
struct docIdSub *docIdSub = docIdSubLoad(row);
cgiDecode(docIdSub->metaData, docIdSub->metaData, strlen(docIdSub->metaData));
//printf("tempFile is %s\n<BR>", tempFile);
FILE *f = mustOpen(tempFile, "w");
fwrite(docIdSub->metaData, strlen(docIdSub->metaData), 1, f);
fclose(f);
boolean validated;
struct mdbObj *mdbObj = mdbObjsLoadFromFormattedFile(tempFile, &validated);
unlink(tempFile);
if (mdbObj->next)
errAbort("got more than one metaObj from metaData");
for(; mdbObj; mdbObj = mdbObj->next)
{
printf("<BR>object: %s\n", mdbObj->obj);
struct mdbVar *vars = mdbObj->vars;
for(; vars; vars = vars->next)
{
printf("<BR>%s %s\n", vars->var, vars->val);
}
}
}
cartWebEnd();
}
void doDocIdReport(struct cart *theCart)
{
char *docId = cartString(theCart, "docId");
cartWebStart(cart, database, "ENCODE DCC: Validation report for docId %s",docId);
struct sqlConnection *conn = sqlConnect(database);
char query[10 * 1024];
struct sqlResult *sr;
char **row;
boolean beenHere = FALSE;
printf("<a href=docIdView?db=%s> Return </a><BR>", database);
sqlSafef(query, sizeof query, "select * from %s where ix=%s", docIdTable,docId);
sr = sqlGetResult(conn, query);
while ((row = sqlNextRow(sr)) != NULL)
{
if (beenHere)
errAbort("found more than one record with ix value %s in table %s",
docId, docIdTable);
beenHere = TRUE;
struct docIdSub *docIdSub = docIdSubLoad(row);
cgiDecode(docIdSub->valReport, docIdSub->valReport, strlen(docIdSub->valReport));
//printf("tempFile is %s\n<BR>", tempFile);
printf("<pre>%s", docIdSub->valReport);
}
cartWebEnd();
}
void doLabContacts(struct cart *theCart)
{
char *subId = cartString(theCart, "lab");
cartWebStart(cart, database, "ENCODE DCC: Contacts for submission: %s",subId);
struct sqlConnection *conn = sqlConnect(database);
char query[10 * 1024];
struct sqlResult *sr;
char **row;
printf("<a href=docIdView?db=%s> Return </a><BR>", database);
sqlSafef(query, sizeof query, "select user_id from %s where id = %s ", "projects",subId);
char *userId = sqlQuickString(conn, query);
sqlSafef(query, sizeof query, "select name,email,pi from %s where id = '%s' ", "users",userId);
sr = sqlGetResult(conn, query);
printf("<pre>");
while ((row = sqlNextRow(sr)) != NULL)
{
printf("Name: %s\nEmail: %s\nPI: %s", row[0], row[1], row[2]);
}
sqlFreeResult(&sr);
sqlDisconnect(&conn);
cartWebEnd();
}
void doMiddle(struct cart *theCart)
/* Set up globals and make web page */
{
if (cgiVarExists("docId"))
{
if (cgiVarExists("meta"))
doDocIdMeta(theCart);
else if (cgiVarExists("report"))
doDocIdReport(theCart);
else if (cgiVarExists("lab"))
doLabContacts(theCart);
}
else
doStandard(theCart);
}
/* Null terminated list of CGI Variables we don't want to save
* permanently. */
char *excludeVars[] = {"Submit", "submit", "docId", NULL,};
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
if (cgiVarExists("db"))
{
database=cgiOptionalString("db");
}
cartEmptyShell(doMiddle, hUserCookie(), excludeVars, oldVars);
return 0;
}
|
DavidsDvm/Dev_Exercises
|
Console/Python/MisionTic/Excercises/test3.py
|
<gh_stars>1-10
name = input ('Digita tu nombre: ')
id = input ('Digite su numero identificacion: ')
workedHours = int(input ('Digite las horas trabajadas: '))
hourValue = int(input ('Digite el valor de las horas: '))
total = workedHours * hourValue
print ("Lo que gano el trabajador por las horas realizadas fue: ", total)
|
Aspose/Aspose.Words-for-Java
|
Examples/src/main/java/com/aspose/words/examples/document_object_model/OwnerDocument.java
|
package com.aspose.words.examples.document_object_model;
import com.aspose.words.Document;
import com.aspose.words.Paragraph;
public class OwnerDocument {
public static void main(String[] args) throws Exception {
// Open a file from disk.
Document doc = new Document();
// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);
// The new paragraph node does not yet have a parent.
System.out.println("Paragraph has no parent node: " + (para.getParentNode() == null));
// But the paragraph node knows its document.
System.out.println("Both nodes' documents are the same: " + (para.getDocument() == doc));
// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.getParagraphFormat().setStyleName("Heading 1");
// Now add the paragraph to the main text of the first section.
doc.getFirstSection().getBody().appendChild(para);
// The paragraph node is now a child of the Body node.
System.out.println("Paragraph has a parent node: " + (para.getParentNode() != null));
}
}
|
xu5343/ffmpegtoolkit_CentOS7
|
gpac-0.7.1/modules/ft_font/ft_font.c
|
/*
* GPAC - Multimedia Framework C SDK
*
* Authors: <NAME>
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / FreeType font engine module
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/modules/font.h>
#include <gpac/list.h>
#include <gpac/utf.h>
#include <gpac/tools.h>
#if !defined(__GNUC__)
# if defined(_WIN32_WCE)
# pragma comment(lib, "freetype")
# elif defined (WIN32)
# pragma comment(lib, "freetype")
# endif
#endif
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_OUTLINE_H
/*TrueType tables*/
#include FT_TRUETYPE_TABLES_H
typedef struct
{
FT_Library library;
FT_Face active_face;
GF_List *font_dirs;
GF_List *loaded_fonts;
/*default fonts*/
char *font_serif, *font_sans, *font_fixed, *font_default;
} FTBuilder;
static const char * BEST_FIXED_FONTS[] = {
"Courier New",
"Courier",
"Monaco",
"Bitstream Vera Monospace",
"Droid Sans Mono",
NULL
};
static const char * BEST_SERIF_FONTS[] = {
"Times New Roman",
"Bitstream Vera",
"Times",
"Droid Serif",
NULL
};
static const char * BEST_SANS_FONTS[] = {
"Arial",
"Tahoma",
"Verdana",
"Helvetica",
"Bitstream Vera Sans",
"Frutiger",
"Droid Sans",
NULL
};
/**
* Choose the best font in the list of fonts
*/
static Bool isBestFontFor(const char * listOfFonts[], const char * currentBestFont, const char * fontName) {
u32 i;
assert( fontName );
assert( listOfFonts );
for (i = 0 ; listOfFonts[i]; i++) {
const char * best = listOfFonts[i];
if (!stricmp(best, fontName))
return GF_TRUE;
if (currentBestFont && !stricmp(best, currentBestFont))
return GF_FALSE;
}
/* Nothing has been found, the font is the best if none has been choosen before */
return currentBestFont == NULL;
}
void setBestFont(const char * listOfFonts[], char ** currentBestFont, const char * fontName) {
if (isBestFontFor(listOfFonts, *currentBestFont, fontName)) {
if (*currentBestFont)
gf_free(*currentBestFont);
*currentBestFont = NULL;
}
if (! (*currentBestFont)) {
*currentBestFont = gf_strdup(fontName);
}
}
static Bool ft_enum_fonts(void *cbck, char *file_name, char *file_path, GF_FileEnumInfo *file_info)
{
char *szfont;
FT_Face face;
u32 num_faces, i;
GF_FontReader *dr = cbck;
FTBuilder *ftpriv = dr->udta;
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("[FreeType] Enumerating font %s (%s)\n", file_name, file_path));
if (FT_New_Face(ftpriv->library, file_path, 0, & face )) return 0;
if (!face || !face->family_name) return 0;
num_faces = (u32) face->num_faces;
/*locate right font in collection if several*/
for (i=0; i<num_faces; i++) {
/*only scan scalable fonts*/
if (face->face_flags & FT_FACE_FLAG_SCALABLE) {
Bool bold, italic;
szfont = gf_malloc(sizeof(char)* (strlen(face->family_name)+100));
if (!szfont) continue;
strcpy(szfont, face->family_name);
/*remember first font found which looks like a alphabetical one*/
if (!ftpriv->font_default) {
u32 gidx;
FT_Select_Charmap(face, FT_ENCODING_UNICODE);
gidx = FT_Get_Char_Index(face, (u32) 'a');
if (gidx) gidx = FT_Get_Char_Index(face, (u32) 'z');
if (gidx) gidx = FT_Get_Char_Index(face, (u32) '1');
if (gidx) gidx = FT_Get_Char_Index(face, (u32) '@');
if (gidx) ftpriv->font_default = gf_strdup(szfont);
}
bold = italic = 0;
if (face->style_name) {
char *name = gf_strdup(face->style_name);
strupr(name);
if (strstr(name, "BOLD")) bold = 1;
if (strstr(name, "ITALIC")) italic = 1;
/*if font is not regular style, append all styles blindly*/
if (!strstr(name, "REGULAR")) {
strcat(szfont, " ");
strcat(szfont, face->style_name);
}
gf_free(name);
} else {
if (face->style_flags & FT_STYLE_FLAG_BOLD) bold = 1;
if (face->style_flags & FT_STYLE_FLAG_ITALIC) italic = 1;
if (bold) strcat(szfont, " Bold");
if (italic) strcat(szfont, " Italic");
}
gf_modules_set_option((GF_BaseInterface *)dr, "FontEngine", szfont, file_path);
/*try to assign default fixed fonts*/
if (!bold && !italic) {
strcpy(szfont, face->family_name);
strlwr(szfont);
if (face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) {
setBestFont(BEST_FIXED_FONTS, &(ftpriv->font_fixed), face->family_name);
}
setBestFont(BEST_SERIF_FONTS, &(ftpriv->font_serif), face->family_name);
setBestFont(BEST_SANS_FONTS, &(ftpriv->font_sans), face->family_name);
}
gf_free(szfont);
}
FT_Done_Face(face);
if (i+1==num_faces) return 0;
/*load next font in collection*/
if (FT_New_Face(ftpriv->library, file_path, i+1, & face )) return 0;
if (!face) return 0;
}
return 0;
}
static Bool ft_enum_fonts_dir(void *cbck, char *file_name, char *file_path, GF_FileEnumInfo *file_info)
{
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("[FreeType] Scanning directory %s (%s)\n", file_name, file_path));
gf_enum_directory(file_path, 0, ft_enum_fonts, cbck, "ttf;ttc");
return (gf_enum_directory(file_path, 1, ft_enum_fonts_dir, cbck, NULL)==GF_OK) ? GF_FALSE : GF_TRUE;
}
static void ft_rescan_fonts(GF_FontReader *dr)
{
u32 i, count;
GF_Config *cfg = gf_modules_get_config((GF_BaseInterface *)dr);
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("[FreeType] Rescaning %d font directories\n", gf_list_count(ftpriv->font_dirs) ));
count = gf_cfg_get_key_count(cfg, "FontEngine");
for (i=0; i<count; i++) {
const char *key = gf_cfg_get_key_name(cfg, "FontEngine", i);
if (!strcmp(key, "FontReader")) continue;
if (!strcmp(key, "FontDirectory")) continue;
if (!strcmp(key, "RescanFonts")) continue;
/*any other persistent options should go here*/
gf_cfg_set_key(cfg, "FontEngine", key, NULL);
count--;
i--;
}
gf_modules_set_option((GF_BaseInterface *)dr, "FontEngine", "RescanFonts", "no");
if (ftpriv->font_fixed) gf_free(ftpriv->font_fixed);
ftpriv->font_fixed = NULL;
if (ftpriv->font_sans) gf_free(ftpriv->font_sans);
ftpriv->font_sans = NULL;
if (ftpriv->font_serif) gf_free(ftpriv->font_serif);
ftpriv->font_serif = NULL;
if (ftpriv->font_default) gf_free(ftpriv->font_default);
ftpriv->font_default = NULL;
count = gf_list_count(ftpriv->font_dirs);
for (i=0; i<count; i++) {
char *font_dir = gf_list_get(ftpriv->font_dirs, i);
if (gf_dir_exists(font_dir)) {
gf_enum_directory(font_dir, 0, ft_enum_fonts, dr, "ttf;ttc");
gf_enum_directory(font_dir, 1, ft_enum_fonts_dir, dr, NULL);
}
}
if (ftpriv->font_fixed) gf_free(ftpriv->font_fixed);
ftpriv->font_fixed = NULL;
if (ftpriv->font_sans) gf_free(ftpriv->font_sans);
ftpriv->font_sans = NULL;
if (ftpriv->font_serif) gf_free(ftpriv->font_serif);
ftpriv->font_serif = NULL;
/* let's check we have fonts that match our default Bold/Italic/BoldItalic conventions*/
count = gf_cfg_get_key_count(cfg, "FontEngine");
for (i=0; i<count; i++) {
const char *opt;
char fkey[GF_MAX_PATH];
const char *key = gf_cfg_get_key_name(cfg, "FontEngine", i);
opt = gf_cfg_get_key(cfg, "FontEngine", key);
if (!strchr(opt, '/') && !strchr(opt, '\\')) continue;
if (!strcmp(key, "FontDirectory")) continue;
if (strstr(key, "Bold")) continue;
if (strstr(key, "Italic")) continue;
strcpy(fkey, key);
strcat(fkey, " Italic");
opt = gf_cfg_get_key(cfg, "FontEngine", fkey);
if (!opt) continue;
strcpy(fkey, key);
strcat(fkey, " Bold");
opt = gf_cfg_get_key(cfg, "FontEngine", fkey);
if (!opt) continue;
strcpy(fkey, key);
strcat(fkey, " Bold Italic");
opt = gf_cfg_get_key(cfg, "FontEngine", fkey);
if (!opt) continue;
strcpy(fkey, key);
strlwr(fkey);
/*this font is suited for our case*/
if (isBestFontFor(BEST_FIXED_FONTS, ftpriv->font_fixed, key) || (!ftpriv->font_fixed && (strstr(fkey, "fixed") || strstr(fkey, "mono")) ) ) {
if (ftpriv->font_fixed) gf_free(ftpriv->font_fixed);
ftpriv->font_fixed = gf_strdup(key);
}
if (isBestFontFor(BEST_SANS_FONTS, ftpriv->font_sans, key) || (!ftpriv->font_sans && strstr(fkey, "sans")) ) {
if (ftpriv->font_sans) gf_free(ftpriv->font_sans);
ftpriv->font_sans = gf_strdup(key);
}
if (isBestFontFor(BEST_SERIF_FONTS, ftpriv->font_serif, key) || (!ftpriv->font_serif && strstr(fkey, "serif")) ) {
if (ftpriv->font_serif) gf_free(ftpriv->font_serif);
ftpriv->font_serif = gf_strdup(key);
}
}
if (!ftpriv->font_serif) ftpriv->font_serif = gf_strdup(ftpriv->font_default ? ftpriv->font_default : "");
if (!ftpriv->font_sans) ftpriv->font_sans = gf_strdup(ftpriv->font_default ? ftpriv->font_default : "");
if (!ftpriv->font_fixed) ftpriv->font_fixed = gf_strdup(ftpriv->font_default ? ftpriv->font_default : "");
gf_modules_set_option((GF_BaseInterface *)dr, "FontEngine", "FontFixed", ftpriv->font_fixed);
gf_modules_set_option((GF_BaseInterface *)dr, "FontEngine", "FontSerif", ftpriv->font_serif);
gf_modules_set_option((GF_BaseInterface *)dr, "FontEngine", "FontSans", ftpriv->font_sans);
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("[FreeType] Font directories scanned\n"));
}
static GF_Err ft_init_font_engine(GF_FontReader *dr)
{
const char *sOpt;
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
sOpt = gf_modules_get_option((GF_BaseInterface *)dr, "FontEngine", "FontDirectory");
if (!sOpt) return GF_BAD_PARAM;
/*inits freetype*/
if (FT_Init_FreeType(&ftpriv->library) ) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[FreeType] Cannot initialize FreeType\n"));
return GF_IO_ERR;
}
while (sOpt) {
char dir[GF_MAX_PATH];
char *sep = (char *) strchr(sOpt, ',');
if (sep) sep[0] = 0;
strcpy(dir, sOpt);
while ( (dir[strlen(dir)-1] == '\n') || (dir[strlen(dir)-1] == '\r') )
dir[strlen(dir)-1] = 0;
if (dir[strlen(dir)-1] != GF_PATH_SEPARATOR) {
char ext[2];
ext[0] = GF_PATH_SEPARATOR;
ext[1] = 0;
strcat(dir, ext);
}
gf_list_add(ftpriv->font_dirs, gf_strdup(dir) );
if (!sep) break;
sep[0] = ',';
sOpt = sep+1;
}
sOpt = gf_modules_get_option((GF_BaseInterface *)dr, "FontEngine", "RescanFonts");
if (!sOpt || !strcmp(sOpt, "yes") )
ft_rescan_fonts(dr);
if (!ftpriv->font_serif) {
sOpt = gf_modules_get_option((GF_BaseInterface *)dr, "FontEngine", "FontSerif");
ftpriv->font_serif = gf_strdup(sOpt ? sOpt : "");
}
if (!ftpriv->font_sans) {
sOpt = gf_modules_get_option((GF_BaseInterface *)dr, "FontEngine", "FontSans");
ftpriv->font_sans = gf_strdup(sOpt ? sOpt : "");
}
if (!ftpriv->font_fixed) {
sOpt = gf_modules_get_option((GF_BaseInterface *)dr, "FontEngine", "FontFixed");
ftpriv->font_fixed = gf_strdup(sOpt ? sOpt : "");
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("[FreeType] Init OK - %d font directory (first %s)\n", gf_list_count(ftpriv->font_dirs), gf_list_get(ftpriv->font_dirs, 0) ));
return GF_OK;
}
static GF_Err ft_shutdown_font_engine(GF_FontReader *dr)
{
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
ftpriv->active_face = NULL;
/*reset loaded fonts*/
while (gf_list_count(ftpriv->loaded_fonts)) {
FT_Face face = gf_list_get(ftpriv->loaded_fonts, 0);
gf_list_rem(ftpriv->loaded_fonts, 0);
FT_Done_Face(face);
}
/*exit FT*/
if (ftpriv->library) FT_Done_FreeType(ftpriv->library);
ftpriv->library = NULL;
return GF_OK;
}
static Bool ft_check_face(FT_Face font, const char *fontName, u32 styles)
{
u32 ft_style, loc_styles;
char *name;
if (fontName && stricmp(font->family_name, fontName)) return 0;
ft_style = 0;
if (font->style_name) {
name = gf_strdup(font->style_name);
strupr(name);
if (strstr(name, "BOLD")) ft_style |= GF_FONT_WEIGHT_BOLD;
if (strstr(name, "ITALIC")) ft_style |= GF_FONT_ITALIC;
gf_free(name);
} else {
if (font->style_flags & FT_STYLE_FLAG_BOLD) ft_style |= GF_FONT_WEIGHT_BOLD;
if (font->style_flags & FT_STYLE_FLAG_ITALIC) ft_style |= GF_FONT_ITALIC;
}
name = gf_strdup(font->family_name);
strupr(name);
if (strstr(name, "BOLD")) ft_style |= GF_FONT_WEIGHT_BOLD;
if (strstr(name, "ITALIC")) ft_style |= GF_FONT_ITALIC;
gf_free(name);
loc_styles = styles & GF_FONT_WEIGHT_MASK;
if (loc_styles>=GF_FONT_WEIGHT_BOLD)
styles = (styles & 0x00000007) | GF_FONT_WEIGHT_BOLD;
else
styles = (styles & 0x00000007);
if (ft_style==styles)
return 1;
return 0;
}
static FT_Face ft_font_in_cache(FTBuilder *ft, const char *fontName, u32 styles)
{
u32 i=0;
FT_Face font;
while ((font = gf_list_enum(ft->loaded_fonts, &i))) {
if (ft_check_face(font, fontName, styles)) return font;
}
return NULL;
}
static GF_Err ft_set_font(GF_FontReader *dr, const char *OrigFontName, u32 styles)
{
char *fname;
char *fontName;
const char *opt;
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
fontName = (char *) OrigFontName;
ftpriv->active_face = NULL;
if (!fontName || !strlen(fontName) || !stricmp(fontName, "SERIF")) {
fontName = ftpriv->font_serif;
}
else if (!stricmp(fontName, "SANS") || !stricmp(fontName, "sans-serif")) {
fontName = ftpriv->font_sans;
}
else if (!stricmp(fontName, "TYPEWRITER") || !stricmp(fontName, "monospace")) {
fontName = ftpriv->font_fixed;
}
/*first look in loaded fonts*/
ftpriv->active_face = ft_font_in_cache(ftpriv, fontName, styles);
if (ftpriv->active_face) return GF_OK;
/*check cfg file - gf_free(type is slow at loading fonts so we keep the (font name + styles)=fontfile associations
in the cfg file*/
if (!fontName || !strlen(fontName)) return GF_NOT_SUPPORTED;
fname = gf_malloc(sizeof(char) * (strlen(fontName) + 50));
{
int checkStyles = (styles & GF_FONT_WEIGHT_BOLD) | (styles & GF_FONT_ITALIC);
checkFont:
strcpy(fname, fontName);
if (styles & GF_FONT_WEIGHT_BOLD & checkStyles) strcat(fname, " Bold");
if (styles & GF_FONT_ITALIC & checkStyles) strcat(fname, " Italic");
opt = gf_modules_get_option((GF_BaseInterface *)dr, "FontEngine", fname);
if (opt) {
FT_Face face;
gf_free(fname);
if (FT_New_Face(ftpriv->library, opt, 0, & face )) return GF_IO_ERR;
if (!face) return GF_IO_ERR;
gf_list_add(ftpriv->loaded_fonts, face);
ftpriv->active_face = face;
return GF_OK;
}
if (checkStyles) {
/* If we tried font + bold + italic -> we will try font + [bold | italic]
If we tried font + [bold | italic] -> we try font
*/
if (checkStyles == (GF_FONT_WEIGHT_BOLD | GF_FONT_ITALIC))
checkStyles = GF_FONT_WEIGHT_BOLD;
else if (checkStyles == GF_FONT_WEIGHT_BOLD && (styles & GF_FONT_ITALIC))
checkStyles = GF_FONT_ITALIC;
else if (checkStyles == GF_FONT_WEIGHT_BOLD || checkStyles == GF_FONT_ITALIC)
checkStyles = 0;
goto checkFont;
}
}
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[FreeType] Font '%s' (%s) not found\n", fontName, fname));
gf_free(fname);
return GF_NOT_SUPPORTED;
}
static GF_Err ft_get_font_info(GF_FontReader *dr, char **font_name, u32 *em_size, s32 *ascent, s32 *descent, s32 *underline, s32 *line_spacing, s32 *max_advance_h, s32 *max_advance_v)
{
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
if (!ftpriv->active_face) return GF_BAD_PARAM;
*em_size = ftpriv->active_face->units_per_EM;
*ascent = ftpriv->active_face->ascender;
*descent = ftpriv->active_face->descender;
*underline = ftpriv->active_face->underline_position;
*line_spacing = ftpriv->active_face->height;
*font_name = gf_strdup(ftpriv->active_face->family_name);
*max_advance_h = ftpriv->active_face->max_advance_width;
*max_advance_v = ftpriv->active_face->max_advance_height;
return GF_OK;
}
static GF_Err ft_get_glyphs(GF_FontReader *dr, const char *utf_string, u32 *glyph_buffer, u32 *io_glyph_buffer_size, const char *xml_lang, Bool *is_rtl)
{
size_t _len;
u32 len;
u32 i;
u16 *conv;
char *utf8 = (char*) utf_string;
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
if (!ftpriv->active_face) return GF_BAD_PARAM;
/*TODO: glyph substitution / ligature */
len = utf_string ? (u32) strlen(utf_string) : 0;
if (!len) {
*io_glyph_buffer_size = 0;
return GF_OK;
}
if (*io_glyph_buffer_size < len+1) {
*io_glyph_buffer_size = len+1;
return GF_BUFFER_TOO_SMALL;
}
_len = gf_utf8_mbstowcs((u16*) glyph_buffer, *io_glyph_buffer_size, (const char **) &utf8);
if (_len==(size_t)-1) return GF_IO_ERR;
len = (u32) _len;
if (utf8) return GF_IO_ERR;
/*perform bidi relayout*/
conv = (u16*) glyph_buffer;
*is_rtl = gf_utf8_reorder_bidi(conv, len);
/*move 16bit buffer to 32bit*/
for (i=len; i>0; i--) {
glyph_buffer[i-1] = (u32) conv[i-1];
}
*io_glyph_buffer_size = len;
return GF_OK;
}
typedef struct
{
FTBuilder *ftpriv;
GF_Path *path;
s32 last_x, last_y;
} ft_outliner;
#if defined(GPAC_IPHONE) || defined(GPAC_ANDROID)
#define FTCST
#else
#define FTCST const
#endif
static int ft_move_to(FTCST FT_Vector *to, void *user)
{
ft_outliner *ftol = (ft_outliner *)user;
gf_path_add_move_to(ftol->path, INT2FIX(to->x), INT2FIX(to->y) );
ftol->last_x = (s32) to->x;
ftol->last_y = (s32) to->y;
return 0;
}
static int ft_line_to(FTCST FT_Vector *to, void *user)
{
ft_outliner *ftol = (ft_outliner *)user;
if ( (ftol->last_x == to->x) && (ftol->last_y == to->y)) {
gf_path_close(ftol->path);
} else {
gf_path_add_line_to(ftol->path, INT2FIX(to->x), INT2FIX(to->y) );
}
return 0;
}
static int ft_conic_to(FTCST FT_Vector * control, FTCST FT_Vector *to, void *user)
{
ft_outliner *ftol = (ft_outliner *)user;
gf_path_add_quadratic_to(ftol->path, INT2FIX(control->x), INT2FIX(control->y), INT2FIX(to->x), INT2FIX(to->y) );
if ( (ftol->last_x == to->x) && (ftol->last_y == to->y)) gf_path_close(ftol->path);
return 0;
}
static int ft_cubic_to(FTCST FT_Vector *c1, FTCST FT_Vector *c2, FTCST FT_Vector *to, void *user)
{
ft_outliner *ftol = (ft_outliner *)user;
gf_path_add_cubic_to(ftol->path, INT2FIX(c1->x), INT2FIX(c1->y), INT2FIX(c2->x), INT2FIX(c2->y), INT2FIX(to->x), INT2FIX(to->y) );
if ( (ftol->last_x == to->x) && (ftol->last_y == to->y)) gf_path_close(ftol->path);
return 0;
}
static GF_Glyph *ft_load_glyph(GF_FontReader *dr, u32 glyph_name)
{
GF_Glyph *glyph;
u32 glyph_idx;
FT_BBox bbox;
FT_OutlineGlyph outline;
ft_outliner outl;
FT_Outline_Funcs ft_outl_funcs;
FTBuilder *ftpriv = (FTBuilder *)dr->udta;
if (!ftpriv->active_face || !glyph_name) return NULL;
FT_Select_Charmap(ftpriv->active_face, FT_ENCODING_UNICODE);
glyph_idx = FT_Get_Char_Index(ftpriv->active_face, glyph_name);
/*missing glyph*/
if (!glyph_idx) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[FreeType] Glyph not found for char %d in font %s (style %s)\n", glyph_name, ftpriv->active_face->family_name, ftpriv->active_face->style_name));
return NULL;
}
/*work in design units*/
FT_Load_Glyph(ftpriv->active_face, glyph_idx, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP);
FT_Get_Glyph(ftpriv->active_face->glyph, (FT_Glyph*)&outline);
#ifdef FT_GLYPH_FORMAT_OUTLINE
/*oops not vectorial...*/
if (outline->root.format != FT_GLYPH_FORMAT_OUTLINE) return NULL;
#endif
GF_SAFEALLOC(glyph, GF_Glyph);
if (!glyph) return NULL;
GF_SAFEALLOC(glyph->path, GF_Path);
if (!glyph->path) {
gf_free(glyph);
return NULL;
}
/*setup outliner*/
ft_outl_funcs.shift = 0;
ft_outl_funcs.delta = 0;
ft_outl_funcs.move_to = ft_move_to;
ft_outl_funcs.line_to = ft_line_to;
ft_outl_funcs.conic_to = ft_conic_to;
ft_outl_funcs.cubic_to = ft_cubic_to;
outl.path = glyph->path;
outl.ftpriv = ftpriv;
/*FreeType is marvelous and gives back the right advance on space char !!!*/
FT_Outline_Decompose(&outline->outline, &ft_outl_funcs, &outl);
FT_Glyph_Get_CBox((FT_Glyph) outline, ft_glyph_bbox_unscaled, &bbox);
glyph->ID = glyph_name;
glyph->utf_name = glyph_name;
glyph->horiz_advance = (s32) ftpriv->active_face->glyph->metrics.horiAdvance;
glyph->vert_advance = (s32) ftpriv->active_face->glyph->metrics.vertAdvance;
/*
glyph->x = bbox.xMin;
glyph->y = bbox.yMax;
*/
glyph->width = (u32) ftpriv->active_face->glyph->metrics.width;
glyph->height = (u32) ftpriv->active_face->glyph->metrics.height;
FT_Done_Glyph((FT_Glyph) outline);
return glyph;
}
static GF_FontReader *ft_load()
{
GF_FontReader *dr;
FTBuilder *ftpriv;
dr = gf_malloc(sizeof(GF_FontReader));
memset(dr, 0, sizeof(GF_FontReader));
GF_REGISTER_MODULE_INTERFACE(dr, GF_FONT_READER_INTERFACE, "FreeType Font Reader", "gpac distribution");
ftpriv = gf_malloc(sizeof(FTBuilder));
memset(ftpriv, 0, sizeof(FTBuilder));
ftpriv->font_dirs = gf_list_new();
ftpriv->loaded_fonts = gf_list_new();
dr->udta = ftpriv;
dr->init_font_engine = ft_init_font_engine;
dr->shutdown_font_engine = ft_shutdown_font_engine;
dr->set_font = ft_set_font;
dr->get_font_info = ft_get_font_info;
dr->get_glyphs = ft_get_glyphs;
dr->load_glyph = ft_load_glyph;
return dr;
}
static void ft_delete(GF_BaseInterface *ifce)
{
GF_FontReader *dr = (GF_FontReader *) ifce;
FTBuilder *ftpriv = dr->udta;
while (gf_list_count(ftpriv->font_dirs)) {
char *font = gf_list_pop_back(ftpriv->font_dirs);
if (font)
gf_free(font);
}
gf_list_del(ftpriv->font_dirs);
if (ftpriv->font_serif) gf_free(ftpriv->font_serif);
if (ftpriv->font_sans) gf_free(ftpriv->font_sans);
if (ftpriv->font_fixed) gf_free(ftpriv->font_fixed);
if (ftpriv->font_default) gf_free(ftpriv->font_default);
assert(!gf_list_count(ftpriv->loaded_fonts) );
gf_list_del(ftpriv->loaded_fonts);
gf_free(dr->udta);
gf_free(dr);
}
#ifndef GPAC_STANDALONE_RENDER_2D
GPAC_MODULE_EXPORT
const u32 *QueryInterfaces()
{
static u32 si [] = {
GF_FONT_READER_INTERFACE,
0
};
return si;
}
GPAC_MODULE_EXPORT
GF_BaseInterface *LoadInterface(u32 InterfaceType)
{
if (InterfaceType == GF_FONT_READER_INTERFACE) return (GF_BaseInterface *)ft_load();
return NULL;
}
GPAC_MODULE_EXPORT
void ShutdownInterface(GF_BaseInterface *ifce)
{
switch (ifce->InterfaceType) {
case GF_FONT_READER_INTERFACE:
ft_delete(ifce);
break;
}
}
GPAC_MODULE_STATIC_DECLARATION( ftfont )
#endif
|
thezeeck/ZUI
|
src/ZUI/components/Tabs/Menu.js
|
<gh_stars>0
import { MenuItem } from "./MenuItem";
import { MenuUI } from "./Tabs.styles";
export const Menu = ({menuOptions}) => {
return (
<MenuUI>
<ul>
{menuOptions.map(elem => <MenuItem tabid={elem.index} key={elem.index}>{elem.title}</MenuItem>)}
</ul>
</MenuUI>
)
}
|
Shuailong/Leetcode
|
solutions/length-of-last-word.py
|
#!/usr/bin/env python
# encoding: utf-8
"""
length-of-last-word.py
Created by Shuailong on 2016-01-16.
https://leetcode.com/problems/length-of-last-word/.
"""
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
s = s.rstrip()
for i in range(len(s)-1,-1,-1):
if s[i] != ' ':
count += 1
else:
break
return count
def main():
solution = Solution()
s = "Hello"
print solution.lengthOfLastWord(s)
if __name__ == '__main__':
main()
|
shaojiankui/iOS10-Runtime-Headers
|
protocols/SKUISortDataRequestDelegate.h
|
/* Generated by RuntimeBrowser.
*/
@protocol SKUISortDataRequestDelegate <NSObject>
@optional
- (void)sortDataRequest:(SKUISortDataRequest *)arg1 didFinishWithLockups:(NSArray *)arg2;
@end
|
zllovesuki/dtls
|
pkg/protocol/extension/renegotiation_info_test.go
|
<filename>pkg/protocol/extension/renegotiation_info_test.go<gh_stars>100-1000
package extension
import "testing"
func TestRenegotiationInfo(t *testing.T) {
extension := RenegotiationInfo{RenegotiatedConnection: 0}
raw, err := extension.Marshal()
if err != nil {
t.Fatal(err)
}
newExtension := RenegotiationInfo{}
err = newExtension.Unmarshal(raw)
if err != nil {
t.Fatal(err)
}
if newExtension.RenegotiatedConnection != extension.RenegotiatedConnection {
t.Errorf("extensionRenegotiationInfo marshal: got %d expected %d", newExtension.RenegotiatedConnection, extension.RenegotiatedConnection)
}
}
|
reels-research/iOS-Private-Frameworks
|
HealthDaemon.framework/HDCodableCodedValue.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/HealthDaemon.framework/HealthDaemon
*/
@interface HDCodableCodedValue : PBCodable <NSCopying> {
HDCodableMedicalCodingList * _codings;
NSMutableArray * _referenceRanges;
HDCodableInspectableValue * _value;
}
@property (nonatomic, retain) HDCodableMedicalCodingList *codings;
@property (nonatomic, readonly) bool hasCodings;
@property (nonatomic, readonly) bool hasValue;
@property (nonatomic, retain) NSMutableArray *referenceRanges;
@property (nonatomic, retain) HDCodableInspectableValue *value;
+ (Class)referenceRangesType;
- (void).cxx_destruct;
- (void)addReferenceRanges:(id)arg1;
- (void)clearReferenceRanges;
- (id)codings;
- (void)copyTo:(id)arg1;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (id)description;
- (id)dictionaryRepresentation;
- (bool)hasCodings;
- (bool)hasValue;
- (unsigned long long)hash;
- (bool)isEqual:(id)arg1;
- (void)mergeFrom:(id)arg1;
- (bool)readFrom:(id)arg1;
- (id)referenceRanges;
- (id)referenceRangesAtIndex:(unsigned long long)arg1;
- (unsigned long long)referenceRangesCount;
- (void)setCodings:(id)arg1;
- (void)setReferenceRanges:(id)arg1;
- (void)setValue:(id)arg1;
- (id)value;
- (void)writeTo:(id)arg1;
@end
|
ap300/pquic
|
plugins/fec/protoops/schedule_frames_on_path.c
|
<filename>plugins/fec/protoops/schedule_frames_on_path.c<gh_stars>10-100
#include "picoquic.h"
#include "../fec_protoops.h"
#define MIN_BYTES_TO_RETRANSMIT_PROTECT 20
static __attribute__((always_inline)) bool is_mtu_probe(picoquic_packet_t *p, picoquic_path_t *path) {
if (!p || !path) return false;
// it is mtu if p->length + p->checksum_overhead > send_path->send_mtu
return get_pkt(p, AK_PKT_LENGTH) + get_pkt(p, AK_PKT_CHECKSUM_OVERHEAD) > get_path(path, AK_PATH_SEND_MTU, 0);
}
/**
* Select the path on which the next packet will be sent.
*
* \param[in] retransmit_p \b picoquic_packet_t* The packet to be retransmitted, or NULL if none
* \param[in] from_path \b picoquic_path_t* The path from which the packet originates, or NULL if none
* \param[in] reason \b char* The reason why packet should be retransmitted, or NULL if none
*
* \return \b picoquic_path_t* The path on which the next packet will be sent.
*/
protoop_arg_t schedule_frames_on_path(picoquic_cnx_t *cnx)
{
picoquic_packet_t *packet = (picoquic_packet_t *) get_cnx(cnx, AK_CNX_INPUT, 0);
picoquic_packet_t *retransmit_p = (picoquic_packet_t *) get_cnx(cnx, AK_CNX_INPUT, 3);
uint32_t length = get_cnx(cnx, AK_CNX_OUTPUT, 1);
// set the current fpid
bpf_state *state = get_bpf_state(cnx);
// protect the source symbol
uint8_t *data = (uint8_t *) get_pkt(packet, AK_PKT_BYTES);
picoquic_packet_type_enum packet_type = retransmit_p ? get_pkt(retransmit_p, AK_PKT_TYPE) : get_pkt(packet, AK_PKT_TYPE);
uint32_t header_length = get_pkt(packet, AK_PKT_OFFSET);
if (state->current_sfpid_frame && (packet_type == picoquic_packet_1rtt_protected_phi0 || packet_type == picoquic_packet_1rtt_protected_phi1)){
PROTOOP_PRINTF(cnx, "TRY TO PROTECT, LENGTH %d, OFFSET = %d, retrans = %d\n", length, header_length, retransmit_p != NULL);
uint8_t *payload_with_pn = my_malloc(cnx, length - header_length + 1 + sizeof(uint64_t));
// copy the packet payload without the header and put it 8 bytes after the start of the buffer
protoop_arg_t args[4];
args[0] = (protoop_arg_t) data + header_length;
args[1] = (protoop_arg_t) payload_with_pn;
args[2] = length - header_length;
args[3] = get_pkt(packet, AK_PKT_SEQUENCE_NUMBER);
uint32_t symbol_length = (uint32_t) run_noparam(cnx, "packet_payload_to_source_symbol", 4, args, NULL);
if (symbol_length <= 1 + sizeof(uint64_t) + 1 + sizeof(source_fpid_frame_t)) {
// this symbol does not need to be protected: undo
my_memset(state->written_sfpid_frame, 0, 1 + sizeof(source_fpid_frame_t));
my_free(cnx, state->current_sfpid_frame);
state->current_sfpid_frame = NULL;
} else {
int err = protect_packet(cnx, &state->current_sfpid_frame->source_fpid, payload_with_pn, symbol_length);
if (err){
PROTOOP_PRINTF(cnx, "ERROR WHILE PROTECTING\n");
return (protoop_arg_t) err;
}
}
my_free(cnx, payload_with_pn);
}
if (state->current_sfpid_frame) {
my_free(cnx, state->current_sfpid_frame);
state->current_sfpid_frame = NULL;
}
return 0;
}
|
Severe-Trip-Project-Arquisoft/FrontEndSevereTrip
|
src/views/SignUp/SignUp.js
|
<reponame>Severe-Trip-Project-Arquisoft/FrontEndSevereTrip
import React, { useState, useEffect } from 'react';
import { Link as RouterLink, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import validate from 'validate.js';
import { makeStyles } from '@material-ui/styles';
import {
Grid,
Button,
TextField,
Link,
FormHelperText,
Checkbox,
Typography,
MenuItem
} from '@material-ui/core';
import { API } from 'API';
import MuiPhoneNumber from 'material-ui-phone-number'
const schema = {
firstName: {
presence: { allowEmpty: false, message: 'is required' },
length: {
maximum: 32
}
},
lastName: {
presence: { allowEmpty: false, message: 'is required' },
length: {
maximum: 32
}
},
address: {
presence: { allowEmpty: false, message: 'is required' },
length: {
maximum: 32
}
},
country: {
presence: { allowEmpty: false, message: 'is required' },
length: {
maximum: 32
}
},
email: {
presence: { allowEmpty: false, message: 'is required' },
email: true,
length: {
maximum: 64
}
},
password: {
presence: { allowEmpty: false, message: 'is required' },
length: {
maximum: 128
}
},
cellphone: {
presence: { allowEmpty: false, message: 'is required' },
},
rol: {
presence: { allowEmpty: false, message: 'is required' },
},
policy: {
presence: { allowEmpty: false, message: 'is required' },
checked: true
}
};
const currencies = [
{
value: 'provider',
label: 'Proveedor',
},
{
value: 'client',
label: 'Cliente',
},
];
const currenciesCountry = [
{
value: 'Antigua y Barbuda',
label: 'Antigua y Barbuda',
}, {
value: 'Argentina',
label: 'Argentina',
}, {
value: 'Bahamas',
label: 'Bahamas',
}, {
value: 'Barbados',
label: 'Barbados',
}, {
value: 'Belice',
label: 'Belice',
}, {
value: 'Bolivia',
label: 'Bolivia',
}, {
value: 'Brasil',
label: 'Brasil',
}, {
value: 'Canadá',
label: 'Canadá',
}, {
value: 'Chile',
label: 'Chile',
}, {
value: 'Colombia',
label: 'Colombia',
}, {
value: 'Costa Rica',
label: 'Costa Rica',
}, {
value: 'Cuba',
label: 'Cuba',
}, {
value: 'Dominica',
label: 'Dominica',
}, {
value: 'Ecuador',
label: 'Ecuador',
}, {
value: 'El Salvador',
label: 'El Salvador',
}, {
value: 'Estados Unidos',
label: 'Estados Unidos',
}, {
value: 'Granada',
label: 'Granada',
}, {
value: 'Guatemala',
label: 'Guatemala',
},
{
value: 'Guyana',
label: 'Guyana',
},
{
value: 'Haití',
label: 'Haití',
},
{
value: 'Honduras',
label: 'Honduras',
},
{
value: 'Jamaica',
label: 'Jamaica',
},
{
value: 'México',
label: 'México',
},
{
value: 'Nicaragua',
label: 'Nicaragua',
},
{
value: 'Panamá',
label: 'Panamá',
},
{
value: 'Paraguay',
label: 'Paraguay',
},
{
value: 'Perú',
label: 'Perú',
},
{
value: 'República Dominicana',
label: 'República Dominicana',
},
{
value: 'San Cristóbal y Nieves',
label: 'San Cristóbal y Nieves',
},
{
value: 'San Vicente y las Granadinas',
label: 'San Vicente y las Granadinas',
},
{
value: 'Santa Lucía',
label: 'Santa Lucía',
},
{
value: 'Surinam',
label: 'Surinam',
},
{
value: 'Trinidad y Tobago',
label: 'Trinidad y Tobago',
},
{
value: 'Uruguay',
label: 'Uruguay',
},
{
value: 'Venezuela',
label: 'Venezuela',
},
];
const useStyles = makeStyles(theme => ({
root: {
// backgroundColor: theme.palette.background.default,
height: '100%'
},
// grid: {
// height: '100%'
// },
contentContainer: {},
content: {
height: '100%',
display: 'flex',
flexDirection: 'column'
},
contentHeader: {
display: 'flex',
alignItems: 'center',
paddingTop: theme.spacing(5),
paddingBototm: theme.spacing(2),
paddingLeft: theme.spacing(2),
paddingRight: theme.spacing(2)
},
// logoImage: {
// marginLeft: theme.spacing(4)
// },
contentBody: {
flexGrow: 1,
display: 'flex',
alignItems: 'center',
[theme.breakpoints.down('md')]: {
justifyContent: 'center'
},
backgroundColor: 'rgba(255, 255, 255, 0.95)',
borderRadius: '25px'
},
form: {
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 50,
flexBasis: 700,
[theme.breakpoints.down('sm')]: {
paddingLeft: theme.spacing(2),
paddingRight: theme.spacing(2)
}
},
title: {
marginTop: theme.spacing(3)
},
textField: {
marginTop: theme.spacing(2),
},
policy: {
marginTop: theme.spacing(1),
display: 'flex',
alignItems: 'center'
},
policyCheckbox: {
marginLeft: '-14px'
},
signUpButton: {
margin: theme.spacing(2, 0)
}
}));
const SignUp = props => {
const { history } = props;
const classes = useStyles();
const [formState, setFormState] = useState({
isValid: false,
values: {},
touched: {},
errors: {},
});
useEffect(() => {
const errors = validate(formState.values, schema);
setFormState(formState => ({
...formState,
isValid: errors ? false : true,
errors: errors || {},
}));
}, [formState.values]);
const handleChange = event => {
event.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[event.target.name]:
event.target.type === 'checkbox'
? event.target.checked
: event.target.value,
},
touched: {
...formState.touched,
[event.target.name]: true
},
}));
};
const handleChangeCellphone = value => {
setFormState(formState => ({
...formState,
values: {
...formState.values,
cellphone : value
},
touched: {
...formState.touched,
cellphone : true
},
}));
};
function numeroAleatorio(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
const handleSignUp = async event => {
event.preventDefault();
var data;
if (formState.values.rol === 'client') {
data = {
username: formState.values.userName,
firstName: formState.values.firstName,
secondName: formState.values.lastName,
localAirport: "Aeropuerto internacional <NAME>",
email: formState.values.email,
address: formState.values.address,
city: "Bogota",
stateProvinceRegion: "Cundinamarca",
postalCode: "11001",
country: formState.values.country,
cellphone: formState.values.cellphone,
password: <PASSWORD>,
favorites: []
}
console.log('envio cliente...', data)
const res = await API.users.createClient(data);
console.log('respuesta creaci0n cliente...', res)
}
if (formState.values.rol === 'provider') {
data = {
username: formState.values.userName,
firstName: formState.values.firstName,
secondName: formState.values.lastName,
yearsExperience: numeroAleatorio(1, 20),
bankAccount: numeroAleatorio(45000000, 60000000),
updateDate: (new Date()).toJSON(),
email: formState.values.email,
address: formState.values.address,
country: formState.values.country,
city: "Bogota",
cellphone: formState.values.cellphone,
password: <PASSWORD>
}
console.log('envio proveedor...', data)
const res = await API.users.createProvider(data);
console.log('respuesta creacion proveedor...', res)
}
history.push('/sign-in');
};
const hasError = field =>
!!(formState.touched[field] && formState.errors[field]);
return (
<div className={classes.root}>
<div className={classes.content}>
<div className={classes.contentBody}>
<form
className={classes.form}
onSubmit={handleSignUp}
>
<Grid
container
// spacing={1}
>
<Grid
item
// md={12}
xs={12}
>
<Typography
className={classes.title}
variant="h2"
>
Crea una cuenta nueva
</Typography>
<Typography
color="textSecondary"
gutterBottom
>
Ingresa tus datos para crear una cuenta nueva.
</Typography>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('userName')}
fullWidth
helperText={
hasError('userName') ? formState.errors.userName[0] : null
}
label="<NAME>"
name="userName"
onChange={handleChange}
type="text"
value={formState.values.userName || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('email')}
fullWidth
helperText={
hasError('email') ? formState.errors.email[0] : null
}
label="Email"
name="email"
onChange={handleChange}
type="text"
value={formState.values.email || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('password')}
fullWidth
helperText={
hasError('password') ? formState.errors.password[0] : null
}
label="Contraseña"
name="password"
onChange={handleChange}
type="password"
value={formState.values.password || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('firstName')}
fullWidth
helperText={
hasError('firstName') ? formState.errors.firstName[0] : null
}
label="Nombre"
name="firstName"
onChange={handleChange}
type="text"
value={formState.values.firstName || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('lastName')}
fullWidth
helperText={
hasError('lastName') ? formState.errors.lastName[0] : null
}
label="Apellido"
name="lastName"
onChange={handleChange}
type="text"
value={formState.values.lastName || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('address')}
fullWidth
helperText={
hasError('address') ? formState.errors.address[0] : null
}
label="Dirección"
name="address"
onChange={handleChange}
type="text"
value={formState.values.address || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('country')}
fullWidth
helperText={
hasError('country') ? formState.errors.country[0] : null
}
label="Selecciona tu país"
name="country"
onChange={handleChange}
select
// type="text"
value={formState.values.country || ''}
variant="outlined"
>
{currenciesCountry.map(option => (
<MenuItem
key={option.value}
value={option.value}
>
{option.label}
</MenuItem>
))}
</TextField>
</Grid>
<Grid
item
md={12}
xs={12}
>
<MuiPhoneNumber
defaultCountry={'co'}
className={classes.textField}
error={hasError('cellphone')}
fullWidth
helperText={
hasError('cellphone') ? formState.errors.cellphone[0] : null
}
label="Telefono móvil"
name="cellphone"
onChange={handleChangeCellphone}
value={formState.values.cellphone || ''}
variant="outlined"
/>
</Grid>
<Grid
item
md={12}
xs={12}
>
<TextField
className={classes.textField}
error={hasError('rol')}
fullWidth
helperText={
hasError('rol') ? formState.errors.rol[0] : null
}
label="Elige tu rol"
name="rol"
onChange={handleChange}
select
value={formState.values.rol || ''}
variant="outlined"
>
{currencies.map(option => (
<MenuItem
key={option.value}
value={option.value}
>
{option.label}
</MenuItem>
))}
</TextField>
</Grid>
<div className={classes.policy}>
<Checkbox
checked={formState.values.policy || false}
className={classes.policyCheckbox}
color="primary"
name="policy"
onChange={handleChange}
/>
<Typography
className={classes.policyText}
color="textSecondary"
variant="body1"
>
He leido los {' '}
<Link
color="primary"
component={RouterLink}
to="#"
underline="always"
variant="h6"
>
Terminos y condiciones
</Link>
</Typography>
</div>
{hasError('policy') && (
<FormHelperText error>
{formState.errors.policy[0]}
</FormHelperText>
)}
<Button
className={classes.signUpButton}
color="primary"
disabled={!formState.isValid}
fullWidth
size="large"
type="submit"
variant="contained"
>
Registrarse ahora
</Button>
<Typography
color="textSecondary"
variant="body1"
>
¿Ya tienes una cuenta?{' '}
<Link
component={RouterLink}
to="/sign-in"
variant="h6"
>
Ingresar
</Link>
</Typography>
</Grid>
</form>
</div>
</div>
</div>
);
};
SignUp.propTypes = {
history: PropTypes.object
};
export default withRouter(SignUp);
|
egonzalez49/hablamos-client
|
src/components/ChatRoomListItem/ChatRoomListItem.js
|
import React from 'react';
import { MdKeyboardArrowRight } from 'react-icons/md';
const ChatRoomListItem = ({ id, title, description, onClick }) => {
return (
<li className="chatroom-list-item" onClick={() => onClick(id)}>
<div className="chatroom-list-item__text">
<h4 className="chatroom-title">{title}</h4>
<p className="chatroom-description">{description}</p>
</div>
<MdKeyboardArrowRight size={30} className="enter-icon" />
</li>
);
};
export default ChatRoomListItem;
|
RodrigoQuesadaDev/XGen4J
|
xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/instantiation/errorWithNoDescriptionAreAbstract/Information.java
|
<filename>xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/instantiation/errorWithNoDescriptionAreAbstract/Information.java
package com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract;
import com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.ErrorInfo.CustomMessageGeneratorErrorDescription;
import com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.ErrorInfo.PlainTextErrorDescription;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Autogenerated by XGen4J on January 1, 0001.
*/
public class Information {
private static List<ErrorInfo> errorInfoList;
private static Map<String, ErrorInfo> idToErrorInfoMap;
private static final AtomicBoolean loaded = new AtomicBoolean();
private static void load() {
if (loaded.compareAndSet(false, true)) {
errorInfoList = new ArrayList<>();
idToErrorInfoMap = new HashMap<>();
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.RootError.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.RootException.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.RootError.CODE,
false
));
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.C1Error.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.C1Exception.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.C1Error.CODE,
true
));
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.c2.C2Error.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.c2.C2Exception.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.c2.C2Error.CODE,
true
));
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.c2.c3.C3Error.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.c2.c3.C3Exception.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.c1.c2.c3.C3Error.CODE,
new PlainTextErrorDescription("ABCDE"),
true
));
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.E1Error.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.E1Exception.TYPE, com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.E1Exception.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.E1Error.CODE,
false
));
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.E2Error.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.E2Exception.TYPE, com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.E2Exception.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.E2Error.CODE,
false
));
errorInfoList.add(new ErrorInfo(
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.e3.E3Error.class,
new ExceptionInfo(com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.e3.E3Exception.TYPE, com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.e3.E3Exception.class),
com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.e1.e2.e3.E3Error.CODE,
new PlainTextErrorDescription("ABCDE"),
false
));
errorInfoList = Collections.unmodifiableList(errorInfoList);
for (ErrorInfo errorInfo : errorInfoList) {
idToErrorInfoMap.put(errorInfo.code().id(), errorInfo);
}
loaded.set(true);
}
}
public static List<ErrorInfo> list() {
load();
return errorInfoList;
}
public static ErrorInfo forId(String id) {
if (id == null) throw new IllegalArgumentException("id");
load();
return idToErrorInfoMap.get(id);
}
}
|
ZenMX/elasticsearch
|
x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/action/TransportGetAutoscalingPolicyActionTests.java
|
<filename>x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/action/TransportGetAutoscalingPolicyActionTests.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.xpack.autoscaling.action;
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.autoscaling.AutoscalingMetadata;
import org.elasticsearch.xpack.autoscaling.AutoscalingTestCase;
import org.elasticsearch.xpack.autoscaling.policy.AutoscalingPolicy;
import java.util.EnumSet;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;
public class TransportGetAutoscalingPolicyActionTests extends AutoscalingTestCase {
public void testReadBlock() {
final TransportGetAutoscalingPolicyAction action = new TransportGetAutoscalingPolicyAction(
mock(TransportService.class),
mock(ClusterService.class),
mock(ThreadPool.class),
mock(ActionFilters.class),
mock(IndexNameExpressionResolver.class)
);
final ClusterBlocks blocks = ClusterBlocks.builder()
.addGlobalBlock(
new ClusterBlock(
randomIntBetween(128, 256),
"metadata read block",
false,
false,
false,
RestStatus.SERVICE_UNAVAILABLE,
EnumSet.of(ClusterBlockLevel.METADATA_READ)
)
)
.build();
final ClusterState state = ClusterState.builder(new ClusterName(randomAlphaOfLength(8))).blocks(blocks).build();
final ClusterBlockException e = action.checkBlock(new GetAutoscalingPolicyAction.Request(randomAlphaOfLength(8)), state);
assertThat(e, not(nullValue()));
}
public void testNoReadBlock() {
final TransportGetAutoscalingPolicyAction action = new TransportGetAutoscalingPolicyAction(
mock(TransportService.class),
mock(ClusterService.class),
mock(ThreadPool.class),
mock(ActionFilters.class),
mock(IndexNameExpressionResolver.class)
);
final ClusterBlocks blocks = ClusterBlocks.builder().build();
final ClusterState state = ClusterState.builder(new ClusterName(randomAlphaOfLength(8))).blocks(blocks).build();
final ClusterBlockException e = action.checkBlock(new GetAutoscalingPolicyAction.Request(randomAlphaOfLength(8)), state);
assertThat(e, nullValue());
}
public void testGetPolicy() {
final ClusterState state;
{
final ClusterState.Builder builder = ClusterState.builder(new ClusterName(randomAlphaOfLength(8)));
builder.metadata(
Metadata.builder().putCustom(AutoscalingMetadata.NAME, randomAutoscalingMetadataOfPolicyCount(randomIntBetween(1, 8)))
);
state = builder.build();
}
final AutoscalingMetadata metadata = state.metadata().custom(AutoscalingMetadata.NAME);
final String name = randomFrom(metadata.policies().keySet());
final AutoscalingPolicy policy = TransportGetAutoscalingPolicyAction.getAutoscalingPolicy(state, name);
assertThat(metadata.policies().get(name).policy(), equalTo(policy));
}
public void testGetNonExistentPolicy() {
final ClusterState state;
{
final ClusterState.Builder builder = ClusterState.builder(new ClusterName(randomAlphaOfLength(8)));
builder.metadata(
Metadata.builder().putCustom(AutoscalingMetadata.NAME, randomAutoscalingMetadataOfPolicyCount(randomIntBetween(1, 8)))
);
state = builder.build();
}
final AutoscalingMetadata metadata = state.metadata().custom(AutoscalingMetadata.NAME);
final String name = randomValueOtherThanMany(metadata.policies().keySet()::contains, () -> randomAlphaOfLength(8));
final ResourceNotFoundException e = expectThrows(
ResourceNotFoundException.class,
() -> TransportGetAutoscalingPolicyAction.getAutoscalingPolicy(state, name)
);
assertThat(e.getMessage(), containsString("autoscaling policy with name [" + name + "] does not exist"));
}
}
|
ArturDrozdz/brix
|
src/gallery/charts/js/pub/views/list/graphs.js
|
<reponame>ArturDrozdz/brix
KISSY.add('brix/gallery/charts/js/pub/views/list/graphs',function(S,Base,node,Global,SVGElement,SVGRenderer,SVGGraphics,Info){
function List(){
var self = this
List.superclass.constructor.apply(self,arguments);
self.init()
}
List.ATTRS = {
w:{
value:0
},
h:{
value:0
},
data:{
value:[]
},
element:{
value:null
},
_info:{
value:null
}
}
S.extend(List,Base,{
init:function(){
var self = this
List.superclass.constructor.apply(self,arguments);
self.set('element', new SVGElement('g')), self.get('element').set('class','list')
self.get('element').setDynamic('childs',[])
self.get('parent').appendChild(self.get('element').element)
},
induce:function($o,$b){
var self = this
if (self.get('_info')) {
self.get('_info').moveRowTxt($o)
}
},
widget:function(){
var self = this
List.superclass.constructor.apply(self,arguments);
self._widget()
},
_widget:function(){
var self = this
var w = self.get('w'), h = self.get('h')
var _info
var data = self.get('data')
//data = self._test()
if(data.length){
self.set('_info', new Info())
_info = self.get('_info')
var o = {
data : data,
parent : self.get('element'),
isBack : 0,
hor_dis: 3,
ver_dis: 5
}
_info.init(o)
w = Math.floor(_info.get('w') / 2), h = Math.floor(_info.get('h') / 2)
_info.get('element').transformXY(w, h)
w = _info.get('w'), h = _info.get('h')
self.set('w', w), self.set('h', h)
}
// var induce = self._drawGraph({w:w,h:h,opacity:0.4})
// self.get('element').appendChild(induce.element)
},
/*
_test:function(){
var data = []
data = test()
function test(){
var data = []
data[0] = []
data[1] = []
// data[2] = []
var o = {}
o.content = '1', o.bold = 1, o.fill = '#333333', o.size = 12, o.ver_align = 3
data[0].push(o)
o = {}
o.content = '浙江', o.bold = 1, o.fill = '#333333', o.size = 12, o.ver_align = 1
data[0].push(o)
o = {}
o.content = '22%', o.bold = 1, o.fill = '#333333', o.size = 12, o.ver_align = 3
data[0].push(o)
o = {}
o.content = '12', o.bold = 1, o.fill = '#333333', o.size = 12, o.ver_align = 3
data[1].push(o)
o = {}
o.content = '黑龙江', o.bold = 1, o.fill = '#333333', o.size = 12, o.ver_align = 1
data[1].push(o)
o = {}
o.content = '7%', o.bold = 1, o.fill = '#333333', o.size = 12, o.ver_align = 3
data[1].push(o)
// o = {}
// o.content = '品牌展位60%', o.bold = 0, o.fill = '#78a64b', o.sign = {has:1,trim:1,fill:'#78a64b' }
// data[2].push(o)
return data
}
return data
},
//画支柱
_drawGraph:function($o){
var w = $o.w,h = $o.h,fill = $o.fill ? $o.fill : '#000000',opacity = $o.opacity ? $o.opacity : 1
var d = SVGRenderer.symbol('square',0,0,w,h).join(' ')
var p = new SVGElement('path')
p.attr({'_w':w,'_h':h,'d':d,'fill':fill,'opacity':opacity})
return p
},*/
});
return List;
}, {
requires:['base','node','../../utils/global','../../utils/svgelement','../../utils/svgrenderer','../svggraphics','../infos/info']
}
);
|
mosaic-cloud/mosaic-distribution-dependencies
|
dependencies/mozilla-js/1.8.5/js/src/jscntxt.h
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=78:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef jscntxt_h___
#define jscntxt_h___
/*
* JS execution context.
*/
#include <string.h>
/* Gross special case for Gecko, which defines malloc/calloc/free. */
#ifdef mozilla_mozalloc_macro_wrappers_h
# define JS_CNTXT_UNDEFD_MOZALLOC_WRAPPERS
/* The "anti-header" */
# include "mozilla/mozalloc_undef_macro_wrappers.h"
#endif
#include "jsprvtd.h"
#include "jsarena.h"
#include "jsclist.h"
#include "jslong.h"
#include "jsatom.h"
#include "jsdhash.h"
#include "jsdtoa.h"
#include "jsfun.h"
#include "jsgc.h"
#include "jsgcchunk.h"
#include "jshashtable.h"
#include "jsinterp.h"
#include "jsmath.h"
#include "jsobj.h"
#include "jspropertycache.h"
#include "jspropertytree.h"
#include "jsstaticcheck.h"
#include "jsutil.h"
#include "jsarray.h"
#include "jsvector.h"
#include "prmjtime.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4100) /* Silence unreferenced formal parameter warnings */
#pragma warning(push)
#pragma warning(disable:4355) /* Silence warning about "this" used in base member initializer list */
#endif
/*
* js_GetSrcNote cache to avoid O(n^2) growth in finding a source note for a
* given pc in a script. We use the script->code pointer to tag the cache,
* instead of the script address itself, so that source notes are always found
* by offset from the bytecode with which they were generated.
*/
typedef struct JSGSNCache {
jsbytecode *code;
JSDHashTable table;
#ifdef JS_GSNMETER
uint32 hits;
uint32 misses;
uint32 fills;
uint32 purges;
# define GSN_CACHE_METER(cache,cnt) (++(cache)->cnt)
#else
# define GSN_CACHE_METER(cache,cnt) /* nothing */
#endif
} JSGSNCache;
#define js_FinishGSNCache(cache) js_PurgeGSNCache(cache)
extern void
js_PurgeGSNCache(JSGSNCache *cache);
/* These helper macros take a cx as parameter and operate on its GSN cache. */
#define JS_PURGE_GSN_CACHE(cx) js_PurgeGSNCache(&JS_GSN_CACHE(cx))
#define JS_METER_GSN_CACHE(cx,cnt) GSN_CACHE_METER(&JS_GSN_CACHE(cx), cnt)
/* Forward declarations of nanojit types. */
namespace nanojit {
class Assembler;
class CodeAlloc;
class Fragment;
template<typename K> struct DefaultHash;
template<typename K, typename V, typename H> class HashMap;
template<typename T> class Seq;
} /* namespace nanojit */
namespace js {
/* Tracer constants. */
static const size_t MONITOR_N_GLOBAL_STATES = 4;
static const size_t FRAGMENT_TABLE_SIZE = 512;
static const size_t MAX_NATIVE_STACK_SLOTS = 4096;
static const size_t MAX_CALL_STACK_ENTRIES = 500;
static const size_t MAX_GLOBAL_SLOTS = 4096;
static const size_t GLOBAL_SLOTS_BUFFER_SIZE = MAX_GLOBAL_SLOTS + 1;
static const size_t MAX_SLOW_NATIVE_EXTRA_SLOTS = 16;
/* Forward declarations of tracer types. */
class VMAllocator;
class FrameInfoCache;
struct FrameInfo;
struct VMSideExit;
struct TreeFragment;
struct TracerState;
template<typename T> class Queue;
typedef Queue<uint16> SlotList;
class TypeMap;
class LoopProfile;
#if defined(JS_JIT_SPEW) || defined(DEBUG)
struct FragPI;
typedef nanojit::HashMap<uint32, FragPI, nanojit::DefaultHash<uint32> > FragStatsMap;
#endif
namespace mjit {
class JaegerCompartment;
}
/*
* Allocation policy that calls JSContext memory functions and reports errors
* to the context. Since the JSContext given on construction is stored for
* the lifetime of the container, this policy may only be used for containers
* whose lifetime is a shorter than the given JSContext.
*/
class ContextAllocPolicy
{
JSContext *cx;
public:
ContextAllocPolicy(JSContext *cx) : cx(cx) {}
JSContext *context() const { return cx; }
/* Inline definitions below. */
void *malloc(size_t bytes);
void free(void *p);
void *realloc(void *p, size_t bytes);
void reportAllocOverflow() const;
};
/*
* A StackSegment (referred to as just a 'segment') contains a prev-linked set
* of stack frames and the slots associated with each frame. A segment and its
* contained frames/slots also have a precise memory layout that is described
* in the js::StackSpace comment. A key layout invariant for segments is that
* prev-linked frames are adjacent in memory, separated only by the values that
* constitute the locals and expression stack of the prev-frame.
*
* The set of stack frames in a non-empty segment start at the segment's
* "current frame", which is the most recently pushed frame, and ends at the
* segment's "initial frame". Note that, while all stack frames in a segment
* are prev-linked, not all prev-linked frames are in the same segment. Hence,
* for a segment |ss|, |ss->getInitialFrame()->prev| may be non-null and in a
* different segment. This occurs when the VM reenters itself (via Invoke or
* Execute). In full generality, a single context may contain a forest of trees
* of stack frames. With respect to this forest, a segment contains a linear
* path along a single tree, not necessarily to the root.
*
* The frames of a non-empty segment must all be in the same context and thus
* each non-empty segment is referred to as being "in" a context. Segments in a
* context have an additional state of being either "active" or "suspended". A
* suspended segment |ss| has a "suspended frame" which is snapshot of |cx->regs|
* when the segment was suspended and serves as the current frame of |ss|.
* There is at most one active segment in a given context. Segments in a
* context execute LIFO and are maintained in a stack. The top of this stack
* is the context's "current segment". If a context |cx| has an active segment
* |ss|, then:
* 1. |ss| is |cx|'s current segment,
* 2. |cx->regs != NULL|, and
* 3. |ss|'s current frame is |cx->regs->fp|.
* Moreover, |cx->regs != NULL| iff |cx| has an active segment.
*
* An empty segment is not associated with any context. Empty segments are
* created when there is not an active segment for a context at the top of the
* stack and claim space for the arguments of an Invoke before the Invoke's
* stack frame is pushed. During the intervals when the arguments have been
* pushed, but not the stack frame, the segment cannot be pushed onto the
* context, since that would require some hack to deal with cx->fp not being
* the current frame of cx->currentSegment.
*
* Finally, (to support JS_SaveFrameChain/JS_RestoreFrameChain) a suspended
* segment may or may not be "saved". Normally, when the active segment is
* popped, the previous segment (which is necessarily suspended) becomes
* active. If the previous segment was saved, however, then it stays suspended
* until it is made active by a call to JS_RestoreFrameChain. This is why a
* context may have a current segment, but not an active segment.
*/
class StackSegment
{
/* The context to which this segment belongs. */
JSContext *cx;
/* Link for JSContext segment stack mentioned in big comment above. */
StackSegment *previousInContext;
/* Link for StackSpace segment stack mentioned in StackSpace comment. */
StackSegment *previousInMemory;
/* The first frame executed in this segment. null iff cx is null */
JSStackFrame *initialFrame;
/* If this segment is suspended, |cx->regs| when it was suspended. */
JSFrameRegs *suspendedRegs;
/* The varobj on entry to initialFrame. */
JSObject *initialVarObj;
/* Whether this segment was suspended by JS_SaveFrameChain. */
bool saved;
/* Align at 8 bytes on all platforms. */
#if JS_BITS_PER_WORD == 32
void *padding;
#endif
/*
* To make isActive a single null-ness check, this non-null constant is
* assigned to suspendedRegs when !inContext.
*/
#define NON_NULL_SUSPENDED_REGS ((JSFrameRegs *)0x1)
public:
StackSegment()
: cx(NULL), previousInContext(NULL), previousInMemory(NULL),
initialFrame(NULL), suspendedRegs(NON_NULL_SUSPENDED_REGS),
initialVarObj(NULL), saved(false)
{
JS_ASSERT(!inContext());
}
/* Safe casts guaranteed by the contiguous-stack layout. */
Value *valueRangeBegin() const {
return (Value *)(this + 1);
}
/*
* As described in the comment at the beginning of the class, a segment
* is in one of three states:
*
* !inContext: the segment has been created to root arguments for a
* future call to Invoke.
* isActive: the segment describes a set of stack frames in a context,
* where the top frame currently executing.
* isSuspended: like isActive, but the top frame has been suspended.
*/
bool inContext() const {
JS_ASSERT(!!cx == !!initialFrame);
JS_ASSERT_IF(!cx, suspendedRegs == NON_NULL_SUSPENDED_REGS && !saved);
return cx;
}
bool isActive() const {
JS_ASSERT_IF(!suspendedRegs, cx && !saved);
JS_ASSERT_IF(!cx, suspendedRegs == NON_NULL_SUSPENDED_REGS);
return !suspendedRegs;
}
bool isSuspended() const {
JS_ASSERT_IF(!cx || !suspendedRegs, !saved);
JS_ASSERT_IF(!cx, suspendedRegs == NON_NULL_SUSPENDED_REGS);
return cx && suspendedRegs;
}
/* Substate of suspended, queryable in any state. */
bool isSaved() const {
JS_ASSERT_IF(saved, isSuspended());
return saved;
}
/* Transitioning between inContext <--> isActive */
void joinContext(JSContext *cx, JSStackFrame *f) {
JS_ASSERT(!inContext());
this->cx = cx;
initialFrame = f;
suspendedRegs = NULL;
JS_ASSERT(isActive());
}
void leaveContext() {
JS_ASSERT(isActive());
this->cx = NULL;
initialFrame = NULL;
suspendedRegs = NON_NULL_SUSPENDED_REGS;
JS_ASSERT(!inContext());
}
JSContext *maybeContext() const {
return cx;
}
#undef NON_NULL_SUSPENDED_REGS
/* Transitioning between isActive <--> isSuspended */
void suspend(JSFrameRegs *regs) {
JS_ASSERT(isActive());
JS_ASSERT(regs && regs->fp && contains(regs->fp));
suspendedRegs = regs;
JS_ASSERT(isSuspended());
}
void resume() {
JS_ASSERT(isSuspended());
suspendedRegs = NULL;
JS_ASSERT(isActive());
}
/* When isSuspended, transitioning isSaved <--> !isSaved */
void save(JSFrameRegs *regs) {
JS_ASSERT(!isSuspended());
suspend(regs);
saved = true;
JS_ASSERT(isSaved());
}
void restore() {
JS_ASSERT(isSaved());
saved = false;
resume();
JS_ASSERT(!isSuspended());
}
/* Data available when inContext */
JSStackFrame *getInitialFrame() const {
JS_ASSERT(inContext());
return initialFrame;
}
inline JSFrameRegs *getCurrentRegs() const;
inline JSStackFrame *getCurrentFrame() const;
/* Data available when isSuspended. */
JSFrameRegs *getSuspendedRegs() const {
JS_ASSERT(isSuspended());
return suspendedRegs;
}
JSStackFrame *getSuspendedFrame() const {
return suspendedRegs->fp;
}
/* JSContext / js::StackSpace bookkeeping. */
void setPreviousInContext(StackSegment *seg) {
previousInContext = seg;
}
StackSegment *getPreviousInContext() const {
return previousInContext;
}
void setPreviousInMemory(StackSegment *seg) {
previousInMemory = seg;
}
StackSegment *getPreviousInMemory() const {
return previousInMemory;
}
void setInitialVarObj(JSObject *obj) {
JS_ASSERT(inContext());
initialVarObj = obj;
}
bool hasInitialVarObj() {
JS_ASSERT(inContext());
return initialVarObj != NULL;
}
JSObject &getInitialVarObj() const {
JS_ASSERT(inContext() && initialVarObj);
return *initialVarObj;
}
#ifdef DEBUG
JS_REQUIRES_STACK bool contains(const JSStackFrame *fp) const;
#endif
};
static const size_t VALUES_PER_STACK_SEGMENT = sizeof(StackSegment) / sizeof(Value);
JS_STATIC_ASSERT(sizeof(StackSegment) % sizeof(Value) == 0);
/* See StackSpace::pushInvokeArgs. */
class InvokeArgsGuard : public CallArgs
{
friend class StackSpace;
JSContext *cx; /* null implies nothing pushed */
StackSegment *seg;
Value *prevInvokeArgEnd;
#ifdef DEBUG
StackSegment *prevInvokeSegment;
JSStackFrame *prevInvokeFrame;
#endif
public:
InvokeArgsGuard() : cx(NULL), seg(NULL) {}
~InvokeArgsGuard();
bool pushed() const { return cx != NULL; }
};
/*
* This type can be used to call Invoke when the arguments have already been
* pushed onto the stack as part of normal execution.
*/
struct InvokeArgsAlreadyOnTheStack : CallArgs
{
InvokeArgsAlreadyOnTheStack(Value *vp, uintN argc) : CallArgs(vp + 2, argc) {}
};
/* See StackSpace::pushInvokeFrame. */
class InvokeFrameGuard
{
friend class StackSpace;
JSContext *cx_; /* null implies nothing pushed */
JSFrameRegs regs_;
JSFrameRegs *prevRegs_;
public:
InvokeFrameGuard() : cx_(NULL) {}
~InvokeFrameGuard() { if (pushed()) pop(); }
bool pushed() const { return cx_ != NULL; }
JSContext *pushedFrameContext() const { JS_ASSERT(pushed()); return cx_; }
void pop();
JSStackFrame *fp() const { return regs_.fp; }
};
/* Reusable base; not for direct use. */
class FrameGuard
{
friend class StackSpace;
JSContext *cx_; /* null implies nothing pushed */
StackSegment *seg_;
Value *vp_;
JSStackFrame *fp_;
public:
FrameGuard() : cx_(NULL), vp_(NULL), fp_(NULL) {}
JS_REQUIRES_STACK ~FrameGuard();
bool pushed() const { return cx_ != NULL; }
StackSegment *segment() const { return seg_; }
Value *vp() const { return vp_; }
JSStackFrame *fp() const { return fp_; }
};
/* See StackSpace::pushExecuteFrame. */
class ExecuteFrameGuard : public FrameGuard
{
friend class StackSpace;
JSFrameRegs regs_;
};
/* See StackSpace::pushDummyFrame. */
class DummyFrameGuard : public FrameGuard
{
friend class StackSpace;
JSFrameRegs regs_;
};
/* See StackSpace::pushGeneratorFrame. */
class GeneratorFrameGuard : public FrameGuard
{};
/*
* Stack layout
*
* Each JSThreadData has one associated StackSpace object which allocates all
* segments for the thread. StackSpace performs all such allocations in a
* single, fixed-size buffer using a specific layout scheme that allows some
* associations between segments, frames, and slots to be implicit, rather
* than explicitly stored as pointers. To maintain useful invariants, stack
* space is not given out arbitrarily, but rather allocated/deallocated for
* specific purposes. The use cases currently supported are: calling a function
* with arguments (e.g. Invoke), executing a script (e.g. Execute), inline
* interpreter calls, and pushing "dummy" frames for bookkeeping purposes. See
* associated member functions below.
*
* First, we consider the layout of individual segments. (See the
* js::StackSegment comment for terminology.) A non-empty segment (i.e., a
* segment in a context) has the following layout:
*
* initial frame current frame ------. if regs,
* .------------. | | regs->sp
* | V V V
* |segment| slots |frame| slots |frame| slots |frame| slots |
* | ^ | ^ |
* ? <----------' `----------' `----------'
* prev prev prev
*
* Moreover, the bytes in the following ranges form a contiguous array of
* Values that are marked during GC:
* 1. between a segment and its first frame
* 2. between two adjacent frames in a segment
* 3. between a segment's current frame and (if fp->regs) fp->regs->sp
* Thus, the VM must ensure that all such Values are safe to be marked.
*
* An empty segment is followed by arguments that are rooted by the
* StackSpace::invokeArgEnd pointer:
*
* invokeArgEnd
* |
* V
* |segment| slots |
*
* Above the level of segments, a StackSpace is simply a contiguous sequence
* of segments kept in a linked list:
*
* base currentSegment firstUnused end
* | | | |
* V V V V
* |segment| --- |segment| --- |segment| ------- | |
* | ^ | ^ |
* 0 <---' `-----------' `-----------'
* previous previous previous
*
* Both js::StackSpace and JSContext maintain a stack of segments, the top of
* which is the "current segment" for that thread or context, respectively.
* Since different contexts can arbitrarily interleave execution in a single
* thread, these stacks are different enough that a segment needs both
* "previousInMemory" and "previousInContext".
*
* For example, in a single thread, a function in segment S1 in a context CX1
* may call out into C++ code that reenters the VM in a context CX2, which
* creates a new segment S2 in CX2, and CX1 may or may not equal CX2.
*
* Note that there is some structure to this interleaving of segments:
* 1. the inclusion from segments in a context to segments in a thread
* preserves order (in terms of previousInContext and previousInMemory,
* respectively).
* 2. the mapping from stack frames to their containing segment preserves
* order (in terms of prev and previousInContext, respectively).
*/
class StackSpace
{
Value *base;
#ifdef XP_WIN
mutable Value *commitEnd;
#endif
Value *end;
StackSegment *currentSegment;
#ifdef DEBUG
/*
* Keep track of which segment/frame bumped invokeArgEnd so that
* firstUnused() can assert that, when invokeArgEnd is used as the top of
* the stack, it is being used appropriately.
*/
StackSegment *invokeSegment;
JSStackFrame *invokeFrame;
#endif
Value *invokeArgEnd;
friend class InvokeArgsGuard;
friend class InvokeFrameGuard;
friend class FrameGuard;
bool pushSegmentForInvoke(JSContext *cx, uintN argc, InvokeArgsGuard *ag);
void popSegmentForInvoke(const InvokeArgsGuard &ag);
bool pushInvokeFrameSlow(JSContext *cx, const InvokeArgsGuard &ag,
InvokeFrameGuard *fg);
void popInvokeFrameSlow(const CallArgs &args);
bool getSegmentAndFrame(JSContext *cx, uintN vplen, uintN nslots,
FrameGuard *fg) const;
void pushSegmentAndFrame(JSContext *cx, JSFrameRegs *regs, FrameGuard *fg);
void popSegmentAndFrame(JSContext *cx);
struct EnsureSpaceCheck {
inline bool operator()(const StackSpace &, JSContext *, Value *, uintN);
};
struct LimitCheck {
JSStackFrame *base;
Value **limit;
LimitCheck(JSStackFrame *base, Value **limit) : base(base), limit(limit) {}
inline bool operator()(const StackSpace &, JSContext *, Value *, uintN);
};
template <class Check>
inline JSStackFrame *getCallFrame(JSContext *cx, Value *sp, uintN nactual,
JSFunction *fun, JSScript *script,
uint32 *pflags, Check check) const;
inline void popInvokeArgs(const InvokeArgsGuard &args);
inline void popInvokeFrame(const InvokeFrameGuard &ag);
inline Value *firstUnused() const;
inline bool isCurrentAndActive(JSContext *cx) const;
friend class AllFramesIter;
StackSegment *getCurrentSegment() const { return currentSegment; }
#ifdef XP_WIN
/* Commit more memory from the reserved stack space. */
JS_FRIEND_API(bool) bumpCommit(Value *from, ptrdiff_t nvals) const;
#endif
public:
static const size_t CAPACITY_VALS = 512 * 1024;
static const size_t CAPACITY_BYTES = CAPACITY_VALS * sizeof(Value);
static const size_t COMMIT_VALS = 16 * 1024;
static const size_t COMMIT_BYTES = COMMIT_VALS * sizeof(Value);
/*
* SunSpider and v8bench have roughly an average of 9 slots per script.
* Our heuristic for a quick over-recursion check uses a generous slot
* count based on this estimate. We take this frame size and multiply it
* by the old recursion limit from the interpreter.
*
* Worst case, if an average size script (<=9 slots) over recurses, it'll
* effectively be the same as having increased the old inline call count
* to <= 5,000.
*/
static const size_t STACK_QUOTA = (VALUES_PER_STACK_FRAME + 18) *
JS_MAX_INLINE_CALL_COUNT;
/* Kept as a member of JSThreadData; cannot use constructor/destructor. */
bool init();
void finish();
#ifdef DEBUG
template <class T>
bool contains(T *t) const {
char *v = (char *)t;
JS_ASSERT(size_t(-1) - uintptr_t(t) >= sizeof(T));
return v >= (char *)base && v + sizeof(T) <= (char *)end;
}
#endif
/*
* When we LeaveTree, we need to rebuild the stack, which requires stack
* allocation. There is no good way to handle an OOM for these allocations,
* so this function checks that they cannot occur using the size of the
* TraceNativeStorage as a conservative upper bound.
*/
inline bool ensureEnoughSpaceToEnterTrace();
/* +1 for slow native's stack frame. */
static const ptrdiff_t MAX_TRACE_SPACE_VALS =
MAX_NATIVE_STACK_SLOTS + MAX_CALL_STACK_ENTRIES * VALUES_PER_STACK_FRAME +
(VALUES_PER_STACK_SEGMENT + VALUES_PER_STACK_FRAME /* synthesized slow native */);
/* Mark all segments, frames, and slots on the stack. */
JS_REQUIRES_STACK void mark(JSTracer *trc);
/*
* For all five use cases below:
* - The boolean-valued functions call js_ReportOutOfScriptQuota on OOM.
* - The "get*Frame" functions do not change any global state, they just
* check OOM and return pointers to an uninitialized frame with the
* requested missing arguments/slots. Only once the "push*Frame"
* function has been called is global state updated. Thus, between
* "get*Frame" and "push*Frame", the frame and slots are unrooted.
* - The "push*Frame" functions will set fp->prev; the caller needn't.
* - Functions taking "*Guard" arguments will use the guard's destructor
* to pop the allocation. The caller must ensure the guard has the
* appropriate lifetime.
* - The get*Frame functions put the 'nmissing' slots contiguously after
* the arguments.
*/
/*
* pushInvokeArgs allocates |argc + 2| rooted values that will be passed as
* the arguments to Invoke. A single allocation can be used for multiple
* Invoke calls. The InvokeArgumentsGuard passed to Invoke must come from
* an immediately-enclosing (stack-wise) call to pushInvokeArgs.
*/
bool pushInvokeArgs(JSContext *cx, uintN argc, InvokeArgsGuard *ag);
/* These functions are called inside Invoke, not Invoke clients. */
bool getInvokeFrame(JSContext *cx, const CallArgs &args, JSFunction *fun,
JSScript *script, uint32 *flags, InvokeFrameGuard *fg) const;
void pushInvokeFrame(JSContext *cx, const CallArgs &args, InvokeFrameGuard *fg);
/* These functions are called inside Execute, not Execute clients. */
bool getExecuteFrame(JSContext *cx, JSScript *script, ExecuteFrameGuard *fg) const;
void pushExecuteFrame(JSContext *cx, JSObject *initialVarObj, ExecuteFrameGuard *fg);
/*
* Since RAII cannot be used for inline frames, callers must manually
* call pushInlineFrame/popInlineFrame.
*/
inline JSStackFrame *getInlineFrame(JSContext *cx, Value *sp, uintN nactual,
JSFunction *fun, JSScript *script,
uint32 *flags) const;
inline void pushInlineFrame(JSContext *cx, JSScript *script, JSStackFrame *fp,
JSFrameRegs *regs);
inline void popInlineFrame(JSContext *cx, JSStackFrame *prev, js::Value *newsp);
/* These functions are called inside SendToGenerator. */
bool getGeneratorFrame(JSContext *cx, uintN vplen, uintN nslots,
GeneratorFrameGuard *fg);
void pushGeneratorFrame(JSContext *cx, JSFrameRegs *regs, GeneratorFrameGuard *fg);
/* Pushes a JSStackFrame::isDummyFrame. */
bool pushDummyFrame(JSContext *cx, JSObject &scopeChain, DummyFrameGuard *fg);
/* Check and bump the given stack limit. */
inline JSStackFrame *getInlineFrameWithinLimit(JSContext *cx, Value *sp, uintN nactual,
JSFunction *fun, JSScript *script, uint32 *flags,
JSStackFrame *base, Value **limit) const;
/*
* Compute a stack limit for entering method jit code which allows the
* method jit to check for end-of-stack and over-recursion with a single
* comparison. See STACK_QUOTA above.
*/
inline Value *getStackLimit(JSContext *cx);
/*
* Try to bump the given 'limit' by bumping the commit limit. Return false
* if fully committed or if 'limit' exceeds 'base' + STACK_QUOTA.
*/
bool bumpCommitAndLimit(JSStackFrame *base, Value *from, uintN nvals, Value **limit) const;
/*
* Allocate nvals on the top of the stack, report error on failure.
* N.B. the caller must ensure |from >= firstUnused()|.
*/
inline bool ensureSpace(JSContext *maybecx, Value *from, ptrdiff_t nvals) const;
};
JS_STATIC_ASSERT(StackSpace::CAPACITY_VALS % StackSpace::COMMIT_VALS == 0);
/*
* While |cx->fp|'s pc/sp are available in |cx->regs|, to compute the saved
* value of pc/sp for any other frame, it is necessary to know about that
* frame's next-frame. This iterator maintains this information when walking
* a chain of stack frames starting at |cx->fp|.
*
* Usage:
* for (FrameRegsIter i(cx); !i.done(); ++i)
* ... i.fp() ... i.sp() ... i.pc()
*/
class FrameRegsIter
{
JSContext *cx;
StackSegment *curseg;
JSStackFrame *curfp;
Value *cursp;
jsbytecode *curpc;
void initSlow();
void incSlow(JSStackFrame *fp, JSStackFrame *prev);
public:
JS_REQUIRES_STACK inline FrameRegsIter(JSContext *cx);
bool done() const { return curfp == NULL; }
inline FrameRegsIter &operator++();
JSStackFrame *fp() const { return curfp; }
Value *sp() const { return cursp; }
jsbytecode *pc() const { return curpc; }
};
/*
* Utility class for iteration over all active stack frames.
*/
class AllFramesIter
{
public:
AllFramesIter(JSContext *cx);
bool done() const { return curfp == NULL; }
AllFramesIter& operator++();
JSStackFrame *fp() const { return curfp; }
private:
StackSegment *curcs;
JSStackFrame *curfp;
};
} /* namespace js */
#ifdef DEBUG
# define FUNCTION_KIND_METER_LIST(_) \
_(allfun), _(heavy), _(nofreeupvar), _(onlyfreevar), \
_(flat), _(badfunarg), \
_(joinedsetmethod), _(joinedinitmethod), \
_(joinedreplace), _(joinedsort), _(joinedmodulepat), \
_(mreadbarrier), _(mwritebarrier), _(mwslotbarrier), \
_(unjoined), _(indynamicscope)
# define identity(x) x
struct JSFunctionMeter {
int32 FUNCTION_KIND_METER_LIST(identity);
};
# undef identity
# define JS_FUNCTION_METER(cx,x) JS_RUNTIME_METER((cx)->runtime, functionMeter.x)
#else
# define JS_FUNCTION_METER(cx,x) ((void)0)
#endif
struct JSPendingProxyOperation {
JSPendingProxyOperation *next;
JSObject *object;
};
struct JSThreadData {
#ifdef JS_THREADSAFE
/* The request depth for this thread. */
unsigned requestDepth;
#endif
#ifdef JS_TRACER
/*
* During trace execution (or during trace recording or
* profiling), these fields point to the compartment doing the
* execution on this thread. At other times, they are NULL. If a
* thread tries to execute/record/profile one trace while another
* is still running, the initial one will abort. Therefore, we
* only need to track one at a time.
*/
JSCompartment *onTraceCompartment;
JSCompartment *recordingCompartment;
JSCompartment *profilingCompartment;
#endif
/*
* If non-zero, we were been asked to call the operation callback as soon
* as possible. If the thread has an active request, this contributes
* towards rt->interruptCounter.
*/
volatile int32 interruptFlags;
/* Keeper of the contiguous stack used by all contexts in this thread. */
js::StackSpace stackSpace;
/*
* Flag indicating that we are waiving any soft limits on the GC heap
* because we want allocations to be infallible (except when we hit OOM).
*/
bool waiveGCQuota;
/*
* The GSN cache is per thread since even multi-cx-per-thread embeddings
* do not interleave js_GetSrcNote calls.
*/
JSGSNCache gsnCache;
/* Property cache for faster call/get/set invocation. */
js::PropertyCache propertyCache;
#ifdef JS_TRACER
/* Maximum size of the tracer's code cache before we start flushing. */
uint32 maxCodeCacheBytes;
#endif
/* State used by dtoa.c. */
DtoaState *dtoaState;
/* Base address of the native stack for the current thread. */
jsuword *nativeStackBase;
/* List of currently pending operations on proxies. */
JSPendingProxyOperation *pendingProxyOperation;
js::ConservativeGCThreadData conservativeGC;
bool init();
void finish();
void mark(JSTracer *trc);
void purge(JSContext *cx);
/* This must be called with the GC lock held. */
inline void triggerOperationCallback(JSRuntime *rt);
};
#ifdef JS_THREADSAFE
/*
* Structure uniquely representing a thread. It holds thread-private data
* that can be accessed without a global lock.
*/
struct JSThread {
typedef js::HashMap<void *,
JSThread *,
js::DefaultHasher<void *>,
js::SystemAllocPolicy> Map;
/* Linked list of all contexts in use on this thread. */
JSCList contextList;
/* Opaque thread-id, from NSPR's PR_GetCurrentThread(). */
void *id;
/* Number of JS_SuspendRequest calls withot JS_ResumeRequest. */
unsigned suspendCount;
# ifdef DEBUG
unsigned checkRequestDepth;
# endif
/* Factored out of JSThread for !JS_THREADSAFE embedding in JSRuntime. */
JSThreadData data;
};
#define JS_THREAD_DATA(cx) (&(cx)->thread->data)
extern JSThread *
js_CurrentThread(JSRuntime *rt);
/*
* The function takes the GC lock and does not release in successful return.
* On error (out of memory) the function releases the lock but delegates
* the error reporting to the caller.
*/
extern JSBool
js_InitContextThread(JSContext *cx);
/*
* On entrance the GC lock must be held and it will be held on exit.
*/
extern void
js_ClearContextThread(JSContext *cx);
#endif /* JS_THREADSAFE */
typedef enum JSDestroyContextMode {
JSDCM_NO_GC,
JSDCM_MAYBE_GC,
JSDCM_FORCE_GC,
JSDCM_NEW_FAILED
} JSDestroyContextMode;
typedef enum JSRuntimeState {
JSRTS_DOWN,
JSRTS_LAUNCHING,
JSRTS_UP,
JSRTS_LANDING
} JSRuntimeState;
typedef struct JSPropertyTreeEntry {
JSDHashEntryHdr hdr;
js::Shape *child;
} JSPropertyTreeEntry;
typedef void
(* JSActivityCallback)(void *arg, JSBool active);
namespace js {
typedef js::Vector<JSCompartment *, 0, js::SystemAllocPolicy> WrapperVector;
}
struct JSRuntime {
/* Default compartment. */
JSCompartment *atomsCompartment;
#ifdef JS_THREADSAFE
bool atomsCompartmentIsLocked;
#endif
/* List of compartments (protected by the GC lock). */
js::WrapperVector compartments;
/* Runtime state, synchronized by the stateChange/gcLock condvar/lock. */
JSRuntimeState state;
/* Context create/destroy callback. */
JSContextCallback cxCallback;
/* Compartment create/destroy callback. */
JSCompartmentCallback compartmentCallback;
/*
* Sets a callback that is run whenever the runtime goes idle - the
* last active request ceases - and begins activity - when it was
* idle and a request begins. Note: The callback is called under the
* GC lock.
*/
void setActivityCallback(JSActivityCallback cb, void *arg) {
activityCallback = cb;
activityCallbackArg = arg;
}
JSActivityCallback activityCallback;
void *activityCallbackArg;
/*
* Shape regenerated whenever a prototype implicated by an "add property"
* property cache fill and induced trace guard has a readonly property or a
* setter defined on it. This number proxies for the shapes of all objects
* along the prototype chain of all objects in the runtime on which such an
* add-property result has been cached/traced.
*
* See bug 492355 for more details.
*
* This comes early in JSRuntime to minimize the immediate format used by
* trace-JITted code that reads it.
*/
uint32 protoHazardShape;
/* Garbage collector state, used by jsgc.c. */
js::GCChunkSet gcChunkSet;
js::RootedValueMap gcRootsHash;
js::GCLocks gcLocksHash;
jsrefcount gcKeepAtoms;
size_t gcBytes;
size_t gcTriggerBytes;
size_t gcLastBytes;
size_t gcMaxBytes;
size_t gcMaxMallocBytes;
size_t gcChunksWaitingToExpire;
uint32 gcEmptyArenaPoolLifespan;
uint32 gcNumber;
js::GCMarker *gcMarkingTracer;
uint32 gcTriggerFactor;
int64 gcJitReleaseTime;
JSGCMode gcMode;
volatile bool gcIsNeeded;
/*
* Compartment that triggered GC. If more than one Compatment need GC,
* gcTriggerCompartment is reset to NULL and a global GC is performed.
*/
JSCompartment *gcTriggerCompartment;
/* Compartment that is currently involved in per-compartment GC */
JSCompartment *gcCurrentCompartment;
/*
* We can pack these flags as only the GC thread writes to them. Atomic
* updates to packed bytes are not guaranteed, so stores issued by one
* thread may be lost due to unsynchronized read-modify-write cycles on
* other threads.
*/
bool gcPoke;
bool gcMarkAndSweep;
bool gcRunning;
bool gcRegenShapes;
#ifdef JS_GC_ZEAL
jsrefcount gcZeal;
#endif
JSGCCallback gcCallback;
private:
/*
* Malloc counter to measure memory pressure for GC scheduling. It runs
* from gcMaxMallocBytes down to zero.
*/
volatile ptrdiff_t gcMallocBytes;
public:
js::GCChunkAllocator *gcChunkAllocator;
void setCustomGCChunkAllocator(js::GCChunkAllocator *allocator) {
JS_ASSERT(allocator);
JS_ASSERT(state == JSRTS_DOWN);
gcChunkAllocator = allocator;
}
/*
* The trace operation and its data argument to trace embedding-specific
* GC roots.
*/
JSTraceDataOp gcExtraRootsTraceOp;
void *gcExtraRootsData;
/* Well-known numbers held for use by this runtime's contexts. */
js::Value NaNValue;
js::Value negativeInfinityValue;
js::Value positiveInfinityValue;
JSFlatString *emptyString;
/* List of active contexts sharing this runtime; protected by gcLock. */
JSCList contextList;
/* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
JSDebugHooks globalDebugHooks;
/*
* Right now, we only support runtime-wide debugging.
*/
JSBool debugMode;
#ifdef JS_TRACER
/* True if any debug hooks not supported by the JIT are enabled. */
bool debuggerInhibitsJIT() const {
return (globalDebugHooks.interruptHook ||
globalDebugHooks.callHook);
}
#endif
/* More debugging state, see jsdbgapi.c. */
JSCList trapList;
JSCList watchPointList;
/* Client opaque pointers */
void *data;
#ifdef JS_THREADSAFE
/* These combine to interlock the GC and new requests. */
PRLock *gcLock;
PRCondVar *gcDone;
PRCondVar *requestDone;
uint32 requestCount;
JSThread *gcThread;
js::GCHelperThread gcHelperThread;
/* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
PRLock *rtLock;
#ifdef DEBUG
void * rtLockOwner;
#endif
/* Used to synchronize down/up state change; protected by gcLock. */
PRCondVar *stateChange;
/*
* Lock serializing trapList and watchPointList accesses, and count of all
* mutations to trapList and watchPointList made by debugger threads. To
* keep the code simple, we define debuggerMutations for the thread-unsafe
* case too.
*/
PRLock *debuggerLock;
JSThread::Map threads;
#endif /* JS_THREADSAFE */
uint32 debuggerMutations;
/*
* Security callbacks set on the runtime are used by each context unless
* an override is set on the context.
*/
JSSecurityCallbacks *securityCallbacks;
/* Structured data callbacks are runtime-wide. */
const JSStructuredCloneCallbacks *structuredCloneCallbacks;
/*
* The propertyRemovals counter is incremented for every JSObject::clear,
* and for each JSObject::remove method call that frees a slot in the given
* object. See js_NativeGet and js_NativeSet in jsobj.cpp.
*/
int32 propertyRemovals;
/* Script filename table. */
struct JSHashTable *scriptFilenameTable;
JSCList scriptFilenamePrefixes;
#ifdef JS_THREADSAFE
PRLock *scriptFilenameTableLock;
#endif
/* Number localization, used by jsnum.c */
const char *thousandsSeparator;
const char *decimalSeparator;
const char *numGrouping;
/*
* Weak references to lazily-created, well-known XML singletons.
*
* NB: Singleton objects must be carefully disconnected from the rest of
* the object graph usually associated with a JSContext's global object,
* including the set of standard class objects. See jsxml.c for details.
*/
JSObject *anynameObject;
JSObject *functionNamespaceObject;
#ifdef JS_THREADSAFE
/* Number of threads with active requests and unhandled interrupts. */
volatile int32 interruptCounter;
#else
JSThreadData threadData;
#define JS_THREAD_DATA(cx) (&(cx)->runtime->threadData)
#endif
/*
* Object shape (property cache structural type) identifier generator.
*
* Type 0 stands for the empty scope, and must not be regenerated due to
* uint32 wrap-around. Since js_GenerateShape (in jsinterp.cpp) uses
* atomic pre-increment, the initial value for the first typed non-empty
* scope will be 1.
*
* If this counter overflows into SHAPE_OVERFLOW_BIT (in jsinterp.h), the
* cache is disabled, to avoid aliasing two different types. It stays
* disabled until a triggered GC at some later moment compresses live
* types, minimizing rt->shapeGen in the process.
*/
volatile uint32 shapeGen;
/* Literal table maintained by jsatom.c functions. */
JSAtomState atomState;
/*
* Various metering fields are defined at the end of JSRuntime. In this
* way there is no need to recompile all the code that refers to other
* fields of JSRuntime after enabling the corresponding metering macro.
*/
#ifdef JS_DUMP_ENUM_CACHE_STATS
int32 nativeEnumProbes;
int32 nativeEnumMisses;
# define ENUM_CACHE_METER(name) JS_ATOMIC_INCREMENT(&cx->runtime->name)
#else
# define ENUM_CACHE_METER(name) ((void) 0)
#endif
#ifdef JS_DUMP_LOOP_STATS
/* Loop statistics, to trigger trace recording and compiling. */
JSBasicStats loopStats;
#endif
#ifdef DEBUG
/* Function invocation metering. */
jsrefcount inlineCalls;
jsrefcount nativeCalls;
jsrefcount nonInlineCalls;
jsrefcount constructs;
jsrefcount liveObjectProps;
jsrefcount liveObjectPropsPreSweep;
/*
* NB: emptyShapes (in JSCompartment) is init'ed iff at least one
* of these envars is set:
*
* JS_PROPTREE_STATFILE statistics on the property tree forest
* JS_PROPTREE_DUMPFILE all paths in the property tree forest
*/
const char *propTreeStatFilename;
const char *propTreeDumpFilename;
bool meterEmptyShapes() const { return propTreeStatFilename || propTreeDumpFilename; }
/* String instrumentation. */
jsrefcount liveStrings;
jsrefcount totalStrings;
jsrefcount liveDependentStrings;
jsrefcount totalDependentStrings;
jsrefcount badUndependStrings;
double lengthSum;
double lengthSquaredSum;
double strdepLengthSum;
double strdepLengthSquaredSum;
/* Script instrumentation. */
jsrefcount liveScripts;
jsrefcount totalScripts;
jsrefcount liveEmptyScripts;
jsrefcount totalEmptyScripts;
jsrefcount highWaterLiveScripts;
#endif /* DEBUG */
#ifdef JS_SCOPE_DEPTH_METER
/*
* Stats on runtime prototype chain lookups and scope chain depths, i.e.,
* counts of objects traversed on a chain until the wanted id is found.
*/
JSBasicStats protoLookupDepthStats;
JSBasicStats scopeSearchDepthStats;
/*
* Stats on compile-time host environment and lexical scope chain lengths
* (maximum depths).
*/
JSBasicStats hostenvScopeDepthStats;
JSBasicStats lexicalScopeDepthStats;
#endif
#ifdef JS_GCMETER
js::gc::JSGCStats gcStats;
js::gc::JSGCArenaStats globalArenaStats[js::gc::FINALIZE_LIMIT];
#endif
#ifdef DEBUG
/*
* If functionMeterFilename, set from an envariable in JSRuntime's ctor, is
* null, the remaining members in this ifdef'ed group are not initialized.
*/
const char *functionMeterFilename;
JSFunctionMeter functionMeter;
char lastScriptFilename[1024];
typedef js::HashMap<JSFunction *,
int32,
js::DefaultHasher<JSFunction *>,
js::SystemAllocPolicy> FunctionCountMap;
FunctionCountMap methodReadBarrierCountMap;
FunctionCountMap unjoinedFunctionCountMap;
#endif
JSWrapObjectCallback wrapObjectCallback;
JSPreWrapCallback preWrapObjectCallback;
#ifdef JS_METHODJIT
uint32 mjitMemoryUsed;
#endif
uint32 stringMemoryUsed;
JSRuntime();
~JSRuntime();
bool init(uint32 maxbytes);
void setGCTriggerFactor(uint32 factor);
void setGCLastBytes(size_t lastBytes);
/*
* Call the system malloc while checking for GC memory pressure and
* reporting OOM error when cx is not null.
*/
void* malloc(size_t bytes, JSContext *cx = NULL) {
updateMallocCounter(bytes);
void *p = ::js_malloc(bytes);
return JS_LIKELY(!!p) ? p : onOutOfMemory(NULL, bytes, cx);
}
/*
* Call the system calloc while checking for GC memory pressure and
* reporting OOM error when cx is not null.
*/
void* calloc(size_t bytes, JSContext *cx = NULL) {
updateMallocCounter(bytes);
void *p = ::js_calloc(bytes);
return JS_LIKELY(!!p) ? p : onOutOfMemory(reinterpret_cast<void *>(1), bytes, cx);
}
void* realloc(void* p, size_t oldBytes, size_t newBytes, JSContext *cx = NULL) {
JS_ASSERT(oldBytes < newBytes);
updateMallocCounter(newBytes - oldBytes);
void *p2 = ::js_realloc(p, newBytes);
return JS_LIKELY(!!p2) ? p2 : onOutOfMemory(p, newBytes, cx);
}
void* realloc(void* p, size_t bytes, JSContext *cx = NULL) {
/*
* For compatibility we do not account for realloc that increases
* previously allocated memory.
*/
if (!p)
updateMallocCounter(bytes);
void *p2 = ::js_realloc(p, bytes);
return JS_LIKELY(!!p2) ? p2 : onOutOfMemory(p, bytes, cx);
}
void free(void* p) { ::js_free(p); }
bool isGCMallocLimitReached() const { return gcMallocBytes <= 0; }
void resetGCMallocBytes() { gcMallocBytes = ptrdiff_t(gcMaxMallocBytes); }
void setGCMaxMallocBytes(size_t value) {
/*
* For compatibility treat any value that exceeds PTRDIFF_T_MAX to
* mean that value.
*/
gcMaxMallocBytes = (ptrdiff_t(value) >= 0) ? value : size_t(-1) >> 1;
resetGCMallocBytes();
}
/*
* Call this after allocating memory held by GC things, to update memory
* pressure counters or report the OOM error if necessary. If oomError and
* cx is not null the function also reports OOM error.
*
* The function must be called outside the GC lock and in case of OOM error
* the caller must ensure that no deadlock possible during OOM reporting.
*/
void updateMallocCounter(size_t nbytes) {
/* We tolerate any thread races when updating gcMallocBytes. */
ptrdiff_t newCount = gcMallocBytes - ptrdiff_t(nbytes);
gcMallocBytes = newCount;
if (JS_UNLIKELY(newCount <= 0))
onTooMuchMalloc();
}
private:
/*
* The function must be called outside the GC lock.
*/
JS_FRIEND_API(void) onTooMuchMalloc();
/*
* This should be called after system malloc/realloc returns NULL to try
* to recove some memory or to report an error. Failures in malloc and
* calloc are signaled by p == null and p == reinterpret_cast<void *>(1).
* Other values of p mean a realloc failure.
*
* The function must be called outside the GC lock.
*/
JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes, JSContext *cx);
};
/* Common macros to access thread-local caches in JSThread or JSRuntime. */
#define JS_GSN_CACHE(cx) (JS_THREAD_DATA(cx)->gsnCache)
#define JS_PROPERTY_CACHE(cx) (JS_THREAD_DATA(cx)->propertyCache)
#ifdef DEBUG
# define JS_RUNTIME_METER(rt, which) JS_ATOMIC_INCREMENT(&(rt)->which)
# define JS_RUNTIME_UNMETER(rt, which) JS_ATOMIC_DECREMENT(&(rt)->which)
#else
# define JS_RUNTIME_METER(rt, which) /* nothing */
# define JS_RUNTIME_UNMETER(rt, which) /* nothing */
#endif
#define JS_KEEP_ATOMS(rt) JS_ATOMIC_INCREMENT(&(rt)->gcKeepAtoms);
#define JS_UNKEEP_ATOMS(rt) JS_ATOMIC_DECREMENT(&(rt)->gcKeepAtoms);
#ifdef JS_ARGUMENT_FORMATTER_DEFINED
/*
* Linked list mapping format strings for JS_{Convert,Push}Arguments{,VA} to
* formatter functions. Elements are sorted in non-increasing format string
* length order.
*/
struct JSArgumentFormatMap {
const char *format;
size_t length;
JSArgumentFormatter formatter;
JSArgumentFormatMap *next;
};
#endif
/*
* Key and entry types for the JSContext.resolvingTable hash table, typedef'd
* here because all consumers need to see these declarations (and not just the
* typedef names, as would be the case for an opaque pointer-to-typedef'd-type
* declaration), along with cx->resolvingTable.
*/
typedef struct JSResolvingKey {
JSObject *obj;
jsid id;
} JSResolvingKey;
typedef struct JSResolvingEntry {
JSDHashEntryHdr hdr;
JSResolvingKey key;
uint32 flags;
} JSResolvingEntry;
#define JSRESFLAG_LOOKUP 0x1 /* resolving id from lookup */
#define JSRESFLAG_WATCH 0x2 /* resolving id from watch */
#define JSRESOLVE_INFER 0xffff /* infer bits from current bytecode */
extern const JSDebugHooks js_NullDebugHooks; /* defined in jsdbgapi.cpp */
namespace js {
class AutoGCRooter;
static inline bool
OptionsHasXML(uint32 options)
{
return !!(options & JSOPTION_XML);
}
static inline bool
OptionsHasAnonFunFix(uint32 options)
{
return !!(options & JSOPTION_ANONFUNFIX);
}
static inline bool
OptionsSameVersionFlags(uint32 self, uint32 other)
{
static const uint32 mask = JSOPTION_XML | JSOPTION_ANONFUNFIX;
return !((self & mask) ^ (other & mask));
}
/*
* Flags accompany script version data so that a) dynamically created scripts
* can inherit their caller's compile-time properties and b) scripts can be
* appropriately compared in the eval cache across global option changes. An
* example of the latter is enabling the top-level-anonymous-function-is-error
* option: subsequent evals of the same, previously-valid script text may have
* become invalid.
*/
namespace VersionFlags {
static const uintN MASK = 0x0FFF; /* see JSVersion in jspubtd.h */
static const uintN HAS_XML = 0x1000; /* flag induced by XML option */
static const uintN ANONFUNFIX = 0x2000; /* see jsapi.h comment on JSOPTION_ANONFUNFIX */
static const uintN FULL_MASK = 0x3FFF;
}
static inline JSVersion
VersionNumber(JSVersion version)
{
return JSVersion(uint32(version) & VersionFlags::MASK);
}
static inline bool
VersionHasXML(JSVersion version)
{
return !!(version & VersionFlags::HAS_XML);
}
/* @warning This is a distinct condition from having the XML flag set. */
static inline bool
VersionShouldParseXML(JSVersion version)
{
return VersionHasXML(version) || VersionNumber(version) >= JSVERSION_1_6;
}
static inline bool
VersionHasAnonFunFix(JSVersion version)
{
return !!(version & VersionFlags::ANONFUNFIX);
}
static inline void
VersionSetXML(JSVersion *version, bool enable)
{
if (enable)
*version = JSVersion(uint32(*version) | VersionFlags::HAS_XML);
else
*version = JSVersion(uint32(*version) & ~VersionFlags::HAS_XML);
}
static inline void
VersionSetAnonFunFix(JSVersion *version, bool enable)
{
if (enable)
*version = JSVersion(uint32(*version) | VersionFlags::ANONFUNFIX);
else
*version = JSVersion(uint32(*version) & ~VersionFlags::ANONFUNFIX);
}
static inline JSVersion
VersionExtractFlags(JSVersion version)
{
return JSVersion(uint32(version) & ~VersionFlags::MASK);
}
static inline void
VersionCopyFlags(JSVersion *version, JSVersion from)
{
*version = JSVersion(VersionNumber(*version) | VersionExtractFlags(from));
}
static inline bool
VersionHasFlags(JSVersion version)
{
return !!VersionExtractFlags(version);
}
static inline uintN
VersionFlagsToOptions(JSVersion version)
{
uintN copts = (VersionHasXML(version) ? JSOPTION_XML : 0) |
(VersionHasAnonFunFix(version) ? JSOPTION_ANONFUNFIX : 0);
JS_ASSERT((copts & JSCOMPILEOPTION_MASK) == copts);
return copts;
}
static inline JSVersion
OptionFlagsToVersion(uintN options, JSVersion version)
{
VersionSetXML(&version, OptionsHasXML(options));
VersionSetAnonFunFix(&version, OptionsHasAnonFunFix(options));
return version;
}
static inline bool
VersionIsKnown(JSVersion version)
{
return VersionNumber(version) != JSVERSION_UNKNOWN;
}
typedef js::HashSet<JSObject *,
js::DefaultHasher<JSObject *>,
js::SystemAllocPolicy> BusyArraysMap;
} /* namespace js */
struct JSContext
{
explicit JSContext(JSRuntime *rt);
/* JSRuntime contextList linkage. */
JSCList link;
private:
/* See JSContext::findVersion. */
JSVersion defaultVersion; /* script compilation version */
JSVersion versionOverride; /* supercedes defaultVersion when valid */
bool hasVersionOverride;
/* Exception state -- the exception member is a GC root by definition. */
JSBool throwing; /* is there a pending exception? */
js::Value exception; /* most-recently-thrown exception */
/* Per-context run options. */
uintN runOptions; /* see jsapi.h for JSOPTION_* */
public:
/* Locale specific callbacks for string conversion. */
JSLocaleCallbacks *localeCallbacks;
/*
* cx->resolvingTable is non-null and non-empty if we are initializing
* standard classes lazily, or if we are otherwise recursing indirectly
* from js_LookupProperty through a Class.resolve hook. It is used to
* limit runaway recursion (see jsapi.c and jsobj.c).
*/
JSDHashTable *resolvingTable;
/*
* True if generating an error, to prevent runaway recursion.
* NB: generatingError packs with throwing below.
*/
JSPackedBool generatingError;
/* Limit pointer for checking native stack consumption during recursion. */
jsuword stackLimit;
/* Quota on the size of arenas used to compile and execute scripts. */
size_t scriptStackQuota;
/* Data shared by threads in an address space. */
JSRuntime *const runtime;
/* GC heap compartment. */
JSCompartment *compartment;
/* Currently executing frame and regs, set by stack operations. */
JS_REQUIRES_STACK
JSFrameRegs *regs;
/* Current frame accessors. */
JSStackFrame* fp() {
JS_ASSERT(regs && regs->fp);
return regs->fp;
}
JSStackFrame* maybefp() {
JS_ASSERT_IF(regs, regs->fp);
return regs ? regs->fp : NULL;
}
bool hasfp() {
JS_ASSERT_IF(regs, regs->fp);
return !!regs;
}
public:
friend class js::StackSpace;
friend bool js::Interpret(JSContext *, JSStackFrame *, uintN, JSInterpMode);
void resetCompartment();
void wrapPendingException();
/* For grep-ability, changes to 'regs' should call this function. */
void setCurrentRegs(JSFrameRegs *regs) {
JS_ASSERT_IF(regs, regs->fp);
this->regs = regs;
}
/* Temporary arena pool used while compiling and decompiling. */
JSArenaPool tempPool;
/* Temporary arena pool used while evaluate regular expressions. */
JSArenaPool regExpPool;
/* Top-level object and pointer to top stack frame's scope chain. */
JSObject *globalObject;
/* State for object and array toSource conversion. */
JSSharpObjectMap sharpObjectMap;
js::BusyArraysMap busyArrays;
/* Argument formatter support for JS_{Convert,Push}Arguments{,VA}. */
JSArgumentFormatMap *argumentFormatMap;
/* Last message string and log file for debugging. */
char *lastMessage;
#ifdef DEBUG
void *logfp;
jsbytecode *logPrevPc;
#endif
/* Per-context optional error reporter. */
JSErrorReporter errorReporter;
/* Branch callback. */
JSOperationCallback operationCallback;
/* Interpreter activation count. */
uintN interpLevel;
/* Client opaque pointers. */
void *data;
void *data2;
private:
/* Linked list of segments. See StackSegment. */
js::StackSegment *currentSegment;
public:
void assertSegmentsInSync() const {
#ifdef DEBUG
if (regs) {
JS_ASSERT(currentSegment->isActive());
if (js::StackSegment *prev = currentSegment->getPreviousInContext())
JS_ASSERT(!prev->isActive());
} else {
JS_ASSERT_IF(currentSegment, !currentSegment->isActive());
}
#endif
}
/* Return whether this context has an active segment. */
bool hasActiveSegment() const {
assertSegmentsInSync();
return !!regs;
}
/* Assuming there is an active segment, return it. */
js::StackSegment *activeSegment() const {
JS_ASSERT(hasActiveSegment());
return currentSegment;
}
/* Return the current segment, which may or may not be active. */
js::StackSegment *getCurrentSegment() const {
assertSegmentsInSync();
return currentSegment;
}
inline js::RegExpStatics *regExpStatics();
/* Add the given segment to the list as the new active segment. */
void pushSegmentAndFrame(js::StackSegment *newseg, JSFrameRegs ®s);
/* Remove the active segment and make the next segment active. */
void popSegmentAndFrame();
/* Mark the top segment as suspended, without pushing a new one. */
void saveActiveSegment();
/* Undoes calls to suspendActiveSegment. */
void restoreSegment();
/* Get the frame whose prev() is fp, which may be in any segment. */
inline JSStackFrame *computeNextFrame(JSStackFrame *fp);
/*
* Perform a linear search of all frames in all segments in the given context
* for the given frame, returning the segment, if found, and null otherwise.
*/
js::StackSegment *containingSegment(const JSStackFrame *target);
/* Search the call stack for the nearest frame with static level targetLevel. */
JSStackFrame *findFrameAtLevel(uintN targetLevel) const {
JSStackFrame *fp = regs->fp;
while (true) {
JS_ASSERT(fp && fp->isScriptFrame());
if (fp->script()->staticLevel == targetLevel)
break;
fp = fp->prev();
}
return fp;
}
public:
/*
* The default script compilation version can be set iff there is no code running.
* This typically occurs via the JSAPI right after a context is constructed.
*/
bool canSetDefaultVersion() const {
return !regs && !hasVersionOverride;
}
/* Force a version for future script compilation. */
void overrideVersion(JSVersion newVersion) {
JS_ASSERT(!canSetDefaultVersion());
versionOverride = newVersion;
hasVersionOverride = true;
}
/* Set the default script compilation version. */
void setDefaultVersion(JSVersion version) {
defaultVersion = version;
}
void clearVersionOverride() { hasVersionOverride = false; }
JSVersion getDefaultVersion() const { return defaultVersion; }
bool isVersionOverridden() const { return hasVersionOverride; }
JSVersion getVersionOverride() const {
JS_ASSERT(isVersionOverridden());
return versionOverride;
}
/*
* Set the default version if possible; otherwise, force the version.
* Return whether an override occurred.
*/
bool maybeOverrideVersion(JSVersion newVersion) {
if (canSetDefaultVersion()) {
setDefaultVersion(newVersion);
return false;
}
overrideVersion(newVersion);
return true;
}
private:
/*
* If there is no code currently executing, turn the override version into
* the default version.
*
* NB: the only time the version is potentially capable of migrating is
* on return from the Execute or ExternalInvoke paths as they call through
* JSContext::popSegmentAndFrame.
*/
void maybeMigrateVersionOverride() {
if (JS_LIKELY(!isVersionOverridden() || currentSegment))
return;
defaultVersion = versionOverride;
clearVersionOverride();
}
public:
/*
* Return:
* - The override version, if there is an override version.
* - The newest scripted frame's version, if there is such a frame.
* - The default verion.
*
* Note: if this ever shows up in a profile, just add caching!
*/
JSVersion findVersion() const {
if (hasVersionOverride)
return versionOverride;
if (regs) {
/* There may be a scripted function somewhere on the stack! */
JSStackFrame *fp = regs->fp;
while (fp && !fp->isScriptFrame())
fp = fp->prev();
if (fp)
return fp->script()->getVersion();
}
return defaultVersion;
}
void setRunOptions(uintN ropts) {
JS_ASSERT((ropts & JSRUNOPTION_MASK) == ropts);
runOptions = ropts;
}
/* Note: may override the version. */
void setCompileOptions(uintN newcopts) {
JS_ASSERT((newcopts & JSCOMPILEOPTION_MASK) == newcopts);
if (JS_LIKELY(getCompileOptions() == newcopts))
return;
JSVersion version = findVersion();
JSVersion newVersion = js::OptionFlagsToVersion(newcopts, version);
maybeOverrideVersion(newVersion);
}
uintN getRunOptions() const { return runOptions; }
uintN getCompileOptions() const { return js::VersionFlagsToOptions(findVersion()); }
uintN allOptions() const { return getRunOptions() | getCompileOptions(); }
bool hasRunOption(uintN ropt) const {
JS_ASSERT((ropt & JSRUNOPTION_MASK) == ropt);
return !!(runOptions & ropt);
}
bool hasStrictOption() const { return hasRunOption(JSOPTION_STRICT); }
bool hasWErrorOption() const { return hasRunOption(JSOPTION_WERROR); }
bool hasAtLineOption() const { return hasRunOption(JSOPTION_ATLINE); }
#ifdef JS_THREADSAFE
JSThread *thread;
unsigned outstandingRequests;/* number of JS_BeginRequest calls
without the corresponding
JS_EndRequest. */
JSCList threadLinks; /* JSThread contextList linkage */
#define CX_FROM_THREAD_LINKS(tl) \
((JSContext *)((char *)(tl) - offsetof(JSContext, threadLinks)))
#endif
/* Stack of thread-stack-allocated GC roots. */
js::AutoGCRooter *autoGCRooters;
/* Debug hooks associated with the current context. */
const JSDebugHooks *debugHooks;
/* Security callbacks that override any defined on the runtime. */
JSSecurityCallbacks *securityCallbacks;
/* Stored here to avoid passing it around as a parameter. */
uintN resolveFlags;
/* Random number generator state, used by jsmath.cpp. */
int64 rngSeed;
/* Location to stash the iteration value between JSOP_MOREITER and JSOP_FOR*. */
js::Value iterValue;
#ifdef JS_TRACER
/*
* True if traces may be executed. Invariant: The value of traceJitenabled
* is always equal to the expression in updateJITEnabled below.
*
* This flag and the fields accessed by updateJITEnabled are written only
* in runtime->gcLock, to avoid race conditions that would leave the wrong
* value in traceJitEnabled. (But the interpreter reads this without
* locking. That can race against another thread setting debug hooks, but
* we always read cx->debugHooks without locking anyway.)
*/
bool traceJitEnabled;
#endif
#ifdef JS_METHODJIT
bool methodJitEnabled;
bool profilingEnabled;
#endif
/* Caller must be holding runtime->gcLock. */
void updateJITEnabled();
#ifdef MOZ_TRACE_JSCALLS
/* Function entry/exit debugging callback. */
JSFunctionCallback functionCallback;
void doFunctionCallback(const JSFunction *fun,
const JSScript *scr,
int entering) const
{
if (functionCallback)
functionCallback(fun, scr, this, entering);
}
#endif
DSTOffsetCache dstOffsetCache;
/* List of currently active non-escaping enumerators (for-in). */
JSObject *enumerators;
private:
/*
* To go from a live generator frame (on the stack) to its generator object
* (see comment js_FloatingFrameIfGenerator), we maintain a stack of active
* generators, pushing and popping when entering and leaving generator
* frames, respectively.
*/
js::Vector<JSGenerator *, 2, js::SystemAllocPolicy> genStack;
public:
#ifdef JS_METHODJIT
inline js::mjit::JaegerCompartment *jaegerCompartment();
#endif
/* Return the generator object for the given generator frame. */
JSGenerator *generatorFor(JSStackFrame *fp) const;
/* Early OOM-check. */
inline bool ensureGeneratorStackSpace();
bool enterGenerator(JSGenerator *gen) {
return genStack.append(gen);
}
void leaveGenerator(JSGenerator *gen) {
JS_ASSERT(genStack.back() == gen);
genStack.popBack();
}
#ifdef JS_THREADSAFE
/*
* When non-null JSContext::free delegates the job to the background
* thread.
*/
js::GCHelperThread *gcBackgroundFree;
#endif
inline void* malloc(size_t bytes) {
return runtime->malloc(bytes, this);
}
inline void* mallocNoReport(size_t bytes) {
JS_ASSERT(bytes != 0);
return runtime->malloc(bytes, NULL);
}
inline void* calloc(size_t bytes) {
JS_ASSERT(bytes != 0);
return runtime->calloc(bytes, this);
}
inline void* realloc(void* p, size_t bytes) {
return runtime->realloc(p, bytes, this);
}
inline void* realloc(void* p, size_t oldBytes, size_t newBytes) {
return runtime->realloc(p, oldBytes, newBytes, this);
}
inline void free(void* p) {
#ifdef JS_THREADSAFE
if (gcBackgroundFree) {
gcBackgroundFree->freeLater(p);
return;
}
#endif
runtime->free(p);
}
/*
* In the common case that we'd like to allocate the memory for an object
* with cx->malloc/free, we cannot use overloaded C++ operators (no
* placement delete). Factor the common workaround into one place.
*/
#define CREATE_BODY(parms) \
void *memory = this->malloc(sizeof(T)); \
if (!memory) \
return NULL; \
return new(memory) T parms;
template <class T>
JS_ALWAYS_INLINE T *create() {
CREATE_BODY(())
}
template <class T, class P1>
JS_ALWAYS_INLINE T *create(const P1 &p1) {
CREATE_BODY((p1))
}
template <class T, class P1, class P2>
JS_ALWAYS_INLINE T *create(const P1 &p1, const P2 &p2) {
CREATE_BODY((p1, p2))
}
template <class T, class P1, class P2, class P3>
JS_ALWAYS_INLINE T *create(const P1 &p1, const P2 &p2, const P3 &p3) {
CREATE_BODY((p1, p2, p3))
}
#undef CREATE_BODY
template <class T>
JS_ALWAYS_INLINE void destroy(T *p) {
p->~T();
this->free(p);
}
void purge();
js::StackSpace &stack() const {
return JS_THREAD_DATA(this)->stackSpace;
}
#ifdef DEBUG
void assertValidStackDepth(uintN depth) {
JS_ASSERT(0 <= regs->sp - regs->fp->base());
JS_ASSERT(depth <= uintptr_t(regs->sp - regs->fp->base()));
}
#else
void assertValidStackDepth(uintN /*depth*/) {}
#endif
bool isExceptionPending() {
return throwing;
}
js::Value getPendingException() {
JS_ASSERT(throwing);
return exception;
}
void setPendingException(js::Value v);
void clearPendingException() {
this->throwing = false;
this->exception.setUndefined();
}
private:
/*
* The allocation code calls the function to indicate either OOM failure
* when p is null or that a memory pressure counter has reached some
* threshold when p is not null. The function takes the pointer and not
* a boolean flag to minimize the amount of code in its inlined callers.
*/
JS_FRIEND_API(void) checkMallocGCPressure(void *p);
}; /* struct JSContext */
#ifdef JS_THREADSAFE
# define JS_THREAD_ID(cx) ((cx)->thread ? (cx)->thread->id : 0)
#endif
#if defined JS_THREADSAFE && defined DEBUG
namespace js {
class AutoCheckRequestDepth {
JSContext *cx;
public:
AutoCheckRequestDepth(JSContext *cx) : cx(cx) { cx->thread->checkRequestDepth++; }
~AutoCheckRequestDepth() {
JS_ASSERT(cx->thread->checkRequestDepth != 0);
cx->thread->checkRequestDepth--;
}
};
}
# define CHECK_REQUEST(cx) \
JS_ASSERT((cx)->thread); \
JS_ASSERT((cx)->thread->data.requestDepth || (cx)->thread == (cx)->runtime->gcThread); \
AutoCheckRequestDepth _autoCheckRequestDepth(cx);
#else
# define CHECK_REQUEST(cx) ((void) 0)
# define CHECK_REQUEST_THREAD(cx) ((void) 0)
#endif
static inline uintN
FramePCOffset(JSContext *cx, JSStackFrame* fp)
{
jsbytecode *pc = fp->hasImacropc() ? fp->imacropc() : fp->pc(cx);
return uintN(pc - fp->script()->code);
}
static inline JSAtom **
FrameAtomBase(JSContext *cx, JSStackFrame *fp)
{
return fp->hasImacropc()
? COMMON_ATOMS_START(&cx->runtime->atomState)
: fp->script()->atomMap.vector;
}
namespace js {
class AutoGCRooter {
public:
AutoGCRooter(JSContext *cx, ptrdiff_t tag)
: down(cx->autoGCRooters), tag(tag), context(cx)
{
JS_ASSERT(this != cx->autoGCRooters);
CHECK_REQUEST(cx);
cx->autoGCRooters = this;
}
~AutoGCRooter() {
JS_ASSERT(this == context->autoGCRooters);
CHECK_REQUEST(context);
context->autoGCRooters = down;
}
/* Implemented in jsgc.cpp. */
inline void trace(JSTracer *trc);
#ifdef __GNUC__
# pragma GCC visibility push(default)
#endif
friend JS_FRIEND_API(void) MarkContext(JSTracer *trc, JSContext *acx);
friend void MarkRuntime(JSTracer *trc);
#ifdef __GNUC__
# pragma GCC visibility pop
#endif
protected:
AutoGCRooter * const down;
/*
* Discriminates actual subclass of this being used. If non-negative, the
* subclass roots an array of values of the length stored in this field.
* If negative, meaning is indicated by the corresponding value in the enum
* below. Any other negative value indicates some deeper problem such as
* memory corruption.
*/
ptrdiff_t tag;
JSContext * const context;
enum {
JSVAL = -1, /* js::AutoValueRooter */
SHAPE = -2, /* js::AutoShapeRooter */
PARSER = -3, /* js::Parser */
SCRIPT = -4, /* js::AutoScriptRooter */
ENUMERATOR = -5, /* js::AutoEnumStateRooter */
IDARRAY = -6, /* js::AutoIdArray */
DESCRIPTORS = -7, /* js::AutoPropDescArrayRooter */
NAMESPACES = -8, /* js::AutoNamespaceArray */
XML = -9, /* js::AutoXMLRooter */
OBJECT = -10, /* js::AutoObjectRooter */
ID = -11, /* js::AutoIdRooter */
VALVECTOR = -12, /* js::AutoValueVector */
DESCRIPTOR = -13, /* js::AutoPropertyDescriptorRooter */
STRING = -14, /* js::AutoStringRooter */
IDVECTOR = -15, /* js::AutoIdVector */
BINDINGS = -16, /* js::Bindings */
SHAPEVECTOR = -17 /* js::AutoShapeVector */
};
private:
/* No copy or assignment semantics. */
AutoGCRooter(AutoGCRooter &ida);
void operator=(AutoGCRooter &ida);
};
/* FIXME(bug 332648): Move this into a public header. */
class AutoValueRooter : private AutoGCRooter
{
public:
explicit AutoValueRooter(JSContext *cx
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, JSVAL), val(js::NullValue())
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
AutoValueRooter(JSContext *cx, const Value &v
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, JSVAL), val(v)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
AutoValueRooter(JSContext *cx, jsval v
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, JSVAL), val(js::Valueify(v))
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
/*
* If you are looking for Object* overloads, use AutoObjectRooter instead;
* rooting Object*s as a js::Value requires discerning whether or not it is
* a function object. Also, AutoObjectRooter is smaller.
*/
void set(Value v) {
JS_ASSERT(tag == JSVAL);
val = v;
}
void set(jsval v) {
JS_ASSERT(tag == JSVAL);
val = js::Valueify(v);
}
const Value &value() const {
JS_ASSERT(tag == JSVAL);
return val;
}
Value *addr() {
JS_ASSERT(tag == JSVAL);
return &val;
}
const jsval &jsval_value() const {
JS_ASSERT(tag == JSVAL);
return Jsvalify(val);
}
jsval *jsval_addr() {
JS_ASSERT(tag == JSVAL);
return Jsvalify(&val);
}
friend void AutoGCRooter::trace(JSTracer *trc);
friend void MarkRuntime(JSTracer *trc);
private:
Value val;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoObjectRooter : private AutoGCRooter {
public:
AutoObjectRooter(JSContext *cx, JSObject *obj = NULL
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, OBJECT), obj(obj)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
void setObject(JSObject *obj) {
this->obj = obj;
}
JSObject * object() const {
return obj;
}
JSObject ** addr() {
return &obj;
}
friend void AutoGCRooter::trace(JSTracer *trc);
friend void MarkRuntime(JSTracer *trc);
private:
JSObject *obj;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoStringRooter : private AutoGCRooter {
public:
AutoStringRooter(JSContext *cx, JSString *str = NULL
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, STRING), str(str)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
void setString(JSString *str) {
this->str = str;
}
JSString * string() const {
return str;
}
JSString ** addr() {
return &str;
}
friend void AutoGCRooter::trace(JSTracer *trc);
private:
JSString *str;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoArrayRooter : private AutoGCRooter {
public:
AutoArrayRooter(JSContext *cx, size_t len, Value *vec
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, len), array(vec)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_ASSERT(tag >= 0);
}
AutoArrayRooter(JSContext *cx, size_t len, jsval *vec
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, len), array(Valueify(vec))
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_ASSERT(tag >= 0);
}
void changeLength(size_t newLength) {
tag = ptrdiff_t(newLength);
JS_ASSERT(tag >= 0);
}
void changeArray(Value *newArray, size_t newLength) {
changeLength(newLength);
array = newArray;
}
Value *array;
friend void AutoGCRooter::trace(JSTracer *trc);
private:
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoShapeRooter : private AutoGCRooter {
public:
AutoShapeRooter(JSContext *cx, const js::Shape *shape
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, SHAPE), shape(shape)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
friend void AutoGCRooter::trace(JSTracer *trc);
friend void MarkRuntime(JSTracer *trc);
private:
const js::Shape * const shape;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoScriptRooter : private AutoGCRooter {
public:
AutoScriptRooter(JSContext *cx, JSScript *script
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, SCRIPT), script(script)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
void setScript(JSScript *script) {
this->script = script;
}
friend void AutoGCRooter::trace(JSTracer *trc);
private:
JSScript *script;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoIdRooter : private AutoGCRooter
{
public:
explicit AutoIdRooter(JSContext *cx, jsid id = INT_TO_JSID(0)
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, ID), id_(id)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
jsid id() {
return id_;
}
jsid * addr() {
return &id_;
}
friend void AutoGCRooter::trace(JSTracer *trc);
friend void MarkRuntime(JSTracer *trc);
private:
jsid id_;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoIdArray : private AutoGCRooter {
public:
AutoIdArray(JSContext *cx, JSIdArray *ida JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, IDARRAY), idArray(ida)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
~AutoIdArray() {
if (idArray)
JS_DestroyIdArray(context, idArray);
}
bool operator!() {
return idArray == NULL;
}
jsid operator[](size_t i) const {
JS_ASSERT(idArray);
JS_ASSERT(i < size_t(idArray->length));
return idArray->vector[i];
}
size_t length() const {
return idArray->length;
}
friend void AutoGCRooter::trace(JSTracer *trc);
JSIdArray *steal() {
JSIdArray *copy = idArray;
idArray = NULL;
return copy;
}
protected:
inline void trace(JSTracer *trc);
private:
JSIdArray * idArray;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
/* No copy or assignment semantics. */
AutoIdArray(AutoIdArray &ida);
void operator=(AutoIdArray &ida);
};
/* The auto-root for enumeration object and its state. */
class AutoEnumStateRooter : private AutoGCRooter
{
public:
AutoEnumStateRooter(JSContext *cx, JSObject *obj
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, ENUMERATOR), obj(obj), stateValue()
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_ASSERT(obj);
}
~AutoEnumStateRooter() {
if (!stateValue.isNull()) {
#ifdef DEBUG
JSBool ok =
#endif
obj->enumerate(context, JSENUMERATE_DESTROY, &stateValue, 0);
JS_ASSERT(ok);
}
}
friend void AutoGCRooter::trace(JSTracer *trc);
const Value &state() const { return stateValue; }
Value *addr() { return &stateValue; }
protected:
void trace(JSTracer *trc);
JSObject * const obj;
private:
Value stateValue;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
#ifdef JS_HAS_XML_SUPPORT
class AutoXMLRooter : private AutoGCRooter {
public:
AutoXMLRooter(JSContext *cx, JSXML *xml
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, XML), xml(xml)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_ASSERT(xml);
}
friend void AutoGCRooter::trace(JSTracer *trc);
friend void MarkRuntime(JSTracer *trc);
private:
JSXML * const xml;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
#endif /* JS_HAS_XML_SUPPORT */
class AutoBindingsRooter : private AutoGCRooter {
public:
AutoBindingsRooter(JSContext *cx, Bindings &bindings
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, BINDINGS), bindings(bindings)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
friend void AutoGCRooter::trace(JSTracer *trc);
private:
Bindings &bindings;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoLockGC {
public:
explicit AutoLockGC(JSRuntime *rt
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: rt(rt)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_LOCK_GC(rt);
}
~AutoLockGC() { JS_UNLOCK_GC(rt); }
private:
JSRuntime *rt;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoUnlockGC {
private:
JSRuntime *rt;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
public:
explicit AutoUnlockGC(JSRuntime *rt
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: rt(rt)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_UNLOCK_GC(rt);
}
~AutoUnlockGC() { JS_LOCK_GC(rt); }
};
class AutoLockAtomsCompartment {
private:
JSContext *cx;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
public:
AutoLockAtomsCompartment(JSContext *cx
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: cx(cx)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_LOCK(cx, &cx->runtime->atomState.lock);
#ifdef JS_THREADSAFE
cx->runtime->atomsCompartmentIsLocked = true;
#endif
}
~AutoLockAtomsCompartment() {
#ifdef JS_THREADSAFE
cx->runtime->atomsCompartmentIsLocked = false;
#endif
JS_UNLOCK(cx, &cx->runtime->atomState.lock);
}
};
class AutoUnlockAtomsCompartment {
JSContext *cx;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
public:
AutoUnlockAtomsCompartment(JSContext *cx
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: cx(cx)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
#ifdef JS_THREADSAFE
cx->runtime->atomsCompartmentIsLocked = false;
#endif
JS_UNLOCK(cx, &cx->runtime->atomState.lock);
}
~AutoUnlockAtomsCompartment() {
JS_LOCK(cx, &cx->runtime->atomState.lock);
#ifdef JS_THREADSAFE
cx->runtime->atomsCompartmentIsLocked = true;
#endif
}
};
class AutoKeepAtoms {
JSRuntime *rt;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
public:
explicit AutoKeepAtoms(JSRuntime *rt
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: rt(rt)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
JS_KEEP_ATOMS(rt);
}
~AutoKeepAtoms() { JS_UNKEEP_ATOMS(rt); }
};
class AutoArenaAllocator {
JSArenaPool *pool;
void *mark;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
public:
explicit AutoArenaAllocator(JSArenaPool *pool
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: pool(pool), mark(JS_ARENA_MARK(pool))
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
~AutoArenaAllocator() { JS_ARENA_RELEASE(pool, mark); }
template <typename T>
T *alloc(size_t elems) {
void *ptr;
JS_ARENA_ALLOCATE(ptr, pool, elems * sizeof(T));
return static_cast<T *>(ptr);
}
};
class AutoReleasePtr {
JSContext *cx;
void *ptr;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
AutoReleasePtr operator=(const AutoReleasePtr &other);
public:
explicit AutoReleasePtr(JSContext *cx, void *ptr
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: cx(cx), ptr(ptr)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
~AutoReleasePtr() { cx->free(ptr); }
};
/*
* FIXME: bug 602774: cleaner API for AutoReleaseNullablePtr
*/
class AutoReleaseNullablePtr {
JSContext *cx;
void *ptr;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
AutoReleaseNullablePtr operator=(const AutoReleaseNullablePtr &other);
public:
explicit AutoReleaseNullablePtr(JSContext *cx, void *ptr
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: cx(cx), ptr(ptr)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
void reset(void *ptr2) {
if (ptr)
cx->free(ptr);
ptr = ptr2;
}
~AutoReleaseNullablePtr() { if (ptr) cx->free(ptr); }
};
class AutoLocalNameArray {
public:
explicit AutoLocalNameArray(JSContext *cx, JSFunction *fun
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: context(cx),
mark(JS_ARENA_MARK(&cx->tempPool)),
names(fun->script()->bindings.getLocalNameArray(cx, &cx->tempPool)),
count(fun->script()->bindings.countLocalNames())
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
~AutoLocalNameArray() {
JS_ARENA_RELEASE(&context->tempPool, mark);
}
operator bool() const { return !!names; }
uint32 length() const { return count; }
const jsuword &operator [](unsigned i) const { return names[i]; }
private:
JSContext *context;
void *mark;
jsuword *names;
uint32 count;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
template <class RefCountable>
class AlreadyIncRefed
{
typedef RefCountable *****ConvertibleToBool;
RefCountable *obj;
public:
explicit AlreadyIncRefed(RefCountable *obj) : obj(obj) {}
bool null() const { return obj == NULL; }
operator ConvertibleToBool() const { return (ConvertibleToBool)obj; }
RefCountable *operator->() const { JS_ASSERT(!null()); return obj; }
RefCountable &operator*() const { JS_ASSERT(!null()); return *obj; }
RefCountable *get() const { return obj; }
};
template <class RefCountable>
class NeedsIncRef
{
typedef RefCountable *****ConvertibleToBool;
RefCountable *obj;
public:
explicit NeedsIncRef(RefCountable *obj) : obj(obj) {}
bool null() const { return obj == NULL; }
operator ConvertibleToBool() const { return (ConvertibleToBool)obj; }
RefCountable *operator->() const { JS_ASSERT(!null()); return obj; }
RefCountable &operator*() const { JS_ASSERT(!null()); return *obj; }
RefCountable *get() const { return obj; }
};
template <class RefCountable>
class AutoRefCount
{
typedef RefCountable *****ConvertibleToBool;
JSContext *const cx;
RefCountable *obj;
AutoRefCount(const AutoRefCount &);
void operator=(const AutoRefCount &);
public:
explicit AutoRefCount(JSContext *cx)
: cx(cx), obj(NULL)
{}
AutoRefCount(JSContext *cx, NeedsIncRef<RefCountable> aobj)
: cx(cx), obj(aobj.get())
{
if (obj)
obj->incref(cx);
}
AutoRefCount(JSContext *cx, AlreadyIncRefed<RefCountable> aobj)
: cx(cx), obj(aobj.get())
{}
~AutoRefCount() {
if (obj)
obj->decref(cx);
}
void reset(NeedsIncRef<RefCountable> aobj) {
if (obj)
obj->decref(cx);
obj = aobj.get();
if (obj)
obj->incref(cx);
}
void reset(AlreadyIncRefed<RefCountable> aobj) {
if (obj)
obj->decref(cx);
obj = aobj.get();
}
bool null() const { return obj == NULL; }
operator ConvertibleToBool() const { return (ConvertibleToBool)obj; }
RefCountable *operator->() const { JS_ASSERT(!null()); return obj; }
RefCountable &operator*() const { JS_ASSERT(!null()); return *obj; }
RefCountable *get() const { return obj; }
};
} /* namespace js */
class JSAutoResolveFlags
{
public:
JSAutoResolveFlags(JSContext *cx, uintN flags
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: mContext(cx), mSaved(cx->resolveFlags)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
cx->resolveFlags = flags;
}
~JSAutoResolveFlags() { mContext->resolveFlags = mSaved; }
private:
JSContext *mContext;
uintN mSaved;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
extern JSThreadData *
js_CurrentThreadData(JSRuntime *rt);
extern JSBool
js_InitThreads(JSRuntime *rt);
extern void
js_FinishThreads(JSRuntime *rt);
extern void
js_PurgeThreads(JSContext *cx);
namespace js {
#ifdef JS_THREADSAFE
/* Iterator over JSThreadData from all JSThread instances. */
class ThreadDataIter : public JSThread::Map::Range
{
public:
ThreadDataIter(JSRuntime *rt) : JSThread::Map::Range(rt->threads.all()) {}
JSThreadData *threadData() const {
return &front().value->data;
}
};
#else /* !JS_THREADSAFE */
class ThreadDataIter
{
JSRuntime *runtime;
bool done;
public:
ThreadDataIter(JSRuntime *rt) : runtime(rt), done(false) {}
bool empty() const {
return done;
}
void popFront() {
JS_ASSERT(!done);
done = true;
}
JSThreadData *threadData() const {
JS_ASSERT(!done);
return &runtime->threadData;
}
};
#endif /* !JS_THREADSAFE */
} /* namespace js */
/*
* Create and destroy functions for JSContext, which is manually allocated
* and exclusively owned.
*/
extern JSContext *
js_NewContext(JSRuntime *rt, size_t stackChunkSize);
extern void
js_DestroyContext(JSContext *cx, JSDestroyContextMode mode);
static JS_INLINE JSContext *
js_ContextFromLinkField(JSCList *link)
{
JS_ASSERT(link);
return (JSContext *) ((uint8 *) link - offsetof(JSContext, link));
}
/*
* If unlocked, acquire and release rt->gcLock around *iterp update; otherwise
* the caller must be holding rt->gcLock.
*/
extern JSContext *
js_ContextIterator(JSRuntime *rt, JSBool unlocked, JSContext **iterp);
/*
* Iterate through contexts with active requests. The caller must be holding
* rt->gcLock in case of a thread-safe build, or otherwise guarantee that the
* context list is not alternated asynchroniously.
*/
extern JS_FRIEND_API(JSContext *)
js_NextActiveContext(JSRuntime *, JSContext *);
/*
* Class.resolve and watchpoint recursion damping machinery.
*/
extern JSBool
js_StartResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
JSResolvingEntry **entryp);
extern void
js_StopResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
JSResolvingEntry *entry, uint32 generation);
/*
* Report an exception, which is currently realized as a printf-style format
* string and its arguments.
*/
typedef enum JSErrNum {
#define MSG_DEF(name, number, count, exception, format) \
name = number,
#include "js.msg"
#undef MSG_DEF
JSErr_Limit
} JSErrNum;
extern JS_FRIEND_API(const JSErrorFormatString *)
js_GetErrorMessage(void *userRef, const char *locale, const uintN errorNumber);
#ifdef va_start
extern JSBool
js_ReportErrorVA(JSContext *cx, uintN flags, const char *format, va_list ap);
extern JSBool
js_ReportErrorNumberVA(JSContext *cx, uintN flags, JSErrorCallback callback,
void *userRef, const uintN errorNumber,
JSBool charArgs, va_list ap);
extern JSBool
js_ExpandErrorArguments(JSContext *cx, JSErrorCallback callback,
void *userRef, const uintN errorNumber,
char **message, JSErrorReport *reportp,
bool charArgs, va_list ap);
#endif
extern void
js_ReportOutOfMemory(JSContext *cx);
/*
* Report that cx->scriptStackQuota is exhausted.
*/
void
js_ReportOutOfScriptQuota(JSContext *cx);
extern JS_FRIEND_API(void)
js_ReportOverRecursed(JSContext *cx);
extern JS_FRIEND_API(void)
js_ReportAllocationOverflow(JSContext *cx);
#define JS_CHECK_RECURSION(cx, onerror) \
JS_BEGIN_MACRO \
int stackDummy_; \
\
if (!JS_CHECK_STACK_SIZE(cx->stackLimit, &stackDummy_)) { \
js_ReportOverRecursed(cx); \
onerror; \
} \
JS_END_MACRO
/*
* Report an exception using a previously composed JSErrorReport.
* XXXbe remove from "friend" API
*/
extern JS_FRIEND_API(void)
js_ReportErrorAgain(JSContext *cx, const char *message, JSErrorReport *report);
extern void
js_ReportIsNotDefined(JSContext *cx, const char *name);
/*
* Report an attempt to access the property of a null or undefined value (v).
*/
extern JSBool
js_ReportIsNullOrUndefined(JSContext *cx, intN spindex, const js::Value &v,
JSString *fallback);
extern void
js_ReportMissingArg(JSContext *cx, const js::Value &v, uintN arg);
/*
* Report error using js_DecompileValueGenerator(cx, spindex, v, fallback) as
* the first argument for the error message. If the error message has less
* then 3 arguments, use null for arg1 or arg2.
*/
extern JSBool
js_ReportValueErrorFlags(JSContext *cx, uintN flags, const uintN errorNumber,
intN spindex, const js::Value &v, JSString *fallback,
const char *arg1, const char *arg2);
#define js_ReportValueError(cx,errorNumber,spindex,v,fallback) \
((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
spindex, v, fallback, NULL, NULL))
#define js_ReportValueError2(cx,errorNumber,spindex,v,fallback,arg1) \
((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
spindex, v, fallback, arg1, NULL))
#define js_ReportValueError3(cx,errorNumber,spindex,v,fallback,arg1,arg2) \
((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
spindex, v, fallback, arg1, arg2))
extern JSErrorFormatString js_ErrorFormatString[JSErr_Limit];
#ifdef JS_THREADSAFE
# define JS_ASSERT_REQUEST_DEPTH(cx) (JS_ASSERT((cx)->thread), \
JS_ASSERT((cx)->thread->data.requestDepth >= 1))
#else
# define JS_ASSERT_REQUEST_DEPTH(cx) ((void) 0)
#endif
/*
* If the operation callback flag was set, call the operation callback.
* This macro can run the full GC. Return true if it is OK to continue and
* false otherwise.
*/
#define JS_CHECK_OPERATION_LIMIT(cx) \
(JS_ASSERT_REQUEST_DEPTH(cx), \
(!JS_THREAD_DATA(cx)->interruptFlags || js_InvokeOperationCallback(cx)))
JS_ALWAYS_INLINE void
JSThreadData::triggerOperationCallback(JSRuntime *rt)
{
/*
* Use JS_ATOMIC_SET and JS_ATOMIC_INCREMENT in the hope that it ensures
* the write will become immediately visible to other processors polling
* the flag. Note that we only care about visibility here, not read/write
* ordering: this field can only be written with the GC lock held.
*/
if (interruptFlags)
return;
JS_ATOMIC_SET(&interruptFlags, 1);
#ifdef JS_THREADSAFE
/* rt->interruptCounter does not reflect suspended threads. */
if (requestDepth != 0)
JS_ATOMIC_INCREMENT(&rt->interruptCounter);
#endif
}
/*
* Invoke the operation callback and return false if the current execution
* is to be terminated.
*/
extern JSBool
js_InvokeOperationCallback(JSContext *cx);
extern JSBool
js_HandleExecutionInterrupt(JSContext *cx);
namespace js {
/* These must be called with GC lock taken. */
JS_FRIEND_API(void)
TriggerOperationCallback(JSContext *cx);
void
TriggerAllOperationCallbacks(JSRuntime *rt);
} /* namespace js */
extern JSStackFrame *
js_GetScriptedCaller(JSContext *cx, JSStackFrame *fp);
extern jsbytecode*
js_GetCurrentBytecodePC(JSContext* cx);
extern bool
js_CurrentPCIsInImacro(JSContext *cx);
namespace js {
class RegExpStatics;
extern JS_FORCES_STACK JS_FRIEND_API(void)
LeaveTrace(JSContext *cx);
} /* namespace js */
/*
* Get the current frame, first lazily instantiating stack frames if needed.
* (Do not access cx->fp() directly except in JS_REQUIRES_STACK code.)
*
* Defined in jstracer.cpp if JS_TRACER is defined.
*/
static JS_FORCES_STACK JS_INLINE JSStackFrame *
js_GetTopStackFrame(JSContext *cx)
{
js::LeaveTrace(cx);
return cx->maybefp();
}
static JS_INLINE JSBool
js_IsPropertyCacheDisabled(JSContext *cx)
{
return cx->runtime->shapeGen >= js::SHAPE_OVERFLOW_BIT;
}
static JS_INLINE uint32
js_RegenerateShapeForGC(JSRuntime *rt)
{
JS_ASSERT(rt->gcRunning);
JS_ASSERT(rt->gcRegenShapes);
/*
* Under the GC, compared with js_GenerateShape, we don't need to use
* atomic increments but we still must make sure that after an overflow
* the shape stays such.
*/
uint32 shape = rt->shapeGen;
shape = (shape + 1) | (shape & js::SHAPE_OVERFLOW_BIT);
rt->shapeGen = shape;
return shape;
}
namespace js {
inline void *
ContextAllocPolicy::malloc(size_t bytes)
{
return cx->malloc(bytes);
}
inline void
ContextAllocPolicy::free(void *p)
{
cx->free(p);
}
inline void *
ContextAllocPolicy::realloc(void *p, size_t bytes)
{
return cx->realloc(p, bytes);
}
inline void
ContextAllocPolicy::reportAllocOverflow() const
{
js_ReportAllocationOverflow(cx);
}
template<class T>
class AutoVectorRooter : protected AutoGCRooter
{
public:
explicit AutoVectorRooter(JSContext *cx, ptrdiff_t tag
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, tag), vector(cx)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
size_t length() const { return vector.length(); }
bool append(const T &v) { return vector.append(v); }
void popBack() { vector.popBack(); }
bool growBy(size_t inc) {
size_t oldLength = vector.length();
if (!vector.growByUninitialized(inc))
return false;
MakeRangeGCSafe(vector.begin() + oldLength, vector.end());
return true;
}
bool resize(size_t newLength) {
size_t oldLength = vector.length();
if (newLength <= oldLength) {
vector.shrinkBy(oldLength - newLength);
return true;
}
if (!vector.growByUninitialized(newLength - oldLength))
return false;
MakeRangeGCSafe(vector.begin() + oldLength, vector.end());
return true;
}
bool reserve(size_t newLength) {
return vector.reserve(newLength);
}
T &operator[](size_t i) { return vector[i]; }
const T &operator[](size_t i) const { return vector[i]; }
const T *begin() const { return vector.begin(); }
T *begin() { return vector.begin(); }
const T *end() const { return vector.end(); }
T *end() { return vector.end(); }
const T &back() const { return vector.back(); }
friend void AutoGCRooter::trace(JSTracer *trc);
private:
Vector<T, 8> vector;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoValueVector : public AutoVectorRooter<Value>
{
public:
explicit AutoValueVector(JSContext *cx
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoVectorRooter<Value>(cx, VALVECTOR)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
const jsval *jsval_begin() const { return Jsvalify(begin()); }
jsval *jsval_begin() { return Jsvalify(begin()); }
const jsval *jsval_end() const { return Jsvalify(end()); }
jsval *jsval_end() { return Jsvalify(end()); }
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoIdVector : public AutoVectorRooter<jsid>
{
public:
explicit AutoIdVector(JSContext *cx
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoVectorRooter<jsid>(cx, IDVECTOR)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class AutoShapeVector : public AutoVectorRooter<const Shape *>
{
public:
explicit AutoShapeVector(JSContext *cx
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoVectorRooter<const Shape *>(cx, SHAPEVECTOR)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
};
JSIdArray *
NewIdArray(JSContext *cx, jsint length);
} /* namespace js */
#ifdef _MSC_VER
#pragma warning(pop)
#pragma warning(pop)
#endif
#ifdef JS_CNTXT_UNDEFD_MOZALLOC_WRAPPERS
# include "mozilla/mozalloc_macro_wrappers.h"
#endif
#endif /* jscntxt_h___ */
|
zaklaus/eco2d
|
flecs-dash/etc/apps/systems/system_entity_graph.js
|
<gh_stars>10-100
const system_entity_chart = {
type: 'line',
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 12, 26, 27, 28, 29, 30,
31, 32, 33, 34, 13, 36, 37, 38, 39, 40,
41, 42, 43, 44, 14, 46, 47, 48, 49, 50,
51, 52, 53, 54, 15, 56, 57, 58, 59, 60],
datasets: [
{
label: 'Matched entities',
data: [],
backgroundColor: [ '#26352c' ],
borderColor: [ '#5BE595', ],
borderWidth: 2,
pointRadius: 0,
fill: true,
yAxisID: "entities"
}
]
},
options: {
title: {
display: false
},
responsive: true,
maintainAspectRatio: false,
lineTension: 1,
animation: {
duration: 0
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 0,
legend: {
display: false
},
elements: {
line: {
tension: 0 // disables bezier curves
}
},
scales: {
yAxes: [{
id: 'entities',
position: 'right',
gridLines: {
display:false
},
ticks: {
display: false,
beginAtZero: true,
maxTicksLimit: 2
}
}],
xAxes: [{
gridLines: {
display:false
},
ticks: {
display: false
}
}]
}
}
}
Vue.component('system-entity-graph', {
props: ['tick', 'system'],
updated() {
this.updateChart();
},
data: function() {
return {
chart: undefined
}
},
methods: {
setValues() {
if (!this.system.history_1m) {
return;
}
if (!this.chart) {
this.createChart();
}
system_entity_chart.data.datasets[0].data = this.system.history_1m.matched_entity_count.avg;
},
createChart() {
const ctx = document.getElementById('system-entity-' + this.system.name + '-graph');
this.chart = new Chart(ctx, {
type: system_entity_chart.type,
data: system_entity_chart.data,
options: system_entity_chart.options
});
},
updateChart() {
if (!this.system.history_1m) {
return;
}
this.setValues();
this.chart.update();
},
entity_count() {
if (!this.system || !this.system.current) {
return;
}
return this.system.current.matched_entity_count;
}
},
template: `
<div class="system-entity-graph">
<div class="system-graph-label system-graph-label-filled">
{{entity_count()}}
</div>
<canvas :id="'system-entity-' + system.name + '-graph'" :data-fps="tick"></canvas>
</div>`
});
|
yuriserka/cp02hero
|
leetcode/easy/104.cc
|
<filename>leetcode/easy/104.cc
// https://leetcode.com/problems/maximum-depth-of-binary-tree/
#include <bits/stdc++.h>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int ls = maxDepth(root->left);
int rs = maxDepth(root->right);
return 1 + max(ls, rs);
}
int max(int a, int b) { return a > b ? a : b; }
};
|
facug91/OJ-Solutions
|
uva.onlinejudge.org/BridgeHands.cpp
|
<reponame>facug91/OJ-Solutions
/*
By: facug91
From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=9
Name: Bridge Hands
Number: 555
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <iterator>
#include <utility>
#include <list>
#include <stack>
#include <iomanip>
#include <bitset>
#define MAX_INT 2147483647
#define MAX_LONG 9223372036854775807ll
#define MAX_ULONG 18446744073709551615ull
#define MAX_DBL 1.7976931348623158e+308
#define EPS 1e-9
//const long double PI = 2*acos(0);
#define INF 1000000000
//
using namespace std;
int value0['Z'], value1['Z'];
struct cmp {
bool operator() (const char * a, const char * b) {
if (a[0] == b[0]) {
return (value1[a[1]] < value1[b[1]]);
} else {
return (value0[a[0]] < value0[b[0]]);
}
}
} mycmp;
char start, deal[30], to_letter[5];
vector<char*> player[4];
int idx, to_pos['Z'], len;
int main() {
to_pos['S'] = 0;
to_pos['W'] = 1;
to_pos['N'] = 2;
to_pos['E'] = 3;
value0['C'] = 0;
value0['D'] = 1;
value0['S'] = 2;
value0['H'] = 3;
value1['2'] = 0;
value1['3'] = 1;
value1['4'] = 2;
value1['5'] = 3;
value1['6'] = 4;
value1['7'] = 5;
value1['8'] = 6;
value1['9'] = 7;
value1['T'] = 8;
value1['J'] = 9;
value1['Q'] = 10;
value1['K'] = 11;
value1['A'] = 12;
while (scanf("%c", &start), start != '#') {
getchar();
idx = (to_pos[start] + 1) % 4;
for (int i=0; i<2; i++) {
gets(deal);
len = strlen(deal);
for (int j=0; j<len; j+=2) {
char * to = new char[3];
strncpy (to, deal+j, 2);
to[2] = '\0';
//cout<<to<<endl;
player[idx].push_back(to);
idx = (idx + 1) % 4;
}
}
for (int j=0; j<4; j++) {
sort(player[j].begin(), player[j].end(), mycmp);
//ni idea por qué esto ¿?
to_letter[0] = 'S';
to_letter[1] = 'W';
to_letter[2] = 'N';
to_letter[3] = 'E';
//pero sino, no funciona
printf("%c:", to_letter[j]);
for (int k=0; k<13; k++)
printf(" %s", player[j][k]);
printf("\n");
}
for (int i=0; i<4; i++)
player[i].clear();
}
return 0;
}
|
senixus/coffee-shop
|
src/components/search/Search.js
|
<filename>src/components/search/Search.js
import React from "react";
import "./search.scss";
const Search = ({ handleChange }) => {
return (
<div className="search">
<div>
<input
type="text"
placeholder="Search"
name="coffee"
onChange={handleChange}
className="search-bar"
/>
</div>
</div>
);
};
export default Search;
|
rkowalewski/minijava_compiler
|
lib/jflex-1.4.1/examples/interpreter/Tprogram.java
|
<gh_stars>10-100
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright (C) 2001 <NAME> <<EMAIL>> *
* Copyright (C) 2001 <NAME> <<EMAIL>> *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License. See the file *
* COPYRIGHT for more information. *
* *
* 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. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* AST node for the whole program (top node).
*
* Also contains two symbol tables, one for input variables,
* one for function names.
*
* All operations like context check, symbol table build up
* etc. start here.
*/
class Tprogram implements AST {
Tparlist parlist; // input variables
Tdekllist dekllist; // function declarations
Texplist explist; // result expressions
Texplist arguments; // input values
public Tprogram(Tparlist p, Tdekllist d, Texplist e, Texplist a) {
parlist=p;
dekllist=d;
explist=e;
arguments=a;
}
public String toString() {
return("Program:\n=============\ninput "+parlist+
"\nfunctions\n"+dekllist+"\noutput "+explist+
"\narguments "+arguments+"\nend");
}
SymTab inputs; // table of input variables
SymTab functions; // table of functions
public void setSymtabs() { // calculate symbol table entries
inputs = new SymTab(); // set input variables
parlist.setSymtab(inputs, true, 0);
functions = new SymTab(inputs);
dekllist.setSymtab(functions);
}
public void printSymtabs() {
System.out.print("Input variables-\n"+inputs);
System.out.print("Functions-\n"+functions);
dekllist.printSymtabs();
}
public void checkcontext() {
dekllist.checkcontext(); // CoCo (DefFun,DefVar,Arity)
// in function bodies
explist.checkcontext(functions); // CoCo (DefFun,DefVar,Arity)
// in result expressions
arguments.checkcontext(new SymTab()); // CoCo (constants)
// in arguments
if (arguments.length()!=inputs.size())
Main.error("Argument list and input variables list differ!");
}
public void prepInterp() { // set pointers and indices
dekllist.prepInterp(functions);
explist.prepInterp(functions);
}
public void interpret() {
int[] inputEnv = new int[inputs.size()]; // set input
arguments.interpret(null,null,inputEnv,0);
System.out.println("Result:\n=============");
int[] ergebnis = new int[explist.length()];
explist.interpret(inputEnv,null,ergebnis,0); // calculate result
int i;
for (i=explist.length()-1; i > 0; i--)
System.out.print(ergebnis[i]+", ");
System.out.println(ergebnis[i]);
}
}
|
play-code-tools/crawling-gocd
|
setup.py
|
<reponame>play-code-tools/crawling-gocd
import pathlib
from setuptools import setup, find_packages
HERE = pathlib.Path(__file__).parent
print("here=>", HERE)
README = (HERE / "readme.pypi.md").read_text()
setup(
name="crawling-gocd",
version="1.3.0",
description="crawling the gocd build histories of pipelines and calculate the metrics",
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/play-code-tools/crawling-gocd",
author="play-code-tools",
author_email="<EMAIL>",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
],
packages=find_packages(exclude=("tests",)),
install_requires=["requests-html", "pyyaml", "pyfunctional"],
entry_points={
"console_scripts": [
"realpython=crawling_gocd.__main__:main",
]
},
)
|
paulocsilvajr/controle_pessoal_de_financas
|
API/v1/dao/lancamento_dao.go
|
<reponame>paulocsilvajr/controle_pessoal_de_financas<filename>API/v1/dao/lancamento_dao.go<gh_stars>1-10
package dao
import (
"database/sql"
"fmt"
"strconv"
"github.com/paulocsilvajr/controle_pessoal_de_financas/API/v1/model/detalhe_lancamento"
"github.com/paulocsilvajr/controle_pessoal_de_financas/API/v1/model/lancamento"
"gorm.io/gorm"
)
var (
lancamentoDB = map[string]string{
"tabela": lancamento.GetNomeTabelaLancamento(),
"tabelaComplementar01": detalhe_lancamento.GetNomeTabelaDetalheLancamento(),
"id": "id",
"cpfPessoa": "cpf_pessoa",
"data": "data",
"numero": "numero",
"descricao": "descricao",
"dataCriacao": "data_criacao",
"dataModificacao": "data_modificacao",
"estado": "estado",
"idTabelaComplementar01": "id_lancamento",
"nomeConta": "nome_conta",
"tabelaPessoa": pessoaDB["tabela"],
"fkPessoa": pessoaDB["cpf"],
}
)
// AdicionaLancamento02 adiciona um lancamento ao BD e retorna o lancamento incluída(*Lancamento) com os dados de acordo como ficou no BD. erro != nil caso ocorra um problema no processo de inclusão. Deve ser informado uma conexão ao BD(*sql.DB) como parâmetro obrigatório e um lancamento(*Lancamento)
func AdicionaLancamento02(db *gorm.DB, novoLancamento *lancamento.Lancamento) (*lancamento.Lancamento, error) {
l, err := lancamento.NewLancamento(novoLancamento.ID, novoLancamento.CpfPessoa, novoLancamento.Data, novoLancamento.Numero, novoLancamento.Descricao)
if err != nil {
return nil, err
}
tLancamento := ConverteLancamentoParaTLancamento(l)
err = db.Create(&tLancamento).Error
if err != nil {
return nil, err
}
lancamento := ConverteTLancamentoParaLancamento(tLancamento)
return lancamento, nil
}
// ProcuraLancamento02 localiza um lancamento no BD e retorna o lancamento procurado(*Lancamento). erro != nil caso ocorra um problema no processo de procura. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório e o ID do lancamento desejado
func ProcuraLancamento02(db *gorm.DB, id int) (*lancamento.Lancamento, error) {
tl := new(lancamento.TLancamento)
tx := db.First(&tl, id)
if err := tx.Error; err != nil {
return nil, err
}
return ConverteTLancamentoParaLancamento(tl), nil
}
// RemoveLancamento02 remove um lancamento do BD e retorna erro != nil caso ocorra um problema no processo de remoção. Deve ser informado uma conexão ao BD(*gorm) como parâmetro obrigatório e um int contendo o ID do lancamento desejado
func RemoveLancamento02(db *gorm.DB, id int) error {
l := &lancamento.TLancamento{ID: id}
tx := db.Delete(l)
if err := tx.Error; err != nil {
return err
}
linhaAfetadas := tx.RowsAffected
var esperado int64 = 1
if linhaAfetadas != esperado {
return fmt.Errorf("remoção de lançamento com ID %d retornou uma quantidade de registros afetados incorreto. Esperado: %d, obtido: %d", id, esperado, linhaAfetadas)
}
return nil
}
// CarregaLancamentos02 retorna uma listagem de todos os lancamentos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório
func CarregaLancamentos02(db *gorm.DB) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
resultado := db.Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// AlteraLancamento02 altera um lancamento com o id(int) informado a partir dos dados do *Lancamento informada no parâmetro lancamentoAlteracao. O campo Estado não é alterado. Use a função específica para essa tarefa(estado). Retorna um *Lancamento alterado no BD e um error. error != nil caso ocorra um problema.
func AlteraLancamento02(db *gorm.DB, transacao *gorm.DB, id int, lancamentoAlteracao *lancamento.Lancamento) (*lancamento.Lancamento, error) {
lancamentoBanco, err := ProcuraLancamento02(db, id)
if err != nil {
return nil, err
}
err = lancamentoBanco.Altera(lancamentoAlteracao.CpfPessoa, lancamentoAlteracao.Data, lancamentoAlteracao.Numero, lancamentoAlteracao.Descricao)
if err != nil {
return nil, err
}
tl := ConverteLancamentoParaTLancamento(lancamentoBanco)
tx := db.Save(&tl)
linhaAfetadas := tx.RowsAffected
var esperado int64 = 1
if linhaAfetadas != esperado {
return nil, fmt.Errorf("alteração de lancamento com ID %d retornou uma quantidade de registros afetados incorreto. Esperado: %d, retorno: %d", id, esperado, linhaAfetadas)
}
if err := tx.Error; err != nil {
return nil, err
}
return ConverteTLancamentoParaLancamento(tl), nil
}
// AtivaLancamento02 ativa um lancamento no BD e retorna o lancamento(*Lancamento) com os dados atualizados. erro != nil caso ocorra um problema no processo de procura. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório e um ID(int) do Lancamento desejado
func AtivaLancamento02(db *gorm.DB, id int) (*lancamento.Lancamento, error) {
lancamentoBanco, err := ProcuraLancamento02(db, id)
if err != nil {
return nil, err
}
lancamentoBanco.Ativa()
tl := ConverteLancamentoParaTLancamento(lancamentoBanco)
tx := db.Save(&tl)
linhasAfetadas := tx.RowsAffected
var esperado int64 = 1
if linhasAfetadas != esperado {
return nil, fmt.Errorf("ativação de lancamento com ID %d retornou uma quantidade de registros afetados incorreto. Esperado: %d, obtido: %d", id, esperado, linhasAfetadas)
}
if err := tx.Error; err != nil {
return nil, err
}
return ConverteTLancamentoParaLancamento(tl), nil
}
// InativaLancamento02 inativa um lancamento no BD e retorna o lancamento(*Lancamento) com os dados atualizados. erro != nil caso ocorra um problema no processo de procura. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório e um ID(int) do Lancamento desejado
func InativaLancamento02(db *gorm.DB, id int) (*lancamento.Lancamento, error) {
lancamentoBanco, err := ProcuraLancamento02(db, id)
if err != nil {
return nil, err
}
lancamentoBanco.Inativa()
tl := ConverteLancamentoParaTLancamento(lancamentoBanco)
tx := db.Save(&tl)
linhasAfetadas := tx.RowsAffected
var esperado int64 = 1
if linhasAfetadas != esperado {
return nil, fmt.Errorf("inativação de lancamento com ID %d retornou uma quantidade de registros afetados incorreto. Esperado: %d, obtido: %d", id, esperado, linhasAfetadas)
}
if err := tx.Error; err != nil {
return nil, err
}
return ConverteTLancamentoParaLancamento(tl), nil
}
// CarregaLancamentosAtivo02 retorna uma listagem de lancamentos ativos(lancamento.Lancamento) e erro = nil do BD caso a consulta ocorra corretamente. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório
func CarregaLancamentosAtivo02(db *gorm.DB) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
var estado bool = true
sql := getTemplateSQL("CarregaLancamentosAtivo02",
"{{.estado}} = ?",
lancamentoDB,
)
resultado := db.Where(sql, estado).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosInativo02 retorna uma listagem de lancamentos inativos(lancamento.Lancamento) e erro = nil do BD caso a consulta ocorra corretamente. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório
func CarregaLancamentosInativo02(db *gorm.DB) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
var estado bool = false
sql := getTemplateSQL("CarregaLancamentosInativo02",
"{{.estado}} = ?",
lancamentoDB,
)
resultado := db.Where(sql, estado).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosPorCPF02 retorna uma listagem de todos os lancamentos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório e uma string contendo o cpf(11 caracteres)
func CarregaLancamentosPorCPF02(db *gorm.DB, cpf string) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
sql := getTemplateSQL("CarregaLancamentosPorCpf02",
"{{.cpfPessoa}} = ?",
lancamentoDB,
)
resultado := db.Where(sql, cpf).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosAtivoPorCPF02 retorna uma listagem de todos os lancamentos ativos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório e uma string contendo o CPF(11 caracteres)
func CarregaLancamentosAtivoPorCPF02(db *gorm.DB, cpf string) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
var estado bool = true
sql := getTemplateSQL("CarregaLancamentosAtivoPorCPF02",
"{{.cpfPessoa}} = ? AND {{.estado}} = ?",
lancamentoDB,
)
resultado := db.Where(sql, cpf, estado).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosInativoPorCPF02 retorna uma listagem de todos os lancamentos ativos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório e uma string contendo o CPF(11 caracteres)
func CarregaLancamentosInativoPorCPF02(db *gorm.DB, cpf string) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
var estado bool = false
sql := getTemplateSQL("CarregaLancamentosAtivoPorCPF02",
"{{.cpfPessoa}} = ? AND {{.estado}} = ?",
lancamentoDB,
)
resultado := db.Where(sql, cpf, estado).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosPorCPFeConta02 retorna uma listagem de todos os lancamentos(lancamento.Lancamentos) de acordo com conta informada e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório, uma string contendo o cpf(11 caracteres) e um nome de conta(string)
func CarregaLancamentosPorCPFeConta02(db *gorm.DB, cpf, conta string) (lancamento.Lancamentos, error) {
var tlanc lancamento.TLancamentos
campos := []string{
lancamentoDB["id"],
lancamentoDB["cpfPessoa"],
lancamentoDB["data"],
lancamentoDB["numero"],
lancamentoDB["descricao"],
lancamentoDB["dataCriacao"],
lancamentoDB["dataModificacao"],
lancamentoDB["estado"],
}
innerJoin := getTemplateSQL("CarregaLancamentosPorCPFeContasJoin",
"INNER JOIN {{.tabelaComplementar01}} ON {{.id}} = {{.tabelaComplementar01}}.{{.idTabelaComplementar01}}",
lancamentoDB,
)
where := getTemplateSQL("CarregaLancamentosPorCPFeContasWhere",
"{{.cpfPessoa}} = ? AND {{.nomeConta}} = ?",
lancamentoDB,
)
resultado := db.Joins(innerJoin).Select(campos).Where(where, cpf, conta).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosAtivosPorCPFeConta02 retorna uma listagem de todos os lancamentos ativos(lancamento.Lancamentos) de acordo com conta informada e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório, uma string contendo o cpf(11 caracteres) e um nome de conta(string)
func CarregaLancamentosAtivosPorCPFeConta02(db *gorm.DB, cpf, conta string) (lancamentos lancamento.Lancamentos, err error) {
var tlanc lancamento.TLancamentos
campos := []string{
lancamentoDB["id"],
lancamentoDB["cpfPessoa"],
lancamentoDB["data"],
lancamentoDB["numero"],
lancamentoDB["descricao"],
lancamentoDB["dataCriacao"],
lancamentoDB["dataModificacao"],
lancamentoDB["estado"],
}
innerJoin := getTemplateSQL("CarregaLancamentosPorCPFeContasJoin",
"INNER JOIN {{.tabelaComplementar01}} ON {{.id}} = {{.tabelaComplementar01}}.{{.idTabelaComplementar01}}",
lancamentoDB,
)
where := getTemplateSQL("CarregaLancamentosPorCPFeContasWhere",
"{{.cpfPessoa}} = ? AND {{.nomeConta}} = ? AND {{.estado}} = ?",
lancamentoDB,
)
estado := true
resultado := db.Joins(innerJoin).Select(campos).Where(where, cpf, conta, estado).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentosInativosPorCPFeConta02 retorna uma listagem de todos os lancamentos inativos(lancamento.Lancamentos) de acordo com conta informada e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD(*gorm.DB) como parâmetro obrigatório, uma string contendo o cpf(11 caracteres) e um nome de conta(string)
func CarregaLancamentosInativosPorCPFeConta02(db *gorm.DB, cpf, conta string) (lancamentos lancamento.Lancamentos, err error) {
var tlanc lancamento.TLancamentos
campos := []string{
lancamentoDB["id"],
lancamentoDB["cpfPessoa"],
lancamentoDB["data"],
lancamentoDB["numero"],
lancamentoDB["descricao"],
lancamentoDB["dataCriacao"],
lancamentoDB["dataModificacao"],
lancamentoDB["estado"],
}
innerJoin := getTemplateSQL("CarregaLancamentosPorCPFeContasJoin",
"INNER JOIN {{.tabelaComplementar01}} ON {{.id}} = {{.tabelaComplementar01}}.{{.idTabelaComplementar01}}",
lancamentoDB,
)
where := getTemplateSQL("CarregaLancamentosPorCPFeContasWhere",
"{{.cpfPessoa}} = ? AND {{.nomeConta}} = ? AND {{.estado}} = ?",
lancamentoDB,
)
estado := false
resultado := db.Joins(innerJoin).Select(campos).Where(where, cpf, conta, estado).Find(&tlanc)
return ConverteTLancamentosParaLancamentos(resultado, &tlanc)
}
// CarregaLancamentos retorna uma listagem de todos os lancamentos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório
func CarregaLancamentos(db *sql.DB) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
`
query := getTemplateQuery("CarregaLancamentos", lancamentoDB, sql)
return carregaLancamentos(db, query)
}
// CarregaLancamentosAtivo retorna uma listagem de lancamentos ativos(lancamento.Lancamento) e erro = nil do BD caso a consulta ocorra corretamente. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório
func CarregaLancamentosAtivo(db *sql.DB) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
WHERE
{{.estado}} = true
`
query := getTemplateQuery("CarregaLancamentosAtivo", lancamentoDB, sql)
return carregaLancamentos(db, query)
}
// CarregaLancamentosInativo retorna uma listagem de lancamentos inativos(lancamento.Lancamento) e erro = nil do BD caso a consulta ocorra corretamente. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório
func CarregaLancamentosInativo(db *sql.DB) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
WHERE
{{.estado}} = false
`
query := getTemplateQuery("CarregaLancamentosAtivo", lancamentoDB, sql)
return carregaLancamentos(db, query)
}
// CarregaLancamentosPorCpf retorna uma listagem de todos os lancamentos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório e uma string contendo o cpf(11 caracteres)
func CarregaLancamentosPorCpf(db *sql.DB, cpf string) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
WHERE
{{.cpfPessoa}} = $1
`
query := getTemplateQuery("CarregaLancamentosPorCpf", lancamentoDB, sql)
return carregaLancamentos(db, query, cpf)
}
// CarregaLancamentosAtivoPorCpf retorna uma listagem de todos os lancamentos ativos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório e uma string contendo o cpf(11 caracteres)
func CarregaLancamentosAtivoPorCpf(db *sql.DB, cpf string) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
WHERE
{{.cpfPessoa}} = $1 AND {{.estado}} = true
`
query := getTemplateQuery("CarregaLancamentosAtivoPorCpf", lancamentoDB, sql)
return carregaLancamentos(db, query, cpf)
}
// CarregaLancamentosInativoPorCpf retorna uma listagem de todos os lancamentos ativos(lancamento.Lancamentos) e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório e uma string contendo o cpf(11 caracteres)
func CarregaLancamentosInativoPorCpf(db *sql.DB, cpf string) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
WHERE
{{.cpfPessoa}} = $1 AND {{.estado}} = false
`
query := getTemplateQuery("CarregaLancamentosInativoPorCpf", lancamentoDB, sql)
return carregaLancamentos(db, query, cpf)
}
// CarregaLancamentosPorCpfEConta retorna uma listagem de todos os lancamentos(lancamento.Lancamentos) de acordo com conta informada e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório, uma string contendo o cpf(11 caracteres) e um nome de conta(string)
func CarregaLancamentosPorCpfEConta(db *sql.DB, cpf, conta string) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
INNER JOIN
{{.tabelaComplementar01}} ON {{.id}} = {{.tabelaComplementar01}}.{{.idTabelaComplementar01}}
WHERE
{{.cpfPessoa}} = $1 AND {{.nomeConta}} = $2
`
query := getTemplateQuery("CarregaLancamentosPorCpfEConta", lancamentoDB, sql)
return carregaLancamentos(db, query, cpf, conta)
}
// CarregaLancamentosAtivoPorCpfEConta retorna uma listagem de todos os lancamentos ativos(lancamento.Lancamentos) de acordo com conta informada e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório, uma string contendo o cpf(11 caracteres) e um nome de conta(string)
func CarregaLancamentosAtivoPorCpfEConta(db *sql.DB, cpf, conta string) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
INNER JOIN
{{.tabelaComplementar01}} ON {{.id}} = {{.tabelaComplementar01}}.{{.idTabelaComplementar01}}
WHERE
{{.cpfPessoa}} = $1 AND {{.nomeConta}} = $2 AND {{.estado}} = true
`
query := getTemplateQuery("CarregaLancamentosAtivoPorCpfEConta", lancamentoDB, sql)
return carregaLancamentos(db, query, cpf, conta)
}
// CarregaLancamentosInativoPorCpfEConta retorna uma listagem de todos os lancamentos inativos(lancamento.Lancamentos) de acordo com conta informada e erro = nil do BD caso a consulta ocorra corretamente a partir do CPF da pessoa informado. erro != nil caso ocorra um problema. Deve ser informado uma conexão ao BD como parâmetro obrigatório, uma string contendo o cpf(11 caracteres) e um nome de conta(string)
func CarregaLancamentosInativoPorCpfEConta(db *sql.DB, cpf, conta string) (lancamentos lancamento.Lancamentos, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
INNER JOIN
{{.tabelaComplementar01}} ON {{.id}} = {{.tabelaComplementar01}}.{{.idTabelaComplementar01}}
WHERE
{{.cpfPessoa}} = $1 AND {{.nomeConta}} = $2 AND {{.estado}} = false
`
query := getTemplateQuery("CarregaLancamentosInativoPorCpfEConta", lancamentoDB, sql)
return carregaLancamentos(db, query, cpf, conta)
}
// AdicionaLancamento adiciona um lancamento ao BD e retorna o lancamento incluída(*Lancamento) com os dados de acordo como ficou no BD. erro != nil caso ocorra um problema no processo de inclusão. Deve ser informado uma conexão ao BD como parâmetro obrigatório e um lancamento(*Lancamento)
func AdicionaLancamento(db *sql.DB, novoLancamento *lancamento.Lancamento) (l *lancamento.Lancamento, err error) {
l, err = lancamento.NewLancamento(novoLancamento.ID, novoLancamento.CpfPessoa, novoLancamento.Data, novoLancamento.Numero, novoLancamento.Descricao)
if err != nil {
return
}
// foi necessário usar a instrução RETURNING em sql para obter a chave gerada ao inserir o Lancamento. O driver "github.com/lib/pq" não tem o método LastInsertId funcional. Detalhes e fonte em função setValoresLancamento01
sql := `
INSERT INTO {{.tabela}}(
{{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}})
VALUES($1, $2, $3, $4, $5, $6, $7)
RETURNING {{.id}}
`
query := getTemplateQuery("AdicionaLancamento", lancamentoDB, sql)
return adicionaLancamento(db, l, query)
}
// ProcuraLancamento localiza um lancamento no BD e retorna o lancamento procurado(*Lancamento). erro != nil caso ocorra um problema no processo de procura. Deve ser informado uma conexão ao BD como parâmetro obrigatório e o ID do lancamento desejado
func ProcuraLancamento(db *sql.DB, id int) (l *lancamento.Lancamento, err error) {
sql := `
SELECT
{{.id}}, {{.cpfPessoa}}, {{.data}}, {{.numero}}, {{.descricao}}, {{.dataCriacao}}, {{.dataModificacao}}, {{.estado}}
FROM
{{.tabela}}
WHERE {{.id}} = $1
`
query := getTemplateQuery("ProcuraLancamento", lancamentoDB, sql)
lancamentos, err := carregaLancamentos(db, query, id)
if len(lancamentos) == 1 {
l = lancamentos[0]
} else {
err = fmt.Errorf("não foi encontrado um registro com o ID %d", id)
}
return
}
// AtivaLancamento ativa um lancamento no BD e retorna o lancamento(*Lancamento) com os dados atualizados. erro != nil caso ocorra um problema no processo de procura. Deve ser informado uma conexão ao BD como parâmetro obrigatório e um ID do Lancamento desejado
func AtivaLancamento(db *sql.DB, id int) (l *lancamento.Lancamento, err error) {
lancamentoBanco, err := ProcuraLancamento(db, id)
if err != nil {
return
}
lancamentoBanco.Ativa()
sql := `
UPDATE {{.tabela}}
SET {{.estado}} = $1, {{.dataModificacao}} = $2
WHERE {{.id}} = $3
`
query := getTemplateQuery("AtivaLancamento", lancamentoDB, sql)
return estadoLancamento(db, lancamentoBanco, query, id)
}
// InativaLancamento inativa um lancamento no BD e retorna o lancamento(*Lancamento) com os dados atualizados. erro != nil caso ocorra um problema no processo de procura. Deve ser informado uma conexão ao BD como parâmetro obrigatório e um ID do Lancamento desejado
func InativaLancamento(db *sql.DB, id int) (l *lancamento.Lancamento, err error) {
lancamentoBanco, err := ProcuraLancamento(db, id)
if err != nil {
return
}
lancamentoBanco.Inativa()
sql := `
UPDATE {{.tabela}}
SET {{.estado}} = $1, {{.dataModificacao}} = $2
WHERE {{.id}} = $3
`
query := getTemplateQuery("InativaLancamento", lancamentoDB, sql)
return estadoLancamento(db, lancamentoBanco, query, id)
}
// AlteraLancamento altera um lancamento com o id(int) informado a partir dos dados do *Lancamento informada no parâmetro lancamentoAlteracao. O campo Estado não é alterado. Use a função específica para essa tarefa(estado). Retorna um *Lancamento alterado no BD e um error. error != nil caso ocorra um problema.
func AlteraLancamento(db *sql.DB, id int, lancamentoAlteracao *lancamento.Lancamento) (l *lancamento.Lancamento, err error) {
lancamentoBanco, err := ProcuraLancamento(db, id)
if err != nil {
return
}
err = lancamentoBanco.Altera(lancamentoAlteracao.CpfPessoa, lancamentoAlteracao.Data, lancamentoAlteracao.Numero, lancamentoAlteracao.Descricao)
if err != nil {
return
}
sql := `
UPDATE {{.tabela}}
SET {{.cpfPessoa}} = $1, {{.data}} = $2, {{.numero}} = $3, {{.descricao}} = $4, {{.dataModificacao}} = $5
WHERE {{.id}} = $6
`
query := getTemplateQuery("AlteraLancamento", lancamentoDB, sql)
return alteraLancamento(db, lancamentoBanco, query, id)
}
// AlteraLancamento2 altera um lancamento com o id(int) informado a partir dos dados do *Lancamento informada no parâmetro lancamentoAlteracao. O campo Estado não é alterado. Use a função específica para essa tarefa(estado). Retorna um *Lancamento alterado no BD e um error. error != nil caso ocorra um problema.
func AlteraLancamento2(db *sql.DB, transacao *sql.Tx, id int, lancamentoAlteracao *lancamento.Lancamento) (l *lancamento.Lancamento, err error) {
lancamentoBanco, err := ProcuraLancamento(db, id)
if err != nil {
return
}
err = lancamentoBanco.Altera(lancamentoAlteracao.CpfPessoa, lancamentoAlteracao.Data, lancamentoAlteracao.Numero, lancamentoAlteracao.Descricao)
if err != nil {
return
}
sql := `
UPDATE {{.tabela}}
SET {{.cpfPessoa}} = $1, {{.data}} = $2, {{.numero}} = $3, {{.descricao}} = $4, {{.dataModificacao}} = $5
WHERE {{.id}} = $6
`
query := getTemplateQuery("AlteraLancamento", lancamentoDB, sql)
return alteraLancamento2(transacao, lancamentoBanco, query, id)
}
// RemoveLancamento remove um lancamento do BD e retorna erro != nil caso ocorra um problema no processo de remoção. Deve ser informado uma conexão ao BD como parâmetro obrigatório e um int contendo o ID do lancamento desejado
func RemoveLancamento(db *sql.DB, id int) (err error) {
sql := `
DELETE FROM
{{.tabela}}
WHERE {{.id}} = $1
`
query := getTemplateQuery("RemoveLancamento", lancamentoDB, sql)
l, err := ProcuraLancamento(db, id)
if l != nil {
err = remove(db, l.ID, query)
}
return
}
func alteraLancamento(db *sql.DB, lancamentoBanco *lancamento.Lancamento, query string, chave int) (l *lancamento.Lancamento, err error) {
chaveString := strconv.Itoa(chave)
resultado, err := altera(db, lancamentoBanco, query, setValoresLancamento03, chaveString)
lancamentoTemp, ok := resultado.(*lancamento.Lancamento)
if ok {
l = lancamentoTemp
l.DataCriacao = l.DataCriacao.Local()
}
return
}
func alteraLancamento2(transacao *sql.Tx, lancamentoBanco *lancamento.Lancamento, query string, chave int) (l *lancamento.Lancamento, err error) {
chaveString := strconv.Itoa(chave)
resultado, err := altera2T(transacao, lancamentoBanco, query, setValoresLancamento04, chaveString)
lancamentoTemp, ok := resultado.(*lancamento.Lancamento)
if ok {
l = lancamentoTemp
l.DataCriacao = l.DataCriacao.Local()
}
return
}
func setValoresLancamento04(stmt *sql.Stmt, novoRegistro interface{}, chave ...interface{}) (r sql.Result, err error) {
novoLancamento, ok := novoRegistro.(*lancamento.Lancamento)
numero := getCamposConvertidosLancamento(novoLancamento)
if ok {
r, err = stmt.Exec(
novoLancamento.CpfPessoa,
novoLancamento.Data,
numero,
novoLancamento.Descricao,
novoLancamento.DataModificacao,
chave[0])
}
return
}
func setValoresLancamento03(stmt *sql.Stmt, novoRegistro interface{}, chave string) (r sql.Result, err error) {
novoLancamento, ok := novoRegistro.(*lancamento.Lancamento)
numero := getCamposConvertidosLancamento(novoLancamento)
if ok {
r, err = stmt.Exec(
novoLancamento.CpfPessoa,
novoLancamento.Data,
numero,
novoLancamento.Descricao,
novoLancamento.DataModificacao,
chave)
}
return
}
func estadoLancamento(db *sql.DB, lancamentoBanco *lancamento.Lancamento, query string, chave int) (l *lancamento.Lancamento, err error) {
chaveString := strconv.Itoa(chave) // convertido chave em string para satisfazer a interface da função setValoresLancamento02. Ao fazer update em banco, é reconhecido o campo como int(5) ou string('5') em where
resultado, err := altera(db, lancamentoBanco, query, setValoresLancamento02, chaveString)
lancamentoTemp, ok := resultado.(*lancamento.Lancamento)
if ok {
l = lancamentoTemp
}
return
}
func setValoresLancamento02(stmt *sql.Stmt, novoRegistro interface{}, chave string) (r sql.Result, err error) {
novoLancamento, ok := novoRegistro.(*lancamento.Lancamento)
if ok {
r, err = stmt.Exec(
novoLancamento.Estado,
novoLancamento.DataModificacao,
chave)
}
return
}
func adicionaLancamento(db *sql.DB, novoLancamento *lancamento.Lancamento, query string) (l *lancamento.Lancamento, err error) {
resultado, err := adiciona(db, novoLancamento, query, setValoresLancamento01)
lancamentoTemp, ok := resultado.(*lancamento.Lancamento)
if ok {
l = lancamentoTemp
}
return
}
func setValoresLancamento01(stmt *sql.Stmt, novoRegistro interface{}) (r sql.Result, err error) {
novoLancamento, ok := novoRegistro.(*lancamento.Lancamento)
numero := getCamposConvertidosLancamento(novoLancamento)
lastInsertID := 0
if ok {
err = stmt.QueryRow(
novoLancamento.CpfPessoa,
novoLancamento.Data,
numero,
novoLancamento.Descricao,
novoLancamento.DataCriacao,
novoLancamento.DataModificacao,
novoLancamento.Estado).Scan(&lastInsertID)
novoLancamento.ID = lastInsertID
// o método de sql.Result LastInsertId não é suportado pelo driver "github.com/lib/pq"
// foi usado um método alternativo(stmt.QueryRow) de acordo com link https://stackoverflow.com/questions/33382981/go-how-to-get-last-insert-id-on-postgresql-with-namedexec
}
return
}
func getCamposConvertidosLancamento(novoLancamento *lancamento.Lancamento) (numero sql.NullString) {
temNumero := len(novoLancamento.Numero) > 0
numero = sql.NullString{String: novoLancamento.Numero, Valid: temNumero}
return
}
func carregaLancamentos(db *sql.DB, query string, args ...interface{}) (lancamentos lancamento.Lancamentos, err error) {
registros, err := carrega(db, query, registrosLancamento01, args...)
lancamentos = converterEmLancamento(registros)
return
}
func registrosLancamento01(rows *sql.Rows, registros []interface{}) (novosRegistros []interface{}, err error) {
lancamentoAtual := new(lancamento.Lancamento)
err = scanLancamento01(rows, lancamentoAtual)
if err != nil {
return
}
lancamentoAtual.CorrigeData()
novosRegistros = append(registros, lancamentoAtual)
return
}
func scanLancamento01(rows *sql.Rows, lancamentoAtual *lancamento.Lancamento) error {
var numero sql.NullString // numero é um campo na tabela lancamento do BD que pode ser nulo
err := rows.Scan(
&lancamentoAtual.ID,
&lancamentoAtual.CpfPessoa,
&lancamentoAtual.Data,
&numero,
&lancamentoAtual.Descricao,
&lancamentoAtual.DataCriacao,
&lancamentoAtual.DataModificacao,
&lancamentoAtual.Estado)
lancamentoAtual.Numero = numero.String
return err
}
func converterEmLancamento(registros []interface{}) (lancamentos lancamento.Lancamentos) {
for _, r := range registros {
l, ok := r.(*lancamento.Lancamento)
if ok {
lancamentos = append(lancamentos, l)
}
}
return
}
|
meixiaoyao/myleesite
|
myleesite-module/src/main/java/com/zyw/myleesite/module/sys/security/FormAuthenticationFilter.java
|
package com.zyw.myleesite.module.sys.security;
import com.zyw.myleesite.common.utils.StringUtils;
import com.zyw.myleesite.module.sys.utils.UserUtils;
import com.zyw.myleesite.module.sys.web.LoginController;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
@Service
public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
public static final String DEFAULT_CAPTCHA_PARAM = "validateCode";
public static final String DEFAULT_MESSAGE_PARAM = "message";
private String catptchaParam = DEFAULT_CAPTCHA_PARAM;
private String messageParam = DEFAULT_MESSAGE_PARAM;
/**
* 创建令牌
* @param request
* @param response
* @return
*/
public AuthenticationToken createToken(ServletRequest request, ServletResponse response){
String username = getUsername(request);
String password = getPassword(request);
if(password == null){
password = "";
}
boolean rememberMe = isRememberMe(request);
String host = StringUtils.getRemoteAddr((HttpServletRequest) request);
String captcha = getCaptcha(request);
return new UsernamePasswordToken(username, password, rememberMe, host, captcha);
}
public String getMessageParam(){
return messageParam;
}
public String getCaptcha(ServletRequest request){
return WebUtils.getCleanParam(request, catptchaParam);
}
/**
* 登录成功跳转
* @param request
* @param response
* @throws Exception
*/
@Override
protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
Principal principal = UserUtils.getPrincipal();
if(principal != null){
// 登录成功清除
LoginController.isValidateCodeLogin(principal.getName(),false,true);
WebUtils.issueRedirect(request, response,"/main", null, true);
}
}
/**
* 登录失败调用
* @param token
* @param e
* @param request
* @param response
* @return
*/
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
String className = e.getClass().getName(), message= "";
if(IncorrectCredentialsException.class.getName().equals(className) || UnknownAccountException.class.getName().equals(className)){
message = "用户名或密码错误,请重试";
}
else if(e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
message = StringUtils.replace(e.getMessage(), "msg:", "");
}else{
message = "系统出现问题,请稍后再试";
e.printStackTrace();
}
request.setAttribute(getFailureKeyAttribute(), className);
request.setAttribute(getMessageParam(), message);
return true;
}
}
|
bosschaert/jclouds
|
apis/vcloud/src/test/java/org/jclouds/vcloud/xml/VmHandlerTest.java
|
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <<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 org.jclouds.vcloud.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.URI;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.vcloud.VCloudMediaType;
import org.jclouds.vcloud.domain.Status;
import org.jclouds.vcloud.domain.Vm;
import org.jclouds.vcloud.domain.internal.ReferenceTypeImpl;
import org.jclouds.vcloud.xml.ovf.VCloudOperatingSystemSectionHandlerTest;
import org.jclouds.vcloud.xml.ovf.VCloudVirtualHardwareSectionHandlerTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code VmHandler}
*
* @author <NAME>
*/
@Test(groups = "unit")
public class VmHandlerTest {
public void testVCloud1_0() {
InputStream is = getClass().getResourceAsStream("/vm-rhel-off-static.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
Vm result = factory.create(injector.getInstance(VmHandler.class)).parse(is);
checkVm(result);
}
static void checkVm(Vm result) {
assertEquals(result.getName(), "RHEL5");
assertEquals(result.getHref(), URI.create("https://vcenterprise.bluelock.com/api/v1.0/vApp/vm-2087535248"));
assertEquals(result.getType(), "application/vnd.vmware.vcloud.vm+xml");
assertEquals(result.getStatus(), Status.OFF);
assertEquals(result.getParent(), new ReferenceTypeImpl(null, VCloudMediaType.VAPP_XML, URI
.create("https://vcenterprise.bluelock.com/api/v1.0/vApp/vapp-607806320")));
assertEquals(result.getDescription(), null);
assertEquals(result.getTasks(), ImmutableList.of());
assertEquals(result.getVAppScopedLocalId(), "10_rhel_template");
VCloudVirtualHardwareSectionHandlerTest.checkHardware(result.getVirtualHardwareSection());
VCloudOperatingSystemSectionHandlerTest.checkOs(result.getOperatingSystemSection());
NetworkConnectionSectionHandlerTest.checkNetworkConnectionSection(result.getNetworkConnectionSection());
GuestCustomizationSectionHandlerTest.checkGuestCustomization(result.getGuestCustomizationSection());
}
}
|
cookrn/imatix_base
|
vendor/openamq/tooling/base1/sfl/sflmysql.c
|
/*===========================================================================*
* *
* sflmysql.c - MySQL database interface *
* *
* Copyright (c) 1991-2009 iMatix Corporation *
* *
* ------------------ GPL Licensed Source Code ------------------ *
* iMatix makes this software available under the GNU General *
* Public License (GPL) license for open source projects. For *
* details of the GPL license please see www.gnu.org or read the *
* file license.gpl provided in this package. *
* *
* 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. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program in the file 'license.gpl'; if *
* not, write to the Free Software Foundation, Inc., 59 Temple *
* Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* You can also license this software under iMatix's General Terms *
* of Business (GTB) for commercial projects. If you have not *
* explicitly licensed this software under the iMatix GTB you may *
* only use it under the terms of the GNU General Public License. *
* *
* For more information, send an email to <EMAIL>. *
* -------------------------------------------------------------- *
*===========================================================================*/
#include "prelude.h"
#include "sflsymb.h"
#include "sflunic.h" /* Unicode support */
#include "sflcons.h"
#include "sflmem.h"
#include "sfldbio.h"
#ifdef DBIO_MYSQL
#include "sflmysql.h"
/*- Global definition -------------------------------------------------------*/
typedef struct {
COMMON_DBIO_CTX
char dbname [50];
char user [50];
char password [50];
char host [100];
long port;
MYSQL *db_handle;
} MYSQL_CONNECT_CTX;
/* ---------------------------------------------------------------------[<]-
Function: dbio_mysql_connect
Synopsis: Connect to a mysql database.
---------------------------------------------------------------------[>]-*/
void *
dbio_mysql_connect (char *name, char *user, char *pwd, char *host)
{
MYSQL_CONNECT_CTX
*handle = NULL;
MYSQL
*mysql;
mysql = mysql_connect (NULL, host, user, pwd);
if (mysql)
{
if (mysql_select_db (mysql, name) != 0)
{
mysql_close (mysql);
mysql = NULL;
}
}
if (mysql)
{
handle = mem_alloc (sizeof (MYSQL_CONNECT_CTX));
memset (handle, 0, sizeof (MYSQL_CONNECT_CTX));
handle-> db_handle = mysql;
handle-> port = MYSQL_PORT;
strcpy (handle-> dbname, name);
if (user && strused (user))
strcpy (handle-> user, user);
if (pwd && strused (pwd))
strcpy (handle-> password, <PASSWORD>);
if (host && strused (host))
strcpy (handle-> host, host);
}
else
coprintf ("Error on Connect to %s in MySql", name);
return ((void *)handle);
}
/* ---------------------------------------------------------------------[<]-
Function: dbio_mysql_disconnect
Synopsis:
---------------------------------------------------------------------[>]-*/
void
dbio_mysql_disconnect (void *context)
{
MYSQL_CONNECT_CTX
*ctx;
if (context)
{
ctx = (MYSQL_CONNECT_CTX *)context;
if (ctx-> db_handle)
{
mysql_close (ctx-> db_handle);
ctx-> db_handle = NULL;
}
mem_free (ctx);
}
}
/* ---------------------------------------------------------------------[<]-
Function: dbio_mysql_commit
Synopsis: Mysql don't support COMMIT/ROLLBACK
---------------------------------------------------------------------[>]-*/
int
dbio_mysql_commit (void *context)
{
int
feedback = TRUE;
return (feedback);
}
/* ---------------------------------------------------------------------[<]-
Function: dbio_mysql_rollback
Synopsis: Mysql don't support COMMIT/ROLLBACK
---------------------------------------------------------------------[>]-*/
int
dbio_mysql_rollback (void *context)
{
int
feedback = TRUE;
return (feedback);
}
/* ---------------------------------------------------------------------[<]-
Function: alloc_mysql_handle
Synopsis:
---------------------------------------------------------------------[>]-*/
MYSQLHANDLE *
alloc_mysql_handle (char *table_name, void *context)
{
MYSQLHANDLE
*handle = NULL; /* mysql Context handle */
MYSQL_CONNECT_CTX
*temp_ctx,
*ctx;
if (context)
{
ctx = (MYSQL_CONNECT_CTX *)context;
temp_ctx = dbio_mysql_connect (ctx-> dbname, ctx-> user, ctx->password,
ctx->host);
if (temp_ctx)
{
handle = mem_alloc (sizeof (MYSQLHANDLE));
if (handle)
{
memset (handle, 0, sizeof (MYSQLHANDLE));
handle-> db_handle = temp_ctx-> db_handle;
if (table_name && strused (table_name))
handle-> table_name = mem_strdup (table_name);
mem_free (temp_ctx);
}
else
{
coprintf ("DBIO MYSQL: Error in alloc_mysql_handle (Memory Allocation)");
dbio_mysql_disconnect (temp_ctx);
}
}
}
return (handle);
}
/* ---------------------------------------------------------------------[<]-
Function: set_mysql_connection
Synopsis: Reconnect to a mysql database.
---------------------------------------------------------------------[>]-*/
void
set_mysql_connection (void *context)
{
}
#endif
|
geeox96/dalike
|
version.js
|
<gh_stars>1-10
/**
* Version
* =====================
* Bot version
*
* @author: <NAME> [@ptkdev] <<EMAIL>> (https://ptk.dev)
* @license: This code and contributions have 'GNU General Public License v3'
* @version: 0.9.0
* @changelog: 0.7.4 initial release
*
*/
module.exports = require("./package.json");
|
atomstech-io/react-lms
|
frontend/src/lms-base/redux/actions/ActionTypes.js
|
<reponame>atomstech-io/react-lms
export const SET_USER_DATA = 'SET_USER_DATA'
export const TOGGLE_API_CALL_ACTIVE = 'TOGGLE_API_CALL_ACTIVE'
export const SET_ACTIVE_USERNAME = 'SET_ACTIVE_USERNAME'
export const SET_AUTH_STATUS = 'SET_AUTH_STATUS'
|
johnml1135/machine.py
|
machine/translation/hmm_word_alignment_model.py
|
from abc import abstractmethod
from .ibm1_word_alignment_model import Ibm1WordAlignmentModel
class HmmWordAlignmentModel(Ibm1WordAlignmentModel):
@abstractmethod
def get_alignment_probability(self, source_length: int, prev_source_index: int, source_index: int) -> float:
...
|
jmdyck/test262-parser-tests
|
early/f7df8b7ca4fd194d.js
|
a: while (true) { a: while (true) { } }
|
ishikawa/modipyd
|
modipyd/monitor.py
|
<reponame>ishikawa/modipyd
"""
This module provides an interface to the mechanisms
used to monitor Python module file modifications.
:copyright: 2008 by <NAME>
:license: MIT, see LICENSE for more details.
"""
import os
from errno import ENOENT
import logging
import time
from os.path import splitext
from modipyd import LOGGER
from modipyd import utils
from modipyd.module import read_module_code, \
collect_python_module_file
from modipyd.resolve import ModuleNameResolver
from modipyd.descriptor import ModuleDescriptor
from modipyd.utils.decorators import require
class Event(object):
"""
The ``Event`` class defines a interface to monitoring events.
"""
# Enumeration that represents event types
TYPES = range(3)
MODULE_MODIFIED, MODULE_CREATED, MODULE_REMOVED = TYPES
@require(type=int, descriptor=ModuleDescriptor)
def __init__(self, event_type, descriptor):
if event_type not in Event.TYPES:
raise RuntimeError("illegal event type: %d" % event_type)
self.type = event_type
self.descriptor = descriptor
class Monitor(object):
"""
This class provides an interface to the mechanisms
used to monitor Python module file modifications.
``start()``, ``refresh()``, ``monitor()`` return generator,
these generater yields ``Event`` instance.
"""
def __init__(self, filepath_or_list, search_path=None):
from modipyd.resolve import normalize_path
super(Monitor, self).__init__()
self.search_path = search_path
# paths will be used as dictionary key,
# so make it normalized.
paths = utils.sequence(filepath_or_list)
self.paths = [normalize_path(i) for i in paths]
assert not isinstance(self.paths, basestring)
self.monitoring = False
self.__descriptors = None
self.__filenames = {}
self.__failures = set()
@property
def descriptors(self):
"""
All the monitoring modules. This is dictionary,
maps name and module descriptors.
"""
if self.__descriptors is None:
self.__descriptors = {}
entries = list(self.refresh())
LOGGER.debug("%d descriptoes" % len(entries))
return self.__descriptors
@require(descriptor=ModuleDescriptor)
def remove(self, descriptor):
"""Remove *descriptor*, and clear dependencies"""
descriptors, filenames = self.descriptors, self.__filenames
filename = splitext(descriptor.filename)[0]
if (descriptor.name not in descriptors or
filename not in filenames):
raise KeyError(
"No monitoring descriptor '%s'" % \
descriptor.name)
LOGGER.debug("Removed: %s" % descriptor.describe())
descriptor.clear_dependencies()
del descriptors[descriptor.name]
del filenames[filename]
@require(descriptor=ModuleDescriptor)
def add(self, descriptor):
"""Add *descriptor*, but doesn't update dependencies"""
descriptors, filenames = self.descriptors, self.__filenames
filename = splitext(descriptor.filename)[0]
descriptors[descriptor.name] = descriptor
filenames[filename] = descriptor
def refresh(self):
assert isinstance(self.paths, (tuple, list))
assert isinstance(self.__descriptors, dict)
assert isinstance(self.__filenames, dict)
assert isinstance(self.__failures, set)
# localize variable access to minimize overhead
# and to reduce the visual noise.
descriptors = self.__descriptors
filenames = self.__filenames
failures = self.__failures
# ``monitor()`` updates all entries and
# removes deleted entries.
for modified in self.monitor():
yield modified
# For now, only need to check new entries.
resolver = ModuleNameResolver(self.search_path)
newcomers = []
for filename, typebits in collect_python_module_file(self.paths):
if filename in filenames or filename in failures:
continue
try:
mc = read_module_code(filename, typebits=typebits,
search_path=self.search_path,
resolver=resolver,
allow_compilation_failure=True,
allow_standalone=True)
except ImportError:
LOGGER.debug("Couldn't import file", exc_info=True)
failures.add(filename)
continue
else:
desc = ModuleDescriptor(mc)
self.add(desc)
# modifieds += new entries
newcomers.append(desc)
LOGGER.debug("Added: %s" % desc.describe())
if newcomers:
# Since there are some entries already refer new entry,
# we need to update dependencies of all entries
for desc in descriptors.itervalues():
desc.update_dependencies(descriptors)
# Notify caller what entries are appended
for desc in newcomers:
yield Event(Event.MODULE_CREATED, desc)
def monitor(self):
descriptors = self.descriptors
removals = []
for desc in descriptors.itervalues():
try:
if desc.modified():
desc.reload(descriptors)
yield Event(Event.MODULE_MODIFIED, desc)
except os.error, e:
if e.errno == ENOENT:
# No such file
removals.append(desc)
else:
raise
# Remove removal entries
for desc in removals:
try:
# yield before remove
yield Event(Event.MODULE_REMOVED, desc)
self.remove(desc)
except KeyError:
LOGGER.debug(
"No monitoring descriptor '%s' for removal" % desc.name,
exc_info=True)
@require(interval=(int, float), refresh_factor=int)
def start(self, interval=1.0, refresh_factor=5):
if refresh_factor < 1:
raise RuntimeError("refresh_factor must be greater or eqaul to 1")
if interval <= 0:
raise RuntimeError("interval must not be negative or 0")
descriptors = self.descriptors
if LOGGER.isEnabledFor(logging.INFO):
desc = "\n".join([
desc.describe(indent=4)
for desc in descriptors.itervalues()])
LOGGER.info("Monitoring:\n%s" % desc)
# Prior to Python 2.5, the ``yield`` statement is not
# allowed in the ``try`` clause of a ``try ... finally``
# construct.
try:
self.monitoring = True
times = 0
while descriptors and self.monitoring:
time.sleep(interval)
times += 1
if times % refresh_factor == 0:
monitor = self.refresh()
else:
monitor = self.monitor()
for modified in monitor:
if not self.monitoring:
break
yield modified
else:
LOGGER.info("Terminating monitor %s" % str(self))
except:
self.monitoring = False
raise
def stop(self):
self.monitoring = False
if __name__ == "__main__":
import doctest
doctest.testmod()
|
davesag/social-media-collector
|
utils/getModuleRules.js
|
<reponame>davesag/social-media-collector
const getModuleRules = () => [
{
enforce: 'pre',
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
failOnError: true
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
},
{
test: /\.html$/,
use: ['raw-loader']
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: ['file-loader']
}
];
module.exports = getModuleRules;
|
imran110219/Medical-Inventory
|
src/main/java/com/sadman/medicalinventory/controller/POSController.java
|
package com.sadman.medicalinventory.controller;
import com.sadman.medicalinventory.dto.InvoiceDTO;
import com.sadman.medicalinventory.dto.MedicineDTO;
import com.sadman.medicalinventory.exception.RecordNotFoundException;
import com.sadman.medicalinventory.iservice.*;
import com.sadman.medicalinventory.iservice.POSService;
import com.sadman.medicalinventory.model.*;
import com.sadman.medicalinventory.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sadman
*/
@Controller
public class POSController {
@Autowired
BrandService brandService;
@Autowired
PurchaseService purchaseService;
@Autowired
StockService stockService;
@Autowired
POSService posService;
@Autowired
SaleInvoiceService saleInvoiceService;
@Autowired
SaleService saleService;
@PostMapping(value="/pos/brand/{id}")
public ResponseEntity<Brand> getBrandById(@PathVariable(value = "id") Long brandId) throws RecordNotFoundException {
Brand brand = brandService.getBrandById(brandId);
return new ResponseEntity<>(brand, HttpStatus.OK);
}
@PostMapping(value="/pos/purchases/{id}")
public ResponseEntity<List<Purchase>> getPurchasesByBrandId(@PathVariable(value = "id") Long brandId){
List<Purchase> PurchaseList = purchaseService.getPurchasesByBrandId(brandId);
return new ResponseEntity<>(PurchaseList, HttpStatus.OK);
}
@PostMapping(value="/pos/stock/{id}")
public ResponseEntity<Stock> getStockByPurchaseId(@PathVariable(value = "id") Long purchaseId){
Stock stock = stockService.getStockByPurchaseId(purchaseId);
return new ResponseEntity<>(stock, HttpStatus.OK);
}
@RequestMapping(value = "/pos")
public String getPOS(Model model) {
List<Brand> brandList = brandService.getAllBrands();
List<MedicineDTO> medicineDTOList = new ArrayList<>();
InvoiceDTO invoiceDTO = new InvoiceDTO();
invoiceDTO.setMedicineDTOList(medicineDTOList);
model.addAttribute("medicinedto", new MedicineDTO());
model.addAttribute("invoicedto", invoiceDTO);
model.addAttribute("brands", brandList);
return "pos";
}
@PostMapping(value="/pos/payment")
public ResponseEntity<SaleInvoice> makePayment(InvoiceDTO invoiceDTO){
SaleInvoice invoice = posService.makePayment(invoiceDTO);
return new ResponseEntity<>(invoice, HttpStatus.OK);
}
@GetMapping(value = "/pos/invoice/{invoiceId}")
public String getInvoice(Model model, @PathVariable(value = "invoiceId") String saleInvoiceId) throws RecordNotFoundException {
SaleInvoice saleInvoice = saleInvoiceService.getSaleInvoiceById(saleInvoiceId);
List<Sale> saleList = saleService.getAllSalesBySaleInvoiceId(saleInvoiceId);
model.addAttribute("invoice", saleInvoice);
model.addAttribute("saleList", saleList);
return "invoice/sale-invoice";
}
@GetMapping(value = "/pos/invoice/{invoiceId}/print")
public String printInvoice(Model model, @PathVariable(value = "invoiceId") String saleInvoiceId) throws RecordNotFoundException {
SaleInvoice saleInvoice = saleInvoiceService.getSaleInvoiceById(saleInvoiceId);
List<Sale> saleList = saleService.getAllSalesBySaleInvoiceId(saleInvoiceId);
model.addAttribute("invoice", saleInvoice);
model.addAttribute("saleList", saleList);
return "invoice/sale-invoice-print";
}
}
|
yonetatuu/kamonohashi
|
web-pages-aquarium/src/api/api.js
|
<filename>web-pages-aquarium/src/api/api.js
import * as gen from './api.generator'
import axiosRoot from 'axios'
import * as ext from '@/util/axios-ext'
// -----------------------------------------------------------------------
// axiosの拡張
// テストでモックさせるためaxiosをexport
let axios = axiosRoot.create({
// VUE_APP_API_HOST: .envから取得
baseURL: 'http://' + (process.env.VUE_APP_API_HOST || ''),
headers: { 'Content-Type': 'application/json' },
})
ext.axiosLoggerInterceptors(axios)
ext.axiosAuthInterceptors(axios)
ext.axiosLoadingInterceptors(axios)
ext.axiosErrorHandlingInterceptors(axios)
gen.setAxios(axios)
// -----------------------------------------------------------------------
// 使いやすいようにAPI領域で再定義
// (swagger-vue で自動生成生成:https://github.com/chenweiqun/swagger-vue)
let api = {
cluster: {
getPartitions: gen.getApiV2TenantPartitions,
getQuota: gen.getApiV2TenantQuota,
getTenantNodes: gen.getApiV2TenantNodes,
admin: {
getQuotas: gen.getApiV2AdminQuotas,
postQuota: gen.postApiV2AdminQuotas,
deleteTensorboards: gen.deleteApiV2AdminTensorboards,
},
},
menuList: {
getMenuList: gen.getApiV2AccountAquariumMenusList,
},
templates: {
admin: {
getById: gen.getApiV2AdminTemplatesById,
get: gen.getApiV2Templates,
post: gen.postApiV2AdminTemplates,
put: gen.putApiV2AdminTemplatesById,
delete: gen.deleteApiV2AdminTemplatesById,
deleteVersion: gen.deleteApiV2AdminTemplatesByIdVersionsByVersionId,
getByIdVersions: gen.getApiV2AdminTemplatesByIdVersions,
postByIdVersions: gen.postApiV2AdminTemplatesByIdVersions,
getByIdVersionsByVersionId:
gen.getApiV2AdminTemplatesByIdVersionsByVersionId,
},
getTenantTemplate: gen.getApiV2TenantTemplates,
},
registry: {
admin: {
get: gen.getApiV2AdminRegistryEndpoints,
getById: gen.getApiV2AdminRegistryEndpointsById,
getType: gen.getApiV2AdminRegistryTypes,
post: gen.postApiV2AdminRegistryEndpoints,
putById: gen.putApiV2AdminRegistryEndpointsById,
deleteById: gen.deleteApiV2AdminRegistryEndpointsById,
},
tenant: {
getEndpoints: gen.getApiV2TenantRegistryEndpoints,
},
getImages: gen.getApiV2RegistriesByRegistryIdImages,
getTags: gen.getApiV2RegistriesByRegistryIdImagesByImageTags,
},
account: {
get: gen.getApiV2Account,
put: gen.putApiV2Account,
putPassword: gen.putApiV2AccountPassword,
postLogin: gen.postApiV2AccountLogin,
postTokenTenants: gen.postApiV2AccountTenantsByTenantIdToken,
getTreeMenus: gen.getApiV2AccountAquariumMenusTree,
getListMenus: gen.getApiV2AccountAquariumMenusList,
getRegistries: gen.getApiV2AccountRegistries,
putRegistries: gen.putApiV2AccountRegistries,
getGits: gen.getApiV2AccountGits,
putGits: gen.putApiV2AccountGits,
getWebhookSlack: gen.getApiV2AccountWebhookSlack,
putWebhookSlack: gen.putApiV2AccountWebhookSlack,
postWebhookSlackTest: gen.postApiV2AccountWebhookSlackTest,
},
data: {
get: gen.getApiV2Data,
post: gen.postApiV2Data,
getById: gen.getApiV2DataById,
putById: gen.putApiV2DataById,
deleteById: gen.deleteApiV2DataById,
getFilesByKey: gen.getApiV2DataByIdFilesByName,
getFilesById: gen.getApiV2DataByIdFiles,
putFilesById: gen.postApiV2DataByIdFiles,
deleteFilesById: gen.deleteApiV2DataByIdFilesByFileId,
getDataTags: gen.getApiV2DataDatatags,
getFileSize: gen.getApiV2DataByIdFilesByNameSize,
},
aquariumDatasets: {
get: gen.getApiV2AquariumDatasets,
post: gen.postApiV2AquariumDatasets,
getByIdVersions: gen.getApiV2AquariumDatasetsByIdVersions,
postByIdVersions: gen.postApiV2AquariumDatasetsByIdVersions,
getByIdVersionsByVersionId:
gen.getApiV2AquariumDatasetsByIdVersionsByVersionId,
delete: gen.deleteApiV2AquariumDatasetsById,
deleteVersion: gen.deleteApiV2AquariumDatasetsByIdVersionsByVersionId,
},
datasets: {
get: gen.getApiV2Datasets,
post: gen.postApiV2Datasets,
getById: gen.getApiV2DatasetsById,
put: gen.putApiV2DatasetsById,
delete: gen.deleteApiV2DatasetsById,
patch: gen.patchApiV2DatasetsById,
getFiles: gen.getApiV2DataByIdFiles,
getDatatypes: gen.getApiV2Datatypes,
},
git: {
admin: {
getEndpoints: gen.getApiV2AdminGitEndpoints,
postEndpoint: gen.postApiV2AdminGitEndpoints,
putEndpoint: gen.putApiV2AdminGitEndpointsById,
getById: gen.getApiV2AdminGitEndpointsById,
deleteById: gen.deleteApiV2AdminGitEndpointsById,
getTypes: gen.getApiV2AdminGitTypes,
},
tenant: {
getEndpoints: gen.getApiV2TenantGitEndpoints,
},
getRepos: gen.getApiV2GitByGitIdRepos,
getBranches: gen.getApiV2GitByGitIdReposByOwnerByRepositoryNameBranches,
getCommits: gen.getApiV2GitByGitIdReposByOwnerByRepositoryNameCommits,
getCommit:
gen.getApiV2GitByGitIdReposByOwnerByRepositoryNameCommitsByCommitId,
// GET /spa/git/repos/{segments}
},
training: {
getSimple: gen.getApiV2TrainingSimple,
get: gen.getApiV2Training,
post: gen.postApiV2TrainingRun,
getById: gen.getApiV2TrainingById,
deleteById: gen.deleteApiV2TrainingById,
putById: gen.putApiV2TrainingById,
// GET /spa/trains/{id}/log
getFilesById: gen.getApiV2TrainingByIdFiles,
getFileSize: gen.getApiV2TrainingByIdFilesByNameSize,
postFilesById: gen.postApiV2TrainingByIdFiles,
getContainerFilesById: gen.getApiV2TrainingByIdContainerFiles,
deleteByIdFilesByFileId: gen.deleteApiV2TrainingByIdFilesByFileId,
getTensorboardById: gen.getApiV2TrainingByIdTensorboard,
putTensorboardById: gen.putApiV2TrainingByIdTensorboard,
deleteTensorboardById: gen.deleteApiV2TrainingByIdTensorboard,
postHaltById: gen.postApiV2TrainingByIdHalt,
postUserCancelById: gen.postApiV2TrainingByIdUserCancel,
getEventsById: gen.getApiV2TrainingByIdEvents,
getMount: gen.getApiV2TrainingMount,
getTags: gen.getApiV2TrainingTags,
},
experiment: {
get: gen.getApiV2Experiment,
post: gen.postApiV2ExperimentRun,
getById: gen.getApiV2ExperimentById,
postPreprocessingCompleteById:
gen.postApiV2ExperimentByIdPreprocessingComplete,
deleteById: gen.deleteApiV2ExperimentById,
getEvaluationsById: gen.getApiV2ExperimentByIdEvaluations,
postEvaluationsById: gen.postApiV2ExperimentByIdEvaluations,
deleteByIdEvaluationsByEvaluationId:
gen.deleteApiV2ExperimentByIdEvaluationsByEvaluationId,
},
storage: {
admin: {
get: gen.getApiV2AdminStorageEndpoints,
post: gen.postApiV2AdminStorageEndpoints,
getById: gen.getApiV2AdminStorageEndpointsById,
put: gen.putApiV2AdminStorageEndpointsById,
delete: gen.deleteApiV2AdminStorageEndpointsById,
},
getUploadParameter: gen.getApiV2UploadParameter,
postUploadComplete: gen.postApiV2UploadComplete,
getDownloadUrl: gen.getApiV2DownloadUrl,
},
version: {
get: gen.getApiV2Version,
},
// dataを取り出すメソッド
f: {
data(response) {
return [response.data]
},
dataTotal(response) {
return [response.data, response.headers['x-total-count']]
},
},
}
export { api as default }
|
lexruee/coach4rb
|
lib/coach4rb/mixin/basic_auth.rb
|
module Coach4rb
module Mixin
module BasicAuth
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
def basic_auth_encryption(username, password)
'Basic ' + Base64.encode64("#{username}:#{password}").chomp
end
end
end
end
end
|
ale180192/openapi-viewer-back
|
core/utils/auth.py
|
<reponame>ale180192/openapi-viewer-back
from rest_framework.authentication import TokenAuthentication
class CustomTokenAuthentication(TokenAuthentication):
keyword = 'Bearer'
|
vjovanov/scalameta
|
foundation/src/main/scala/org/scalameta/show/Escape.scala
|
package org.scalameta.show
object escape {
def apply(s: String): String = {
// TODO: comprehensive handling
val codepage = Map(
"\t" -> "\\t",
"\b" -> "\\b",
"\n" -> "\\n",
"\r" -> "\\r",
"\f" -> "\\f",
"\\" -> "\\\\"
)
s.flatMap(c => codepage.getOrElse(c.toString, c.toString))
}
}
|
Neo-Turak/DevUtils
|
lib/Environment/DevEnvironmentCompilerRelease/src/main/java/dev/environment/compiler/Utils.java
|
package dev.environment.compiler;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import dev.environment.annotation.Environment;
import dev.environment.annotation.Module;
import dev.environment.bean.EnvironmentBean;
import dev.environment.bean.ModuleBean;
import dev.environment.listener.OnEnvironmentChangeListener;
import dev.environment.log.LogUtils;
import dev.environment.type.ParameterizedTypeImpl;
/**
* detail: 内部工具类
* @author Ttt
*/
final class Utils {
// 包名
static final String PACKAGE_NAME = "dev.environment";
// 工具类文件名
static final String ENVIRONMENT_FILE_NAME = "DevEnvironment";
// 方法名
static final String METHOD_RESET = "reset";
static final String METHOD_IS_RELEASE = "isRelease";
static final String METHOD_GET_MODULE_LIST = "getModuleList";
static final String METHOD_GET_MODULE_ENVIRONMENTS_LIST = "getEnvironments";
static final String METHOD_GET_ENVIRONMENTS_VALUE = "getValue";
static final String METHOD_ADD_ONENVIRONMENT_CHANGE_LISTENER = "addOnEnvironmentChangeListener";
static final String METHOD_REMOVE_ONENVIRONMENT_CHANGE_LISTENER = "removeOnEnvironmentChangeListener";
static final String METHOD_CLEAR_ONENVIRONMENT_CHANGE_LISTENER = "clearOnEnvironmentChangeListener";
static final String METHOD_GET_STORAGE_DIR = "getStorageDir";
static final String METHOD_DELETE_STORAGE_DIR = "deleteStorageDir";
static final String METHOD_IS_ANNOTATION = "is%sAnnotation";
// 变量相关
static final String VAR_MODULE_PREFIX = "MODULE_";
static final String VAR_ENVIRONMENT_PREFIX = "ENVIRONMENT_";
static final String VAR_MODULELIST = "moduleList";
static final String VAR_MODULE_LIST = "MODULE_LIST";
static final String VAR_CONTEXT = "context";
static final String VAR_NEW_ENVIRONMENT = "newEnvironment";
static final String VAR_LISTENER = "listener";
static final String VAR_FILE_NAME = "fileName";
// 常量字符串
static final String STR_MODULE = "Module";
static final String STR_ENVIRONMENT = "Environment";
static final String STR_ENVIRONMENT_VALUE = "EnvironmentValue";
static final String STR_RELEASE_ENVIRONMENT = "ReleaseEnvironment";
// 其他
static final TypeName TYPE_NAME_CONTEXT = ClassName.get("android.content", "Context");
// ===============
// = 内部生成方法 =
// ===============
// 用于记录 Module 名 Map<Module Name, List<Environment var Name>>
static final LinkedHashMap<String, List<String>> sModuleNameMap = new LinkedHashMap<>();
// ========
// = 通用 =
// ========
/**
* 构建 DevEnvironment 类对象
* @return {@link TypeSpec.Builder}
*/
public static TypeSpec.Builder builderDevEnvironment_Class() {
// 创建 DevEnvironment 类
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(ENVIRONMENT_FILE_NAME)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addJavadoc("detail: 环境配置工具类\n")
.addJavadoc("@author Ttt\n");
// 创建 DevEnvironment 无参构造函数
// private DevEnvironment() {}
MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();
return classBuilder.addMethod(constructor);
}
/**
* 创建 DevEnvironment JAVA 文件
* @param classBuilder DevEnvironment 类构建对象
* @param processingEnv {@link ProcessingEnvironment}
* @return {@code true} success, {@code false} fail
*/
public static boolean createDevEnvironmentJavaFile(
final TypeSpec.Builder classBuilder,
final ProcessingEnvironment processingEnv
) {
JavaFile javaFile = JavaFile.builder(PACKAGE_NAME, classBuilder.build()).build();
try {
javaFile.writeTo(processingEnv.getFiler());
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// =
/**
* 创建 Module 数据
* @param classBuilder DevEnvironment 类构建对象
* @param moduleElement 使用注解修饰的 Module Element
* @param processingEnv {@link ProcessingEnvironment}
*/
public static void builderModule_DATA(
final TypeSpec.Builder classBuilder,
final Element moduleElement,
final ProcessingEnvironment processingEnv
)
throws Exception {
Module moduleAnnotation = moduleElement.getAnnotation(Module.class);
if (moduleAnnotation == null) return;
// Module 信息
String moduleName = moduleElement.getSimpleName().toString();
String moduleAlias = moduleAnnotation.alias();
// 获取 Module Release Environment 数据
Element environmentElement = _getModuleReleaseEnvironment(moduleElement, processingEnv);
if (environmentElement != null) {
// 创建 Environment 变量名 List
List<String> environmentVarNameList = new ArrayList<>();
sModuleNameMap.put(moduleName, environmentVarNameList);
// 创建私有常量变量
// private static final ModuleBean MODULE_XXX = new ModuleBean();
FieldSpec moduleField = FieldSpec
.builder(ModuleBean.class, _getModuleVarName_UpperCase(moduleName))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer("new $T($S, $S)", ModuleBean.class, moduleName, moduleAlias)
.addJavadoc(String.format("[ Module ] name: %s, alias: %s\n", moduleName, moduleAlias))
.build();
classBuilder.addField(moduleField);
// 创建 Module Environment 数据
builderModuleEnvironment_DATA(classBuilder, moduleElement, environmentElement);
}
}
/**
* 创建 Module Environment 数据
* @param classBuilder DevEnvironment 类构建对象
* @param moduleElement 使用注解修饰的 Module Element
* @param environmentElement 使用注解修饰的 Environment Element
*/
public static void builderModuleEnvironment_DATA(
final TypeSpec.Builder classBuilder,
final Element moduleElement,
final Element environmentElement
) {
// Module 信息
String moduleName = moduleElement.getSimpleName().toString();
// Environment 信息
Environment environmentAnnotation = environmentElement.getAnnotation(Environment.class);
String environmentName = environmentElement.getSimpleName().toString();
String environmentValue = environmentAnnotation.value();
String environmentAlias = environmentAnnotation.alias();
// 创建私有常量变量
// private static final EnvironmentBean ENVIRONMENT_MODULENAME_XXX = new EnvironmentBean();
FieldSpec environmentField = FieldSpec
.builder(EnvironmentBean.class, _getEnvironmentVarName_UpperCase(moduleName, environmentName))
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer("new $T($S, $S, $S, $N)", EnvironmentBean.class, environmentName,
environmentValue, environmentAlias, _getModuleVarName_UpperCase(moduleName))
.addJavadoc(String.format("[ Environment ] name: %s, alias: %s, [ Module ] name: %s\n",
environmentName, environmentAlias, moduleName))
.build();
classBuilder.addField(environmentField);
// 记录 Environment 变量名 ( 传入的 environmentElement ) 属于 Release Environment Element 存储在 index 0
sModuleNameMap.get(moduleName).add(_getEnvironmentVarName_UpperCase(moduleName, environmentName));
}
/**
* 构建 Reset 方法
* @param classBuilder DevEnvironment 类构建对象
*/
public static void builderResetMethod(final TypeSpec.Builder classBuilder) {
// 构建 reset 实现代码
CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
codeBlockBuilder.add("if ($N != null && $N($N)) {\n", VAR_CONTEXT, METHOD_DELETE_STORAGE_DIR, VAR_CONTEXT);
codeBlockBuilder.add(" return true;\n");
codeBlockBuilder.add("}\n");
// public static final void reset() {}
MethodSpec resetMethod = MethodSpec
.methodBuilder(METHOD_RESET)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.addCode(codeBlockBuilder.build())
.returns(Boolean.class)
.addStatement("return false")
.addJavadoc("重置操作\n")
.addJavadoc("<p>Reset Operating\n")
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(resetMethod);
}
/**
* 构建 isRelease 方法
* @param classBuilder DevEnvironment 类构建对象
*/
public static void builderIsReleaseMethod(final TypeSpec.Builder classBuilder) {
// public static final Boolean isRelease() {}
MethodSpec isReleaseMethod = MethodSpec
.methodBuilder(METHOD_IS_RELEASE)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return true")
.addJavadoc("是否使用 releaseAnnotationProcessor 构建\n")
.addJavadoc("<p>Whether Release Annotation Processor Compile\n")
.addJavadoc("@return {@code true} yes, {@code false} no\n")
.build();
classBuilder.addMethod(isReleaseMethod);
}
/**
* 构建 static{} 初始化代码
* @param classBuilder DevEnvironment 类构建对象
*/
public static void builderStaticInit(final TypeSpec.Builder classBuilder) {
// 创建 Module List 集合变量
FieldSpec moduleListField = FieldSpec
.builder(_getListType(ModuleBean.class), VAR_MODULE_LIST, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
// .initializer("new $T<$T>()", ArrayList.class, ModuleBean.class)
.addJavadoc("Module List\n")
.build();
classBuilder.addField(moduleListField);
if (!sModuleNameMap.isEmpty()) {
// 构建 static {} 初始化代码
CodeBlock.Builder staticCodeBlockBuilder = CodeBlock.builder();
// 创建 module List 集合 VAR_MODULELIST
staticCodeBlockBuilder.addStatement("List<$T> $N = new $T<>()", ModuleBean.class,
VAR_MODULELIST, ArrayList.class);
Iterator<Map.Entry<String, List<String>>> iterator = sModuleNameMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, List<String>> entry = iterator.next();
// Module 名
String moduleName = entry.getKey();
// Environment 变量名 ( 因为 release 只能有一个, 这里直接获取 0 )
String environmentVarName = entry.getValue().get(0);
// 添加 moduleVarName 到 VAR_MODULELIST 中
staticCodeBlockBuilder.add("\n")
.addStatement("$N.add($N)", VAR_MODULELIST, _getModuleVarName_UpperCase(moduleName));
// 添加 Environment 到对应 ModuleBean.getEnvironments() 中
staticCodeBlockBuilder.addStatement("$N.$N().add($N)", _getModuleVarName_UpperCase(moduleName),
METHOD_GET_MODULE_ENVIRONMENTS_LIST, environmentVarName);
}
// 初始化 Module List 集合变量 VAR_MODULE_LIST
staticCodeBlockBuilder.add("\n")
.addStatement("$N = $T.unmodifiableList($N)", VAR_MODULE_LIST, Collections.class, VAR_MODULELIST);
// 创建代码
classBuilder.addStaticBlock(staticCodeBlockBuilder.build());
}
}
/**
* 构建 getXxx 方法代码
* @param classBuilder DevEnvironment 类构建对象
*/
public static void builderGetMethod(final TypeSpec.Builder classBuilder) {
// public static final List<ModuleBean> getModuleList() {}
MethodSpec getModuleListMethod = MethodSpec
.methodBuilder(METHOD_GET_MODULE_LIST)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.returns(_getListType(ModuleBean.class))
.addStatement("return $N", VAR_MODULE_LIST)
.addJavadoc("获取全部 $N 配置列表\n", ModuleBean.class.getSimpleName())
.addJavadoc("<p>Get All $N List\n", ModuleBean.class.getSimpleName())
.addJavadoc("@return List<$N>\n", ModuleBean.class.getSimpleName())
.build();
classBuilder.addMethod(getModuleListMethod);
// 创建 Module Environment get 方法
Iterator<Map.Entry<String, List<String>>> iterator = sModuleNameMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, List<String>> entry = iterator.next();
// Module 名
String moduleName = entry.getKey();
// Environment 变量名 ( 因为 release 只能有一个, 这里直接获取 0 )
String environmentVarName = entry.getValue().get(0);
// public static final ModuleBean getModule() {}
String getModuleMethodName = "get" + moduleName + STR_MODULE;
MethodSpec getModuleMethod = MethodSpec
.methodBuilder(getModuleMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.returns(ModuleBean.class)
.addStatement("return $N", _getModuleVarName_UpperCase(moduleName))
.addJavadoc("获取 $N [ Module ] Bean\n", moduleName)
.addJavadoc("<p>Get $N [ Module ] Bean\n", moduleName)
.addJavadoc("@return $N [ Module ] Bean\n", moduleName)
.build();
classBuilder.addMethod(getModuleMethod);
// =
// public static final EnvironmentBean getModuleReleaseEnvironment() {}
String getModuleReleaseEnvironmentMethodName = "get" + moduleName + STR_RELEASE_ENVIRONMENT;
MethodSpec getModuleReleaseEnvironmentMethod = MethodSpec
.methodBuilder(getModuleReleaseEnvironmentMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.returns(EnvironmentBean.class)
.addStatement("return $N", environmentVarName)
.addJavadoc("获取 $N [ Module ] Release Environment Bean\n", moduleName)
.addJavadoc("<p>Get $N [ Module ] Release Environment Bean\n", moduleName)
.addJavadoc("@return $N [ Module ] Release Environment Bean\n", moduleName)
.build();
classBuilder.addMethod(getModuleReleaseEnvironmentMethod);
// =
// public static final EnvironmentBean getModuleEnvironment(final Context context) {}
String getModuleEnvironmentMethodName = "get" + moduleName + STR_ENVIRONMENT;
MethodSpec getModuleEnvironmentMethod = MethodSpec
.methodBuilder(getModuleEnvironmentMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.returns(EnvironmentBean.class)
.addStatement("return $N()", getModuleReleaseEnvironmentMethodName)
.addJavadoc("获取 $N [ Module ] Selected Environment Bean\n", moduleName)
.addJavadoc("<p>Get $N [ Module ] Selected Environment Bean\n", moduleName)
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return $N [ Module ] Selected Environment Bean\n", moduleName)
.build();
classBuilder.addMethod(getModuleEnvironmentMethod);
// =
// public static final String getModuleEnvironmentValue(final Context context) {}
String getModuleEnvironmentValueMethodName = "get" + moduleName + STR_ENVIRONMENT_VALUE;
MethodSpec getModuleEnvironmentValueMethod = MethodSpec
.methodBuilder(getModuleEnvironmentValueMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.returns(String.class)
.addStatement("return $N($N).$N()", getModuleEnvironmentMethodName, VAR_CONTEXT, METHOD_GET_ENVIRONMENTS_VALUE)
.addJavadoc("获取 $N [ Module ] Selected Environment Value\n", moduleName)
.addJavadoc("<p>Get $N [ Module ] Selected Environment Value\n", moduleName)
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return $N [ Module ] Selected Environment Value\n", moduleName)
.build();
classBuilder.addMethod(getModuleEnvironmentValueMethod);
// =
// public static final Boolean setModuleEnvironment(final Context context, final EnvironmentBean newEnvironment) {}
String setModuleEnvironmentMethodName = "set" + moduleName + STR_ENVIRONMENT;
MethodSpec setModuleEnvironmentMethod = MethodSpec
.methodBuilder(setModuleEnvironmentMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.addParameter(EnvironmentBean.class, VAR_NEW_ENVIRONMENT, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return false")
.addJavadoc("设置 $N [ Module ] Selected Environment Bean\n", moduleName)
.addJavadoc("<p>Set $N [ Module ] Selected Environment Bean\n", moduleName)
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@param $N environment bean\n", VAR_NEW_ENVIRONMENT)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(setModuleEnvironmentMethod);
// =
// public static final Boolean resetModule(final Context context) {}
String resetModuleMethodName = METHOD_RESET + moduleName;
MethodSpec resetModuleMethod = MethodSpec
.methodBuilder(resetModuleMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return false")
.addJavadoc("重置 $N [ Module ] Selected Environment Bean\n", moduleName)
.addJavadoc("<p>Reset $N [ Module ] Selected Environment Bean\n", moduleName)
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(resetModuleMethod);
// =
// public static final Boolean isModuleAnnotation(final Context context) {}
String isModuleAnnotationMethodName = String.format(METHOD_IS_ANNOTATION, moduleName);
MethodSpec isModuleAnnotationMethod = MethodSpec
.methodBuilder(isModuleAnnotationMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return true")
.addJavadoc("是否 $N [ Module ] Annotation Environment Bean\n", moduleName)
.addJavadoc("<p>Whether $N [ Module ] Annotation Environment Bean\n", moduleName)
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(isModuleAnnotationMethod);
}
}
/**
* 构建模块环境改变触发事件方法
* @param classBuilder DevEnvironment 类构建对象
*/
public static void builderEnvironmentChangeListener(final TypeSpec.Builder classBuilder) {
// public static final Boolean addOnEnvironmentChangeListener(final OnEnvironmentChangeListener listener) {}
MethodSpec addOnEnvironmentChangeListenerMethod = MethodSpec
.methodBuilder(METHOD_ADD_ONENVIRONMENT_CHANGE_LISTENER)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(OnEnvironmentChangeListener.class, VAR_LISTENER, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return false")
.addJavadoc("添加模块环境改变触发事件\n")
.addJavadoc("<p>Add Environment Change Listener\n")
.addJavadoc("@param $N environment change listener\n", VAR_LISTENER)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(addOnEnvironmentChangeListenerMethod);
// =
// public static final Boolean removeOnEnvironmentChangeListener(final OnEnvironmentChangeListener listener) {}
MethodSpec removeOnEnvironmentChangeListenerMethod = MethodSpec
.methodBuilder(METHOD_REMOVE_ONENVIRONMENT_CHANGE_LISTENER)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addParameter(OnEnvironmentChangeListener.class, VAR_LISTENER, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return false")
.addJavadoc("移除模块环境改变触发事件\n")
.addJavadoc("<p>Remove Environment Change Listener\n")
.addJavadoc("@param $N environment change listener\n", VAR_LISTENER)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(removeOnEnvironmentChangeListenerMethod);
// =
// public static final Boolean clearOnEnvironmentChangeListener() {}
MethodSpec clearOnEnvironmentChangeListenerMethod = MethodSpec
.methodBuilder(METHOD_CLEAR_ONENVIRONMENT_CHANGE_LISTENER)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.returns(Boolean.class)
.addStatement("return false")
.addJavadoc("清空模块环境改变触发事件\n")
.addJavadoc("<p>Clear All Environment Change Listener\n")
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(clearOnEnvironmentChangeListenerMethod);
}
/**
* 构建存储相关方法
* @param classBuilder DevEnvironment 类构建对象
*/
public static void builderStorageMethod(final TypeSpec.Builder classBuilder) {
// 构建 getStorageDir 实现代码
CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
codeBlockBuilder.add("try {\n");
codeBlockBuilder.add(" File file = new File($N.getCacheDir(), $S);\n", VAR_CONTEXT, ENVIRONMENT_FILE_NAME);
codeBlockBuilder.add(" if (!file.exists()) file.mkdirs();\n");
codeBlockBuilder.add(" return file;\n");
codeBlockBuilder.add("} catch (Exception e) {\n");
codeBlockBuilder.add(" $T.printStackTrace(e);\n", LogUtils.class);
codeBlockBuilder.add("}\n");
// private static final File getStorageDir(final Context context) {}
MethodSpec getStorageDirMethod = MethodSpec
.methodBuilder(METHOD_GET_STORAGE_DIR)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.returns(File.class)
.addCode(codeBlockBuilder.build())
.addStatement("return null")
.addJavadoc("获取环境配置存储路径 - path /data/data/package/cache/$N\n", ENVIRONMENT_FILE_NAME)
.addJavadoc("<p>Get Environment Configure Storage Dir - path /data/data/package/cache/$N\n", ENVIRONMENT_FILE_NAME)
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return /data/data/package/cache/$N\n", ENVIRONMENT_FILE_NAME)
.build();
classBuilder.addMethod(getStorageDirMethod);
// =
// 构建 deleteStorageDir 实现代码
codeBlockBuilder = CodeBlock.builder();
codeBlockBuilder.add("try {\n");
codeBlockBuilder.add(" File storage = $N($N);\n", METHOD_GET_STORAGE_DIR, VAR_CONTEXT);
codeBlockBuilder.add(" if (storage != null) {\n");
codeBlockBuilder.add(" String[] strs = storage.list();\n");
codeBlockBuilder.add(" for (String fileName : strs) {\n");
codeBlockBuilder.add(" File file = new File(storage, fileName);\n");
codeBlockBuilder.add(" if (!file.isDirectory()) file.delete();\n");
codeBlockBuilder.add(" }\n");
codeBlockBuilder.add(" return true;\n");
codeBlockBuilder.add(" }\n");
codeBlockBuilder.add("} catch (Exception e) {\n");
codeBlockBuilder.add(" $T.printStackTrace(e);\n", LogUtils.class);
codeBlockBuilder.add("}\n");
// private static final Boolean deleteStorageDir(final Context context) {}
MethodSpec deleteStorageDirMethod = MethodSpec
.methodBuilder(METHOD_DELETE_STORAGE_DIR)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
.returns(Boolean.class)
.addCode(codeBlockBuilder.build())
.addStatement("return false")
.addJavadoc("删除环境存储配置文件\n")
.addJavadoc("<p>Delete Environment Storage Configure File\n")
.addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
.addJavadoc("@return {@code true} success, {@code false} fail\n")
.build();
classBuilder.addMethod(deleteStorageDirMethod);
}
// ===========
// = 其他方法 =
// ===========
/**
* 获取 Module Release Environment 数据
* @param moduleElement 使用注解修饰的 Module Element
* @param processingEnv {@link ProcessingEnvironment}
* @return Module Release Environment 数据
*/
private static Element _getModuleReleaseEnvironment(
final Element moduleElement,
final ProcessingEnvironment processingEnv
)
throws Exception {
Element environmentElement = null;
List<? extends Element> allMembers = processingEnv.getElementUtils().getAllMembers((TypeElement) moduleElement);
for (Element member : allMembers) {
Environment environmentAnnotation = member.getAnnotation(Environment.class);
if (environmentAnnotation == null) continue;
if (environmentAnnotation.isRelease()) {
if (environmentElement != null) { // 每个 Module 只能有一个 release 环境配置
String moduleName = moduleElement.getSimpleName().toString();
throw new Exception(moduleName + " module can be only one release environment configuration ( 每个 Module 只能有一个 release 环境配置 )");
}
environmentElement = member;
}
}
if (environmentElement == null) { // 每个 Module 必须有一个 release 环境配置
String moduleName = moduleElement.getSimpleName().toString();
throw new Exception(moduleName + " module must have a release environment configuration ( 每个 Module 必须有一个 release 环境配置 )");
}
return environmentElement;
}
/**
* 获取 List Type
* @param type Bean.class
* @return List<Bean> Type
*/
private static Type _getListType(final Class<?> type) {
return new ParameterizedTypeImpl(new Type[]{type}, null, List.class);
}
/**
* 获取 Module 拼接变量名
* @param moduleName Module Name
* @return Module 拼接变量名
*/
private static String _getModuleVarName_UpperCase(final String moduleName) {
return VAR_MODULE_PREFIX + moduleName.toUpperCase();
}
/**
* 获取 Environment 拼接变量名
* @param moduleName Module Name
* @param environmentName Environment Name
* @return Environment 拼接变量名
*/
private static String _getEnvironmentVarName_UpperCase(
final String moduleName,
final String environmentName
) {
return VAR_ENVIRONMENT_PREFIX + moduleName.toUpperCase() + "_" + environmentName.toUpperCase();
}
}
|
DarkShadow44/kaitai_struct_tests
|
spec/python/test_integers_min_max.py
|
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from integers_min_max import IntegersMinMax
class TestIntegersMinMax(unittest.TestCase):
def test_integers_min_max(self):
with IntegersMinMax.from_file('src/integers_min_max.bin') as r:
self.assertEqual(r.unsigned_min.u1, 0)
self.assertEqual(r.unsigned_min.u2le, 0)
self.assertEqual(r.unsigned_min.u4le, 0)
self.assertEqual(r.unsigned_min.u8le, 0)
self.assertEqual(r.unsigned_min.u2be, 0)
self.assertEqual(r.unsigned_min.u4be, 0)
self.assertEqual(r.unsigned_min.u8be, 0)
self.assertEqual(r.unsigned_max.u1, 255)
self.assertEqual(r.unsigned_max.u2le, 65535)
self.assertEqual(r.unsigned_max.u4le, 4294967295)
self.assertEqual(r.unsigned_max.u8le, 18446744073709551615)
self.assertEqual(r.unsigned_max.u2be, 65535)
self.assertEqual(r.unsigned_max.u4be, 4294967295)
self.assertEqual(r.unsigned_max.u8be, 18446744073709551615)
self.assertEqual(r.signed_min.s1, -128)
self.assertEqual(r.signed_min.s2le, -32768)
self.assertEqual(r.signed_min.s4le, -2147483648)
self.assertEqual(r.signed_min.s8le, -9223372036854775808)
self.assertEqual(r.signed_min.s2be, -32768)
self.assertEqual(r.signed_min.s4be, -2147483648)
self.assertEqual(r.signed_min.s8be, -9223372036854775808)
self.assertEqual(r.signed_max.s1, 127)
self.assertEqual(r.signed_max.s2le, 32767)
self.assertEqual(r.signed_max.s4le, 2147483647)
self.assertEqual(r.signed_max.s8le, 9223372036854775807)
self.assertEqual(r.signed_max.s2be, 32767)
self.assertEqual(r.signed_max.s4be, 2147483647)
self.assertEqual(r.signed_max.s8be, 9223372036854775807)
|
NengLu/topopy
|
test/temp/test_get_stream_segments.py
|
<reponame>NengLu/topopy
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 09:42:34 2018
@author: vicen
"""
import sys
sys.path.append("../../")
from topopy import Flow, Grid
import numpy as np
from scipy.sparse import csc_matrix
fd = Flow()
fd.load_gtiff("../data/tunez_fd.tif")
threshold = 1000
def get_stream_segments(self, threshold, asgrid=True):
"""
TODO - Write documentation
"""
# Create the flow accumulation file
fac = fd.get_flow_accumulation(nodata = False, asgrid=False)
w = fac > threshold
# Build a sparse array with giver-receivers cells
w = w.ravel()
I = w[fd._ix]
ix = fd._ix[I]
ixc = fd._ixc[I]
aux_vals = np.ones(ix.shape, dtype=np.int8)
# We don't use get_stream_poi because it implies creating the flow accumulation 3x
sp_arr = csc_matrix((aux_vals, (ix, ixc)), shape=(fd._ncells, fd._ncells))
del I, aux_vals, fac # Clean up
# Get heads
sum_arr = np.asarray(np.sum(sp_arr, 0)).ravel()
head_pos = (sum_arr == 0) & w
head_ind = np.where(head_pos)
# Get confluences
sum_arr = np.asarray(np.sum(sp_arr, 0)).ravel()
conf_pos = sum_arr > 1
conf_ind = np.where(conf_pos)
del sum_arr, sp_arr, w, conf_pos, head_pos # Clean up
# Merge all heads and confluences
all_ind = np.append(head_ind, conf_ind)
del conf_ind, head_ind # Clean up
# We created a zeros arrays and put in confuences and heads their id
# Those id will be consecutive numbers starting in one
seg_arr = np.zeros(fd._ncells, dtype=np.int32)
for n, inds in enumerate(all_ind):
seg_arr[inds] = n+1
# Move throught giver list. If receiver is 0, give the same id that giver.
# If a receiver is not 0, that means that we are in a confluence.
for n in range(len(ix)):
if seg_arr[ixc[n]] == 0:
seg_arr[ixc[n]] = seg_arr[ix[n]]
# Reshape and output
seg_arr = seg_arr.reshape(fd._dims)
if asgrid:
return fd._create_output_grid(seg_arr, 0)
else:
return seg_arr
links = get_stream_segments(threshold, True)
links.save("tunez_segments.tif")
|
aaronstanek/UltralightweightCalculator
|
docs/html/search/files_0.js
|
<reponame>aaronstanek/UltralightweightCalculator
var searchData=
[
['arithmetic_2ecpp_210',['Arithmetic.cpp',['../_arithmetic_8cpp.html',1,'']]],
['assign_2ecpp_211',['Assign.cpp',['../_assign_8cpp.html',1,'']]]
];
|
FranicevicNikola/OOP
|
Nikola/Laboratory/src/main/java/com/nikolafranicevic/lambdaComparator/GardenMain.java
|
<filename>Nikola/Laboratory/src/main/java/com/nikolafranicevic/lambdaComparator/GardenMain.java
package com.nikolafranicevic.lambdaComparator;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
public class GardenMain {
public static void main(String[] args) {
List<Plant> pList1 = new ArrayList<>();
pList1.add(new Plant("Leucanthemum vulgare", "Ivancica"));
pList1.add(new Plant("Pinus cembra", "Limba"));
Garden g1 = new Garden("Bakin", pList1);
List<Plant> pList2 = new ArrayList<>();
pList2.add(new Plant("Calendula officinalis", "Neven"));
pList2.add(new Plant("Pinus cembra", "Limba"));
Garden g2 = new Garden("Mamin", pList2);
BiFunction<Garden, Garden, Integer> checkBiFunction = Task.numberOfSamePlantsFunction();
System.out.println(checkBiFunction.apply(g1, g2));
System.out.println(g1.toString());
BiConsumer<Garden, List<Plant>> checkBiConsumer = Task.saveDeliveredPlantsFunction();
checkBiConsumer.accept(g1, pList2);
System.out.println(g1.toString());
}
}
|
willcode/PothosComms
|
math/SIMD/Beta.cpp
|
<reponame>willcode/PothosComms
// Copyright (c) 2020 <NAME>
// SPDX-License-Identifier: BSD-3-Clause
#include <xsimd/xsimd.hpp>
#include <Pothos/Util/XSIMDTraits.hpp>
#include <cmath>
// Actually enforce EnableIf*
#ifdef _MSC_VER
#pragma warning(error: 4667) // no function template defined that matches forced instantiation
#endif
#if !defined POTHOS_SIMD_NAMESPACE
#error Must define POTHOS_SIMD_NAMESPACE to build this file
#endif
namespace PothosCommsSIMD { namespace POTHOS_SIMD_NAMESPACE {
namespace detail
{
template <typename T>
static void betaUnoptimized(const T* in0, const T* in1, T* out, size_t len)
{
for (size_t elem = 0; elem < len; ++elem)
{
#if __cplusplus >= 201703L
out[elem] = std::beta(in0[elem], in1[elem]);
#else
out[elem] = std::exp(std::lgamma(in0[elem]) + std::lgamma(in1[elem]) - std::lgamma(in0[elem] + in1[elem]));
#endif
}
}
template <typename T>
static Pothos::Util::EnableIfXSIMDSupports<T, void> beta(const T* in0, const T* in1, T* out, size_t len)
{
static constexpr size_t simdSize = xsimd::simd_traits<T>::size;
const auto numSIMDFrames = len / simdSize;
const T* in0Ptr = in0;
const T* in1Ptr = in1;
T* outPtr = out;
for (size_t frameIndex = 0; frameIndex < numSIMDFrames; ++frameIndex)
{
auto in0Reg = xsimd::load_unaligned(in0Ptr);
auto in1Reg = xsimd::load_unaligned(in1Ptr);
auto outReg = xsimd::exp(xsimd::lgamma(in0Reg) + xsimd::lgamma(in1Reg) - xsimd::lgamma(in0Reg + in1Reg));
outReg.store_unaligned(outPtr);
in0Ptr += simdSize;
in1Ptr += simdSize;
outPtr += simdSize;
}
// Perform remaining operations manually.
betaUnoptimized(in0Ptr, in1Ptr, outPtr, (len - (in0Ptr - in0)));
}
template <typename T>
static Pothos::Util::EnableIfXSIMDDoesNotSupport<T, void> beta(const T* in0, const T* in1, T* out, size_t len)
{
betaUnoptimized(in0, in1, out, len);
}
}
// Hide the SFINAE
template <typename T>
void beta(const T* in0, const T* in1, T* out, size_t len)
{
detail::beta(in0, in1, out, len);
}
#define BETA(T) template void beta(const T*, const T*, T*, size_t);
BETA(float)
BETA(double)
}}
|
AlexRogalskiy/DevArtifacts
|
master/protocode4-master/protocode4-master/app/scripts/controllers/controller_ui_phone_control_index_label_control_scene.js
|
/*
templates/scene/control_label.hbs
*/
App.SceneControlLabelController = App.ControlLabelIndexController.extend();
|
mbheinen/CIMApplication
|
CIMWeb/src/main/webapp/js/model/WindDynamics.js
|
define
(
["model/base", "model/Core", "model/StandardModels"],
/**
* Wind turbines are generally divided into four types, which are currently significant in power systems.
*
* The four types have the following characteristics:
* - type 1: wind turbine with directly grid connected asynchronous generator with fixed rotor resistance (typically squirrel cage);
* - type 2: wind turbine with directly grid connected asynchronous generator with variable rotor resistance;
* - type 3: wind turbines with doubly-fed asynchronous generators (directly connected stator and rotor connected through power converter);
* - type 4: wind turbines connected to the grid through a full size power converter.
* Models included in this package are according to IEC 61400-27-1:2015.
*
*/
function (base, Core, StandardModels)
{
/**
* Function of the lookup table.
*
*/
let WindLookupTableFunctionKind =
{
"prr": "prr",
"omegap": "omegap",
"ipmax": "ipmax",
"iqmax": "iqmax",
"pwp": "pwp",
"tcwdu": "tcwdu",
"tduwt": "tduwt",
"qmaxp": "qmaxp",
"qminp": "qminp",
"qmaxu": "qmaxu",
"qminu": "qminu",
"tuover": "tuover",
"tuunder": "tuunder",
"tfover": "tfover",
"tfunder": "tfunder",
"qwp": "qwp"
};
Object.freeze (WindLookupTableFunctionKind);
/**
* UVRT Q control modes <i>M</i><i><sub>qUVRT</sub></i><i>.</i>
*
*/
let WindUVRTQcontrolModeKind =
{
"mode0": "mode0",
"mode1": "mode1",
"mode2": "mode2"
};
Object.freeze (WindUVRTQcontrolModeKind);
/**
* General wind turbine Q control modes <i>M</i><i><sub>qG</sub></i><i>.</i>
*
*/
let WindQcontrolModeKind =
{
"voltage": "voltage",
"reactivePower": "reactivePower",
"openLoopReactivePower": "openLoopReactivePower",
"powerFactor": "powerFactor",
"openLooppowerFactor": "openLooppowerFactor"
};
Object.freeze (WindQcontrolModeKind);
/**
* Reactive power/voltage controller mode.
*
*/
let WindPlantQcontrolModeKind =
{
"reactivePower": "reactivePower",
"powerFactor": "powerFactor",
"uqStatic": "uqStatic",
"voltageControl": "voltageControl"
};
Object.freeze (WindPlantQcontrolModeKind);
/**
* Two mass model.
*
* Reference: IEC 61400-27-1:2015, 5.6.2.1.
*
*/
class WindMechIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindMechIEC;
if (null == bucket)
cim_data.WindMechIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindMechIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindMechIEC";
base.parse_element (/<cim:WindMechIEC.cdrt>([\s\S]*?)<\/cim:WindMechIEC.cdrt>/g, obj, "cdrt", base.to_string, sub, context);
base.parse_element (/<cim:WindMechIEC.hgen>([\s\S]*?)<\/cim:WindMechIEC.hgen>/g, obj, "hgen", base.to_string, sub, context);
base.parse_element (/<cim:WindMechIEC.hwtr>([\s\S]*?)<\/cim:WindMechIEC.hwtr>/g, obj, "hwtr", base.to_string, sub, context);
base.parse_element (/<cim:WindMechIEC.kdrt>([\s\S]*?)<\/cim:WindMechIEC.kdrt>/g, obj, "kdrt", base.to_string, sub, context);
base.parse_attribute (/<cim:WindMechIEC.WindTurbineType1or2IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType1or2IEC", sub, context);
base.parse_attribute (/<cim:WindMechIEC.WindTurbineType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3IEC", sub, context);
base.parse_attribute (/<cim:WindMechIEC.WindTurbineType4bIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType4bIEC", sub, context);
let bucket = context.parsed.WindMechIEC;
if (null == bucket)
context.parsed.WindMechIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindMechIEC", "cdrt", "cdrt", base.from_string, fields);
base.export_element (obj, "WindMechIEC", "hgen", "hgen", base.from_string, fields);
base.export_element (obj, "WindMechIEC", "hwtr", "hwtr", base.from_string, fields);
base.export_element (obj, "WindMechIEC", "kdrt", "kdrt", base.from_string, fields);
base.export_attribute (obj, "WindMechIEC", "WindTurbineType1or2IEC", "WindTurbineType1or2IEC", fields);
base.export_attribute (obj, "WindMechIEC", "WindTurbineType3IEC", "WindTurbineType3IEC", fields);
base.export_attribute (obj, "WindMechIEC", "WindTurbineType4bIEC", "WindTurbineType4bIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindMechIEC_collapse" aria-expanded="true" aria-controls="WindMechIEC_collapse" style="margin-left: 10px;">WindMechIEC</a></legend>
<div id="WindMechIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#cdrt}}<div><b>cdrt</b>: {{cdrt}}</div>{{/cdrt}}
{{#hgen}}<div><b>hgen</b>: {{hgen}}</div>{{/hgen}}
{{#hwtr}}<div><b>hwtr</b>: {{hwtr}}</div>{{/hwtr}}
{{#kdrt}}<div><b>kdrt</b>: {{kdrt}}</div>{{/kdrt}}
{{#WindTurbineType1or2IEC}}<div><b>WindTurbineType1or2IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType1or2IEC}}");}); return false;'>{{WindTurbineType1or2IEC}}</a></div>{{/WindTurbineType1or2IEC}}
{{#WindTurbineType3IEC}}<div><b>WindTurbineType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3IEC}}");}); return false;'>{{WindTurbineType3IEC}}</a></div>{{/WindTurbineType3IEC}}
{{#WindTurbineType4bIEC}}<div><b>WindTurbineType4bIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType4bIEC}}");}); return false;'>{{WindTurbineType4bIEC}}</a></div>{{/WindTurbineType4bIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindMechIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindMechIEC_collapse" style="margin-left: 10px;">WindMechIEC</a></legend>
<div id="{{id}}_WindMechIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_cdrt'>cdrt: </label><div class='col-sm-8'><input id='{{id}}_cdrt' class='form-control' type='text'{{#cdrt}} value='{{cdrt}}'{{/cdrt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_hgen'>hgen: </label><div class='col-sm-8'><input id='{{id}}_hgen' class='form-control' type='text'{{#hgen}} value='{{hgen}}'{{/hgen}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_hwtr'>hwtr: </label><div class='col-sm-8'><input id='{{id}}_hwtr' class='form-control' type='text'{{#hwtr}} value='{{hwtr}}'{{/hwtr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kdrt'>kdrt: </label><div class='col-sm-8'><input id='{{id}}_kdrt' class='form-control' type='text'{{#kdrt}} value='{{kdrt}}'{{/kdrt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType1or2IEC'>WindTurbineType1or2IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType1or2IEC' class='form-control' type='text'{{#WindTurbineType1or2IEC}} value='{{WindTurbineType1or2IEC}}'{{/WindTurbineType1or2IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3IEC'>WindTurbineType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3IEC' class='form-control' type='text'{{#WindTurbineType3IEC}} value='{{WindTurbineType3IEC}}'{{/WindTurbineType3IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType4bIEC'>WindTurbineType4bIEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType4bIEC' class='form-control' type='text'{{#WindTurbineType4bIEC}} value='{{WindTurbineType4bIEC}}'{{/WindTurbineType4bIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindMechIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_cdrt").value; if ("" !== temp) obj["cdrt"] = temp;
temp = document.getElementById (id + "_hgen").value; if ("" !== temp) obj["hgen"] = temp;
temp = document.getElementById (id + "_hwtr").value; if ("" !== temp) obj["hwtr"] = temp;
temp = document.getElementById (id + "_kdrt").value; if ("" !== temp) obj["kdrt"] = temp;
temp = document.getElementById (id + "_WindTurbineType1or2IEC").value; if ("" !== temp) obj["WindTurbineType1or2IEC"] = temp;
temp = document.getElementById (id + "_WindTurbineType3IEC").value; if ("" !== temp) obj["WindTurbineType3IEC"] = temp;
temp = document.getElementById (id + "_WindTurbineType4bIEC").value; if ("" !== temp) obj["WindTurbineType4bIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType1or2IEC", "0..1", "1", "WindTurbineType1or2IEC", "WindMechIEC"],
["WindTurbineType3IEC", "0..1", "1", "WindTurbineType3IEC", "WindMechIEC"],
["WindTurbineType4bIEC", "0..1", "1", "WindTurbineType4bIEC", "WindMechIEC"]
]
)
);
}
}
/**
* Constant aerodynamic torque model which assumes that the aerodynamic torque is constant.
*
* Reference: IEC 61400-27-1:2015, 5.6.1.1.
*
*/
class WindAeroConstIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindAeroConstIEC;
if (null == bucket)
cim_data.WindAeroConstIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindAeroConstIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindAeroConstIEC";
base.parse_attribute (/<cim:WindAeroConstIEC.WindGenTurbineType1aIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenTurbineType1aIEC", sub, context);
let bucket = context.parsed.WindAeroConstIEC;
if (null == bucket)
context.parsed.WindAeroConstIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindAeroConstIEC", "WindGenTurbineType1aIEC", "WindGenTurbineType1aIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindAeroConstIEC_collapse" aria-expanded="true" aria-controls="WindAeroConstIEC_collapse" style="margin-left: 10px;">WindAeroConstIEC</a></legend>
<div id="WindAeroConstIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#WindGenTurbineType1aIEC}}<div><b>WindGenTurbineType1aIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenTurbineType1aIEC}}");}); return false;'>{{WindGenTurbineType1aIEC}}</a></div>{{/WindGenTurbineType1aIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindAeroConstIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindAeroConstIEC_collapse" style="margin-left: 10px;">WindAeroConstIEC</a></legend>
<div id="{{id}}_WindAeroConstIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenTurbineType1aIEC'>WindGenTurbineType1aIEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenTurbineType1aIEC' class='form-control' type='text'{{#WindGenTurbineType1aIEC}} value='{{WindGenTurbineType1aIEC}}'{{/WindGenTurbineType1aIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindAeroConstIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindGenTurbineType1aIEC").value; if ("" !== temp) obj["WindGenTurbineType1aIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindGenTurbineType1aIEC", "1", "1", "WindGenTurbineType1aIEC", "WindAeroConstIEC"]
]
)
);
}
}
/**
* Current limitation model.
*
* The current limitation model combines the physical limits and the control limits.
* Reference: IEC 61400-27-1:2015, 5.6.5.8.
*
*/
class WindContCurrLimIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContCurrLimIEC;
if (null == bucket)
cim_data.WindContCurrLimIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContCurrLimIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContCurrLimIEC";
base.parse_element (/<cim:WindContCurrLimIEC.imax>([\s\S]*?)<\/cim:WindContCurrLimIEC.imax>/g, obj, "imax", base.to_string, sub, context);
base.parse_element (/<cim:WindContCurrLimIEC.imaxdip>([\s\S]*?)<\/cim:WindContCurrLimIEC.imaxdip>/g, obj, "imaxdip", base.to_string, sub, context);
base.parse_element (/<cim:WindContCurrLimIEC.kpqu>([\s\S]*?)<\/cim:WindContCurrLimIEC.kpqu>/g, obj, "kpqu", base.to_string, sub, context);
base.parse_element (/<cim:WindContCurrLimIEC.mdfslim>([\s\S]*?)<\/cim:WindContCurrLimIEC.mdfslim>/g, obj, "mdfslim", base.to_boolean, sub, context);
base.parse_element (/<cim:WindContCurrLimIEC.mqpri>([\s\S]*?)<\/cim:WindContCurrLimIEC.mqpri>/g, obj, "mqpri", base.to_boolean, sub, context);
base.parse_element (/<cim:WindContCurrLimIEC.tufiltcl>([\s\S]*?)<\/cim:WindContCurrLimIEC.tufiltcl>/g, obj, "tufiltcl", base.to_string, sub, context);
base.parse_element (/<cim:WindContCurrLimIEC.upqumax>([\s\S]*?)<\/cim:WindContCurrLimIEC.upqumax>/g, obj, "upqumax", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContCurrLimIEC.WindTurbineType3or4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4IEC", sub, context);
base.parse_attributes (/<cim:WindContCurrLimIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
let bucket = context.parsed.WindContCurrLimIEC;
if (null == bucket)
context.parsed.WindContCurrLimIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContCurrLimIEC", "imax", "imax", base.from_string, fields);
base.export_element (obj, "WindContCurrLimIEC", "imaxdip", "imaxdip", base.from_string, fields);
base.export_element (obj, "WindContCurrLimIEC", "kpqu", "kpqu", base.from_string, fields);
base.export_element (obj, "WindContCurrLimIEC", "mdfslim", "mdfslim", base.from_boolean, fields);
base.export_element (obj, "WindContCurrLimIEC", "mqpri", "mqpri", base.from_boolean, fields);
base.export_element (obj, "WindContCurrLimIEC", "tufiltcl", "tufiltcl", base.from_string, fields);
base.export_element (obj, "WindContCurrLimIEC", "upqumax", "upqumax", base.from_string, fields);
base.export_attribute (obj, "WindContCurrLimIEC", "WindTurbineType3or4IEC", "WindTurbineType3or4IEC", fields);
base.export_attributes (obj, "WindContCurrLimIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContCurrLimIEC_collapse" aria-expanded="true" aria-controls="WindContCurrLimIEC_collapse" style="margin-left: 10px;">WindContCurrLimIEC</a></legend>
<div id="WindContCurrLimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#imax}}<div><b>imax</b>: {{imax}}</div>{{/imax}}
{{#imaxdip}}<div><b>imaxdip</b>: {{imaxdip}}</div>{{/imaxdip}}
{{#kpqu}}<div><b>kpqu</b>: {{kpqu}}</div>{{/kpqu}}
{{#mdfslim}}<div><b>mdfslim</b>: {{mdfslim}}</div>{{/mdfslim}}
{{#mqpri}}<div><b>mqpri</b>: {{mqpri}}</div>{{/mqpri}}
{{#tufiltcl}}<div><b>tufiltcl</b>: {{tufiltcl}}</div>{{/tufiltcl}}
{{#upqumax}}<div><b>upqumax</b>: {{upqumax}}</div>{{/upqumax}}
{{#WindTurbineType3or4IEC}}<div><b>WindTurbineType3or4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3or4IEC}}");}); return false;'>{{WindTurbineType3or4IEC}}</a></div>{{/WindTurbineType3or4IEC}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContCurrLimIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContCurrLimIEC_collapse" style="margin-left: 10px;">WindContCurrLimIEC</a></legend>
<div id="{{id}}_WindContCurrLimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_imax'>imax: </label><div class='col-sm-8'><input id='{{id}}_imax' class='form-control' type='text'{{#imax}} value='{{imax}}'{{/imax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_imaxdip'>imaxdip: </label><div class='col-sm-8'><input id='{{id}}_imaxdip' class='form-control' type='text'{{#imaxdip}} value='{{imaxdip}}'{{/imaxdip}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpqu'>kpqu: </label><div class='col-sm-8'><input id='{{id}}_kpqu' class='form-control' type='text'{{#kpqu}} value='{{kpqu}}'{{/kpqu}}></div></div>
<div class='form-group row'><div class='col-sm-4' for='{{id}}_mdfslim'>mdfslim: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_mdfslim' class='form-check-input' type='checkbox'{{#mdfslim}} checked{{/mdfslim}}></div></div></div>
<div class='form-group row'><div class='col-sm-4' for='{{id}}_mqpri'>mqpri: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_mqpri' class='form-check-input' type='checkbox'{{#mqpri}} checked{{/mqpri}}></div></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tufiltcl'>tufiltcl: </label><div class='col-sm-8'><input id='{{id}}_tufiltcl' class='form-control' type='text'{{#tufiltcl}} value='{{tufiltcl}}'{{/tufiltcl}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_upqumax'>upqumax: </label><div class='col-sm-8'><input id='{{id}}_upqumax' class='form-control' type='text'{{#upqumax}} value='{{upqumax}}'{{/upqumax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3or4IEC'>WindTurbineType3or4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3or4IEC' class='form-control' type='text'{{#WindTurbineType3or4IEC}} value='{{WindTurbineType3or4IEC}}'{{/WindTurbineType3or4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContCurrLimIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_imax").value; if ("" !== temp) obj["imax"] = temp;
temp = document.getElementById (id + "_imaxdip").value; if ("" !== temp) obj["imaxdip"] = temp;
temp = document.getElementById (id + "_kpqu").value; if ("" !== temp) obj["kpqu"] = temp;
temp = document.getElementById (id + "_mdfslim").checked; if (temp) obj["mdfslim"] = true;
temp = document.getElementById (id + "_mqpri").checked; if (temp) obj["mqpri"] = true;
temp = document.getElementById (id + "_tufiltcl").value; if ("" !== temp) obj["tufiltcl"] = temp;
temp = document.getElementById (id + "_upqumax").value; if ("" !== temp) obj["upqumax"] = temp;
temp = document.getElementById (id + "_WindTurbineType3or4IEC").value; if ("" !== temp) obj["WindTurbineType3or4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3or4IEC", "1", "1", "WindTurbineType3or4IEC", "WindContCurrLimIEC"],
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindContCurrLimIEC"]
]
)
);
}
}
/**
* IEC type 4 generator set model.
*
* Reference: IEC 61400-27-1:2015, 5.6.3.4.
*
*/
class WindGenType4IEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenType4IEC;
if (null == bucket)
cim_data.WindGenType4IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenType4IEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindGenType4IEC";
base.parse_element (/<cim:WindGenType4IEC.dipmax>([\s\S]*?)<\/cim:WindGenType4IEC.dipmax>/g, obj, "dipmax", base.to_string, sub, context);
base.parse_element (/<cim:WindGenType4IEC.diqmax>([\s\S]*?)<\/cim:WindGenType4IEC.diqmax>/g, obj, "diqmax", base.to_string, sub, context);
base.parse_element (/<cim:WindGenType4IEC.diqmin>([\s\S]*?)<\/cim:WindGenType4IEC.diqmin>/g, obj, "diqmin", base.to_string, sub, context);
base.parse_element (/<cim:WindGenType4IEC.tg>([\s\S]*?)<\/cim:WindGenType4IEC.tg>/g, obj, "tg", base.to_string, sub, context);
base.parse_attribute (/<cim:WindGenType4IEC.WindTurbineType4aIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType4aIEC", sub, context);
base.parse_attribute (/<cim:WindGenType4IEC.WindTurbineType4bIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType4bIEC", sub, context);
let bucket = context.parsed.WindGenType4IEC;
if (null == bucket)
context.parsed.WindGenType4IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindGenType4IEC", "dipmax", "dipmax", base.from_string, fields);
base.export_element (obj, "WindGenType4IEC", "diqmax", "diqmax", base.from_string, fields);
base.export_element (obj, "WindGenType4IEC", "diqmin", "diqmin", base.from_string, fields);
base.export_element (obj, "WindGenType4IEC", "tg", "tg", base.from_string, fields);
base.export_attribute (obj, "WindGenType4IEC", "WindTurbineType4aIEC", "WindTurbineType4aIEC", fields);
base.export_attribute (obj, "WindGenType4IEC", "WindTurbineType4bIEC", "WindTurbineType4bIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenType4IEC_collapse" aria-expanded="true" aria-controls="WindGenType4IEC_collapse" style="margin-left: 10px;">WindGenType4IEC</a></legend>
<div id="WindGenType4IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dipmax}}<div><b>dipmax</b>: {{dipmax}}</div>{{/dipmax}}
{{#diqmax}}<div><b>diqmax</b>: {{diqmax}}</div>{{/diqmax}}
{{#diqmin}}<div><b>diqmin</b>: {{diqmin}}</div>{{/diqmin}}
{{#tg}}<div><b>tg</b>: {{tg}}</div>{{/tg}}
{{#WindTurbineType4aIEC}}<div><b>WindTurbineType4aIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType4aIEC}}");}); return false;'>{{WindTurbineType4aIEC}}</a></div>{{/WindTurbineType4aIEC}}
{{#WindTurbineType4bIEC}}<div><b>WindTurbineType4bIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType4bIEC}}");}); return false;'>{{WindTurbineType4bIEC}}</a></div>{{/WindTurbineType4bIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenType4IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenType4IEC_collapse" style="margin-left: 10px;">WindGenType4IEC</a></legend>
<div id="{{id}}_WindGenType4IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dipmax'>dipmax: </label><div class='col-sm-8'><input id='{{id}}_dipmax' class='form-control' type='text'{{#dipmax}} value='{{dipmax}}'{{/dipmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_diqmax'>diqmax: </label><div class='col-sm-8'><input id='{{id}}_diqmax' class='form-control' type='text'{{#diqmax}} value='{{diqmax}}'{{/diqmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_diqmin'>diqmin: </label><div class='col-sm-8'><input id='{{id}}_diqmin' class='form-control' type='text'{{#diqmin}} value='{{diqmin}}'{{/diqmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tg'>tg: </label><div class='col-sm-8'><input id='{{id}}_tg' class='form-control' type='text'{{#tg}} value='{{tg}}'{{/tg}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType4aIEC'>WindTurbineType4aIEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType4aIEC' class='form-control' type='text'{{#WindTurbineType4aIEC}} value='{{WindTurbineType4aIEC}}'{{/WindTurbineType4aIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType4bIEC'>WindTurbineType4bIEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType4bIEC' class='form-control' type='text'{{#WindTurbineType4bIEC}} value='{{WindTurbineType4bIEC}}'{{/WindTurbineType4bIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenType4IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dipmax").value; if ("" !== temp) obj["dipmax"] = temp;
temp = document.getElementById (id + "_diqmax").value; if ("" !== temp) obj["diqmax"] = temp;
temp = document.getElementById (id + "_diqmin").value; if ("" !== temp) obj["diqmin"] = temp;
temp = document.getElementById (id + "_tg").value; if ("" !== temp) obj["tg"] = temp;
temp = document.getElementById (id + "_WindTurbineType4aIEC").value; if ("" !== temp) obj["WindTurbineType4aIEC"] = temp;
temp = document.getElementById (id + "_WindTurbineType4bIEC").value; if ("" !== temp) obj["WindTurbineType4bIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType4aIEC", "0..1", "0..1", "WindTurbineType4aIEC", "WindGenType4IEC"],
["WindTurbineType4bIEC", "0..1", "0..1", "WindTurbineType4bIEC", "WindGenType4IEC"]
]
)
);
}
}
/**
* Pitch angle control model.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.2.
*
*/
class WindContPitchAngleIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContPitchAngleIEC;
if (null == bucket)
cim_data.WindContPitchAngleIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContPitchAngleIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContPitchAngleIEC";
base.parse_element (/<cim:WindContPitchAngleIEC.dthetamax>([\s\S]*?)<\/cim:WindContPitchAngleIEC.dthetamax>/g, obj, "dthetamax", base.to_float, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.dthetamin>([\s\S]*?)<\/cim:WindContPitchAngleIEC.dthetamin>/g, obj, "dthetamin", base.to_float, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.kic>([\s\S]*?)<\/cim:WindContPitchAngleIEC.kic>/g, obj, "kic", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.kiomega>([\s\S]*?)<\/cim:WindContPitchAngleIEC.kiomega>/g, obj, "kiomega", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.kpc>([\s\S]*?)<\/cim:WindContPitchAngleIEC.kpc>/g, obj, "kpc", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.kpomega>([\s\S]*?)<\/cim:WindContPitchAngleIEC.kpomega>/g, obj, "kpomega", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.kpx>([\s\S]*?)<\/cim:WindContPitchAngleIEC.kpx>/g, obj, "kpx", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.thetamax>([\s\S]*?)<\/cim:WindContPitchAngleIEC.thetamax>/g, obj, "thetamax", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.thetamin>([\s\S]*?)<\/cim:WindContPitchAngleIEC.thetamin>/g, obj, "thetamin", base.to_string, sub, context);
base.parse_element (/<cim:WindContPitchAngleIEC.ttheta>([\s\S]*?)<\/cim:WindContPitchAngleIEC.ttheta>/g, obj, "ttheta", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContPitchAngleIEC.WindTurbineType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3IEC", sub, context);
let bucket = context.parsed.WindContPitchAngleIEC;
if (null == bucket)
context.parsed.WindContPitchAngleIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContPitchAngleIEC", "dthetamax", "dthetamax", base.from_float, fields);
base.export_element (obj, "WindContPitchAngleIEC", "dthetamin", "dthetamin", base.from_float, fields);
base.export_element (obj, "WindContPitchAngleIEC", "kic", "kic", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "kiomega", "kiomega", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "kpc", "kpc", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "kpomega", "kpomega", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "kpx", "kpx", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "thetamax", "thetamax", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "thetamin", "thetamin", base.from_string, fields);
base.export_element (obj, "WindContPitchAngleIEC", "ttheta", "ttheta", base.from_string, fields);
base.export_attribute (obj, "WindContPitchAngleIEC", "WindTurbineType3IEC", "WindTurbineType3IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContPitchAngleIEC_collapse" aria-expanded="true" aria-controls="WindContPitchAngleIEC_collapse" style="margin-left: 10px;">WindContPitchAngleIEC</a></legend>
<div id="WindContPitchAngleIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dthetamax}}<div><b>dthetamax</b>: {{dthetamax}}</div>{{/dthetamax}}
{{#dthetamin}}<div><b>dthetamin</b>: {{dthetamin}}</div>{{/dthetamin}}
{{#kic}}<div><b>kic</b>: {{kic}}</div>{{/kic}}
{{#kiomega}}<div><b>kiomega</b>: {{kiomega}}</div>{{/kiomega}}
{{#kpc}}<div><b>kpc</b>: {{kpc}}</div>{{/kpc}}
{{#kpomega}}<div><b>kpomega</b>: {{kpomega}}</div>{{/kpomega}}
{{#kpx}}<div><b>kpx</b>: {{kpx}}</div>{{/kpx}}
{{#thetamax}}<div><b>thetamax</b>: {{thetamax}}</div>{{/thetamax}}
{{#thetamin}}<div><b>thetamin</b>: {{thetamin}}</div>{{/thetamin}}
{{#ttheta}}<div><b>ttheta</b>: {{ttheta}}</div>{{/ttheta}}
{{#WindTurbineType3IEC}}<div><b>WindTurbineType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3IEC}}");}); return false;'>{{WindTurbineType3IEC}}</a></div>{{/WindTurbineType3IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContPitchAngleIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContPitchAngleIEC_collapse" style="margin-left: 10px;">WindContPitchAngleIEC</a></legend>
<div id="{{id}}_WindContPitchAngleIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dthetamax'>dthetamax: </label><div class='col-sm-8'><input id='{{id}}_dthetamax' class='form-control' type='text'{{#dthetamax}} value='{{dthetamax}}'{{/dthetamax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dthetamin'>dthetamin: </label><div class='col-sm-8'><input id='{{id}}_dthetamin' class='form-control' type='text'{{#dthetamin}} value='{{dthetamin}}'{{/dthetamin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kic'>kic: </label><div class='col-sm-8'><input id='{{id}}_kic' class='form-control' type='text'{{#kic}} value='{{kic}}'{{/kic}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiomega'>kiomega: </label><div class='col-sm-8'><input id='{{id}}_kiomega' class='form-control' type='text'{{#kiomega}} value='{{kiomega}}'{{/kiomega}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpc'>kpc: </label><div class='col-sm-8'><input id='{{id}}_kpc' class='form-control' type='text'{{#kpc}} value='{{kpc}}'{{/kpc}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpomega'>kpomega: </label><div class='col-sm-8'><input id='{{id}}_kpomega' class='form-control' type='text'{{#kpomega}} value='{{kpomega}}'{{/kpomega}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpx'>kpx: </label><div class='col-sm-8'><input id='{{id}}_kpx' class='form-control' type='text'{{#kpx}} value='{{kpx}}'{{/kpx}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetamax'>thetamax: </label><div class='col-sm-8'><input id='{{id}}_thetamax' class='form-control' type='text'{{#thetamax}} value='{{thetamax}}'{{/thetamax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetamin'>thetamin: </label><div class='col-sm-8'><input id='{{id}}_thetamin' class='form-control' type='text'{{#thetamin}} value='{{thetamin}}'{{/thetamin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ttheta'>ttheta: </label><div class='col-sm-8'><input id='{{id}}_ttheta' class='form-control' type='text'{{#ttheta}} value='{{ttheta}}'{{/ttheta}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3IEC'>WindTurbineType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3IEC' class='form-control' type='text'{{#WindTurbineType3IEC}} value='{{WindTurbineType3IEC}}'{{/WindTurbineType3IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContPitchAngleIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dthetamax").value; if ("" !== temp) obj["dthetamax"] = temp;
temp = document.getElementById (id + "_dthetamin").value; if ("" !== temp) obj["dthetamin"] = temp;
temp = document.getElementById (id + "_kic").value; if ("" !== temp) obj["kic"] = temp;
temp = document.getElementById (id + "_kiomega").value; if ("" !== temp) obj["kiomega"] = temp;
temp = document.getElementById (id + "_kpc").value; if ("" !== temp) obj["kpc"] = temp;
temp = document.getElementById (id + "_kpomega").value; if ("" !== temp) obj["kpomega"] = temp;
temp = document.getElementById (id + "_kpx").value; if ("" !== temp) obj["kpx"] = temp;
temp = document.getElementById (id + "_thetamax").value; if ("" !== temp) obj["thetamax"] = temp;
temp = document.getElementById (id + "_thetamin").value; if ("" !== temp) obj["thetamin"] = temp;
temp = document.getElementById (id + "_ttheta").value; if ("" !== temp) obj["ttheta"] = temp;
temp = document.getElementById (id + "_WindTurbineType3IEC").value; if ("" !== temp) obj["WindTurbineType3IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3IEC", "1", "1", "WindTurbineType3IEC", "WindContPitchAngleIEC"]
]
)
);
}
}
/**
* P control model type 4A.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.5.
*
*/
class WindContPType4aIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContPType4aIEC;
if (null == bucket)
cim_data.WindContPType4aIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContPType4aIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContPType4aIEC";
base.parse_element (/<cim:WindContPType4aIEC.dpmaxp4a>([\s\S]*?)<\/cim:WindContPType4aIEC.dpmaxp4a>/g, obj, "dpmaxp4a", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType4aIEC.tpordp4a>([\s\S]*?)<\/cim:WindContPType4aIEC.tpordp4a>/g, obj, "tpordp4a", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType4aIEC.tufiltp4a>([\s\S]*?)<\/cim:WindContPType4aIEC.tufiltp4a>/g, obj, "tufiltp4a", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContPType4aIEC.WindTurbineType4aIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType4aIEC", sub, context);
let bucket = context.parsed.WindContPType4aIEC;
if (null == bucket)
context.parsed.WindContPType4aIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContPType4aIEC", "dpmaxp4a", "dpmaxp4a", base.from_string, fields);
base.export_element (obj, "WindContPType4aIEC", "tpordp4a", "tpordp4a", base.from_string, fields);
base.export_element (obj, "WindContPType4aIEC", "tufiltp4a", "tufiltp4a", base.from_string, fields);
base.export_attribute (obj, "WindContPType4aIEC", "WindTurbineType4aIEC", "WindTurbineType4aIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContPType4aIEC_collapse" aria-expanded="true" aria-controls="WindContPType4aIEC_collapse" style="margin-left: 10px;">WindContPType4aIEC</a></legend>
<div id="WindContPType4aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dpmaxp4a}}<div><b>dpmaxp4a</b>: {{dpmaxp4a}}</div>{{/dpmaxp4a}}
{{#tpordp4a}}<div><b>tpordp4a</b>: {{tpordp4a}}</div>{{/tpordp4a}}
{{#tufiltp4a}}<div><b>tufiltp4a</b>: {{tufiltp4a}}</div>{{/tufiltp4a}}
{{#WindTurbineType4aIEC}}<div><b>WindTurbineType4aIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType4aIEC}}");}); return false;'>{{WindTurbineType4aIEC}}</a></div>{{/WindTurbineType4aIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContPType4aIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContPType4aIEC_collapse" style="margin-left: 10px;">WindContPType4aIEC</a></legend>
<div id="{{id}}_WindContPType4aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpmaxp4a'>dpmaxp4a: </label><div class='col-sm-8'><input id='{{id}}_dpmaxp4a' class='form-control' type='text'{{#dpmaxp4a}} value='{{dpmaxp4a}}'{{/dpmaxp4a}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpordp4a'>tpordp4a: </label><div class='col-sm-8'><input id='{{id}}_tpordp4a' class='form-control' type='text'{{#tpordp4a}} value='{{tpordp4a}}'{{/tpordp4a}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tufiltp4a'>tufiltp4a: </label><div class='col-sm-8'><input id='{{id}}_tufiltp4a' class='form-control' type='text'{{#tufiltp4a}} value='{{tufiltp4a}}'{{/tufiltp4a}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType4aIEC'>WindTurbineType4aIEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType4aIEC' class='form-control' type='text'{{#WindTurbineType4aIEC}} value='{{WindTurbineType4aIEC}}'{{/WindTurbineType4aIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContPType4aIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dpmaxp4a").value; if ("" !== temp) obj["dpmaxp4a"] = temp;
temp = document.getElementById (id + "_tpordp4a").value; if ("" !== temp) obj["tpordp4a"] = temp;
temp = document.getElementById (id + "_tufiltp4a").value; if ("" !== temp) obj["tufiltp4a"] = temp;
temp = document.getElementById (id + "_WindTurbineType4aIEC").value; if ("" !== temp) obj["WindTurbineType4aIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType4aIEC", "1", "1", "WindTurbineType4aIEC", "WindContPType4aIEC"]
]
)
);
}
}
/**
* The grid protection model includes protection against over- and under-voltage, and against over- and under-frequency.
*
* Reference: IEC 61400-27-1:2015, 5.6.6.
*
*/
class WindProtectionIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindProtectionIEC;
if (null == bucket)
cim_data.WindProtectionIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindProtectionIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindProtectionIEC";
base.parse_element (/<cim:WindProtectionIEC.dfimax>([\s\S]*?)<\/cim:WindProtectionIEC.dfimax>/g, obj, "dfimax", base.to_string, sub, context);
base.parse_element (/<cim:WindProtectionIEC.fover>([\s\S]*?)<\/cim:WindProtectionIEC.fover>/g, obj, "fover", base.to_string, sub, context);
base.parse_element (/<cim:WindProtectionIEC.funder>([\s\S]*?)<\/cim:WindProtectionIEC.funder>/g, obj, "funder", base.to_string, sub, context);
base.parse_element (/<cim:WindProtectionIEC.mzc>([\s\S]*?)<\/cim:WindProtectionIEC.mzc>/g, obj, "mzc", base.to_boolean, sub, context);
base.parse_element (/<cim:WindProtectionIEC.tfma>([\s\S]*?)<\/cim:WindProtectionIEC.tfma>/g, obj, "tfma", base.to_string, sub, context);
base.parse_element (/<cim:WindProtectionIEC.uover>([\s\S]*?)<\/cim:WindProtectionIEC.uover>/g, obj, "uover", base.to_string, sub, context);
base.parse_element (/<cim:WindProtectionIEC.uunder>([\s\S]*?)<\/cim:WindProtectionIEC.uunder>/g, obj, "uunder", base.to_string, sub, context);
base.parse_attributes (/<cim:WindProtectionIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
base.parse_attribute (/<cim:WindProtectionIEC.WindTurbineType1or2IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType1or2IEC", sub, context);
base.parse_attribute (/<cim:WindProtectionIEC.WindTurbineType3or4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4IEC", sub, context);
let bucket = context.parsed.WindProtectionIEC;
if (null == bucket)
context.parsed.WindProtectionIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindProtectionIEC", "dfimax", "dfimax", base.from_string, fields);
base.export_element (obj, "WindProtectionIEC", "fover", "fover", base.from_string, fields);
base.export_element (obj, "WindProtectionIEC", "funder", "funder", base.from_string, fields);
base.export_element (obj, "WindProtectionIEC", "mzc", "mzc", base.from_boolean, fields);
base.export_element (obj, "WindProtectionIEC", "tfma", "tfma", base.from_string, fields);
base.export_element (obj, "WindProtectionIEC", "uover", "uover", base.from_string, fields);
base.export_element (obj, "WindProtectionIEC", "uunder", "uunder", base.from_string, fields);
base.export_attributes (obj, "WindProtectionIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
base.export_attribute (obj, "WindProtectionIEC", "WindTurbineType1or2IEC", "WindTurbineType1or2IEC", fields);
base.export_attribute (obj, "WindProtectionIEC", "WindTurbineType3or4IEC", "WindTurbineType3or4IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindProtectionIEC_collapse" aria-expanded="true" aria-controls="WindProtectionIEC_collapse" style="margin-left: 10px;">WindProtectionIEC</a></legend>
<div id="WindProtectionIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dfimax}}<div><b>dfimax</b>: {{dfimax}}</div>{{/dfimax}}
{{#fover}}<div><b>fover</b>: {{fover}}</div>{{/fover}}
{{#funder}}<div><b>funder</b>: {{funder}}</div>{{/funder}}
{{#mzc}}<div><b>mzc</b>: {{mzc}}</div>{{/mzc}}
{{#tfma}}<div><b>tfma</b>: {{tfma}}</div>{{/tfma}}
{{#uover}}<div><b>uover</b>: {{uover}}</div>{{/uover}}
{{#uunder}}<div><b>uunder</b>: {{uunder}}</div>{{/uunder}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
{{#WindTurbineType1or2IEC}}<div><b>WindTurbineType1or2IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType1or2IEC}}");}); return false;'>{{WindTurbineType1or2IEC}}</a></div>{{/WindTurbineType1or2IEC}}
{{#WindTurbineType3or4IEC}}<div><b>WindTurbineType3or4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3or4IEC}}");}); return false;'>{{WindTurbineType3or4IEC}}</a></div>{{/WindTurbineType3or4IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindProtectionIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindProtectionIEC_collapse" style="margin-left: 10px;">WindProtectionIEC</a></legend>
<div id="{{id}}_WindProtectionIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dfimax'>dfimax: </label><div class='col-sm-8'><input id='{{id}}_dfimax' class='form-control' type='text'{{#dfimax}} value='{{dfimax}}'{{/dfimax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_fover'>fover: </label><div class='col-sm-8'><input id='{{id}}_fover' class='form-control' type='text'{{#fover}} value='{{fover}}'{{/fover}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_funder'>funder: </label><div class='col-sm-8'><input id='{{id}}_funder' class='form-control' type='text'{{#funder}} value='{{funder}}'{{/funder}}></div></div>
<div class='form-group row'><div class='col-sm-4' for='{{id}}_mzc'>mzc: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_mzc' class='form-check-input' type='checkbox'{{#mzc}} checked{{/mzc}}></div></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tfma'>tfma: </label><div class='col-sm-8'><input id='{{id}}_tfma' class='form-control' type='text'{{#tfma}} value='{{tfma}}'{{/tfma}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_uover'>uover: </label><div class='col-sm-8'><input id='{{id}}_uover' class='form-control' type='text'{{#uover}} value='{{uover}}'{{/uover}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_uunder'>uunder: </label><div class='col-sm-8'><input id='{{id}}_uunder' class='form-control' type='text'{{#uunder}} value='{{uunder}}'{{/uunder}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType1or2IEC'>WindTurbineType1or2IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType1or2IEC' class='form-control' type='text'{{#WindTurbineType1or2IEC}} value='{{WindTurbineType1or2IEC}}'{{/WindTurbineType1or2IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3or4IEC'>WindTurbineType3or4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3or4IEC' class='form-control' type='text'{{#WindTurbineType3or4IEC}} value='{{WindTurbineType3or4IEC}}'{{/WindTurbineType3or4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindProtectionIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dfimax").value; if ("" !== temp) obj["dfimax"] = temp;
temp = document.getElementById (id + "_fover").value; if ("" !== temp) obj["fover"] = temp;
temp = document.getElementById (id + "_funder").value; if ("" !== temp) obj["funder"] = temp;
temp = document.getElementById (id + "_mzc").checked; if (temp) obj["mzc"] = true;
temp = document.getElementById (id + "_tfma").value; if ("" !== temp) obj["tfma"] = temp;
temp = document.getElementById (id + "_uover").value; if ("" !== temp) obj["uover"] = temp;
temp = document.getElementById (id + "_uunder").value; if ("" !== temp) obj["uunder"] = temp;
temp = document.getElementById (id + "_WindTurbineType1or2IEC").value; if ("" !== temp) obj["WindTurbineType1or2IEC"] = temp;
temp = document.getElementById (id + "_WindTurbineType3or4IEC").value; if ("" !== temp) obj["WindTurbineType3or4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindProtectionIEC"],
["WindTurbineType1or2IEC", "0..1", "1", "WindTurbineType1or2IEC", "WindProtectionIEC"],
["WindTurbineType3or4IEC", "0..1", "1", "WindTurbineType3or4IEC", "WindProtectionIEC"]
]
)
);
}
}
/**
* Two-dimensional aerodynamic model.
*
* Reference: IEC 61400-27-1:2015, 5.6.1.3.
*
*/
class WindAeroTwoDimIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindAeroTwoDimIEC;
if (null == bucket)
cim_data.WindAeroTwoDimIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindAeroTwoDimIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindAeroTwoDimIEC";
base.parse_element (/<cim:WindAeroTwoDimIEC.dpomega>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.dpomega>/g, obj, "dpomega", base.to_string, sub, context);
base.parse_element (/<cim:WindAeroTwoDimIEC.dptheta>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.dptheta>/g, obj, "dptheta", base.to_string, sub, context);
base.parse_element (/<cim:WindAeroTwoDimIEC.dpv1>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.dpv1>/g, obj, "dpv1", base.to_string, sub, context);
base.parse_element (/<cim:WindAeroTwoDimIEC.omegazero>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.omegazero>/g, obj, "omegazero", base.to_string, sub, context);
base.parse_element (/<cim:WindAeroTwoDimIEC.pavail>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.pavail>/g, obj, "pavail", base.to_string, sub, context);
base.parse_element (/<cim:WindAeroTwoDimIEC.thetav2>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.thetav2>/g, obj, "thetav2", base.to_string, sub, context);
base.parse_element (/<cim:WindAeroTwoDimIEC.thetazero>([\s\S]*?)<\/cim:WindAeroTwoDimIEC.thetazero>/g, obj, "thetazero", base.to_string, sub, context);
base.parse_attribute (/<cim:WindAeroTwoDimIEC.WindTurbineType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3IEC", sub, context);
let bucket = context.parsed.WindAeroTwoDimIEC;
if (null == bucket)
context.parsed.WindAeroTwoDimIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindAeroTwoDimIEC", "dpomega", "dpomega", base.from_string, fields);
base.export_element (obj, "WindAeroTwoDimIEC", "dptheta", "dptheta", base.from_string, fields);
base.export_element (obj, "WindAeroTwoDimIEC", "dpv1", "dpv1", base.from_string, fields);
base.export_element (obj, "WindAeroTwoDimIEC", "omegazero", "omegazero", base.from_string, fields);
base.export_element (obj, "WindAeroTwoDimIEC", "pavail", "pavail", base.from_string, fields);
base.export_element (obj, "WindAeroTwoDimIEC", "thetav2", "thetav2", base.from_string, fields);
base.export_element (obj, "WindAeroTwoDimIEC", "thetazero", "thetazero", base.from_string, fields);
base.export_attribute (obj, "WindAeroTwoDimIEC", "WindTurbineType3IEC", "WindTurbineType3IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindAeroTwoDimIEC_collapse" aria-expanded="true" aria-controls="WindAeroTwoDimIEC_collapse" style="margin-left: 10px;">WindAeroTwoDimIEC</a></legend>
<div id="WindAeroTwoDimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dpomega}}<div><b>dpomega</b>: {{dpomega}}</div>{{/dpomega}}
{{#dptheta}}<div><b>dptheta</b>: {{dptheta}}</div>{{/dptheta}}
{{#dpv1}}<div><b>dpv1</b>: {{dpv1}}</div>{{/dpv1}}
{{#omegazero}}<div><b>omegazero</b>: {{omegazero}}</div>{{/omegazero}}
{{#pavail}}<div><b>pavail</b>: {{pavail}}</div>{{/pavail}}
{{#thetav2}}<div><b>thetav2</b>: {{thetav2}}</div>{{/thetav2}}
{{#thetazero}}<div><b>thetazero</b>: {{thetazero}}</div>{{/thetazero}}
{{#WindTurbineType3IEC}}<div><b>WindTurbineType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3IEC}}");}); return false;'>{{WindTurbineType3IEC}}</a></div>{{/WindTurbineType3IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindAeroTwoDimIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindAeroTwoDimIEC_collapse" style="margin-left: 10px;">WindAeroTwoDimIEC</a></legend>
<div id="{{id}}_WindAeroTwoDimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpomega'>dpomega: </label><div class='col-sm-8'><input id='{{id}}_dpomega' class='form-control' type='text'{{#dpomega}} value='{{dpomega}}'{{/dpomega}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dptheta'>dptheta: </label><div class='col-sm-8'><input id='{{id}}_dptheta' class='form-control' type='text'{{#dptheta}} value='{{dptheta}}'{{/dptheta}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpv1'>dpv1: </label><div class='col-sm-8'><input id='{{id}}_dpv1' class='form-control' type='text'{{#dpv1}} value='{{dpv1}}'{{/dpv1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_omegazero'>omegazero: </label><div class='col-sm-8'><input id='{{id}}_omegazero' class='form-control' type='text'{{#omegazero}} value='{{omegazero}}'{{/omegazero}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pavail'>pavail: </label><div class='col-sm-8'><input id='{{id}}_pavail' class='form-control' type='text'{{#pavail}} value='{{pavail}}'{{/pavail}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetav2'>thetav2: </label><div class='col-sm-8'><input id='{{id}}_thetav2' class='form-control' type='text'{{#thetav2}} value='{{thetav2}}'{{/thetav2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetazero'>thetazero: </label><div class='col-sm-8'><input id='{{id}}_thetazero' class='form-control' type='text'{{#thetazero}} value='{{thetazero}}'{{/thetazero}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3IEC'>WindTurbineType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3IEC' class='form-control' type='text'{{#WindTurbineType3IEC}} value='{{WindTurbineType3IEC}}'{{/WindTurbineType3IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindAeroTwoDimIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dpomega").value; if ("" !== temp) obj["dpomega"] = temp;
temp = document.getElementById (id + "_dptheta").value; if ("" !== temp) obj["dptheta"] = temp;
temp = document.getElementById (id + "_dpv1").value; if ("" !== temp) obj["dpv1"] = temp;
temp = document.getElementById (id + "_omegazero").value; if ("" !== temp) obj["omegazero"] = temp;
temp = document.getElementById (id + "_pavail").value; if ("" !== temp) obj["pavail"] = temp;
temp = document.getElementById (id + "_thetav2").value; if ("" !== temp) obj["thetav2"] = temp;
temp = document.getElementById (id + "_thetazero").value; if ("" !== temp) obj["thetazero"] = temp;
temp = document.getElementById (id + "_WindTurbineType3IEC").value; if ("" !== temp) obj["WindTurbineType3IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3IEC", "1", "0..1", "WindTurbineType3IEC", "WindAeroTwoDimIEC"]
]
)
);
}
}
/**
* P control model type 3.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.4.
*
*/
class WindContPType3IEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContPType3IEC;
if (null == bucket)
cim_data.WindContPType3IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContPType3IEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContPType3IEC";
base.parse_element (/<cim:WindContPType3IEC.dpmax>([\s\S]*?)<\/cim:WindContPType3IEC.dpmax>/g, obj, "dpmax", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.dprefmax>([\s\S]*?)<\/cim:WindContPType3IEC.dprefmax>/g, obj, "dprefmax", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.dprefmin>([\s\S]*?)<\/cim:WindContPType3IEC.dprefmin>/g, obj, "dprefmin", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.dthetamax>([\s\S]*?)<\/cim:WindContPType3IEC.dthetamax>/g, obj, "dthetamax", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.dthetamaxuvrt>([\s\S]*?)<\/cim:WindContPType3IEC.dthetamaxuvrt>/g, obj, "dthetamaxuvrt", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.kdtd>([\s\S]*?)<\/cim:WindContPType3IEC.kdtd>/g, obj, "kdtd", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.kip>([\s\S]*?)<\/cim:WindContPType3IEC.kip>/g, obj, "kip", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.kpp>([\s\S]*?)<\/cim:WindContPType3IEC.kpp>/g, obj, "kpp", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.mpuvrt>([\s\S]*?)<\/cim:WindContPType3IEC.mpuvrt>/g, obj, "mpuvrt", base.to_boolean, sub, context);
base.parse_element (/<cim:WindContPType3IEC.omegadtd>([\s\S]*?)<\/cim:WindContPType3IEC.omegadtd>/g, obj, "omegadtd", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.omegaoffset>([\s\S]*?)<\/cim:WindContPType3IEC.omegaoffset>/g, obj, "omegaoffset", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.pdtdmax>([\s\S]*?)<\/cim:WindContPType3IEC.pdtdmax>/g, obj, "pdtdmax", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.tdvs>([\s\S]*?)<\/cim:WindContPType3IEC.tdvs>/g, obj, "tdvs", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.thetaemin>([\s\S]*?)<\/cim:WindContPType3IEC.thetaemin>/g, obj, "thetaemin", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.thetauscale>([\s\S]*?)<\/cim:WindContPType3IEC.thetauscale>/g, obj, "thetauscale", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.tomegafiltp3>([\s\S]*?)<\/cim:WindContPType3IEC.tomegafiltp3>/g, obj, "tomegafiltp3", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.tomegaref>([\s\S]*?)<\/cim:WindContPType3IEC.tomegaref>/g, obj, "tomegaref", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.tpfiltp3>([\s\S]*?)<\/cim:WindContPType3IEC.tpfiltp3>/g, obj, "tpfiltp3", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.tpord>([\s\S]*?)<\/cim:WindContPType3IEC.tpord>/g, obj, "tpord", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.tufiltp3>([\s\S]*?)<\/cim:WindContPType3IEC.tufiltp3>/g, obj, "tufiltp3", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.udvs>([\s\S]*?)<\/cim:WindContPType3IEC.udvs>/g, obj, "udvs", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.updip>([\s\S]*?)<\/cim:WindContPType3IEC.updip>/g, obj, "updip", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType3IEC.zeta>([\s\S]*?)<\/cim:WindContPType3IEC.zeta>/g, obj, "zeta", base.to_float, sub, context);
base.parse_attributes (/<cim:WindContPType3IEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
base.parse_attribute (/<cim:WindContPType3IEC.WindTurbineType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3IEC", sub, context);
let bucket = context.parsed.WindContPType3IEC;
if (null == bucket)
context.parsed.WindContPType3IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContPType3IEC", "dpmax", "dpmax", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "dprefmax", "dprefmax", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "dprefmin", "dprefmin", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "dthetamax", "dthetamax", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "dthetamaxuvrt", "dthetamaxuvrt", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "kdtd", "kdtd", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "kip", "kip", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "kpp", "kpp", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "mpuvrt", "mpuvrt", base.from_boolean, fields);
base.export_element (obj, "WindContPType3IEC", "omegadtd", "omegadtd", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "omegaoffset", "omegaoffset", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "pdtdmax", "pdtdmax", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "tdvs", "tdvs", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "thetaemin", "thetaemin", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "thetauscale", "thetauscale", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "tomegafiltp3", "tomegafiltp3", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "tomegaref", "tomegaref", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "tpfiltp3", "tpfiltp3", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "tpord", "tpord", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "tufiltp3", "tufiltp3", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "udvs", "udvs", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "updip", "updip", base.from_string, fields);
base.export_element (obj, "WindContPType3IEC", "zeta", "zeta", base.from_float, fields);
base.export_attributes (obj, "WindContPType3IEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
base.export_attribute (obj, "WindContPType3IEC", "WindTurbineType3IEC", "WindTurbineType3IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContPType3IEC_collapse" aria-expanded="true" aria-controls="WindContPType3IEC_collapse" style="margin-left: 10px;">WindContPType3IEC</a></legend>
<div id="WindContPType3IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dpmax}}<div><b>dpmax</b>: {{dpmax}}</div>{{/dpmax}}
{{#dprefmax}}<div><b>dprefmax</b>: {{dprefmax}}</div>{{/dprefmax}}
{{#dprefmin}}<div><b>dprefmin</b>: {{dprefmin}}</div>{{/dprefmin}}
{{#dthetamax}}<div><b>dthetamax</b>: {{dthetamax}}</div>{{/dthetamax}}
{{#dthetamaxuvrt}}<div><b>dthetamaxuvrt</b>: {{dthetamaxuvrt}}</div>{{/dthetamaxuvrt}}
{{#kdtd}}<div><b>kdtd</b>: {{kdtd}}</div>{{/kdtd}}
{{#kip}}<div><b>kip</b>: {{kip}}</div>{{/kip}}
{{#kpp}}<div><b>kpp</b>: {{kpp}}</div>{{/kpp}}
{{#mpuvrt}}<div><b>mpuvrt</b>: {{mpuvrt}}</div>{{/mpuvrt}}
{{#omegadtd}}<div><b>omegadtd</b>: {{omegadtd}}</div>{{/omegadtd}}
{{#omegaoffset}}<div><b>omegaoffset</b>: {{omegaoffset}}</div>{{/omegaoffset}}
{{#pdtdmax}}<div><b>pdtdmax</b>: {{pdtdmax}}</div>{{/pdtdmax}}
{{#tdvs}}<div><b>tdvs</b>: {{tdvs}}</div>{{/tdvs}}
{{#thetaemin}}<div><b>thetaemin</b>: {{thetaemin}}</div>{{/thetaemin}}
{{#thetauscale}}<div><b>thetauscale</b>: {{thetauscale}}</div>{{/thetauscale}}
{{#tomegafiltp3}}<div><b>tomegafiltp3</b>: {{tomegafiltp3}}</div>{{/tomegafiltp3}}
{{#tomegaref}}<div><b>tomegaref</b>: {{tomegaref}}</div>{{/tomegaref}}
{{#tpfiltp3}}<div><b>tpfiltp3</b>: {{tpfiltp3}}</div>{{/tpfiltp3}}
{{#tpord}}<div><b>tpord</b>: {{tpord}}</div>{{/tpord}}
{{#tufiltp3}}<div><b>tufiltp3</b>: {{tufiltp3}}</div>{{/tufiltp3}}
{{#udvs}}<div><b>udvs</b>: {{udvs}}</div>{{/udvs}}
{{#updip}}<div><b>updip</b>: {{updip}}</div>{{/updip}}
{{#zeta}}<div><b>zeta</b>: {{zeta}}</div>{{/zeta}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
{{#WindTurbineType3IEC}}<div><b>WindTurbineType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3IEC}}");}); return false;'>{{WindTurbineType3IEC}}</a></div>{{/WindTurbineType3IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContPType3IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContPType3IEC_collapse" style="margin-left: 10px;">WindContPType3IEC</a></legend>
<div id="{{id}}_WindContPType3IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpmax'>dpmax: </label><div class='col-sm-8'><input id='{{id}}_dpmax' class='form-control' type='text'{{#dpmax}} value='{{dpmax}}'{{/dpmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dprefmax'>dprefmax: </label><div class='col-sm-8'><input id='{{id}}_dprefmax' class='form-control' type='text'{{#dprefmax}} value='{{dprefmax}}'{{/dprefmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dprefmin'>dprefmin: </label><div class='col-sm-8'><input id='{{id}}_dprefmin' class='form-control' type='text'{{#dprefmin}} value='{{dprefmin}}'{{/dprefmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dthetamax'>dthetamax: </label><div class='col-sm-8'><input id='{{id}}_dthetamax' class='form-control' type='text'{{#dthetamax}} value='{{dthetamax}}'{{/dthetamax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dthetamaxuvrt'>dthetamaxuvrt: </label><div class='col-sm-8'><input id='{{id}}_dthetamaxuvrt' class='form-control' type='text'{{#dthetamaxuvrt}} value='{{dthetamaxuvrt}}'{{/dthetamaxuvrt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kdtd'>kdtd: </label><div class='col-sm-8'><input id='{{id}}_kdtd' class='form-control' type='text'{{#kdtd}} value='{{kdtd}}'{{/kdtd}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kip'>kip: </label><div class='col-sm-8'><input id='{{id}}_kip' class='form-control' type='text'{{#kip}} value='{{kip}}'{{/kip}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpp'>kpp: </label><div class='col-sm-8'><input id='{{id}}_kpp' class='form-control' type='text'{{#kpp}} value='{{kpp}}'{{/kpp}}></div></div>
<div class='form-group row'><div class='col-sm-4' for='{{id}}_mpuvrt'>mpuvrt: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_mpuvrt' class='form-check-input' type='checkbox'{{#mpuvrt}} checked{{/mpuvrt}}></div></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_omegadtd'>omegadtd: </label><div class='col-sm-8'><input id='{{id}}_omegadtd' class='form-control' type='text'{{#omegadtd}} value='{{omegadtd}}'{{/omegadtd}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_omegaoffset'>omegaoffset: </label><div class='col-sm-8'><input id='{{id}}_omegaoffset' class='form-control' type='text'{{#omegaoffset}} value='{{omegaoffset}}'{{/omegaoffset}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pdtdmax'>pdtdmax: </label><div class='col-sm-8'><input id='{{id}}_pdtdmax' class='form-control' type='text'{{#pdtdmax}} value='{{pdtdmax}}'{{/pdtdmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tdvs'>tdvs: </label><div class='col-sm-8'><input id='{{id}}_tdvs' class='form-control' type='text'{{#tdvs}} value='{{tdvs}}'{{/tdvs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetaemin'>thetaemin: </label><div class='col-sm-8'><input id='{{id}}_thetaemin' class='form-control' type='text'{{#thetaemin}} value='{{thetaemin}}'{{/thetaemin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetauscale'>thetauscale: </label><div class='col-sm-8'><input id='{{id}}_thetauscale' class='form-control' type='text'{{#thetauscale}} value='{{thetauscale}}'{{/thetauscale}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tomegafiltp3'>tomegafiltp3: </label><div class='col-sm-8'><input id='{{id}}_tomegafiltp3' class='form-control' type='text'{{#tomegafiltp3}} value='{{tomegafiltp3}}'{{/tomegafiltp3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tomegaref'>tomegaref: </label><div class='col-sm-8'><input id='{{id}}_tomegaref' class='form-control' type='text'{{#tomegaref}} value='{{tomegaref}}'{{/tomegaref}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpfiltp3'>tpfiltp3: </label><div class='col-sm-8'><input id='{{id}}_tpfiltp3' class='form-control' type='text'{{#tpfiltp3}} value='{{tpfiltp3}}'{{/tpfiltp3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpord'>tpord: </label><div class='col-sm-8'><input id='{{id}}_tpord' class='form-control' type='text'{{#tpord}} value='{{tpord}}'{{/tpord}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tufiltp3'>tufiltp3: </label><div class='col-sm-8'><input id='{{id}}_tufiltp3' class='form-control' type='text'{{#tufiltp3}} value='{{tufiltp3}}'{{/tufiltp3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_udvs'>udvs: </label><div class='col-sm-8'><input id='{{id}}_udvs' class='form-control' type='text'{{#udvs}} value='{{udvs}}'{{/udvs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_updip'>updip: </label><div class='col-sm-8'><input id='{{id}}_updip' class='form-control' type='text'{{#updip}} value='{{updip}}'{{/updip}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_zeta'>zeta: </label><div class='col-sm-8'><input id='{{id}}_zeta' class='form-control' type='text'{{#zeta}} value='{{zeta}}'{{/zeta}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3IEC'>WindTurbineType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3IEC' class='form-control' type='text'{{#WindTurbineType3IEC}} value='{{WindTurbineType3IEC}}'{{/WindTurbineType3IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContPType3IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dpmax").value; if ("" !== temp) obj["dpmax"] = temp;
temp = document.getElementById (id + "_dprefmax").value; if ("" !== temp) obj["dprefmax"] = temp;
temp = document.getElementById (id + "_dprefmin").value; if ("" !== temp) obj["dprefmin"] = temp;
temp = document.getElementById (id + "_dthetamax").value; if ("" !== temp) obj["dthetamax"] = temp;
temp = document.getElementById (id + "_dthetamaxuvrt").value; if ("" !== temp) obj["dthetamaxuvrt"] = temp;
temp = document.getElementById (id + "_kdtd").value; if ("" !== temp) obj["kdtd"] = temp;
temp = document.getElementById (id + "_kip").value; if ("" !== temp) obj["kip"] = temp;
temp = document.getElementById (id + "_kpp").value; if ("" !== temp) obj["kpp"] = temp;
temp = document.getElementById (id + "_mpuvrt").checked; if (temp) obj["mpuvrt"] = true;
temp = document.getElementById (id + "_omegadtd").value; if ("" !== temp) obj["omegadtd"] = temp;
temp = document.getElementById (id + "_omegaoffset").value; if ("" !== temp) obj["omegaoffset"] = temp;
temp = document.getElementById (id + "_pdtdmax").value; if ("" !== temp) obj["pdtdmax"] = temp;
temp = document.getElementById (id + "_tdvs").value; if ("" !== temp) obj["tdvs"] = temp;
temp = document.getElementById (id + "_thetaemin").value; if ("" !== temp) obj["thetaemin"] = temp;
temp = document.getElementById (id + "_thetauscale").value; if ("" !== temp) obj["thetauscale"] = temp;
temp = document.getElementById (id + "_tomegafiltp3").value; if ("" !== temp) obj["tomegafiltp3"] = temp;
temp = document.getElementById (id + "_tomegaref").value; if ("" !== temp) obj["tomegaref"] = temp;
temp = document.getElementById (id + "_tpfiltp3").value; if ("" !== temp) obj["tpfiltp3"] = temp;
temp = document.getElementById (id + "_tpord").value; if ("" !== temp) obj["tpord"] = temp;
temp = document.getElementById (id + "_tufiltp3").value; if ("" !== temp) obj["tufiltp3"] = temp;
temp = document.getElementById (id + "_udvs").value; if ("" !== temp) obj["udvs"] = temp;
temp = document.getElementById (id + "_updip").value; if ("" !== temp) obj["updip"] = temp;
temp = document.getElementById (id + "_zeta").value; if ("" !== temp) obj["zeta"] = temp;
temp = document.getElementById (id + "_WindTurbineType3IEC").value; if ("" !== temp) obj["WindTurbineType3IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindContPType3IEC"],
["WindTurbineType3IEC", "1", "1", "WindTurbineType3IEC", "WindContPType3IEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to wind turbines type 3 and type 4 and wind plant IEC and user-defined wind plants including their control models.
*
*/
class WindPlantDynamics extends StandardModels.DynamicsFunctionBlock
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindPlantDynamics;
if (null == bucket)
cim_data.WindPlantDynamics = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindPlantDynamics[obj.id];
}
parse (context, sub)
{
let obj = StandardModels.DynamicsFunctionBlock.prototype.parse.call (this, context, sub);
obj.cls = "WindPlantDynamics";
base.parse_attribute (/<cim:WindPlantDynamics.RemoteInputSignal\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "RemoteInputSignal", sub, context);
base.parse_attributes (/<cim:WindPlantDynamics.WindTurbineType3or4Dynamics\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4Dynamics", sub, context);
let bucket = context.parsed.WindPlantDynamics;
if (null == bucket)
context.parsed.WindPlantDynamics = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = StandardModels.DynamicsFunctionBlock.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindPlantDynamics", "RemoteInputSignal", "RemoteInputSignal", fields);
base.export_attributes (obj, "WindPlantDynamics", "WindTurbineType3or4Dynamics", "WindTurbineType3or4Dynamics", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindPlantDynamics_collapse" aria-expanded="true" aria-controls="WindPlantDynamics_collapse" style="margin-left: 10px;">WindPlantDynamics</a></legend>
<div id="WindPlantDynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ StandardModels.DynamicsFunctionBlock.prototype.template.call (this) +
`
{{#RemoteInputSignal}}<div><b>RemoteInputSignal</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{RemoteInputSignal}}");}); return false;'>{{RemoteInputSignal}}</a></div>{{/RemoteInputSignal}}
{{#WindTurbineType3or4Dynamics}}<div><b>WindTurbineType3or4Dynamics</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindTurbineType3or4Dynamics}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindTurbineType3or4Dynamics"]) obj["WindTurbineType3or4Dynamics_string"] = obj["WindTurbineType3or4Dynamics"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindTurbineType3or4Dynamics_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindPlantDynamics_collapse" aria-expanded="true" aria-controls="{{id}}_WindPlantDynamics_collapse" style="margin-left: 10px;">WindPlantDynamics</a></legend>
<div id="{{id}}_WindPlantDynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ StandardModels.DynamicsFunctionBlock.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_RemoteInputSignal'>RemoteInputSignal: </label><div class='col-sm-8'><input id='{{id}}_RemoteInputSignal' class='form-control' type='text'{{#RemoteInputSignal}} value='{{RemoteInputSignal}}'{{/RemoteInputSignal}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindPlantDynamics" };
super.submit (id, obj);
temp = document.getElementById (id + "_RemoteInputSignal").value; if ("" !== temp) obj["RemoteInputSignal"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["RemoteInputSignal", "0..1", "0..1", "RemoteInputSignal", "WindPlantDynamics"],
["WindTurbineType3or4Dynamics", "1..*", "0..1", "WindTurbineType3or4Dynamics", "WindPlantDynamics"]
]
)
);
}
}
/**
* Parent class supporting relationships to IEC wind turbines type 3 generator models of IEC type 3A and 3B.
*
*/
class WindGenType3IEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenType3IEC;
if (null == bucket)
cim_data.WindGenType3IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenType3IEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindGenType3IEC";
base.parse_element (/<cim:WindGenType3IEC.dipmax>([\s\S]*?)<\/cim:WindGenType3IEC.dipmax>/g, obj, "dipmax", base.to_string, sub, context);
base.parse_element (/<cim:WindGenType3IEC.diqmax>([\s\S]*?)<\/cim:WindGenType3IEC.diqmax>/g, obj, "diqmax", base.to_string, sub, context);
base.parse_element (/<cim:WindGenType3IEC.xs>([\s\S]*?)<\/cim:WindGenType3IEC.xs>/g, obj, "xs", base.to_string, sub, context);
base.parse_attribute (/<cim:WindGenType3IEC.WindTurbineType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3IEC", sub, context);
let bucket = context.parsed.WindGenType3IEC;
if (null == bucket)
context.parsed.WindGenType3IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindGenType3IEC", "dipmax", "dipmax", base.from_string, fields);
base.export_element (obj, "WindGenType3IEC", "diqmax", "diqmax", base.from_string, fields);
base.export_element (obj, "WindGenType3IEC", "xs", "xs", base.from_string, fields);
base.export_attribute (obj, "WindGenType3IEC", "WindTurbineType3IEC", "WindTurbineType3IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenType3IEC_collapse" aria-expanded="true" aria-controls="WindGenType3IEC_collapse" style="margin-left: 10px;">WindGenType3IEC</a></legend>
<div id="WindGenType3IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dipmax}}<div><b>dipmax</b>: {{dipmax}}</div>{{/dipmax}}
{{#diqmax}}<div><b>diqmax</b>: {{diqmax}}</div>{{/diqmax}}
{{#xs}}<div><b>xs</b>: {{xs}}</div>{{/xs}}
{{#WindTurbineType3IEC}}<div><b>WindTurbineType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3IEC}}");}); return false;'>{{WindTurbineType3IEC}}</a></div>{{/WindTurbineType3IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenType3IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenType3IEC_collapse" style="margin-left: 10px;">WindGenType3IEC</a></legend>
<div id="{{id}}_WindGenType3IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dipmax'>dipmax: </label><div class='col-sm-8'><input id='{{id}}_dipmax' class='form-control' type='text'{{#dipmax}} value='{{dipmax}}'{{/dipmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_diqmax'>diqmax: </label><div class='col-sm-8'><input id='{{id}}_diqmax' class='form-control' type='text'{{#diqmax}} value='{{diqmax}}'{{/diqmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_xs'>xs: </label><div class='col-sm-8'><input id='{{id}}_xs' class='form-control' type='text'{{#xs}} value='{{xs}}'{{/xs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3IEC'>WindTurbineType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3IEC' class='form-control' type='text'{{#WindTurbineType3IEC}} value='{{WindTurbineType3IEC}}'{{/WindTurbineType3IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenType3IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dipmax").value; if ("" !== temp) obj["dipmax"] = temp;
temp = document.getElementById (id + "_diqmax").value; if ("" !== temp) obj["diqmax"] = temp;
temp = document.getElementById (id + "_xs").value; if ("" !== temp) obj["xs"] = temp;
temp = document.getElementById (id + "_WindTurbineType3IEC").value; if ("" !== temp) obj["WindTurbineType3IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3IEC", "0..1", "0..1", "WindTurbineType3IEC", "WindGenType3IEC"]
]
)
);
}
}
/**
* QP and QU limitation model.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.10.
*
*/
class WindContQPQULimIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContQPQULimIEC;
if (null == bucket)
cim_data.WindContQPQULimIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContQPQULimIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContQPQULimIEC";
base.parse_element (/<cim:WindContQPQULimIEC.tpfiltql>([\s\S]*?)<\/cim:WindContQPQULimIEC.tpfiltql>/g, obj, "tpfiltql", base.to_string, sub, context);
base.parse_element (/<cim:WindContQPQULimIEC.tufiltql>([\s\S]*?)<\/cim:WindContQPQULimIEC.tufiltql>/g, obj, "tufiltql", base.to_string, sub, context);
base.parse_attributes (/<cim:WindContQPQULimIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
base.parse_attribute (/<cim:WindContQPQULimIEC.WindTurbineType3or4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4IEC", sub, context);
let bucket = context.parsed.WindContQPQULimIEC;
if (null == bucket)
context.parsed.WindContQPQULimIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContQPQULimIEC", "tpfiltql", "tpfiltql", base.from_string, fields);
base.export_element (obj, "WindContQPQULimIEC", "tufiltql", "tufiltql", base.from_string, fields);
base.export_attributes (obj, "WindContQPQULimIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
base.export_attribute (obj, "WindContQPQULimIEC", "WindTurbineType3or4IEC", "WindTurbineType3or4IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContQPQULimIEC_collapse" aria-expanded="true" aria-controls="WindContQPQULimIEC_collapse" style="margin-left: 10px;">WindContQPQULimIEC</a></legend>
<div id="WindContQPQULimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#tpfiltql}}<div><b>tpfiltql</b>: {{tpfiltql}}</div>{{/tpfiltql}}
{{#tufiltql}}<div><b>tufiltql</b>: {{tufiltql}}</div>{{/tufiltql}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
{{#WindTurbineType3or4IEC}}<div><b>WindTurbineType3or4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3or4IEC}}");}); return false;'>{{WindTurbineType3or4IEC}}</a></div>{{/WindTurbineType3or4IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContQPQULimIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContQPQULimIEC_collapse" style="margin-left: 10px;">WindContQPQULimIEC</a></legend>
<div id="{{id}}_WindContQPQULimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpfiltql'>tpfiltql: </label><div class='col-sm-8'><input id='{{id}}_tpfiltql' class='form-control' type='text'{{#tpfiltql}} value='{{tpfiltql}}'{{/tpfiltql}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tufiltql'>tufiltql: </label><div class='col-sm-8'><input id='{{id}}_tufiltql' class='form-control' type='text'{{#tufiltql}} value='{{tufiltql}}'{{/tufiltql}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3or4IEC'>WindTurbineType3or4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3or4IEC' class='form-control' type='text'{{#WindTurbineType3or4IEC}} value='{{WindTurbineType3or4IEC}}'{{/WindTurbineType3or4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContQPQULimIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_tpfiltql").value; if ("" !== temp) obj["tpfiltql"] = temp;
temp = document.getElementById (id + "_tufiltql").value; if ("" !== temp) obj["tufiltql"] = temp;
temp = document.getElementById (id + "_WindTurbineType3or4IEC").value; if ("" !== temp) obj["WindTurbineType3or4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindContQPQULimIEC"],
["WindTurbineType3or4IEC", "0..1", "0..1", "WindTurbineType3or4IEC", "WindContQPQULimIEC"]
]
)
);
}
}
/**
* Simplified plant voltage and reactive power control model for use with type 3 and type 4 wind turbine models.
*
* Reference: IEC 61400-27-1:2015, Annex D.
*
*/
class WindPlantReactiveControlIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindPlantReactiveControlIEC;
if (null == bucket)
cim_data.WindPlantReactiveControlIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindPlantReactiveControlIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindPlantReactiveControlIEC";
base.parse_element (/<cim:WindPlantReactiveControlIEC.dxrefmax>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.dxrefmax>/g, obj, "dxrefmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.dxrefmin>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.dxrefmin>/g, obj, "dxrefmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.kiwpx>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.kiwpx>/g, obj, "kiwpx", base.to_float, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.kiwpxmax>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.kiwpxmax>/g, obj, "kiwpxmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.kiwpxmin>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.kiwpxmin>/g, obj, "kiwpxmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.kpwpx>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.kpwpx>/g, obj, "kpwpx", base.to_float, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.kwpqref>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.kwpqref>/g, obj, "kwpqref", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.kwpqu>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.kwpqu>/g, obj, "kwpqu", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.tuqfilt>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.tuqfilt>/g, obj, "tuqfilt", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.twppfiltq>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.twppfiltq>/g, obj, "twppfiltq", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.twpqfiltq>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.twpqfiltq>/g, obj, "twpqfiltq", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.twpufiltq>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.twpufiltq>/g, obj, "twpufiltq", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.txft>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.txft>/g, obj, "txft", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.txfv>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.txfv>/g, obj, "txfv", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.uwpqdip>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.uwpqdip>/g, obj, "uwpqdip", base.to_string, sub, context);
base.parse_attribute (/<cim:WindPlantReactiveControlIEC.windPlantQcontrolModesType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "windPlantQcontrolModesType", sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.xrefmax>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.xrefmax>/g, obj, "xrefmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantReactiveControlIEC.xrefmin>([\s\S]*?)<\/cim:WindPlantReactiveControlIEC.xrefmin>/g, obj, "xrefmin", base.to_string, sub, context);
base.parse_attributes (/<cim:WindPlantReactiveControlIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
base.parse_attribute (/<cim:WindPlantReactiveControlIEC.WindPlantIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantIEC", sub, context);
let bucket = context.parsed.WindPlantReactiveControlIEC;
if (null == bucket)
context.parsed.WindPlantReactiveControlIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindPlantReactiveControlIEC", "dxrefmax", "dxrefmax", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "dxrefmin", "dxrefmin", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "kiwpx", "kiwpx", base.from_float, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "kiwpxmax", "kiwpxmax", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "kiwpxmin", "kiwpxmin", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "kpwpx", "kpwpx", base.from_float, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "kwpqref", "kwpqref", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "kwpqu", "kwpqu", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "tuqfilt", "tuqfilt", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "twppfiltq", "twppfiltq", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "twpqfiltq", "twpqfiltq", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "twpufiltq", "twpufiltq", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "txft", "txft", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "txfv", "txfv", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "uwpqdip", "uwpqdip", base.from_string, fields);
base.export_attribute (obj, "WindPlantReactiveControlIEC", "windPlantQcontrolModesType", "windPlantQcontrolModesType", fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "xrefmax", "xrefmax", base.from_string, fields);
base.export_element (obj, "WindPlantReactiveControlIEC", "xrefmin", "xrefmin", base.from_string, fields);
base.export_attributes (obj, "WindPlantReactiveControlIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
base.export_attribute (obj, "WindPlantReactiveControlIEC", "WindPlantIEC", "WindPlantIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindPlantReactiveControlIEC_collapse" aria-expanded="true" aria-controls="WindPlantReactiveControlIEC_collapse" style="margin-left: 10px;">WindPlantReactiveControlIEC</a></legend>
<div id="WindPlantReactiveControlIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dxrefmax}}<div><b>dxrefmax</b>: {{dxrefmax}}</div>{{/dxrefmax}}
{{#dxrefmin}}<div><b>dxrefmin</b>: {{dxrefmin}}</div>{{/dxrefmin}}
{{#kiwpx}}<div><b>kiwpx</b>: {{kiwpx}}</div>{{/kiwpx}}
{{#kiwpxmax}}<div><b>kiwpxmax</b>: {{kiwpxmax}}</div>{{/kiwpxmax}}
{{#kiwpxmin}}<div><b>kiwpxmin</b>: {{kiwpxmin}}</div>{{/kiwpxmin}}
{{#kpwpx}}<div><b>kpwpx</b>: {{kpwpx}}</div>{{/kpwpx}}
{{#kwpqref}}<div><b>kwpqref</b>: {{kwpqref}}</div>{{/kwpqref}}
{{#kwpqu}}<div><b>kwpqu</b>: {{kwpqu}}</div>{{/kwpqu}}
{{#tuqfilt}}<div><b>tuqfilt</b>: {{tuqfilt}}</div>{{/tuqfilt}}
{{#twppfiltq}}<div><b>twppfiltq</b>: {{twppfiltq}}</div>{{/twppfiltq}}
{{#twpqfiltq}}<div><b>twpqfiltq</b>: {{twpqfiltq}}</div>{{/twpqfiltq}}
{{#twpufiltq}}<div><b>twpufiltq</b>: {{twpufiltq}}</div>{{/twpufiltq}}
{{#txft}}<div><b>txft</b>: {{txft}}</div>{{/txft}}
{{#txfv}}<div><b>txfv</b>: {{txfv}}</div>{{/txfv}}
{{#uwpqdip}}<div><b>uwpqdip</b>: {{uwpqdip}}</div>{{/uwpqdip}}
{{#windPlantQcontrolModesType}}<div><b>windPlantQcontrolModesType</b>: {{windPlantQcontrolModesType}}</div>{{/windPlantQcontrolModesType}}
{{#xrefmax}}<div><b>xrefmax</b>: {{xrefmax}}</div>{{/xrefmax}}
{{#xrefmin}}<div><b>xrefmin</b>: {{xrefmin}}</div>{{/xrefmin}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
{{#WindPlantIEC}}<div><b>WindPlantIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantIEC}}");}); return false;'>{{WindPlantIEC}}</a></div>{{/WindPlantIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["windPlantQcontrolModesTypeWindPlantQcontrolModeKind"] = [{ id: '', selected: (!obj["windPlantQcontrolModesType"])}]; for (let property in WindPlantQcontrolModeKind) obj["windPlantQcontrolModesTypeWindPlantQcontrolModeKind"].push ({ id: property, selected: obj["windPlantQcontrolModesType"] && obj["windPlantQcontrolModesType"].endsWith ('.' + property)});
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["windPlantQcontrolModesTypeWindPlantQcontrolModeKind"];
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindPlantReactiveControlIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindPlantReactiveControlIEC_collapse" style="margin-left: 10px;">WindPlantReactiveControlIEC</a></legend>
<div id="{{id}}_WindPlantReactiveControlIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dxrefmax'>dxrefmax: </label><div class='col-sm-8'><input id='{{id}}_dxrefmax' class='form-control' type='text'{{#dxrefmax}} value='{{dxrefmax}}'{{/dxrefmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dxrefmin'>dxrefmin: </label><div class='col-sm-8'><input id='{{id}}_dxrefmin' class='form-control' type='text'{{#dxrefmin}} value='{{dxrefmin}}'{{/dxrefmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiwpx'>kiwpx: </label><div class='col-sm-8'><input id='{{id}}_kiwpx' class='form-control' type='text'{{#kiwpx}} value='{{kiwpx}}'{{/kiwpx}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiwpxmax'>kiwpxmax: </label><div class='col-sm-8'><input id='{{id}}_kiwpxmax' class='form-control' type='text'{{#kiwpxmax}} value='{{kiwpxmax}}'{{/kiwpxmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiwpxmin'>kiwpxmin: </label><div class='col-sm-8'><input id='{{id}}_kiwpxmin' class='form-control' type='text'{{#kiwpxmin}} value='{{kiwpxmin}}'{{/kiwpxmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpwpx'>kpwpx: </label><div class='col-sm-8'><input id='{{id}}_kpwpx' class='form-control' type='text'{{#kpwpx}} value='{{kpwpx}}'{{/kpwpx}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kwpqref'>kwpqref: </label><div class='col-sm-8'><input id='{{id}}_kwpqref' class='form-control' type='text'{{#kwpqref}} value='{{kwpqref}}'{{/kwpqref}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kwpqu'>kwpqu: </label><div class='col-sm-8'><input id='{{id}}_kwpqu' class='form-control' type='text'{{#kwpqu}} value='{{kwpqu}}'{{/kwpqu}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tuqfilt'>tuqfilt: </label><div class='col-sm-8'><input id='{{id}}_tuqfilt' class='form-control' type='text'{{#tuqfilt}} value='{{tuqfilt}}'{{/tuqfilt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_twppfiltq'>twppfiltq: </label><div class='col-sm-8'><input id='{{id}}_twppfiltq' class='form-control' type='text'{{#twppfiltq}} value='{{twppfiltq}}'{{/twppfiltq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_twpqfiltq'>twpqfiltq: </label><div class='col-sm-8'><input id='{{id}}_twpqfiltq' class='form-control' type='text'{{#twpqfiltq}} value='{{twpqfiltq}}'{{/twpqfiltq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_twpufiltq'>twpufiltq: </label><div class='col-sm-8'><input id='{{id}}_twpufiltq' class='form-control' type='text'{{#twpufiltq}} value='{{twpufiltq}}'{{/twpufiltq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_txft'>txft: </label><div class='col-sm-8'><input id='{{id}}_txft' class='form-control' type='text'{{#txft}} value='{{txft}}'{{/txft}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_txfv'>txfv: </label><div class='col-sm-8'><input id='{{id}}_txfv' class='form-control' type='text'{{#txfv}} value='{{txfv}}'{{/txfv}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_uwpqdip'>uwpqdip: </label><div class='col-sm-8'><input id='{{id}}_uwpqdip' class='form-control' type='text'{{#uwpqdip}} value='{{uwpqdip}}'{{/uwpqdip}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_windPlantQcontrolModesType'>windPlantQcontrolModesType: </label><div class='col-sm-8'><select id='{{id}}_windPlantQcontrolModesType' class='form-control custom-select'>{{#windPlantQcontrolModesTypeWindPlantQcontrolModeKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/windPlantQcontrolModesTypeWindPlantQcontrolModeKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_xrefmax'>xrefmax: </label><div class='col-sm-8'><input id='{{id}}_xrefmax' class='form-control' type='text'{{#xrefmax}} value='{{xrefmax}}'{{/xrefmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_xrefmin'>xrefmin: </label><div class='col-sm-8'><input id='{{id}}_xrefmin' class='form-control' type='text'{{#xrefmin}} value='{{xrefmin}}'{{/xrefmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantIEC'>WindPlantIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPlantIEC' class='form-control' type='text'{{#WindPlantIEC}} value='{{WindPlantIEC}}'{{/WindPlantIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindPlantReactiveControlIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dxrefmax").value; if ("" !== temp) obj["dxrefmax"] = temp;
temp = document.getElementById (id + "_dxrefmin").value; if ("" !== temp) obj["dxrefmin"] = temp;
temp = document.getElementById (id + "_kiwpx").value; if ("" !== temp) obj["kiwpx"] = temp;
temp = document.getElementById (id + "_kiwpxmax").value; if ("" !== temp) obj["kiwpxmax"] = temp;
temp = document.getElementById (id + "_kiwpxmin").value; if ("" !== temp) obj["kiwpxmin"] = temp;
temp = document.getElementById (id + "_kpwpx").value; if ("" !== temp) obj["kpwpx"] = temp;
temp = document.getElementById (id + "_kwpqref").value; if ("" !== temp) obj["kwpqref"] = temp;
temp = document.getElementById (id + "_kwpqu").value; if ("" !== temp) obj["kwpqu"] = temp;
temp = document.getElementById (id + "_tuqfilt").value; if ("" !== temp) obj["tuqfilt"] = temp;
temp = document.getElementById (id + "_twppfiltq").value; if ("" !== temp) obj["twppfiltq"] = temp;
temp = document.getElementById (id + "_twpqfiltq").value; if ("" !== temp) obj["twpqfiltq"] = temp;
temp = document.getElementById (id + "_twpufiltq").value; if ("" !== temp) obj["twpufiltq"] = temp;
temp = document.getElementById (id + "_txft").value; if ("" !== temp) obj["txft"] = temp;
temp = document.getElementById (id + "_txfv").value; if ("" !== temp) obj["txfv"] = temp;
temp = document.getElementById (id + "_uwpqdip").value; if ("" !== temp) obj["uwpqdip"] = temp;
temp = WindPlantQcontrolModeKind[document.getElementById (id + "_windPlantQcontrolModesType").value]; if (temp) obj["windPlantQcontrolModesType"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#WindPlantQcontrolModeKind." + temp; else delete obj["windPlantQcontrolModesType"];
temp = document.getElementById (id + "_xrefmax").value; if ("" !== temp) obj["xrefmax"] = temp;
temp = document.getElementById (id + "_xrefmin").value; if ("" !== temp) obj["xrefmin"] = temp;
temp = document.getElementById (id + "_WindPlantIEC").value; if ("" !== temp) obj["WindPlantIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindPlantReactiveControlIEC"],
["WindPlantIEC", "1", "1", "WindPlantIEC", "WindPlantReactiveControlIEC"]
]
)
);
}
}
/**
* Constant Q limitation model.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.9.
*
*/
class WindContQLimIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContQLimIEC;
if (null == bucket)
cim_data.WindContQLimIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContQLimIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContQLimIEC";
base.parse_element (/<cim:WindContQLimIEC.qmax>([\s\S]*?)<\/cim:WindContQLimIEC.qmax>/g, obj, "qmax", base.to_string, sub, context);
base.parse_element (/<cim:WindContQLimIEC.qmin>([\s\S]*?)<\/cim:WindContQLimIEC.qmin>/g, obj, "qmin", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContQLimIEC.WindTurbineType3or4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4IEC", sub, context);
let bucket = context.parsed.WindContQLimIEC;
if (null == bucket)
context.parsed.WindContQLimIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContQLimIEC", "qmax", "qmax", base.from_string, fields);
base.export_element (obj, "WindContQLimIEC", "qmin", "qmin", base.from_string, fields);
base.export_attribute (obj, "WindContQLimIEC", "WindTurbineType3or4IEC", "WindTurbineType3or4IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContQLimIEC_collapse" aria-expanded="true" aria-controls="WindContQLimIEC_collapse" style="margin-left: 10px;">WindContQLimIEC</a></legend>
<div id="WindContQLimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#qmax}}<div><b>qmax</b>: {{qmax}}</div>{{/qmax}}
{{#qmin}}<div><b>qmin</b>: {{qmin}}</div>{{/qmin}}
{{#WindTurbineType3or4IEC}}<div><b>WindTurbineType3or4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3or4IEC}}");}); return false;'>{{WindTurbineType3or4IEC}}</a></div>{{/WindTurbineType3or4IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContQLimIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContQLimIEC_collapse" style="margin-left: 10px;">WindContQLimIEC</a></legend>
<div id="{{id}}_WindContQLimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_qmax'>qmax: </label><div class='col-sm-8'><input id='{{id}}_qmax' class='form-control' type='text'{{#qmax}} value='{{qmax}}'{{/qmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_qmin'>qmin: </label><div class='col-sm-8'><input id='{{id}}_qmin' class='form-control' type='text'{{#qmin}} value='{{qmin}}'{{/qmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3or4IEC'>WindTurbineType3or4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3or4IEC' class='form-control' type='text'{{#WindTurbineType3or4IEC}} value='{{WindTurbineType3or4IEC}}'{{/WindTurbineType3or4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContQLimIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_qmax").value; if ("" !== temp) obj["qmax"] = temp;
temp = document.getElementById (id + "_qmin").value; if ("" !== temp) obj["qmin"] = temp;
temp = document.getElementById (id + "_WindTurbineType3or4IEC").value; if ("" !== temp) obj["WindTurbineType3or4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3or4IEC", "0..1", "0..1", "WindTurbineType3or4IEC", "WindContQLimIEC"]
]
)
);
}
}
/**
* One-dimensional aerodynamic model.
*
* Reference: IEC 61400-27-1:2015, 5.6.1.2.
*
*/
class WindAeroOneDimIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindAeroOneDimIEC;
if (null == bucket)
cim_data.WindAeroOneDimIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindAeroOneDimIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindAeroOneDimIEC";
base.parse_element (/<cim:WindAeroOneDimIEC.ka>([\s\S]*?)<\/cim:WindAeroOneDimIEC.ka>/g, obj, "ka", base.to_float, sub, context);
base.parse_element (/<cim:WindAeroOneDimIEC.thetaomega>([\s\S]*?)<\/cim:WindAeroOneDimIEC.thetaomega>/g, obj, "thetaomega", base.to_string, sub, context);
base.parse_attribute (/<cim:WindAeroOneDimIEC.WindTurbineType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3IEC", sub, context);
let bucket = context.parsed.WindAeroOneDimIEC;
if (null == bucket)
context.parsed.WindAeroOneDimIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindAeroOneDimIEC", "ka", "ka", base.from_float, fields);
base.export_element (obj, "WindAeroOneDimIEC", "thetaomega", "thetaomega", base.from_string, fields);
base.export_attribute (obj, "WindAeroOneDimIEC", "WindTurbineType3IEC", "WindTurbineType3IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindAeroOneDimIEC_collapse" aria-expanded="true" aria-controls="WindAeroOneDimIEC_collapse" style="margin-left: 10px;">WindAeroOneDimIEC</a></legend>
<div id="WindAeroOneDimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#ka}}<div><b>ka</b>: {{ka}}</div>{{/ka}}
{{#thetaomega}}<div><b>thetaomega</b>: {{thetaomega}}</div>{{/thetaomega}}
{{#WindTurbineType3IEC}}<div><b>WindTurbineType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3IEC}}");}); return false;'>{{WindTurbineType3IEC}}</a></div>{{/WindTurbineType3IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindAeroOneDimIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindAeroOneDimIEC_collapse" style="margin-left: 10px;">WindAeroOneDimIEC</a></legend>
<div id="{{id}}_WindAeroOneDimIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ka'>ka: </label><div class='col-sm-8'><input id='{{id}}_ka' class='form-control' type='text'{{#ka}} value='{{ka}}'{{/ka}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_thetaomega'>thetaomega: </label><div class='col-sm-8'><input id='{{id}}_thetaomega' class='form-control' type='text'{{#thetaomega}} value='{{thetaomega}}'{{/thetaomega}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3IEC'>WindTurbineType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3IEC' class='form-control' type='text'{{#WindTurbineType3IEC}} value='{{WindTurbineType3IEC}}'{{/WindTurbineType3IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindAeroOneDimIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_ka").value; if ("" !== temp) obj["ka"] = temp;
temp = document.getElementById (id + "_thetaomega").value; if ("" !== temp) obj["thetaomega"] = temp;
temp = document.getElementById (id + "_WindTurbineType3IEC").value; if ("" !== temp) obj["WindTurbineType3IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3IEC", "1", "0..1", "WindTurbineType3IEC", "WindAeroOneDimIEC"]
]
)
);
}
}
/**
* Rotor resistance control model.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.3.
*
*/
class WindContRotorRIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContRotorRIEC;
if (null == bucket)
cim_data.WindContRotorRIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContRotorRIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContRotorRIEC";
base.parse_element (/<cim:WindContRotorRIEC.kirr>([\s\S]*?)<\/cim:WindContRotorRIEC.kirr>/g, obj, "kirr", base.to_string, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.komegafilt>([\s\S]*?)<\/cim:WindContRotorRIEC.komegafilt>/g, obj, "komegafilt", base.to_float, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.kpfilt>([\s\S]*?)<\/cim:WindContRotorRIEC.kpfilt>/g, obj, "kpfilt", base.to_float, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.kprr>([\s\S]*?)<\/cim:WindContRotorRIEC.kprr>/g, obj, "kprr", base.to_string, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.rmax>([\s\S]*?)<\/cim:WindContRotorRIEC.rmax>/g, obj, "rmax", base.to_string, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.rmin>([\s\S]*?)<\/cim:WindContRotorRIEC.rmin>/g, obj, "rmin", base.to_string, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.tomegafiltrr>([\s\S]*?)<\/cim:WindContRotorRIEC.tomegafiltrr>/g, obj, "tomegafiltrr", base.to_string, sub, context);
base.parse_element (/<cim:WindContRotorRIEC.tpfiltrr>([\s\S]*?)<\/cim:WindContRotorRIEC.tpfiltrr>/g, obj, "tpfiltrr", base.to_string, sub, context);
base.parse_attributes (/<cim:WindContRotorRIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
base.parse_attribute (/<cim:WindContRotorRIEC.WindGenTurbineType2IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenTurbineType2IEC", sub, context);
let bucket = context.parsed.WindContRotorRIEC;
if (null == bucket)
context.parsed.WindContRotorRIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContRotorRIEC", "kirr", "kirr", base.from_string, fields);
base.export_element (obj, "WindContRotorRIEC", "komegafilt", "komegafilt", base.from_float, fields);
base.export_element (obj, "WindContRotorRIEC", "kpfilt", "kpfilt", base.from_float, fields);
base.export_element (obj, "WindContRotorRIEC", "kprr", "kprr", base.from_string, fields);
base.export_element (obj, "WindContRotorRIEC", "rmax", "rmax", base.from_string, fields);
base.export_element (obj, "WindContRotorRIEC", "rmin", "rmin", base.from_string, fields);
base.export_element (obj, "WindContRotorRIEC", "tomegafiltrr", "tomegafiltrr", base.from_string, fields);
base.export_element (obj, "WindContRotorRIEC", "tpfiltrr", "tpfiltrr", base.from_string, fields);
base.export_attributes (obj, "WindContRotorRIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
base.export_attribute (obj, "WindContRotorRIEC", "WindGenTurbineType2IEC", "WindGenTurbineType2IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContRotorRIEC_collapse" aria-expanded="true" aria-controls="WindContRotorRIEC_collapse" style="margin-left: 10px;">WindContRotorRIEC</a></legend>
<div id="WindContRotorRIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#kirr}}<div><b>kirr</b>: {{kirr}}</div>{{/kirr}}
{{#komegafilt}}<div><b>komegafilt</b>: {{komegafilt}}</div>{{/komegafilt}}
{{#kpfilt}}<div><b>kpfilt</b>: {{kpfilt}}</div>{{/kpfilt}}
{{#kprr}}<div><b>kprr</b>: {{kprr}}</div>{{/kprr}}
{{#rmax}}<div><b>rmax</b>: {{rmax}}</div>{{/rmax}}
{{#rmin}}<div><b>rmin</b>: {{rmin}}</div>{{/rmin}}
{{#tomegafiltrr}}<div><b>tomegafiltrr</b>: {{tomegafiltrr}}</div>{{/tomegafiltrr}}
{{#tpfiltrr}}<div><b>tpfiltrr</b>: {{tpfiltrr}}</div>{{/tpfiltrr}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
{{#WindGenTurbineType2IEC}}<div><b>WindGenTurbineType2IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenTurbineType2IEC}}");}); return false;'>{{WindGenTurbineType2IEC}}</a></div>{{/WindGenTurbineType2IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContRotorRIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContRotorRIEC_collapse" style="margin-left: 10px;">WindContRotorRIEC</a></legend>
<div id="{{id}}_WindContRotorRIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kirr'>kirr: </label><div class='col-sm-8'><input id='{{id}}_kirr' class='form-control' type='text'{{#kirr}} value='{{kirr}}'{{/kirr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_komegafilt'>komegafilt: </label><div class='col-sm-8'><input id='{{id}}_komegafilt' class='form-control' type='text'{{#komegafilt}} value='{{komegafilt}}'{{/komegafilt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpfilt'>kpfilt: </label><div class='col-sm-8'><input id='{{id}}_kpfilt' class='form-control' type='text'{{#kpfilt}} value='{{kpfilt}}'{{/kpfilt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kprr'>kprr: </label><div class='col-sm-8'><input id='{{id}}_kprr' class='form-control' type='text'{{#kprr}} value='{{kprr}}'{{/kprr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rmax'>rmax: </label><div class='col-sm-8'><input id='{{id}}_rmax' class='form-control' type='text'{{#rmax}} value='{{rmax}}'{{/rmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rmin'>rmin: </label><div class='col-sm-8'><input id='{{id}}_rmin' class='form-control' type='text'{{#rmin}} value='{{rmin}}'{{/rmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tomegafiltrr'>tomegafiltrr: </label><div class='col-sm-8'><input id='{{id}}_tomegafiltrr' class='form-control' type='text'{{#tomegafiltrr}} value='{{tomegafiltrr}}'{{/tomegafiltrr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpfiltrr'>tpfiltrr: </label><div class='col-sm-8'><input id='{{id}}_tpfiltrr' class='form-control' type='text'{{#tpfiltrr}} value='{{tpfiltrr}}'{{/tpfiltrr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenTurbineType2IEC'>WindGenTurbineType2IEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenTurbineType2IEC' class='form-control' type='text'{{#WindGenTurbineType2IEC}} value='{{WindGenTurbineType2IEC}}'{{/WindGenTurbineType2IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContRotorRIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_kirr").value; if ("" !== temp) obj["kirr"] = temp;
temp = document.getElementById (id + "_komegafilt").value; if ("" !== temp) obj["komegafilt"] = temp;
temp = document.getElementById (id + "_kpfilt").value; if ("" !== temp) obj["kpfilt"] = temp;
temp = document.getElementById (id + "_kprr").value; if ("" !== temp) obj["kprr"] = temp;
temp = document.getElementById (id + "_rmax").value; if ("" !== temp) obj["rmax"] = temp;
temp = document.getElementById (id + "_rmin").value; if ("" !== temp) obj["rmin"] = temp;
temp = document.getElementById (id + "_tomegafiltrr").value; if ("" !== temp) obj["tomegafiltrr"] = temp;
temp = document.getElementById (id + "_tpfiltrr").value; if ("" !== temp) obj["tpfiltrr"] = temp;
temp = document.getElementById (id + "_WindGenTurbineType2IEC").value; if ("" !== temp) obj["WindGenTurbineType2IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindContRotorRIEC"],
["WindGenTurbineType2IEC", "1", "1", "WindGenTurbineType2IEC", "WindContRotorRIEC"]
]
)
);
}
}
/**
* Frequency and active power controller model.
*
* Reference: IEC 61400-27-1:2015, Annex D.
*
*/
class WindPlantFreqPcontrolIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindPlantFreqPcontrolIEC;
if (null == bucket)
cim_data.WindPlantFreqPcontrolIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindPlantFreqPcontrolIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindPlantFreqPcontrolIEC";
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.dprefmax>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.dprefmax>/g, obj, "dprefmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.dprefmin>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.dprefmin>/g, obj, "dprefmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.dpwprefmax>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.dpwprefmax>/g, obj, "dpwprefmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.dpwprefmin>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.dpwprefmin>/g, obj, "dpwprefmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.kiwpp>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.kiwpp>/g, obj, "kiwpp", base.to_float, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.kiwppmax>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.kiwppmax>/g, obj, "kiwppmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.kiwppmin>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.kiwppmin>/g, obj, "kiwppmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.kpwpp>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.kpwpp>/g, obj, "kpwpp", base.to_float, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.kwppref>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.kwppref>/g, obj, "kwppref", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.prefmax>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.prefmax>/g, obj, "prefmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.prefmin>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.prefmin>/g, obj, "prefmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.tpft>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.tpft>/g, obj, "tpft", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.tpfv>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.tpfv>/g, obj, "tpfv", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.twpffiltp>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.twpffiltp>/g, obj, "twpffiltp", base.to_string, sub, context);
base.parse_element (/<cim:WindPlantFreqPcontrolIEC.twppfiltp>([\s\S]*?)<\/cim:WindPlantFreqPcontrolIEC.twppfiltp>/g, obj, "twppfiltp", base.to_string, sub, context);
base.parse_attribute (/<cim:WindPlantFreqPcontrolIEC.WindPlantIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantIEC", sub, context);
base.parse_attributes (/<cim:WindPlantFreqPcontrolIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
let bucket = context.parsed.WindPlantFreqPcontrolIEC;
if (null == bucket)
context.parsed.WindPlantFreqPcontrolIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "dprefmax", "dprefmax", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "dprefmin", "dprefmin", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "dpwprefmax", "dpwprefmax", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "dpwprefmin", "dpwprefmin", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "kiwpp", "kiwpp", base.from_float, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "kiwppmax", "kiwppmax", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "kiwppmin", "kiwppmin", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "kpwpp", "kpwpp", base.from_float, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "kwppref", "kwppref", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "prefmax", "prefmax", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "prefmin", "prefmin", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "tpft", "tpft", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "tpfv", "tpfv", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "twpffiltp", "twpffiltp", base.from_string, fields);
base.export_element (obj, "WindPlantFreqPcontrolIEC", "twppfiltp", "twppfiltp", base.from_string, fields);
base.export_attribute (obj, "WindPlantFreqPcontrolIEC", "WindPlantIEC", "WindPlantIEC", fields);
base.export_attributes (obj, "WindPlantFreqPcontrolIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindPlantFreqPcontrolIEC_collapse" aria-expanded="true" aria-controls="WindPlantFreqPcontrolIEC_collapse" style="margin-left: 10px;">WindPlantFreqPcontrolIEC</a></legend>
<div id="WindPlantFreqPcontrolIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dprefmax}}<div><b>dprefmax</b>: {{dprefmax}}</div>{{/dprefmax}}
{{#dprefmin}}<div><b>dprefmin</b>: {{dprefmin}}</div>{{/dprefmin}}
{{#dpwprefmax}}<div><b>dpwprefmax</b>: {{dpwprefmax}}</div>{{/dpwprefmax}}
{{#dpwprefmin}}<div><b>dpwprefmin</b>: {{dpwprefmin}}</div>{{/dpwprefmin}}
{{#kiwpp}}<div><b>kiwpp</b>: {{kiwpp}}</div>{{/kiwpp}}
{{#kiwppmax}}<div><b>kiwppmax</b>: {{kiwppmax}}</div>{{/kiwppmax}}
{{#kiwppmin}}<div><b>kiwppmin</b>: {{kiwppmin}}</div>{{/kiwppmin}}
{{#kpwpp}}<div><b>kpwpp</b>: {{kpwpp}}</div>{{/kpwpp}}
{{#kwppref}}<div><b>kwppref</b>: {{kwppref}}</div>{{/kwppref}}
{{#prefmax}}<div><b>prefmax</b>: {{prefmax}}</div>{{/prefmax}}
{{#prefmin}}<div><b>prefmin</b>: {{prefmin}}</div>{{/prefmin}}
{{#tpft}}<div><b>tpft</b>: {{tpft}}</div>{{/tpft}}
{{#tpfv}}<div><b>tpfv</b>: {{tpfv}}</div>{{/tpfv}}
{{#twpffiltp}}<div><b>twpffiltp</b>: {{twpffiltp}}</div>{{/twpffiltp}}
{{#twppfiltp}}<div><b>twppfiltp</b>: {{twppfiltp}}</div>{{/twppfiltp}}
{{#WindPlantIEC}}<div><b>WindPlantIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantIEC}}");}); return false;'>{{WindPlantIEC}}</a></div>{{/WindPlantIEC}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindPlantFreqPcontrolIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindPlantFreqPcontrolIEC_collapse" style="margin-left: 10px;">WindPlantFreqPcontrolIEC</a></legend>
<div id="{{id}}_WindPlantFreqPcontrolIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dprefmax'>dprefmax: </label><div class='col-sm-8'><input id='{{id}}_dprefmax' class='form-control' type='text'{{#dprefmax}} value='{{dprefmax}}'{{/dprefmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dprefmin'>dprefmin: </label><div class='col-sm-8'><input id='{{id}}_dprefmin' class='form-control' type='text'{{#dprefmin}} value='{{dprefmin}}'{{/dprefmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpwprefmax'>dpwprefmax: </label><div class='col-sm-8'><input id='{{id}}_dpwprefmax' class='form-control' type='text'{{#dpwprefmax}} value='{{dpwprefmax}}'{{/dpwprefmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpwprefmin'>dpwprefmin: </label><div class='col-sm-8'><input id='{{id}}_dpwprefmin' class='form-control' type='text'{{#dpwprefmin}} value='{{dpwprefmin}}'{{/dpwprefmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiwpp'>kiwpp: </label><div class='col-sm-8'><input id='{{id}}_kiwpp' class='form-control' type='text'{{#kiwpp}} value='{{kiwpp}}'{{/kiwpp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiwppmax'>kiwppmax: </label><div class='col-sm-8'><input id='{{id}}_kiwppmax' class='form-control' type='text'{{#kiwppmax}} value='{{kiwppmax}}'{{/kiwppmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiwppmin'>kiwppmin: </label><div class='col-sm-8'><input id='{{id}}_kiwppmin' class='form-control' type='text'{{#kiwppmin}} value='{{kiwppmin}}'{{/kiwppmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpwpp'>kpwpp: </label><div class='col-sm-8'><input id='{{id}}_kpwpp' class='form-control' type='text'{{#kpwpp}} value='{{kpwpp}}'{{/kpwpp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kwppref'>kwppref: </label><div class='col-sm-8'><input id='{{id}}_kwppref' class='form-control' type='text'{{#kwppref}} value='{{kwppref}}'{{/kwppref}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_prefmax'>prefmax: </label><div class='col-sm-8'><input id='{{id}}_prefmax' class='form-control' type='text'{{#prefmax}} value='{{prefmax}}'{{/prefmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_prefmin'>prefmin: </label><div class='col-sm-8'><input id='{{id}}_prefmin' class='form-control' type='text'{{#prefmin}} value='{{prefmin}}'{{/prefmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpft'>tpft: </label><div class='col-sm-8'><input id='{{id}}_tpft' class='form-control' type='text'{{#tpft}} value='{{tpft}}'{{/tpft}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpfv'>tpfv: </label><div class='col-sm-8'><input id='{{id}}_tpfv' class='form-control' type='text'{{#tpfv}} value='{{tpfv}}'{{/tpfv}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_twpffiltp'>twpffiltp: </label><div class='col-sm-8'><input id='{{id}}_twpffiltp' class='form-control' type='text'{{#twpffiltp}} value='{{twpffiltp}}'{{/twpffiltp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_twppfiltp'>twppfiltp: </label><div class='col-sm-8'><input id='{{id}}_twppfiltp' class='form-control' type='text'{{#twppfiltp}} value='{{twppfiltp}}'{{/twppfiltp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantIEC'>WindPlantIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPlantIEC' class='form-control' type='text'{{#WindPlantIEC}} value='{{WindPlantIEC}}'{{/WindPlantIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindPlantFreqPcontrolIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dprefmax").value; if ("" !== temp) obj["dprefmax"] = temp;
temp = document.getElementById (id + "_dprefmin").value; if ("" !== temp) obj["dprefmin"] = temp;
temp = document.getElementById (id + "_dpwprefmax").value; if ("" !== temp) obj["dpwprefmax"] = temp;
temp = document.getElementById (id + "_dpwprefmin").value; if ("" !== temp) obj["dpwprefmin"] = temp;
temp = document.getElementById (id + "_kiwpp").value; if ("" !== temp) obj["kiwpp"] = temp;
temp = document.getElementById (id + "_kiwppmax").value; if ("" !== temp) obj["kiwppmax"] = temp;
temp = document.getElementById (id + "_kiwppmin").value; if ("" !== temp) obj["kiwppmin"] = temp;
temp = document.getElementById (id + "_kpwpp").value; if ("" !== temp) obj["kpwpp"] = temp;
temp = document.getElementById (id + "_kwppref").value; if ("" !== temp) obj["kwppref"] = temp;
temp = document.getElementById (id + "_prefmax").value; if ("" !== temp) obj["prefmax"] = temp;
temp = document.getElementById (id + "_prefmin").value; if ("" !== temp) obj["prefmin"] = temp;
temp = document.getElementById (id + "_tpft").value; if ("" !== temp) obj["tpft"] = temp;
temp = document.getElementById (id + "_tpfv").value; if ("" !== temp) obj["tpfv"] = temp;
temp = document.getElementById (id + "_twpffiltp").value; if ("" !== temp) obj["twpffiltp"] = temp;
temp = document.getElementById (id + "_twppfiltp").value; if ("" !== temp) obj["twppfiltp"] = temp;
temp = document.getElementById (id + "_WindPlantIEC").value; if ("" !== temp) obj["WindPlantIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindPlantIEC", "1", "1", "WindPlantIEC", "WindPlantFreqPcontrolIEC"],
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindPlantFreqPcontrolIEC"]
]
)
);
}
}
/**
* Reference frame rotation model.
*
* Reference: IEC 61400-27-1:2015, 5.6.3.5.
*
*/
class WindRefFrameRotIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindRefFrameRotIEC;
if (null == bucket)
cim_data.WindRefFrameRotIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindRefFrameRotIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindRefFrameRotIEC";
base.parse_element (/<cim:WindRefFrameRotIEC.tpll>([\s\S]*?)<\/cim:WindRefFrameRotIEC.tpll>/g, obj, "tpll", base.to_string, sub, context);
base.parse_element (/<cim:WindRefFrameRotIEC.upll1>([\s\S]*?)<\/cim:WindRefFrameRotIEC.upll1>/g, obj, "upll1", base.to_string, sub, context);
base.parse_element (/<cim:WindRefFrameRotIEC.upll2>([\s\S]*?)<\/cim:WindRefFrameRotIEC.upll2>/g, obj, "upll2", base.to_string, sub, context);
base.parse_attribute (/<cim:WindRefFrameRotIEC.WindTurbineType3or4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4IEC", sub, context);
let bucket = context.parsed.WindRefFrameRotIEC;
if (null == bucket)
context.parsed.WindRefFrameRotIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindRefFrameRotIEC", "tpll", "tpll", base.from_string, fields);
base.export_element (obj, "WindRefFrameRotIEC", "upll1", "upll1", base.from_string, fields);
base.export_element (obj, "WindRefFrameRotIEC", "upll2", "upll2", base.from_string, fields);
base.export_attribute (obj, "WindRefFrameRotIEC", "WindTurbineType3or4IEC", "WindTurbineType3or4IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindRefFrameRotIEC_collapse" aria-expanded="true" aria-controls="WindRefFrameRotIEC_collapse" style="margin-left: 10px;">WindRefFrameRotIEC</a></legend>
<div id="WindRefFrameRotIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#tpll}}<div><b>tpll</b>: {{tpll}}</div>{{/tpll}}
{{#upll1}}<div><b>upll1</b>: {{upll1}}</div>{{/upll1}}
{{#upll2}}<div><b>upll2</b>: {{upll2}}</div>{{/upll2}}
{{#WindTurbineType3or4IEC}}<div><b>WindTurbineType3or4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3or4IEC}}");}); return false;'>{{WindTurbineType3or4IEC}}</a></div>{{/WindTurbineType3or4IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindRefFrameRotIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindRefFrameRotIEC_collapse" style="margin-left: 10px;">WindRefFrameRotIEC</a></legend>
<div id="{{id}}_WindRefFrameRotIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpll'>tpll: </label><div class='col-sm-8'><input id='{{id}}_tpll' class='form-control' type='text'{{#tpll}} value='{{tpll}}'{{/tpll}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_upll1'>upll1: </label><div class='col-sm-8'><input id='{{id}}_upll1' class='form-control' type='text'{{#upll1}} value='{{upll1}}'{{/upll1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_upll2'>upll2: </label><div class='col-sm-8'><input id='{{id}}_upll2' class='form-control' type='text'{{#upll2}} value='{{upll2}}'{{/upll2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3or4IEC'>WindTurbineType3or4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3or4IEC' class='form-control' type='text'{{#WindTurbineType3or4IEC}} value='{{WindTurbineType3or4IEC}}'{{/WindTurbineType3or4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindRefFrameRotIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_tpll").value; if ("" !== temp) obj["tpll"] = temp;
temp = document.getElementById (id + "_upll1").value; if ("" !== temp) obj["upll1"] = temp;
temp = document.getElementById (id + "_upll2").value; if ("" !== temp) obj["upll2"] = temp;
temp = document.getElementById (id + "_WindTurbineType3or4IEC").value; if ("" !== temp) obj["WindTurbineType3or4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3or4IEC", "1", "1", "WindTurbineType3or4IEC", "WindRefFrameRotIEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to wind turbines type 1 and type 2 and their control models.
*
* Generator model for wind turbine of type 1 or type 2 is a standard asynchronous generator model.
*
*/
class WindTurbineType1or2Dynamics extends StandardModels.DynamicsFunctionBlock
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType1or2Dynamics;
if (null == bucket)
cim_data.WindTurbineType1or2Dynamics = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType1or2Dynamics[obj.id];
}
parse (context, sub)
{
let obj = StandardModels.DynamicsFunctionBlock.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType1or2Dynamics";
base.parse_attribute (/<cim:WindTurbineType1or2Dynamics.RemoteInputSignal\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "RemoteInputSignal", sub, context);
base.parse_attribute (/<cim:WindTurbineType1or2Dynamics.AsynchronousMachineDynamics\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AsynchronousMachineDynamics", sub, context);
let bucket = context.parsed.WindTurbineType1or2Dynamics;
if (null == bucket)
context.parsed.WindTurbineType1or2Dynamics = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = StandardModels.DynamicsFunctionBlock.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType1or2Dynamics", "RemoteInputSignal", "RemoteInputSignal", fields);
base.export_attribute (obj, "WindTurbineType1or2Dynamics", "AsynchronousMachineDynamics", "AsynchronousMachineDynamics", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType1or2Dynamics_collapse" aria-expanded="true" aria-controls="WindTurbineType1or2Dynamics_collapse" style="margin-left: 10px;">WindTurbineType1or2Dynamics</a></legend>
<div id="WindTurbineType1or2Dynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ StandardModels.DynamicsFunctionBlock.prototype.template.call (this) +
`
{{#RemoteInputSignal}}<div><b>RemoteInputSignal</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{RemoteInputSignal}}");}); return false;'>{{RemoteInputSignal}}</a></div>{{/RemoteInputSignal}}
{{#AsynchronousMachineDynamics}}<div><b>AsynchronousMachineDynamics</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AsynchronousMachineDynamics}}");}); return false;'>{{AsynchronousMachineDynamics}}</a></div>{{/AsynchronousMachineDynamics}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType1or2Dynamics_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType1or2Dynamics_collapse" style="margin-left: 10px;">WindTurbineType1or2Dynamics</a></legend>
<div id="{{id}}_WindTurbineType1or2Dynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ StandardModels.DynamicsFunctionBlock.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_RemoteInputSignal'>RemoteInputSignal: </label><div class='col-sm-8'><input id='{{id}}_RemoteInputSignal' class='form-control' type='text'{{#RemoteInputSignal}} value='{{RemoteInputSignal}}'{{/RemoteInputSignal}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AsynchronousMachineDynamics'>AsynchronousMachineDynamics: </label><div class='col-sm-8'><input id='{{id}}_AsynchronousMachineDynamics' class='form-control' type='text'{{#AsynchronousMachineDynamics}} value='{{AsynchronousMachineDynamics}}'{{/AsynchronousMachineDynamics}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType1or2Dynamics" };
super.submit (id, obj);
temp = document.getElementById (id + "_RemoteInputSignal").value; if ("" !== temp) obj["RemoteInputSignal"] = temp;
temp = document.getElementById (id + "_AsynchronousMachineDynamics").value; if ("" !== temp) obj["AsynchronousMachineDynamics"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["RemoteInputSignal", "0..1", "0..1", "RemoteInputSignal", "WindTurbineType1or2Dynamics"],
["AsynchronousMachineDynamics", "1", "0..1", "AsynchronousMachineDynamics", "WindTurbineType1or2Dynamics"]
]
)
);
}
}
/**
* Pitch control power model.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.1.
*
*/
class WindPitchContPowerIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindPitchContPowerIEC;
if (null == bucket)
cim_data.WindPitchContPowerIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindPitchContPowerIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindPitchContPowerIEC";
base.parse_element (/<cim:WindPitchContPowerIEC.dpmax>([\s\S]*?)<\/cim:WindPitchContPowerIEC.dpmax>/g, obj, "dpmax", base.to_string, sub, context);
base.parse_element (/<cim:WindPitchContPowerIEC.dpmin>([\s\S]*?)<\/cim:WindPitchContPowerIEC.dpmin>/g, obj, "dpmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPitchContPowerIEC.pmin>([\s\S]*?)<\/cim:WindPitchContPowerIEC.pmin>/g, obj, "pmin", base.to_string, sub, context);
base.parse_element (/<cim:WindPitchContPowerIEC.pset>([\s\S]*?)<\/cim:WindPitchContPowerIEC.pset>/g, obj, "pset", base.to_string, sub, context);
base.parse_element (/<cim:WindPitchContPowerIEC.t1>([\s\S]*?)<\/cim:WindPitchContPowerIEC.t1>/g, obj, "t1", base.to_string, sub, context);
base.parse_element (/<cim:WindPitchContPowerIEC.tr>([\s\S]*?)<\/cim:WindPitchContPowerIEC.tr>/g, obj, "tr", base.to_string, sub, context);
base.parse_element (/<cim:WindPitchContPowerIEC.uuvrt>([\s\S]*?)<\/cim:WindPitchContPowerIEC.uuvrt>/g, obj, "uuvrt", base.to_string, sub, context);
base.parse_attribute (/<cim:WindPitchContPowerIEC.WindGenTurbineType2IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenTurbineType2IEC", sub, context);
base.parse_attribute (/<cim:WindPitchContPowerIEC.WindGenTurbineType1bIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenTurbineType1bIEC", sub, context);
base.parse_attributes (/<cim:WindPitchContPowerIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
let bucket = context.parsed.WindPitchContPowerIEC;
if (null == bucket)
context.parsed.WindPitchContPowerIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindPitchContPowerIEC", "dpmax", "dpmax", base.from_string, fields);
base.export_element (obj, "WindPitchContPowerIEC", "dpmin", "dpmin", base.from_string, fields);
base.export_element (obj, "WindPitchContPowerIEC", "pmin", "pmin", base.from_string, fields);
base.export_element (obj, "WindPitchContPowerIEC", "pset", "pset", base.from_string, fields);
base.export_element (obj, "WindPitchContPowerIEC", "t1", "t1", base.from_string, fields);
base.export_element (obj, "WindPitchContPowerIEC", "tr", "tr", base.from_string, fields);
base.export_element (obj, "WindPitchContPowerIEC", "uuvrt", "uuvrt", base.from_string, fields);
base.export_attribute (obj, "WindPitchContPowerIEC", "WindGenTurbineType2IEC", "WindGenTurbineType2IEC", fields);
base.export_attribute (obj, "WindPitchContPowerIEC", "WindGenTurbineType1bIEC", "WindGenTurbineType1bIEC", fields);
base.export_attributes (obj, "WindPitchContPowerIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindPitchContPowerIEC_collapse" aria-expanded="true" aria-controls="WindPitchContPowerIEC_collapse" style="margin-left: 10px;">WindPitchContPowerIEC</a></legend>
<div id="WindPitchContPowerIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dpmax}}<div><b>dpmax</b>: {{dpmax}}</div>{{/dpmax}}
{{#dpmin}}<div><b>dpmin</b>: {{dpmin}}</div>{{/dpmin}}
{{#pmin}}<div><b>pmin</b>: {{pmin}}</div>{{/pmin}}
{{#pset}}<div><b>pset</b>: {{pset}}</div>{{/pset}}
{{#t1}}<div><b>t1</b>: {{t1}}</div>{{/t1}}
{{#tr}}<div><b>tr</b>: {{tr}}</div>{{/tr}}
{{#uuvrt}}<div><b>uuvrt</b>: {{uuvrt}}</div>{{/uuvrt}}
{{#WindGenTurbineType2IEC}}<div><b>WindGenTurbineType2IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenTurbineType2IEC}}");}); return false;'>{{WindGenTurbineType2IEC}}</a></div>{{/WindGenTurbineType2IEC}}
{{#WindGenTurbineType1bIEC}}<div><b>WindGenTurbineType1bIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenTurbineType1bIEC}}");}); return false;'>{{WindGenTurbineType1bIEC}}</a></div>{{/WindGenTurbineType1bIEC}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindPitchContPowerIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindPitchContPowerIEC_collapse" style="margin-left: 10px;">WindPitchContPowerIEC</a></legend>
<div id="{{id}}_WindPitchContPowerIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpmax'>dpmax: </label><div class='col-sm-8'><input id='{{id}}_dpmax' class='form-control' type='text'{{#dpmax}} value='{{dpmax}}'{{/dpmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpmin'>dpmin: </label><div class='col-sm-8'><input id='{{id}}_dpmin' class='form-control' type='text'{{#dpmin}} value='{{dpmin}}'{{/dpmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pmin'>pmin: </label><div class='col-sm-8'><input id='{{id}}_pmin' class='form-control' type='text'{{#pmin}} value='{{pmin}}'{{/pmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pset'>pset: </label><div class='col-sm-8'><input id='{{id}}_pset' class='form-control' type='text'{{#pset}} value='{{pset}}'{{/pset}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_t1'>t1: </label><div class='col-sm-8'><input id='{{id}}_t1' class='form-control' type='text'{{#t1}} value='{{t1}}'{{/t1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tr'>tr: </label><div class='col-sm-8'><input id='{{id}}_tr' class='form-control' type='text'{{#tr}} value='{{tr}}'{{/tr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_uuvrt'>uuvrt: </label><div class='col-sm-8'><input id='{{id}}_uuvrt' class='form-control' type='text'{{#uuvrt}} value='{{uuvrt}}'{{/uuvrt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenTurbineType2IEC'>WindGenTurbineType2IEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenTurbineType2IEC' class='form-control' type='text'{{#WindGenTurbineType2IEC}} value='{{WindGenTurbineType2IEC}}'{{/WindGenTurbineType2IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenTurbineType1bIEC'>WindGenTurbineType1bIEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenTurbineType1bIEC' class='form-control' type='text'{{#WindGenTurbineType1bIEC}} value='{{WindGenTurbineType1bIEC}}'{{/WindGenTurbineType1bIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindPitchContPowerIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dpmax").value; if ("" !== temp) obj["dpmax"] = temp;
temp = document.getElementById (id + "_dpmin").value; if ("" !== temp) obj["dpmin"] = temp;
temp = document.getElementById (id + "_pmin").value; if ("" !== temp) obj["pmin"] = temp;
temp = document.getElementById (id + "_pset").value; if ("" !== temp) obj["pset"] = temp;
temp = document.getElementById (id + "_t1").value; if ("" !== temp) obj["t1"] = temp;
temp = document.getElementById (id + "_tr").value; if ("" !== temp) obj["tr"] = temp;
temp = document.getElementById (id + "_uuvrt").value; if ("" !== temp) obj["uuvrt"] = temp;
temp = document.getElementById (id + "_WindGenTurbineType2IEC").value; if ("" !== temp) obj["WindGenTurbineType2IEC"] = temp;
temp = document.getElementById (id + "_WindGenTurbineType1bIEC").value; if ("" !== temp) obj["WindGenTurbineType1bIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindGenTurbineType2IEC", "0..1", "1", "WindGenTurbineType2IEC", "WindPitchContPowerIEC"],
["WindGenTurbineType1bIEC", "0..1", "1", "WindGenTurbineType1bIEC", "WindPitchContPowerIEC"],
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindPitchContPowerIEC"]
]
)
);
}
}
/**
* Q control model.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.7.
*
*/
class WindContQIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContQIEC;
if (null == bucket)
cim_data.WindContQIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContQIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContQIEC";
base.parse_element (/<cim:WindContQIEC.iqh1>([\s\S]*?)<\/cim:WindContQIEC.iqh1>/g, obj, "iqh1", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.iqmax>([\s\S]*?)<\/cim:WindContQIEC.iqmax>/g, obj, "iqmax", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.iqmin>([\s\S]*?)<\/cim:WindContQIEC.iqmin>/g, obj, "iqmin", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.iqpost>([\s\S]*?)<\/cim:WindContQIEC.iqpost>/g, obj, "iqpost", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.kiq>([\s\S]*?)<\/cim:WindContQIEC.kiq>/g, obj, "kiq", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.kiu>([\s\S]*?)<\/cim:WindContQIEC.kiu>/g, obj, "kiu", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.kpq>([\s\S]*?)<\/cim:WindContQIEC.kpq>/g, obj, "kpq", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.kpu>([\s\S]*?)<\/cim:WindContQIEC.kpu>/g, obj, "kpu", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.kqv>([\s\S]*?)<\/cim:WindContQIEC.kqv>/g, obj, "kqv", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.rdroop>([\s\S]*?)<\/cim:WindContQIEC.rdroop>/g, obj, "rdroop", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.tpfiltq>([\s\S]*?)<\/cim:WindContQIEC.tpfiltq>/g, obj, "tpfiltq", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.tpost>([\s\S]*?)<\/cim:WindContQIEC.tpost>/g, obj, "tpost", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.tqord>([\s\S]*?)<\/cim:WindContQIEC.tqord>/g, obj, "tqord", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.tufiltq>([\s\S]*?)<\/cim:WindContQIEC.tufiltq>/g, obj, "tufiltq", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.udb1>([\s\S]*?)<\/cim:WindContQIEC.udb1>/g, obj, "udb1", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.udb2>([\s\S]*?)<\/cim:WindContQIEC.udb2>/g, obj, "udb2", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.umax>([\s\S]*?)<\/cim:WindContQIEC.umax>/g, obj, "umax", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.umin>([\s\S]*?)<\/cim:WindContQIEC.umin>/g, obj, "umin", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.uqdip>([\s\S]*?)<\/cim:WindContQIEC.uqdip>/g, obj, "uqdip", base.to_string, sub, context);
base.parse_element (/<cim:WindContQIEC.uref0>([\s\S]*?)<\/cim:WindContQIEC.uref0>/g, obj, "uref0", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContQIEC.windQcontrolModesType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "windQcontrolModesType", sub, context);
base.parse_attribute (/<cim:WindContQIEC.windUVRTQcontrolModesType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "windUVRTQcontrolModesType", sub, context);
base.parse_element (/<cim:WindContQIEC.xdroop>([\s\S]*?)<\/cim:WindContQIEC.xdroop>/g, obj, "xdroop", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContQIEC.WindTurbineType3or4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType3or4IEC", sub, context);
let bucket = context.parsed.WindContQIEC;
if (null == bucket)
context.parsed.WindContQIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContQIEC", "iqh1", "iqh1", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "iqmax", "iqmax", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "iqmin", "iqmin", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "iqpost", "iqpost", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "kiq", "kiq", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "kiu", "kiu", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "kpq", "kpq", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "kpu", "kpu", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "kqv", "kqv", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "rdroop", "rdroop", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "tpfiltq", "tpfiltq", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "tpost", "tpost", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "tqord", "tqord", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "tufiltq", "tufiltq", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "udb1", "udb1", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "udb2", "udb2", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "umax", "umax", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "umin", "umin", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "uqdip", "uqdip", base.from_string, fields);
base.export_element (obj, "WindContQIEC", "uref0", "uref0", base.from_string, fields);
base.export_attribute (obj, "WindContQIEC", "windQcontrolModesType", "windQcontrolModesType", fields);
base.export_attribute (obj, "WindContQIEC", "windUVRTQcontrolModesType", "windUVRTQcontrolModesType", fields);
base.export_element (obj, "WindContQIEC", "xdroop", "xdroop", base.from_string, fields);
base.export_attribute (obj, "WindContQIEC", "WindTurbineType3or4IEC", "WindTurbineType3or4IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContQIEC_collapse" aria-expanded="true" aria-controls="WindContQIEC_collapse" style="margin-left: 10px;">WindContQIEC</a></legend>
<div id="WindContQIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#iqh1}}<div><b>iqh1</b>: {{iqh1}}</div>{{/iqh1}}
{{#iqmax}}<div><b>iqmax</b>: {{iqmax}}</div>{{/iqmax}}
{{#iqmin}}<div><b>iqmin</b>: {{iqmin}}</div>{{/iqmin}}
{{#iqpost}}<div><b>iqpost</b>: {{iqpost}}</div>{{/iqpost}}
{{#kiq}}<div><b>kiq</b>: {{kiq}}</div>{{/kiq}}
{{#kiu}}<div><b>kiu</b>: {{kiu}}</div>{{/kiu}}
{{#kpq}}<div><b>kpq</b>: {{kpq}}</div>{{/kpq}}
{{#kpu}}<div><b>kpu</b>: {{kpu}}</div>{{/kpu}}
{{#kqv}}<div><b>kqv</b>: {{kqv}}</div>{{/kqv}}
{{#rdroop}}<div><b>rdroop</b>: {{rdroop}}</div>{{/rdroop}}
{{#tpfiltq}}<div><b>tpfiltq</b>: {{tpfiltq}}</div>{{/tpfiltq}}
{{#tpost}}<div><b>tpost</b>: {{tpost}}</div>{{/tpost}}
{{#tqord}}<div><b>tqord</b>: {{tqord}}</div>{{/tqord}}
{{#tufiltq}}<div><b>tufiltq</b>: {{tufiltq}}</div>{{/tufiltq}}
{{#udb1}}<div><b>udb1</b>: {{udb1}}</div>{{/udb1}}
{{#udb2}}<div><b>udb2</b>: {{udb2}}</div>{{/udb2}}
{{#umax}}<div><b>umax</b>: {{umax}}</div>{{/umax}}
{{#umin}}<div><b>umin</b>: {{umin}}</div>{{/umin}}
{{#uqdip}}<div><b>uqdip</b>: {{uqdip}}</div>{{/uqdip}}
{{#uref0}}<div><b>uref0</b>: {{uref0}}</div>{{/uref0}}
{{#windQcontrolModesType}}<div><b>windQcontrolModesType</b>: {{windQcontrolModesType}}</div>{{/windQcontrolModesType}}
{{#windUVRTQcontrolModesType}}<div><b>windUVRTQcontrolModesType</b>: {{windUVRTQcontrolModesType}}</div>{{/windUVRTQcontrolModesType}}
{{#xdroop}}<div><b>xdroop</b>: {{xdroop}}</div>{{/xdroop}}
{{#WindTurbineType3or4IEC}}<div><b>WindTurbineType3or4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType3or4IEC}}");}); return false;'>{{WindTurbineType3or4IEC}}</a></div>{{/WindTurbineType3or4IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["windQcontrolModesTypeWindQcontrolModeKind"] = [{ id: '', selected: (!obj["windQcontrolModesType"])}]; for (let property in WindQcontrolModeKind) obj["windQcontrolModesTypeWindQcontrolModeKind"].push ({ id: property, selected: obj["windQcontrolModesType"] && obj["windQcontrolModesType"].endsWith ('.' + property)});
obj["windUVRTQcontrolModesTypeWindUVRTQcontrolModeKind"] = [{ id: '', selected: (!obj["windUVRTQcontrolModesType"])}]; for (let property in WindUVRTQcontrolModeKind) obj["windUVRTQcontrolModesTypeWindUVRTQcontrolModeKind"].push ({ id: property, selected: obj["windUVRTQcontrolModesType"] && obj["windUVRTQcontrolModesType"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["windQcontrolModesTypeWindQcontrolModeKind"];
delete obj["windUVRTQcontrolModesTypeWindUVRTQcontrolModeKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContQIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContQIEC_collapse" style="margin-left: 10px;">WindContQIEC</a></legend>
<div id="{{id}}_WindContQIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_iqh1'>iqh1: </label><div class='col-sm-8'><input id='{{id}}_iqh1' class='form-control' type='text'{{#iqh1}} value='{{iqh1}}'{{/iqh1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_iqmax'>iqmax: </label><div class='col-sm-8'><input id='{{id}}_iqmax' class='form-control' type='text'{{#iqmax}} value='{{iqmax}}'{{/iqmax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_iqmin'>iqmin: </label><div class='col-sm-8'><input id='{{id}}_iqmin' class='form-control' type='text'{{#iqmin}} value='{{iqmin}}'{{/iqmin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_iqpost'>iqpost: </label><div class='col-sm-8'><input id='{{id}}_iqpost' class='form-control' type='text'{{#iqpost}} value='{{iqpost}}'{{/iqpost}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiq'>kiq: </label><div class='col-sm-8'><input id='{{id}}_kiq' class='form-control' type='text'{{#kiq}} value='{{kiq}}'{{/kiq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kiu'>kiu: </label><div class='col-sm-8'><input id='{{id}}_kiu' class='form-control' type='text'{{#kiu}} value='{{kiu}}'{{/kiu}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpq'>kpq: </label><div class='col-sm-8'><input id='{{id}}_kpq' class='form-control' type='text'{{#kpq}} value='{{kpq}}'{{/kpq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpu'>kpu: </label><div class='col-sm-8'><input id='{{id}}_kpu' class='form-control' type='text'{{#kpu}} value='{{kpu}}'{{/kpu}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kqv'>kqv: </label><div class='col-sm-8'><input id='{{id}}_kqv' class='form-control' type='text'{{#kqv}} value='{{kqv}}'{{/kqv}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rdroop'>rdroop: </label><div class='col-sm-8'><input id='{{id}}_rdroop' class='form-control' type='text'{{#rdroop}} value='{{rdroop}}'{{/rdroop}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpfiltq'>tpfiltq: </label><div class='col-sm-8'><input id='{{id}}_tpfiltq' class='form-control' type='text'{{#tpfiltq}} value='{{tpfiltq}}'{{/tpfiltq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpost'>tpost: </label><div class='col-sm-8'><input id='{{id}}_tpost' class='form-control' type='text'{{#tpost}} value='{{tpost}}'{{/tpost}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tqord'>tqord: </label><div class='col-sm-8'><input id='{{id}}_tqord' class='form-control' type='text'{{#tqord}} value='{{tqord}}'{{/tqord}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tufiltq'>tufiltq: </label><div class='col-sm-8'><input id='{{id}}_tufiltq' class='form-control' type='text'{{#tufiltq}} value='{{tufiltq}}'{{/tufiltq}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_udb1'>udb1: </label><div class='col-sm-8'><input id='{{id}}_udb1' class='form-control' type='text'{{#udb1}} value='{{udb1}}'{{/udb1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_udb2'>udb2: </label><div class='col-sm-8'><input id='{{id}}_udb2' class='form-control' type='text'{{#udb2}} value='{{udb2}}'{{/udb2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_umax'>umax: </label><div class='col-sm-8'><input id='{{id}}_umax' class='form-control' type='text'{{#umax}} value='{{umax}}'{{/umax}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_umin'>umin: </label><div class='col-sm-8'><input id='{{id}}_umin' class='form-control' type='text'{{#umin}} value='{{umin}}'{{/umin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_uqdip'>uqdip: </label><div class='col-sm-8'><input id='{{id}}_uqdip' class='form-control' type='text'{{#uqdip}} value='{{uqdip}}'{{/uqdip}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_uref0'>uref0: </label><div class='col-sm-8'><input id='{{id}}_uref0' class='form-control' type='text'{{#uref0}} value='{{uref0}}'{{/uref0}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_windQcontrolModesType'>windQcontrolModesType: </label><div class='col-sm-8'><select id='{{id}}_windQcontrolModesType' class='form-control custom-select'>{{#windQcontrolModesTypeWindQcontrolModeKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/windQcontrolModesTypeWindQcontrolModeKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_windUVRTQcontrolModesType'>windUVRTQcontrolModesType: </label><div class='col-sm-8'><select id='{{id}}_windUVRTQcontrolModesType' class='form-control custom-select'>{{#windUVRTQcontrolModesTypeWindUVRTQcontrolModeKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/windUVRTQcontrolModesTypeWindUVRTQcontrolModeKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_xdroop'>xdroop: </label><div class='col-sm-8'><input id='{{id}}_xdroop' class='form-control' type='text'{{#xdroop}} value='{{xdroop}}'{{/xdroop}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType3or4IEC'>WindTurbineType3or4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType3or4IEC' class='form-control' type='text'{{#WindTurbineType3or4IEC}} value='{{WindTurbineType3or4IEC}}'{{/WindTurbineType3or4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContQIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_iqh1").value; if ("" !== temp) obj["iqh1"] = temp;
temp = document.getElementById (id + "_iqmax").value; if ("" !== temp) obj["iqmax"] = temp;
temp = document.getElementById (id + "_iqmin").value; if ("" !== temp) obj["iqmin"] = temp;
temp = document.getElementById (id + "_iqpost").value; if ("" !== temp) obj["iqpost"] = temp;
temp = document.getElementById (id + "_kiq").value; if ("" !== temp) obj["kiq"] = temp;
temp = document.getElementById (id + "_kiu").value; if ("" !== temp) obj["kiu"] = temp;
temp = document.getElementById (id + "_kpq").value; if ("" !== temp) obj["kpq"] = temp;
temp = document.getElementById (id + "_kpu").value; if ("" !== temp) obj["kpu"] = temp;
temp = document.getElementById (id + "_kqv").value; if ("" !== temp) obj["kqv"] = temp;
temp = document.getElementById (id + "_rdroop").value; if ("" !== temp) obj["rdroop"] = temp;
temp = document.getElementById (id + "_tpfiltq").value; if ("" !== temp) obj["tpfiltq"] = temp;
temp = document.getElementById (id + "_tpost").value; if ("" !== temp) obj["tpost"] = temp;
temp = document.getElementById (id + "_tqord").value; if ("" !== temp) obj["tqord"] = temp;
temp = document.getElementById (id + "_tufiltq").value; if ("" !== temp) obj["tufiltq"] = temp;
temp = document.getElementById (id + "_udb1").value; if ("" !== temp) obj["udb1"] = temp;
temp = document.getElementById (id + "_udb2").value; if ("" !== temp) obj["udb2"] = temp;
temp = document.getElementById (id + "_umax").value; if ("" !== temp) obj["umax"] = temp;
temp = document.getElementById (id + "_umin").value; if ("" !== temp) obj["umin"] = temp;
temp = document.getElementById (id + "_uqdip").value; if ("" !== temp) obj["uqdip"] = temp;
temp = document.getElementById (id + "_uref0").value; if ("" !== temp) obj["uref0"] = temp;
temp = WindQcontrolModeKind[document.getElementById (id + "_windQcontrolModesType").value]; if (temp) obj["windQcontrolModesType"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#WindQcontrolModeKind." + temp; else delete obj["windQcontrolModesType"];
temp = WindUVRTQcontrolModeKind[document.getElementById (id + "_windUVRTQcontrolModesType").value]; if (temp) obj["windUVRTQcontrolModesType"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#WindUVRTQcontrolModeKind." + temp; else delete obj["windUVRTQcontrolModesType"];
temp = document.getElementById (id + "_xdroop").value; if ("" !== temp) obj["xdroop"] = temp;
temp = document.getElementById (id + "_WindTurbineType3or4IEC").value; if ("" !== temp) obj["WindTurbineType3or4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType3or4IEC", "1", "1", "WindTurbineType3or4IEC", "WIndContQIEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to wind turbines type 3 and type 4 and wind plant including their control models.
*
*/
class WindTurbineType3or4Dynamics extends StandardModels.DynamicsFunctionBlock
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType3or4Dynamics;
if (null == bucket)
cim_data.WindTurbineType3or4Dynamics = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType3or4Dynamics[obj.id];
}
parse (context, sub)
{
let obj = StandardModels.DynamicsFunctionBlock.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType3or4Dynamics";
base.parse_attribute (/<cim:WindTurbineType3or4Dynamics.PowerElectronicsConnection\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "PowerElectronicsConnection", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4Dynamics.WindPlantDynamics\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantDynamics", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4Dynamics.RemoteInputSignal\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "RemoteInputSignal", sub, context);
let bucket = context.parsed.WindTurbineType3or4Dynamics;
if (null == bucket)
context.parsed.WindTurbineType3or4Dynamics = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = StandardModels.DynamicsFunctionBlock.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType3or4Dynamics", "PowerElectronicsConnection", "PowerElectronicsConnection", fields);
base.export_attribute (obj, "WindTurbineType3or4Dynamics", "WindPlantDynamics", "WindPlantDynamics", fields);
base.export_attribute (obj, "WindTurbineType3or4Dynamics", "RemoteInputSignal", "RemoteInputSignal", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType3or4Dynamics_collapse" aria-expanded="true" aria-controls="WindTurbineType3or4Dynamics_collapse" style="margin-left: 10px;">WindTurbineType3or4Dynamics</a></legend>
<div id="WindTurbineType3or4Dynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ StandardModels.DynamicsFunctionBlock.prototype.template.call (this) +
`
{{#PowerElectronicsConnection}}<div><b>PowerElectronicsConnection</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{PowerElectronicsConnection}}");}); return false;'>{{PowerElectronicsConnection}}</a></div>{{/PowerElectronicsConnection}}
{{#WindPlantDynamics}}<div><b>WindPlantDynamics</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantDynamics}}");}); return false;'>{{WindPlantDynamics}}</a></div>{{/WindPlantDynamics}}
{{#RemoteInputSignal}}<div><b>RemoteInputSignal</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{RemoteInputSignal}}");}); return false;'>{{RemoteInputSignal}}</a></div>{{/RemoteInputSignal}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType3or4Dynamics_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType3or4Dynamics_collapse" style="margin-left: 10px;">WindTurbineType3or4Dynamics</a></legend>
<div id="{{id}}_WindTurbineType3or4Dynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ StandardModels.DynamicsFunctionBlock.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_PowerElectronicsConnection'>PowerElectronicsConnection: </label><div class='col-sm-8'><input id='{{id}}_PowerElectronicsConnection' class='form-control' type='text'{{#PowerElectronicsConnection}} value='{{PowerElectronicsConnection}}'{{/PowerElectronicsConnection}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantDynamics'>WindPlantDynamics: </label><div class='col-sm-8'><input id='{{id}}_WindPlantDynamics' class='form-control' type='text'{{#WindPlantDynamics}} value='{{WindPlantDynamics}}'{{/WindPlantDynamics}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_RemoteInputSignal'>RemoteInputSignal: </label><div class='col-sm-8'><input id='{{id}}_RemoteInputSignal' class='form-control' type='text'{{#RemoteInputSignal}} value='{{RemoteInputSignal}}'{{/RemoteInputSignal}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType3or4Dynamics" };
super.submit (id, obj);
temp = document.getElementById (id + "_PowerElectronicsConnection").value; if ("" !== temp) obj["PowerElectronicsConnection"] = temp;
temp = document.getElementById (id + "_WindPlantDynamics").value; if ("" !== temp) obj["WindPlantDynamics"] = temp;
temp = document.getElementById (id + "_RemoteInputSignal").value; if ("" !== temp) obj["RemoteInputSignal"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["PowerElectronicsConnection", "1", "0..1", "PowerElectronicsConnection", "WindTurbineType3or4Dynamics"],
["WindPlantDynamics", "0..1", "1..*", "WindPlantDynamics", "WindTurbineType3or4Dynamics"],
["RemoteInputSignal", "0..1", "0..1", "RemoteInputSignal", "WindTurbineType3or4Dynamics"]
]
)
);
}
}
/**
* Look up table for the purpose of wind standard models.
*
*/
class WindDynamicsLookupTable extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindDynamicsLookupTable;
if (null == bucket)
cim_data.WindDynamicsLookupTable = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindDynamicsLookupTable[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindDynamicsLookupTable";
base.parse_element (/<cim:WindDynamicsLookupTable.input>([\s\S]*?)<\/cim:WindDynamicsLookupTable.input>/g, obj, "input", base.to_float, sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.lookupTableFunctionType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "lookupTableFunctionType", sub, context);
base.parse_element (/<cim:WindDynamicsLookupTable.output>([\s\S]*?)<\/cim:WindDynamicsLookupTable.output>/g, obj, "output", base.to_float, sub, context);
base.parse_element (/<cim:WindDynamicsLookupTable.sequence>([\s\S]*?)<\/cim:WindDynamicsLookupTable.sequence>/g, obj, "sequence", base.to_string, sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindPlantReactiveControlIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantReactiveControlIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindContRotorRIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContRotorRIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindGenType3bIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenType3bIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindContCurrLimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContCurrLimIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindContQPQULimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContQPQULimIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindContPType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContPType3IEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindProtectionIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindProtectionIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindPlantFreqPcontrolIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantFreqPcontrolIEC", sub, context);
base.parse_attribute (/<cim:WindDynamicsLookupTable.WindPitchContPowerIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPitchContPowerIEC", sub, context);
let bucket = context.parsed.WindDynamicsLookupTable;
if (null == bucket)
context.parsed.WindDynamicsLookupTable = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindDynamicsLookupTable", "input", "input", base.from_float, fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "lookupTableFunctionType", "lookupTableFunctionType", fields);
base.export_element (obj, "WindDynamicsLookupTable", "output", "output", base.from_float, fields);
base.export_element (obj, "WindDynamicsLookupTable", "sequence", "sequence", base.from_string, fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindPlantReactiveControlIEC", "WindPlantReactiveControlIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindContRotorRIEC", "WindContRotorRIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindGenType3bIEC", "WindGenType3bIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindContCurrLimIEC", "WindContCurrLimIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindContQPQULimIEC", "WindContQPQULimIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindContPType3IEC", "WindContPType3IEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindProtectionIEC", "WindProtectionIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindPlantFreqPcontrolIEC", "WindPlantFreqPcontrolIEC", fields);
base.export_attribute (obj, "WindDynamicsLookupTable", "WindPitchContPowerIEC", "WindPitchContPowerIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindDynamicsLookupTable_collapse" aria-expanded="true" aria-controls="WindDynamicsLookupTable_collapse" style="margin-left: 10px;">WindDynamicsLookupTable</a></legend>
<div id="WindDynamicsLookupTable_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#input}}<div><b>input</b>: {{input}}</div>{{/input}}
{{#lookupTableFunctionType}}<div><b>lookupTableFunctionType</b>: {{lookupTableFunctionType}}</div>{{/lookupTableFunctionType}}
{{#output}}<div><b>output</b>: {{output}}</div>{{/output}}
{{#sequence}}<div><b>sequence</b>: {{sequence}}</div>{{/sequence}}
{{#WindPlantReactiveControlIEC}}<div><b>WindPlantReactiveControlIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantReactiveControlIEC}}");}); return false;'>{{WindPlantReactiveControlIEC}}</a></div>{{/WindPlantReactiveControlIEC}}
{{#WindContRotorRIEC}}<div><b>WindContRotorRIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContRotorRIEC}}");}); return false;'>{{WindContRotorRIEC}}</a></div>{{/WindContRotorRIEC}}
{{#WindGenType3bIEC}}<div><b>WindGenType3bIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenType3bIEC}}");}); return false;'>{{WindGenType3bIEC}}</a></div>{{/WindGenType3bIEC}}
{{#WindContCurrLimIEC}}<div><b>WindContCurrLimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContCurrLimIEC}}");}); return false;'>{{WindContCurrLimIEC}}</a></div>{{/WindContCurrLimIEC}}
{{#WindContQPQULimIEC}}<div><b>WindContQPQULimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContQPQULimIEC}}");}); return false;'>{{WindContQPQULimIEC}}</a></div>{{/WindContQPQULimIEC}}
{{#WindContPType3IEC}}<div><b>WindContPType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContPType3IEC}}");}); return false;'>{{WindContPType3IEC}}</a></div>{{/WindContPType3IEC}}
{{#WindProtectionIEC}}<div><b>WindProtectionIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindProtectionIEC}}");}); return false;'>{{WindProtectionIEC}}</a></div>{{/WindProtectionIEC}}
{{#WindPlantFreqPcontrolIEC}}<div><b>WindPlantFreqPcontrolIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantFreqPcontrolIEC}}");}); return false;'>{{WindPlantFreqPcontrolIEC}}</a></div>{{/WindPlantFreqPcontrolIEC}}
{{#WindPitchContPowerIEC}}<div><b>WindPitchContPowerIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPitchContPowerIEC}}");}); return false;'>{{WindPitchContPowerIEC}}</a></div>{{/WindPitchContPowerIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["lookupTableFunctionTypeWindLookupTableFunctionKind"] = [{ id: '', selected: (!obj["lookupTableFunctionType"])}]; for (let property in WindLookupTableFunctionKind) obj["lookupTableFunctionTypeWindLookupTableFunctionKind"].push ({ id: property, selected: obj["lookupTableFunctionType"] && obj["lookupTableFunctionType"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["lookupTableFunctionTypeWindLookupTableFunctionKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindDynamicsLookupTable_collapse" aria-expanded="true" aria-controls="{{id}}_WindDynamicsLookupTable_collapse" style="margin-left: 10px;">WindDynamicsLookupTable</a></legend>
<div id="{{id}}_WindDynamicsLookupTable_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_input'>input: </label><div class='col-sm-8'><input id='{{id}}_input' class='form-control' type='text'{{#input}} value='{{input}}'{{/input}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lookupTableFunctionType'>lookupTableFunctionType: </label><div class='col-sm-8'><select id='{{id}}_lookupTableFunctionType' class='form-control custom-select'>{{#lookupTableFunctionTypeWindLookupTableFunctionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/lookupTableFunctionTypeWindLookupTableFunctionKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_output'>output: </label><div class='col-sm-8'><input id='{{id}}_output' class='form-control' type='text'{{#output}} value='{{output}}'{{/output}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_sequence'>sequence: </label><div class='col-sm-8'><input id='{{id}}_sequence' class='form-control' type='text'{{#sequence}} value='{{sequence}}'{{/sequence}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantReactiveControlIEC'>WindPlantReactiveControlIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPlantReactiveControlIEC' class='form-control' type='text'{{#WindPlantReactiveControlIEC}} value='{{WindPlantReactiveControlIEC}}'{{/WindPlantReactiveControlIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContRotorRIEC'>WindContRotorRIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContRotorRIEC' class='form-control' type='text'{{#WindContRotorRIEC}} value='{{WindContRotorRIEC}}'{{/WindContRotorRIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenType3bIEC'>WindGenType3bIEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenType3bIEC' class='form-control' type='text'{{#WindGenType3bIEC}} value='{{WindGenType3bIEC}}'{{/WindGenType3bIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContCurrLimIEC'>WindContCurrLimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContCurrLimIEC' class='form-control' type='text'{{#WindContCurrLimIEC}} value='{{WindContCurrLimIEC}}'{{/WindContCurrLimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContQPQULimIEC'>WindContQPQULimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContQPQULimIEC' class='form-control' type='text'{{#WindContQPQULimIEC}} value='{{WindContQPQULimIEC}}'{{/WindContQPQULimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContPType3IEC'>WindContPType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindContPType3IEC' class='form-control' type='text'{{#WindContPType3IEC}} value='{{WindContPType3IEC}}'{{/WindContPType3IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindProtectionIEC'>WindProtectionIEC: </label><div class='col-sm-8'><input id='{{id}}_WindProtectionIEC' class='form-control' type='text'{{#WindProtectionIEC}} value='{{WindProtectionIEC}}'{{/WindProtectionIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantFreqPcontrolIEC'>WindPlantFreqPcontrolIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPlantFreqPcontrolIEC' class='form-control' type='text'{{#WindPlantFreqPcontrolIEC}} value='{{WindPlantFreqPcontrolIEC}}'{{/WindPlantFreqPcontrolIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPitchContPowerIEC'>WindPitchContPowerIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPitchContPowerIEC' class='form-control' type='text'{{#WindPitchContPowerIEC}} value='{{WindPitchContPowerIEC}}'{{/WindPitchContPowerIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindDynamicsLookupTable" };
super.submit (id, obj);
temp = document.getElementById (id + "_input").value; if ("" !== temp) obj["input"] = temp;
temp = WindLookupTableFunctionKind[document.getElementById (id + "_lookupTableFunctionType").value]; if (temp) obj["lookupTableFunctionType"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#WindLookupTableFunctionKind." + temp; else delete obj["lookupTableFunctionType"];
temp = document.getElementById (id + "_output").value; if ("" !== temp) obj["output"] = temp;
temp = document.getElementById (id + "_sequence").value; if ("" !== temp) obj["sequence"] = temp;
temp = document.getElementById (id + "_WindPlantReactiveControlIEC").value; if ("" !== temp) obj["WindPlantReactiveControlIEC"] = temp;
temp = document.getElementById (id + "_WindContRotorRIEC").value; if ("" !== temp) obj["WindContRotorRIEC"] = temp;
temp = document.getElementById (id + "_WindGenType3bIEC").value; if ("" !== temp) obj["WindGenType3bIEC"] = temp;
temp = document.getElementById (id + "_WindContCurrLimIEC").value; if ("" !== temp) obj["WindContCurrLimIEC"] = temp;
temp = document.getElementById (id + "_WindContQPQULimIEC").value; if ("" !== temp) obj["WindContQPQULimIEC"] = temp;
temp = document.getElementById (id + "_WindContPType3IEC").value; if ("" !== temp) obj["WindContPType3IEC"] = temp;
temp = document.getElementById (id + "_WindProtectionIEC").value; if ("" !== temp) obj["WindProtectionIEC"] = temp;
temp = document.getElementById (id + "_WindPlantFreqPcontrolIEC").value; if ("" !== temp) obj["WindPlantFreqPcontrolIEC"] = temp;
temp = document.getElementById (id + "_WindPitchContPowerIEC").value; if ("" !== temp) obj["WindPitchContPowerIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindPlantReactiveControlIEC", "0..1", "1..*", "WindPlantReactiveControlIEC", "WindDynamicsLookupTable"],
["WindContRotorRIEC", "0..1", "1..*", "WindContRotorRIEC", "WindDynamicsLookupTable"],
["WindGenType3bIEC", "0..1", "1..*", "WindGenType3bIEC", "WindDynamicsLookupTable"],
["WindContCurrLimIEC", "0..1", "1..*", "WindContCurrLimIEC", "WindDynamicsLookupTable"],
["WindContQPQULimIEC", "0..1", "1..*", "WindContQPQULimIEC", "WindDynamicsLookupTable"],
["WindContPType3IEC", "0..1", "1..*", "WindContPType3IEC", "WindDynamicsLookupTable"],
["WindProtectionIEC", "0..1", "1..*", "WindProtectionIEC", "WindDynamicsLookupTable"],
["WindPlantFreqPcontrolIEC", "0..1", "1..*", "WindPlantFreqPcontrolIEC", "WindDynamicsLookupTable"],
["WindPitchContPowerIEC", "0..1", "1..*", "WindPitchContPowerIEC", "WindDynamicsLookupTable"]
]
)
);
}
}
/**
* P control model type 4B.
*
* Reference: IEC 61400-27-1:2015, 5.6.5.6.
*
*/
class WindContPType4bIEC extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindContPType4bIEC;
if (null == bucket)
cim_data.WindContPType4bIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindContPType4bIEC[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "WindContPType4bIEC";
base.parse_element (/<cim:WindContPType4bIEC.dpmaxp4b>([\s\S]*?)<\/cim:WindContPType4bIEC.dpmaxp4b>/g, obj, "dpmaxp4b", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType4bIEC.tpaero>([\s\S]*?)<\/cim:WindContPType4bIEC.tpaero>/g, obj, "tpaero", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType4bIEC.tpordp4b>([\s\S]*?)<\/cim:WindContPType4bIEC.tpordp4b>/g, obj, "tpordp4b", base.to_string, sub, context);
base.parse_element (/<cim:WindContPType4bIEC.tufiltp4b>([\s\S]*?)<\/cim:WindContPType4bIEC.tufiltp4b>/g, obj, "tufiltp4b", base.to_string, sub, context);
base.parse_attribute (/<cim:WindContPType4bIEC.WindTurbineType4bIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType4bIEC", sub, context);
let bucket = context.parsed.WindContPType4bIEC;
if (null == bucket)
context.parsed.WindContPType4bIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "WindContPType4bIEC", "dpmaxp4b", "dpmaxp4b", base.from_string, fields);
base.export_element (obj, "WindContPType4bIEC", "tpaero", "tpaero", base.from_string, fields);
base.export_element (obj, "WindContPType4bIEC", "tpordp4b", "tpordp4b", base.from_string, fields);
base.export_element (obj, "WindContPType4bIEC", "tufiltp4b", "tufiltp4b", base.from_string, fields);
base.export_attribute (obj, "WindContPType4bIEC", "WindTurbineType4bIEC", "WindTurbineType4bIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindContPType4bIEC_collapse" aria-expanded="true" aria-controls="WindContPType4bIEC_collapse" style="margin-left: 10px;">WindContPType4bIEC</a></legend>
<div id="WindContPType4bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#dpmaxp4b}}<div><b>dpmaxp4b</b>: {{dpmaxp4b}}</div>{{/dpmaxp4b}}
{{#tpaero}}<div><b>tpaero</b>: {{tpaero}}</div>{{/tpaero}}
{{#tpordp4b}}<div><b>tpordp4b</b>: {{tpordp4b}}</div>{{/tpordp4b}}
{{#tufiltp4b}}<div><b>tufiltp4b</b>: {{tufiltp4b}}</div>{{/tufiltp4b}}
{{#WindTurbineType4bIEC}}<div><b>WindTurbineType4bIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType4bIEC}}");}); return false;'>{{WindTurbineType4bIEC}}</a></div>{{/WindTurbineType4bIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindContPType4bIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindContPType4bIEC_collapse" style="margin-left: 10px;">WindContPType4bIEC</a></legend>
<div id="{{id}}_WindContPType4bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dpmaxp4b'>dpmaxp4b: </label><div class='col-sm-8'><input id='{{id}}_dpmaxp4b' class='form-control' type='text'{{#dpmaxp4b}} value='{{dpmaxp4b}}'{{/dpmaxp4b}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpaero'>tpaero: </label><div class='col-sm-8'><input id='{{id}}_tpaero' class='form-control' type='text'{{#tpaero}} value='{{tpaero}}'{{/tpaero}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpordp4b'>tpordp4b: </label><div class='col-sm-8'><input id='{{id}}_tpordp4b' class='form-control' type='text'{{#tpordp4b}} value='{{tpordp4b}}'{{/tpordp4b}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tufiltp4b'>tufiltp4b: </label><div class='col-sm-8'><input id='{{id}}_tufiltp4b' class='form-control' type='text'{{#tufiltp4b}} value='{{tufiltp4b}}'{{/tufiltp4b}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType4bIEC'>WindTurbineType4bIEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType4bIEC' class='form-control' type='text'{{#WindTurbineType4bIEC}} value='{{WindTurbineType4bIEC}}'{{/WindTurbineType4bIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindContPType4bIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_dpmaxp4b").value; if ("" !== temp) obj["dpmaxp4b"] = temp;
temp = document.getElementById (id + "_tpaero").value; if ("" !== temp) obj["tpaero"] = temp;
temp = document.getElementById (id + "_tpordp4b").value; if ("" !== temp) obj["tpordp4b"] = temp;
temp = document.getElementById (id + "_tufiltp4b").value; if ("" !== temp) obj["tufiltp4b"] = temp;
temp = document.getElementById (id + "_WindTurbineType4bIEC").value; if ("" !== temp) obj["WindTurbineType4bIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType4bIEC", "1", "1", "WindTurbineType4bIEC", "WindContPType4bIEC"]
]
)
);
}
}
/**
* Simplified IEC type plant level model.
*
* Reference: IEC 61400-27-1:2015, Annex D.
*
*/
class WindPlantIEC extends WindPlantDynamics
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindPlantIEC;
if (null == bucket)
cim_data.WindPlantIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindPlantIEC[obj.id];
}
parse (context, sub)
{
let obj = WindPlantDynamics.prototype.parse.call (this, context, sub);
obj.cls = "WindPlantIEC";
base.parse_attribute (/<cim:WindPlantIEC.WindPlantFreqPcontrolIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantFreqPcontrolIEC", sub, context);
base.parse_attribute (/<cim:WindPlantIEC.WindPlantReactiveControlIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPlantReactiveControlIEC", sub, context);
let bucket = context.parsed.WindPlantIEC;
if (null == bucket)
context.parsed.WindPlantIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindPlantDynamics.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindPlantIEC", "WindPlantFreqPcontrolIEC", "WindPlantFreqPcontrolIEC", fields);
base.export_attribute (obj, "WindPlantIEC", "WindPlantReactiveControlIEC", "WindPlantReactiveControlIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindPlantIEC_collapse" aria-expanded="true" aria-controls="WindPlantIEC_collapse" style="margin-left: 10px;">WindPlantIEC</a></legend>
<div id="WindPlantIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindPlantDynamics.prototype.template.call (this) +
`
{{#WindPlantFreqPcontrolIEC}}<div><b>WindPlantFreqPcontrolIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantFreqPcontrolIEC}}");}); return false;'>{{WindPlantFreqPcontrolIEC}}</a></div>{{/WindPlantFreqPcontrolIEC}}
{{#WindPlantReactiveControlIEC}}<div><b>WindPlantReactiveControlIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPlantReactiveControlIEC}}");}); return false;'>{{WindPlantReactiveControlIEC}}</a></div>{{/WindPlantReactiveControlIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindPlantIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindPlantIEC_collapse" style="margin-left: 10px;">WindPlantIEC</a></legend>
<div id="{{id}}_WindPlantIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindPlantDynamics.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantFreqPcontrolIEC'>WindPlantFreqPcontrolIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPlantFreqPcontrolIEC' class='form-control' type='text'{{#WindPlantFreqPcontrolIEC}} value='{{WindPlantFreqPcontrolIEC}}'{{/WindPlantFreqPcontrolIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPlantReactiveControlIEC'>WindPlantReactiveControlIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPlantReactiveControlIEC' class='form-control' type='text'{{#WindPlantReactiveControlIEC}} value='{{WindPlantReactiveControlIEC}}'{{/WindPlantReactiveControlIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindPlantIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindPlantFreqPcontrolIEC").value; if ("" !== temp) obj["WindPlantFreqPcontrolIEC"] = temp;
temp = document.getElementById (id + "_WindPlantReactiveControlIEC").value; if ("" !== temp) obj["WindPlantReactiveControlIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindPlantFreqPcontrolIEC", "1", "1", "WindPlantFreqPcontrolIEC", "WindPlantIEC"],
["WindPlantReactiveControlIEC", "1", "1", "WindPlantReactiveControlIEC", "WindPlantIEC"]
]
)
);
}
}
/**
* IEC type 3B generator set model.
*
* Reference: IEC 61400-27-1:2015, 5.6.3.3.
*
*/
class WindGenType3bIEC extends WindGenType3IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenType3bIEC;
if (null == bucket)
cim_data.WindGenType3bIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenType3bIEC[obj.id];
}
parse (context, sub)
{
let obj = WindGenType3IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindGenType3bIEC";
base.parse_element (/<cim:WindGenType3bIEC.mwtcwp>([\s\S]*?)<\/cim:WindGenType3bIEC.mwtcwp>/g, obj, "mwtcwp", base.to_boolean, sub, context);
base.parse_element (/<cim:WindGenType3bIEC.tg>([\s\S]*?)<\/cim:WindGenType3bIEC.tg>/g, obj, "tg", base.to_string, sub, context);
base.parse_element (/<cim:WindGenType3bIEC.two>([\s\S]*?)<\/cim:WindGenType3bIEC.two>/g, obj, "two", base.to_string, sub, context);
base.parse_attributes (/<cim:WindGenType3bIEC.WindDynamicsLookupTable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindDynamicsLookupTable", sub, context);
let bucket = context.parsed.WindGenType3bIEC;
if (null == bucket)
context.parsed.WindGenType3bIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindGenType3IEC.prototype.export.call (this, obj, false);
base.export_element (obj, "WindGenType3bIEC", "mwtcwp", "mwtcwp", base.from_boolean, fields);
base.export_element (obj, "WindGenType3bIEC", "tg", "tg", base.from_string, fields);
base.export_element (obj, "WindGenType3bIEC", "two", "two", base.from_string, fields);
base.export_attributes (obj, "WindGenType3bIEC", "WindDynamicsLookupTable", "WindDynamicsLookupTable", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenType3bIEC_collapse" aria-expanded="true" aria-controls="WindGenType3bIEC_collapse" style="margin-left: 10px;">WindGenType3bIEC</a></legend>
<div id="WindGenType3bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindGenType3IEC.prototype.template.call (this) +
`
{{#mwtcwp}}<div><b>mwtcwp</b>: {{mwtcwp}}</div>{{/mwtcwp}}
{{#tg}}<div><b>tg</b>: {{tg}}</div>{{/tg}}
{{#two}}<div><b>two</b>: {{two}}</div>{{/two}}
{{#WindDynamicsLookupTable}}<div><b>WindDynamicsLookupTable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WindDynamicsLookupTable}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WindDynamicsLookupTable"]) obj["WindDynamicsLookupTable_string"] = obj["WindDynamicsLookupTable"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WindDynamicsLookupTable_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenType3bIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenType3bIEC_collapse" style="margin-left: 10px;">WindGenType3bIEC</a></legend>
<div id="{{id}}_WindGenType3bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindGenType3IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><div class='col-sm-4' for='{{id}}_mwtcwp'>mwtcwp: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_mwtcwp' class='form-check-input' type='checkbox'{{#mwtcwp}} checked{{/mwtcwp}}></div></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tg'>tg: </label><div class='col-sm-8'><input id='{{id}}_tg' class='form-control' type='text'{{#tg}} value='{{tg}}'{{/tg}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_two'>two: </label><div class='col-sm-8'><input id='{{id}}_two' class='form-control' type='text'{{#two}} value='{{two}}'{{/two}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenType3bIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_mwtcwp").checked; if (temp) obj["mwtcwp"] = true;
temp = document.getElementById (id + "_tg").value; if ("" !== temp) obj["tg"] = temp;
temp = document.getElementById (id + "_two").value; if ("" !== temp) obj["two"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindDynamicsLookupTable", "1..*", "0..1", "WindDynamicsLookupTable", "WindGenType3bIEC"]
]
)
);
}
}
/**
* IEC type 3A generator set model.
*
* Reference: IEC 61400-27-1:2015, 5.6.3.2.
*
*/
class WindGenType3aIEC extends WindGenType3IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenType3aIEC;
if (null == bucket)
cim_data.WindGenType3aIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenType3aIEC[obj.id];
}
parse (context, sub)
{
let obj = WindGenType3IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindGenType3aIEC";
base.parse_element (/<cim:WindGenType3aIEC.kpc>([\s\S]*?)<\/cim:WindGenType3aIEC.kpc>/g, obj, "kpc", base.to_float, sub, context);
base.parse_element (/<cim:WindGenType3aIEC.tic>([\s\S]*?)<\/cim:WindGenType3aIEC.tic>/g, obj, "tic", base.to_string, sub, context);
base.parse_attribute (/<cim:WindGenType3aIEC.WindTurbineType4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindTurbineType4IEC", sub, context);
let bucket = context.parsed.WindGenType3aIEC;
if (null == bucket)
context.parsed.WindGenType3aIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindGenType3IEC.prototype.export.call (this, obj, false);
base.export_element (obj, "WindGenType3aIEC", "kpc", "kpc", base.from_float, fields);
base.export_element (obj, "WindGenType3aIEC", "tic", "tic", base.from_string, fields);
base.export_attribute (obj, "WindGenType3aIEC", "WindTurbineType4IEC", "WindTurbineType4IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenType3aIEC_collapse" aria-expanded="true" aria-controls="WindGenType3aIEC_collapse" style="margin-left: 10px;">WindGenType3aIEC</a></legend>
<div id="WindGenType3aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindGenType3IEC.prototype.template.call (this) +
`
{{#kpc}}<div><b>kpc</b>: {{kpc}}</div>{{/kpc}}
{{#tic}}<div><b>tic</b>: {{tic}}</div>{{/tic}}
{{#WindTurbineType4IEC}}<div><b>WindTurbineType4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindTurbineType4IEC}}");}); return false;'>{{WindTurbineType4IEC}}</a></div>{{/WindTurbineType4IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenType3aIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenType3aIEC_collapse" style="margin-left: 10px;">WindGenType3aIEC</a></legend>
<div id="{{id}}_WindGenType3aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindGenType3IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpc'>kpc: </label><div class='col-sm-8'><input id='{{id}}_kpc' class='form-control' type='text'{{#kpc}} value='{{kpc}}'{{/kpc}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tic'>tic: </label><div class='col-sm-8'><input id='{{id}}_tic' class='form-control' type='text'{{#tic}} value='{{tic}}'{{/tic}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindTurbineType4IEC'>WindTurbineType4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindTurbineType4IEC' class='form-control' type='text'{{#WindTurbineType4IEC}} value='{{WindTurbineType4IEC}}'{{/WindTurbineType4IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenType3aIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_kpc").value; if ("" !== temp) obj["kpc"] = temp;
temp = document.getElementById (id + "_tic").value; if ("" !== temp) obj["tic"] = temp;
temp = document.getElementById (id + "_WindTurbineType4IEC").value; if ("" !== temp) obj["WindTurbineType4IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindTurbineType4IEC", "0..1", "0..1", "WindTurbineType4IEC", "WindGenType3aIEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to IEC wind turbines type 1 and type 2 including their control models.
*
* Generator model for wind turbine of IEC type 1 or type 2 is a standard asynchronous generator model.
* Reference: IEC 61400-27-1:2015, 5.5.2 and 5.5.3.
*
*/
class WindTurbineType1or2IEC extends WindTurbineType1or2Dynamics
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType1or2IEC;
if (null == bucket)
cim_data.WindTurbineType1or2IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType1or2IEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType1or2Dynamics.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType1or2IEC";
base.parse_attribute (/<cim:WindTurbineType1or2IEC.WindMechIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindMechIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType1or2IEC.WindProtectionIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindProtectionIEC", sub, context);
let bucket = context.parsed.WindTurbineType1or2IEC;
if (null == bucket)
context.parsed.WindTurbineType1or2IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType1or2Dynamics.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType1or2IEC", "WindMechIEC", "WindMechIEC", fields);
base.export_attribute (obj, "WindTurbineType1or2IEC", "WindProtectionIEC", "WindProtectionIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType1or2IEC_collapse" aria-expanded="true" aria-controls="WindTurbineType1or2IEC_collapse" style="margin-left: 10px;">WindTurbineType1or2IEC</a></legend>
<div id="WindTurbineType1or2IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2Dynamics.prototype.template.call (this) +
`
{{#WindMechIEC}}<div><b>WindMechIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindMechIEC}}");}); return false;'>{{WindMechIEC}}</a></div>{{/WindMechIEC}}
{{#WindProtectionIEC}}<div><b>WindProtectionIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindProtectionIEC}}");}); return false;'>{{WindProtectionIEC}}</a></div>{{/WindProtectionIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType1or2IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType1or2IEC_collapse" style="margin-left: 10px;">WindTurbineType1or2IEC</a></legend>
<div id="{{id}}_WindTurbineType1or2IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2Dynamics.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindMechIEC'>WindMechIEC: </label><div class='col-sm-8'><input id='{{id}}_WindMechIEC' class='form-control' type='text'{{#WindMechIEC}} value='{{WindMechIEC}}'{{/WindMechIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindProtectionIEC'>WindProtectionIEC: </label><div class='col-sm-8'><input id='{{id}}_WindProtectionIEC' class='form-control' type='text'{{#WindProtectionIEC}} value='{{WindProtectionIEC}}'{{/WindProtectionIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType1or2IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindMechIEC").value; if ("" !== temp) obj["WindMechIEC"] = temp;
temp = document.getElementById (id + "_WindProtectionIEC").value; if ("" !== temp) obj["WindProtectionIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindMechIEC", "1", "0..1", "WindMechIEC", "WindTurbineType1or2IEC"],
["WindProtectionIEC", "1", "0..1", "WindProtectionIEC", "WindTurbineType1or2IEC"]
]
)
);
}
}
/**
* Wind turbine IEC type 1A.
*
* Reference: IEC 61400-27-1:2015, 5.5.2.2.
*
*/
class WindGenTurbineType1aIEC extends WindTurbineType1or2IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenTurbineType1aIEC;
if (null == bucket)
cim_data.WindGenTurbineType1aIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenTurbineType1aIEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType1or2IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindGenTurbineType1aIEC";
base.parse_attribute (/<cim:WindGenTurbineType1aIEC.WindAeroConstIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindAeroConstIEC", sub, context);
let bucket = context.parsed.WindGenTurbineType1aIEC;
if (null == bucket)
context.parsed.WindGenTurbineType1aIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType1or2IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindGenTurbineType1aIEC", "WindAeroConstIEC", "WindAeroConstIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenTurbineType1aIEC_collapse" aria-expanded="true" aria-controls="WindGenTurbineType1aIEC_collapse" style="margin-left: 10px;">WindGenTurbineType1aIEC</a></legend>
<div id="WindGenTurbineType1aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2IEC.prototype.template.call (this) +
`
{{#WindAeroConstIEC}}<div><b>WindAeroConstIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindAeroConstIEC}}");}); return false;'>{{WindAeroConstIEC}}</a></div>{{/WindAeroConstIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenTurbineType1aIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenTurbineType1aIEC_collapse" style="margin-left: 10px;">WindGenTurbineType1aIEC</a></legend>
<div id="{{id}}_WindGenTurbineType1aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindAeroConstIEC'>WindAeroConstIEC: </label><div class='col-sm-8'><input id='{{id}}_WindAeroConstIEC' class='form-control' type='text'{{#WindAeroConstIEC}} value='{{WindAeroConstIEC}}'{{/WindAeroConstIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenTurbineType1aIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindAeroConstIEC").value; if ("" !== temp) obj["WindAeroConstIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindAeroConstIEC", "1", "1", "WindAeroConstIEC", "WindGenTurbineType1aIEC"]
]
)
);
}
}
/**
* Wind turbine IEC type 2.
*
* Reference: IEC 61400-27-1:2015, 5.5.3.
*
*/
class WindGenTurbineType2IEC extends WindTurbineType1or2IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenTurbineType2IEC;
if (null == bucket)
cim_data.WindGenTurbineType2IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenTurbineType2IEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType1or2IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindGenTurbineType2IEC";
base.parse_attribute (/<cim:WindGenTurbineType2IEC.WindPitchContPowerIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPitchContPowerIEC", sub, context);
base.parse_attribute (/<cim:WindGenTurbineType2IEC.WindContRotorRIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContRotorRIEC", sub, context);
let bucket = context.parsed.WindGenTurbineType2IEC;
if (null == bucket)
context.parsed.WindGenTurbineType2IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType1or2IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindGenTurbineType2IEC", "WindPitchContPowerIEC", "WindPitchContPowerIEC", fields);
base.export_attribute (obj, "WindGenTurbineType2IEC", "WindContRotorRIEC", "WindContRotorRIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenTurbineType2IEC_collapse" aria-expanded="true" aria-controls="WindGenTurbineType2IEC_collapse" style="margin-left: 10px;">WindGenTurbineType2IEC</a></legend>
<div id="WindGenTurbineType2IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2IEC.prototype.template.call (this) +
`
{{#WindPitchContPowerIEC}}<div><b>WindPitchContPowerIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPitchContPowerIEC}}");}); return false;'>{{WindPitchContPowerIEC}}</a></div>{{/WindPitchContPowerIEC}}
{{#WindContRotorRIEC}}<div><b>WindContRotorRIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContRotorRIEC}}");}); return false;'>{{WindContRotorRIEC}}</a></div>{{/WindContRotorRIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenTurbineType2IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenTurbineType2IEC_collapse" style="margin-left: 10px;">WindGenTurbineType2IEC</a></legend>
<div id="{{id}}_WindGenTurbineType2IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPitchContPowerIEC'>WindPitchContPowerIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPitchContPowerIEC' class='form-control' type='text'{{#WindPitchContPowerIEC}} value='{{WindPitchContPowerIEC}}'{{/WindPitchContPowerIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContRotorRIEC'>WindContRotorRIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContRotorRIEC' class='form-control' type='text'{{#WindContRotorRIEC}} value='{{WindContRotorRIEC}}'{{/WindContRotorRIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenTurbineType2IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindPitchContPowerIEC").value; if ("" !== temp) obj["WindPitchContPowerIEC"] = temp;
temp = document.getElementById (id + "_WindContRotorRIEC").value; if ("" !== temp) obj["WindContRotorRIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindPitchContPowerIEC", "1", "0..1", "WindPitchContPowerIEC", "WindGenTurbineType2IEC"],
["WindContRotorRIEC", "1", "1", "WindContRotorRIEC", "WindGenTurbineType2IEC"]
]
)
);
}
}
/**
* Wind turbine IEC type 1B.
*
* Reference: IEC 61400-27-1:2015, 5.5.2.3.
*
*/
class WindGenTurbineType1bIEC extends WindTurbineType1or2IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindGenTurbineType1bIEC;
if (null == bucket)
cim_data.WindGenTurbineType1bIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindGenTurbineType1bIEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType1or2IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindGenTurbineType1bIEC";
base.parse_attribute (/<cim:WindGenTurbineType1bIEC.WindPitchContPowerIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindPitchContPowerIEC", sub, context);
let bucket = context.parsed.WindGenTurbineType1bIEC;
if (null == bucket)
context.parsed.WindGenTurbineType1bIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType1or2IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindGenTurbineType1bIEC", "WindPitchContPowerIEC", "WindPitchContPowerIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindGenTurbineType1bIEC_collapse" aria-expanded="true" aria-controls="WindGenTurbineType1bIEC_collapse" style="margin-left: 10px;">WindGenTurbineType1bIEC</a></legend>
<div id="WindGenTurbineType1bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2IEC.prototype.template.call (this) +
`
{{#WindPitchContPowerIEC}}<div><b>WindPitchContPowerIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindPitchContPowerIEC}}");}); return false;'>{{WindPitchContPowerIEC}}</a></div>{{/WindPitchContPowerIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindGenTurbineType1bIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindGenTurbineType1bIEC_collapse" style="margin-left: 10px;">WindGenTurbineType1bIEC</a></legend>
<div id="{{id}}_WindGenTurbineType1bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType1or2IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindPitchContPowerIEC'>WindPitchContPowerIEC: </label><div class='col-sm-8'><input id='{{id}}_WindPitchContPowerIEC' class='form-control' type='text'{{#WindPitchContPowerIEC}} value='{{WindPitchContPowerIEC}}'{{/WindPitchContPowerIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindGenTurbineType1bIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindPitchContPowerIEC").value; if ("" !== temp) obj["WindPitchContPowerIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindPitchContPowerIEC", "1", "0..1", "WindPitchContPowerIEC", "WindGenTurbineType1bIEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to IEC wind turbines type 3 and type 4 including their control models.
*
*/
class WindTurbineType3or4IEC extends WindTurbineType3or4Dynamics
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType3or4IEC;
if (null == bucket)
cim_data.WindTurbineType3or4IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType3or4IEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType3or4Dynamics.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType3or4IEC";
base.parse_attribute (/<cim:WindTurbineType3or4IEC.WindContCurrLimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContCurrLimIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4IEC.WIndContQIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WIndContQIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4IEC.WindContQLimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContQLimIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4IEC.WindContQPQULimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContQPQULimIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4IEC.WindRefFrameRotIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindRefFrameRotIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3or4IEC.WindProtectionIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindProtectionIEC", sub, context);
let bucket = context.parsed.WindTurbineType3or4IEC;
if (null == bucket)
context.parsed.WindTurbineType3or4IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType3or4Dynamics.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType3or4IEC", "WindContCurrLimIEC", "WindContCurrLimIEC", fields);
base.export_attribute (obj, "WindTurbineType3or4IEC", "WIndContQIEC", "WIndContQIEC", fields);
base.export_attribute (obj, "WindTurbineType3or4IEC", "WindContQLimIEC", "WindContQLimIEC", fields);
base.export_attribute (obj, "WindTurbineType3or4IEC", "WindContQPQULimIEC", "WindContQPQULimIEC", fields);
base.export_attribute (obj, "WindTurbineType3or4IEC", "WindRefFrameRotIEC", "WindRefFrameRotIEC", fields);
base.export_attribute (obj, "WindTurbineType3or4IEC", "WindProtectionIEC", "WindProtectionIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType3or4IEC_collapse" aria-expanded="true" aria-controls="WindTurbineType3or4IEC_collapse" style="margin-left: 10px;">WindTurbineType3or4IEC</a></legend>
<div id="WindTurbineType3or4IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType3or4Dynamics.prototype.template.call (this) +
`
{{#WindContCurrLimIEC}}<div><b>WindContCurrLimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContCurrLimIEC}}");}); return false;'>{{WindContCurrLimIEC}}</a></div>{{/WindContCurrLimIEC}}
{{#WIndContQIEC}}<div><b>WIndContQIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WIndContQIEC}}");}); return false;'>{{WIndContQIEC}}</a></div>{{/WIndContQIEC}}
{{#WindContQLimIEC}}<div><b>WindContQLimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContQLimIEC}}");}); return false;'>{{WindContQLimIEC}}</a></div>{{/WindContQLimIEC}}
{{#WindContQPQULimIEC}}<div><b>WindContQPQULimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContQPQULimIEC}}");}); return false;'>{{WindContQPQULimIEC}}</a></div>{{/WindContQPQULimIEC}}
{{#WindRefFrameRotIEC}}<div><b>WindRefFrameRotIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindRefFrameRotIEC}}");}); return false;'>{{WindRefFrameRotIEC}}</a></div>{{/WindRefFrameRotIEC}}
{{#WindProtectionIEC}}<div><b>WindProtectionIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindProtectionIEC}}");}); return false;'>{{WindProtectionIEC}}</a></div>{{/WindProtectionIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType3or4IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType3or4IEC_collapse" style="margin-left: 10px;">WindTurbineType3or4IEC</a></legend>
<div id="{{id}}_WindTurbineType3or4IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType3or4Dynamics.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContCurrLimIEC'>WindContCurrLimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContCurrLimIEC' class='form-control' type='text'{{#WindContCurrLimIEC}} value='{{WindContCurrLimIEC}}'{{/WindContCurrLimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WIndContQIEC'>WIndContQIEC: </label><div class='col-sm-8'><input id='{{id}}_WIndContQIEC' class='form-control' type='text'{{#WIndContQIEC}} value='{{WIndContQIEC}}'{{/WIndContQIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContQLimIEC'>WindContQLimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContQLimIEC' class='form-control' type='text'{{#WindContQLimIEC}} value='{{WindContQLimIEC}}'{{/WindContQLimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContQPQULimIEC'>WindContQPQULimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContQPQULimIEC' class='form-control' type='text'{{#WindContQPQULimIEC}} value='{{WindContQPQULimIEC}}'{{/WindContQPQULimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindRefFrameRotIEC'>WindRefFrameRotIEC: </label><div class='col-sm-8'><input id='{{id}}_WindRefFrameRotIEC' class='form-control' type='text'{{#WindRefFrameRotIEC}} value='{{WindRefFrameRotIEC}}'{{/WindRefFrameRotIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindProtectionIEC'>WindProtectionIEC: </label><div class='col-sm-8'><input id='{{id}}_WindProtectionIEC' class='form-control' type='text'{{#WindProtectionIEC}} value='{{WindProtectionIEC}}'{{/WindProtectionIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType3or4IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindContCurrLimIEC").value; if ("" !== temp) obj["WindContCurrLimIEC"] = temp;
temp = document.getElementById (id + "_WIndContQIEC").value; if ("" !== temp) obj["WIndContQIEC"] = temp;
temp = document.getElementById (id + "_WindContQLimIEC").value; if ("" !== temp) obj["WindContQLimIEC"] = temp;
temp = document.getElementById (id + "_WindContQPQULimIEC").value; if ("" !== temp) obj["WindContQPQULimIEC"] = temp;
temp = document.getElementById (id + "_WindRefFrameRotIEC").value; if ("" !== temp) obj["WindRefFrameRotIEC"] = temp;
temp = document.getElementById (id + "_WindProtectionIEC").value; if ("" !== temp) obj["WindProtectionIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindContCurrLimIEC", "1", "1", "WindContCurrLimIEC", "WindTurbineType3or4IEC"],
["WIndContQIEC", "1", "1", "WindContQIEC", "WindTurbineType3or4IEC"],
["WindContQLimIEC", "0..1", "0..1", "WindContQLimIEC", "WindTurbineType3or4IEC"],
["WindContQPQULimIEC", "0..1", "0..1", "WindContQPQULimIEC", "WindTurbineType3or4IEC"],
["WindRefFrameRotIEC", "1", "1", "WindRefFrameRotIEC", "WindTurbineType3or4IEC"],
["WindProtectionIEC", "1", "0..1", "WindProtectionIEC", "WindTurbineType3or4IEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to IEC wind turbines type 4 including their control models.
*
*/
class WindTurbineType4IEC extends WindTurbineType3or4IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType4IEC;
if (null == bucket)
cim_data.WindTurbineType4IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType4IEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType3or4IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType4IEC";
base.parse_attribute (/<cim:WindTurbineType4IEC.WindGenType3aIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenType3aIEC", sub, context);
let bucket = context.parsed.WindTurbineType4IEC;
if (null == bucket)
context.parsed.WindTurbineType4IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType3or4IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType4IEC", "WindGenType3aIEC", "WindGenType3aIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType4IEC_collapse" aria-expanded="true" aria-controls="WindTurbineType4IEC_collapse" style="margin-left: 10px;">WindTurbineType4IEC</a></legend>
<div id="WindTurbineType4IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType3or4IEC.prototype.template.call (this) +
`
{{#WindGenType3aIEC}}<div><b>WindGenType3aIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenType3aIEC}}");}); return false;'>{{WindGenType3aIEC}}</a></div>{{/WindGenType3aIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType4IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType4IEC_collapse" style="margin-left: 10px;">WindTurbineType4IEC</a></legend>
<div id="{{id}}_WindTurbineType4IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType3or4IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenType3aIEC'>WindGenType3aIEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenType3aIEC' class='form-control' type='text'{{#WindGenType3aIEC}} value='{{WindGenType3aIEC}}'{{/WindGenType3aIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType4IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindGenType3aIEC").value; if ("" !== temp) obj["WindGenType3aIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindGenType3aIEC", "0..1", "0..1", "WindGenType3aIEC", "WindTurbineType4IEC"]
]
)
);
}
}
/**
* Wind turbine IEC type 4B.
*
* Reference: IEC 61400-27-1:2015, 5.5.5.3.
*
*/
class WindTurbineType4bIEC extends WindTurbineType4IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType4bIEC;
if (null == bucket)
cim_data.WindTurbineType4bIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType4bIEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType4IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType4bIEC";
base.parse_attribute (/<cim:WindTurbineType4bIEC.WindGenType4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenType4IEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType4bIEC.WindMechIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindMechIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType4bIEC.WindContPType4bIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContPType4bIEC", sub, context);
let bucket = context.parsed.WindTurbineType4bIEC;
if (null == bucket)
context.parsed.WindTurbineType4bIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType4IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType4bIEC", "WindGenType4IEC", "WindGenType4IEC", fields);
base.export_attribute (obj, "WindTurbineType4bIEC", "WindMechIEC", "WindMechIEC", fields);
base.export_attribute (obj, "WindTurbineType4bIEC", "WindContPType4bIEC", "WindContPType4bIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType4bIEC_collapse" aria-expanded="true" aria-controls="WindTurbineType4bIEC_collapse" style="margin-left: 10px;">WindTurbineType4bIEC</a></legend>
<div id="WindTurbineType4bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType4IEC.prototype.template.call (this) +
`
{{#WindGenType4IEC}}<div><b>WindGenType4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenType4IEC}}");}); return false;'>{{WindGenType4IEC}}</a></div>{{/WindGenType4IEC}}
{{#WindMechIEC}}<div><b>WindMechIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindMechIEC}}");}); return false;'>{{WindMechIEC}}</a></div>{{/WindMechIEC}}
{{#WindContPType4bIEC}}<div><b>WindContPType4bIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContPType4bIEC}}");}); return false;'>{{WindContPType4bIEC}}</a></div>{{/WindContPType4bIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType4bIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType4bIEC_collapse" style="margin-left: 10px;">WindTurbineType4bIEC</a></legend>
<div id="{{id}}_WindTurbineType4bIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType4IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenType4IEC'>WindGenType4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenType4IEC' class='form-control' type='text'{{#WindGenType4IEC}} value='{{WindGenType4IEC}}'{{/WindGenType4IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindMechIEC'>WindMechIEC: </label><div class='col-sm-8'><input id='{{id}}_WindMechIEC' class='form-control' type='text'{{#WindMechIEC}} value='{{WindMechIEC}}'{{/WindMechIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContPType4bIEC'>WindContPType4bIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContPType4bIEC' class='form-control' type='text'{{#WindContPType4bIEC}} value='{{WindContPType4bIEC}}'{{/WindContPType4bIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType4bIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindGenType4IEC").value; if ("" !== temp) obj["WindGenType4IEC"] = temp;
temp = document.getElementById (id + "_WindMechIEC").value; if ("" !== temp) obj["WindMechIEC"] = temp;
temp = document.getElementById (id + "_WindContPType4bIEC").value; if ("" !== temp) obj["WindContPType4bIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindGenType4IEC", "0..1", "0..1", "WindGenType4IEC", "WindTurbineType4bIEC"],
["WindMechIEC", "1", "0..1", "WindMechIEC", "WindTurbineType4bIEC"],
["WindContPType4bIEC", "1", "1", "WindContPType4bIEC", "WindTurbineType4bIEC"]
]
)
);
}
}
/**
* Parent class supporting relationships to IEC wind turbines type 3 including their control models.
*
*/
class WindTurbineType3IEC extends WindTurbineType3or4IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType3IEC;
if (null == bucket)
cim_data.WindTurbineType3IEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType3IEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType3or4IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType3IEC";
base.parse_attribute (/<cim:WindTurbineType3IEC.WindAeroTwoDimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindAeroTwoDimIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3IEC.WindContPitchAngleIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContPitchAngleIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3IEC.WindMechIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindMechIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3IEC.WindGenType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenType3IEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3IEC.WindAeroOneDimIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindAeroOneDimIEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType3IEC.WindContPType3IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContPType3IEC", sub, context);
let bucket = context.parsed.WindTurbineType3IEC;
if (null == bucket)
context.parsed.WindTurbineType3IEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType3or4IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType3IEC", "WindAeroTwoDimIEC", "WindAeroTwoDimIEC", fields);
base.export_attribute (obj, "WindTurbineType3IEC", "WindContPitchAngleIEC", "WindContPitchAngleIEC", fields);
base.export_attribute (obj, "WindTurbineType3IEC", "WindMechIEC", "WindMechIEC", fields);
base.export_attribute (obj, "WindTurbineType3IEC", "WindGenType3IEC", "WindGenType3IEC", fields);
base.export_attribute (obj, "WindTurbineType3IEC", "WindAeroOneDimIEC", "WindAeroOneDimIEC", fields);
base.export_attribute (obj, "WindTurbineType3IEC", "WindContPType3IEC", "WindContPType3IEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType3IEC_collapse" aria-expanded="true" aria-controls="WindTurbineType3IEC_collapse" style="margin-left: 10px;">WindTurbineType3IEC</a></legend>
<div id="WindTurbineType3IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType3or4IEC.prototype.template.call (this) +
`
{{#WindAeroTwoDimIEC}}<div><b>WindAeroTwoDimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindAeroTwoDimIEC}}");}); return false;'>{{WindAeroTwoDimIEC}}</a></div>{{/WindAeroTwoDimIEC}}
{{#WindContPitchAngleIEC}}<div><b>WindContPitchAngleIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContPitchAngleIEC}}");}); return false;'>{{WindContPitchAngleIEC}}</a></div>{{/WindContPitchAngleIEC}}
{{#WindMechIEC}}<div><b>WindMechIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindMechIEC}}");}); return false;'>{{WindMechIEC}}</a></div>{{/WindMechIEC}}
{{#WindGenType3IEC}}<div><b>WindGenType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenType3IEC}}");}); return false;'>{{WindGenType3IEC}}</a></div>{{/WindGenType3IEC}}
{{#WindAeroOneDimIEC}}<div><b>WindAeroOneDimIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindAeroOneDimIEC}}");}); return false;'>{{WindAeroOneDimIEC}}</a></div>{{/WindAeroOneDimIEC}}
{{#WindContPType3IEC}}<div><b>WindContPType3IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContPType3IEC}}");}); return false;'>{{WindContPType3IEC}}</a></div>{{/WindContPType3IEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType3IEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType3IEC_collapse" style="margin-left: 10px;">WindTurbineType3IEC</a></legend>
<div id="{{id}}_WindTurbineType3IEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType3or4IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindAeroTwoDimIEC'>WindAeroTwoDimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindAeroTwoDimIEC' class='form-control' type='text'{{#WindAeroTwoDimIEC}} value='{{WindAeroTwoDimIEC}}'{{/WindAeroTwoDimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContPitchAngleIEC'>WindContPitchAngleIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContPitchAngleIEC' class='form-control' type='text'{{#WindContPitchAngleIEC}} value='{{WindContPitchAngleIEC}}'{{/WindContPitchAngleIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindMechIEC'>WindMechIEC: </label><div class='col-sm-8'><input id='{{id}}_WindMechIEC' class='form-control' type='text'{{#WindMechIEC}} value='{{WindMechIEC}}'{{/WindMechIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenType3IEC'>WindGenType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenType3IEC' class='form-control' type='text'{{#WindGenType3IEC}} value='{{WindGenType3IEC}}'{{/WindGenType3IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindAeroOneDimIEC'>WindAeroOneDimIEC: </label><div class='col-sm-8'><input id='{{id}}_WindAeroOneDimIEC' class='form-control' type='text'{{#WindAeroOneDimIEC}} value='{{WindAeroOneDimIEC}}'{{/WindAeroOneDimIEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContPType3IEC'>WindContPType3IEC: </label><div class='col-sm-8'><input id='{{id}}_WindContPType3IEC' class='form-control' type='text'{{#WindContPType3IEC}} value='{{WindContPType3IEC}}'{{/WindContPType3IEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType3IEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindAeroTwoDimIEC").value; if ("" !== temp) obj["WindAeroTwoDimIEC"] = temp;
temp = document.getElementById (id + "_WindContPitchAngleIEC").value; if ("" !== temp) obj["WindContPitchAngleIEC"] = temp;
temp = document.getElementById (id + "_WindMechIEC").value; if ("" !== temp) obj["WindMechIEC"] = temp;
temp = document.getElementById (id + "_WindGenType3IEC").value; if ("" !== temp) obj["WindGenType3IEC"] = temp;
temp = document.getElementById (id + "_WindAeroOneDimIEC").value; if ("" !== temp) obj["WindAeroOneDimIEC"] = temp;
temp = document.getElementById (id + "_WindContPType3IEC").value; if ("" !== temp) obj["WindContPType3IEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindAeroTwoDimIEC", "0..1", "1", "WindAeroTwoDimIEC", "WindTurbineType3IEC"],
["WindContPitchAngleIEC", "1", "1", "WindContPitchAngleIEC", "WindTurbineType3IEC"],
["WindMechIEC", "1", "0..1", "WindMechIEC", "WindTurbineType3IEC"],
["WindGenType3IEC", "0..1", "0..1", "WindGenType3IEC", "WindTurbineType3IEC"],
["WindAeroOneDimIEC", "0..1", "1", "WindAeroOneDimIEC", "WindTurbineType3IEC"],
["WindContPType3IEC", "1", "1", "WindContPType3IEC", "WindTurbineType3IEC"]
]
)
);
}
}
/**
* Wind turbine IEC type 4A.
*
* Reference: IEC 61400-27-1:2015, 5.5.5.2.
*
*/
class WindTurbineType4aIEC extends WindTurbineType4IEC
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WindTurbineType4aIEC;
if (null == bucket)
cim_data.WindTurbineType4aIEC = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WindTurbineType4aIEC[obj.id];
}
parse (context, sub)
{
let obj = WindTurbineType4IEC.prototype.parse.call (this, context, sub);
obj.cls = "WindTurbineType4aIEC";
base.parse_attribute (/<cim:WindTurbineType4aIEC.WindGenType4IEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindGenType4IEC", sub, context);
base.parse_attribute (/<cim:WindTurbineType4aIEC.WindContPType4aIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WindContPType4aIEC", sub, context);
let bucket = context.parsed.WindTurbineType4aIEC;
if (null == bucket)
context.parsed.WindTurbineType4aIEC = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = WindTurbineType4IEC.prototype.export.call (this, obj, false);
base.export_attribute (obj, "WindTurbineType4aIEC", "WindGenType4IEC", "WindGenType4IEC", fields);
base.export_attribute (obj, "WindTurbineType4aIEC", "WindContPType4aIEC", "WindContPType4aIEC", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WindTurbineType4aIEC_collapse" aria-expanded="true" aria-controls="WindTurbineType4aIEC_collapse" style="margin-left: 10px;">WindTurbineType4aIEC</a></legend>
<div id="WindTurbineType4aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType4IEC.prototype.template.call (this) +
`
{{#WindGenType4IEC}}<div><b>WindGenType4IEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindGenType4IEC}}");}); return false;'>{{WindGenType4IEC}}</a></div>{{/WindGenType4IEC}}
{{#WindContPType4aIEC}}<div><b>WindContPType4aIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WindContPType4aIEC}}");}); return false;'>{{WindContPType4aIEC}}</a></div>{{/WindContPType4aIEC}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WindTurbineType4aIEC_collapse" aria-expanded="true" aria-controls="{{id}}_WindTurbineType4aIEC_collapse" style="margin-left: 10px;">WindTurbineType4aIEC</a></legend>
<div id="{{id}}_WindTurbineType4aIEC_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ WindTurbineType4IEC.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindGenType4IEC'>WindGenType4IEC: </label><div class='col-sm-8'><input id='{{id}}_WindGenType4IEC' class='form-control' type='text'{{#WindGenType4IEC}} value='{{WindGenType4IEC}}'{{/WindGenType4IEC}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WindContPType4aIEC'>WindContPType4aIEC: </label><div class='col-sm-8'><input id='{{id}}_WindContPType4aIEC' class='form-control' type='text'{{#WindContPType4aIEC}} value='{{WindContPType4aIEC}}'{{/WindContPType4aIEC}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WindTurbineType4aIEC" };
super.submit (id, obj);
temp = document.getElementById (id + "_WindGenType4IEC").value; if ("" !== temp) obj["WindGenType4IEC"] = temp;
temp = document.getElementById (id + "_WindContPType4aIEC").value; if ("" !== temp) obj["WindContPType4aIEC"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WindGenType4IEC", "0..1", "0..1", "WindGenType4IEC", "WindTurbineType4aIEC"],
["WindContPType4aIEC", "1", "1", "WindContPType4aIEC", "WindTurbineType4aIEC"]
]
)
);
}
}
return (
{
WindTurbineType4IEC: WindTurbineType4IEC,
WindGenTurbineType1bIEC: WindGenTurbineType1bIEC,
WindTurbineType3or4Dynamics: WindTurbineType3or4Dynamics,
WindTurbineType1or2IEC: WindTurbineType1or2IEC,
WindGenTurbineType2IEC: WindGenTurbineType2IEC,
WindPlantIEC: WindPlantIEC,
WindAeroConstIEC: WindAeroConstIEC,
WindTurbineType4aIEC: WindTurbineType4aIEC,
WindContRotorRIEC: WindContRotorRIEC,
WindGenTurbineType1aIEC: WindGenTurbineType1aIEC,
WindContCurrLimIEC: WindContCurrLimIEC,
WindGenType4IEC: WindGenType4IEC,
WindTurbineType4bIEC: WindTurbineType4bIEC,
WindTurbineType3IEC: WindTurbineType3IEC,
WindContQLimIEC: WindContQLimIEC,
WindContQIEC: WindContQIEC,
WindContPType3IEC: WindContPType3IEC,
WindGenType3aIEC: WindGenType3aIEC,
WindPlantReactiveControlIEC: WindPlantReactiveControlIEC,
WindPlantDynamics: WindPlantDynamics,
WindQcontrolModeKind: WindQcontrolModeKind,
WindMechIEC: WindMechIEC,
WindGenType3bIEC: WindGenType3bIEC,
WindContPType4bIEC: WindContPType4bIEC,
WindTurbineType1or2Dynamics: WindTurbineType1or2Dynamics,
WindContQPQULimIEC: WindContQPQULimIEC,
WindContPitchAngleIEC: WindContPitchAngleIEC,
WindRefFrameRotIEC: WindRefFrameRotIEC,
WindLookupTableFunctionKind: WindLookupTableFunctionKind,
WindAeroOneDimIEC: WindAeroOneDimIEC,
WindContPType4aIEC: WindContPType4aIEC,
WindPlantQcontrolModeKind: WindPlantQcontrolModeKind,
WindPitchContPowerIEC: WindPitchContPowerIEC,
WindDynamicsLookupTable: WindDynamicsLookupTable,
WindProtectionIEC: WindProtectionIEC,
WindTurbineType3or4IEC: WindTurbineType3or4IEC,
WindUVRTQcontrolModeKind: WindUVRTQcontrolModeKind,
WindAeroTwoDimIEC: WindAeroTwoDimIEC,
WindPlantFreqPcontrolIEC: WindPlantFreqPcontrolIEC,
WindGenType3IEC: WindGenType3IEC
}
);
}
);
|
ramanujam/parsestore
|
Pods/ArtisanSDK/ArtisanSDK.framework/Versions/A/Headers/UIView+ArtisanEventTags.h
|
<reponame>ramanujam/parsestore<filename>Pods/ArtisanSDK/ArtisanSDK.framework/Versions/A/Headers/UIView+ArtisanEventTags.h
//
// UIView+ArtisanEventTags.h
//
// Copyright (c) 2014 Artisan Mobile. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
Category that adds the artisanEventTags property to UIViews.
*/
@interface UIView (ArtisanEventTags)
/**
Use this property to add ArtisanEventTags to your UIViews (e.g. UIButton, UITableViewCell).
ArtisanEventTags are a collection of key/values that can be attached to a UIView so that any automatically-collected analytics events, like button tap events, will be tagged or categorized with the appropriate values.
<h3>Usage Example</h3>
Here I am adding a tag for the button title which will perform the currentTitle selector to get the current title of the button at the time that any automatically-collected analytics event is recorded. This could be useful if the title on my button changes while it is on the screen and I want to know what it said when the user tapped on it. In this example self is my UIViewController.
<code><pre>
ArtisanEventTags *extraButtonInfo = [ArtisanEventTags artisanEventTags];
[extraButtonInfo setSelector:@selector(currentTitle) forKey:@"buttonTitle"];
self.addToCartButton.artisanEventTags = extraButtonInfo;
</pre></code>
*/
@property (nonatomic, retain) ArtisanEventTags *artisanEventTags;
@end
|
Andreas237/AndroidPolicyAutomation
|
ExtractedJars/LibriVox_app.librivox.android/javafiles/android/support/design/widget/BaseTransientBottomBar.java
|
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.design.widget;
import android.animation.ValueAnimator;
import android.os.Handler;
import android.os.Looper;
import android.support.design.a.a;
import android.support.design.c;
import android.support.v4.view.ac;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import java.util.List;
// Referenced classes of package android.support.design.widget:
// f, g, h, s,
// bs, am, i, SwipeDismissBehavior,
// j, l, o, m,
// n, bu
public abstract class BaseTransientBottomBar
{
static android.support.design.h.a a(BaseTransientBottomBar basetransientbottombar)
{
return basetransientbottombar.g;
// 0 0:aload_0
// 1 1:getfield #63 <Field android.support.design.h.a g>
// 2 4:areturn
}
private void d(int k)
{
ValueAnimator valueanimator = new ValueAnimator();
// 0 0:new #66 <Class ValueAnimator>
// 1 3:dup
// 2 4:invokespecial #67 <Method void ValueAnimator()>
// 3 7:astore_2
valueanimator.setIntValues(new int[] {
0, h()
});
// 4 8:aload_2
// 5 9:iconst_2
// 6 10:newarray int[]
// 7 12:dup
// 8 13:iconst_0
// 9 14:iconst_0
// 10 15:iastore
// 11 16:dup
// 12 17:iconst_1
// 13 18:aload_0
// 14 19:invokespecial #70 <Method int h()>
// 15 22:iastore
// 16 23:invokevirtual #74 <Method void ValueAnimator.setIntValues(int[])>
valueanimator.setInterpolator(a.b);
// 17 26:aload_2
// 18 27:getstatic #79 <Field android.animation.TimeInterpolator a.b>
// 19 30:invokevirtual #83 <Method void ValueAnimator.setInterpolator(android.animation.TimeInterpolator)>
valueanimator.setDuration(250L);
// 20 33:aload_2
// 21 34:ldc2w #84 <Long 250L>
// 22 37:invokevirtual #89 <Method ValueAnimator ValueAnimator.setDuration(long)>
// 23 40:pop
valueanimator.addListener(((android.animation.Animator.AnimatorListener) (new g(this, k))));
// 24 41:aload_2
// 25 42:new #91 <Class g>
// 26 45:dup
// 27 46:aload_0
// 28 47:iload_1
// 29 48:invokespecial #94 <Method void g(BaseTransientBottomBar, int)>
// 30 51:invokevirtual #98 <Method void ValueAnimator.addListener(android.animation.Animator$AnimatorListener)>
valueanimator.addUpdateListener(((android.animation.ValueAnimator.AnimatorUpdateListener) (new h(this))));
// 31 54:aload_2
// 32 55:new #100 <Class h>
// 33 58:dup
// 34 59:aload_0
// 35 60:invokespecial #103 <Method void h(BaseTransientBottomBar)>
// 36 63:invokevirtual #107 <Method void ValueAnimator.addUpdateListener(android.animation.ValueAnimator$AnimatorUpdateListener)>
valueanimator.start();
// 37 66:aload_2
// 38 67:invokevirtual #110 <Method void ValueAnimator.start()>
// 39 70:return
}
static boolean g()
{
return d;
// 0 0:getstatic #34 <Field boolean d>
// 1 3:ireturn
}
private int h()
{
int i1 = b.getHeight();
// 0 0:aload_0
// 1 1:getfield #113 <Field s b>
// 2 4:invokevirtual #118 <Method int s.getHeight()>
// 3 7:istore_2
android.view.ViewGroup.LayoutParams layoutparams = b.getLayoutParams();
// 4 8:aload_0
// 5 9:getfield #113 <Field s b>
// 6 12:invokevirtual #122 <Method android.view.ViewGroup$LayoutParams s.getLayoutParams()>
// 7 15:astore_3
int k = i1;
// 8 16:iload_2
// 9 17:istore_1
if(layoutparams instanceof android.view.ViewGroup.MarginLayoutParams)
//* 10 18:aload_3
//* 11 19:instanceof #124 <Class android.view.ViewGroup$MarginLayoutParams>
//* 12 22:ifeq 35
k = i1 + ((android.view.ViewGroup.MarginLayoutParams)layoutparams).bottomMargin;
// 13 25:iload_2
// 14 26:aload_3
// 15 27:checkcast #124 <Class android.view.ViewGroup$MarginLayoutParams>
// 16 30:getfield #127 <Field int android.view.ViewGroup$MarginLayoutParams.bottomMargin>
// 17 33:iadd
// 18 34:istore_1
return k;
// 19 35:iload_1
// 20 36:ireturn
}
protected void a(int k)
{
android.support.design.widget.bs.a().a(c, k);
// 0 0:invokestatic #132 <Method bs android.support.design.widget.bs.a()>
// 1 3:aload_0
// 2 4:getfield #134 <Field bu c>
// 3 7:iload_1
// 4 8:invokevirtual #137 <Method void android.support.design.widget.bs.a(bu, int)>
// 5 11:return
}
public boolean a()
{
return android.support.design.widget.bs.a().e(c);
// 0 0:invokestatic #132 <Method bs android.support.design.widget.bs.a()>
// 1 3:aload_0
// 2 4:getfield #134 <Field bu c>
// 3 7:invokevirtual #140 <Method boolean bs.e(bu)>
// 4 10:ireturn
}
protected SwipeDismissBehavior b()
{
return ((SwipeDismissBehavior) (new Behavior()));
// 0 0:new #143 <Class BaseTransientBottomBar$Behavior>
// 1 3:dup
// 2 4:invokespecial #144 <Method void BaseTransientBottomBar$Behavior()>
// 3 7:areturn
}
final void b(int k)
{
if(f() && b.getVisibility() == 0)
//* 0 0:aload_0
//* 1 1:invokevirtual #146 <Method boolean f()>
//* 2 4:ifeq 23
//* 3 7:aload_0
//* 4 8:getfield #113 <Field s b>
//* 5 11:invokevirtual #149 <Method int s.getVisibility()>
//* 6 14:ifne 23
{
d(k);
// 7 17:aload_0
// 8 18:iload_1
// 9 19:invokespecial #151 <Method void d(int)>
return;
// 10 22:return
} else
{
c(k);
// 11 23:aload_0
// 12 24:iload_1
// 13 25:invokevirtual #153 <Method void c(int)>
return;
// 14 28:return
}
}
final void c()
{
if(b.getParent() == null)
//* 0 0:aload_0
//* 1 1:getfield #113 <Field s b>
//* 2 4:invokevirtual #157 <Method android.view.ViewParent s.getParent()>
//* 3 7:ifnonnull 95
{
Object obj = ((Object) (b.getLayoutParams()));
// 4 10:aload_0
// 5 11:getfield #113 <Field s b>
// 6 14:invokevirtual #122 <Method android.view.ViewGroup$LayoutParams s.getLayoutParams()>
// 7 17:astore_1
if(obj instanceof am)
//* 8 18:aload_1
//* 9 19:instanceof #159 <Class am>
//* 10 22:ifeq 84
{
am am1 = (am)obj;
// 11 25:aload_1
// 12 26:checkcast #159 <Class am>
// 13 29:astore_3
Behavior behavior = i;
// 14 30:aload_0
// 15 31:getfield #161 <Field BaseTransientBottomBar$Behavior i>
// 16 34:astore_2
obj = ((Object) (behavior));
// 17 35:aload_2
// 18 36:astore_1
if(behavior == null)
//* 19 37:aload_2
//* 20 38:ifnonnull 46
obj = ((Object) (b()));
// 21 41:aload_0
// 22 42:invokevirtual #163 <Method SwipeDismissBehavior b()>
// 23 45:astore_1
if(obj instanceof Behavior)
//* 24 46:aload_1
//* 25 47:instanceof #143 <Class BaseTransientBottomBar$Behavior>
//* 26 50:ifeq 61
android.support.design.widget.Behavior.a((Behavior)obj, this);
// 27 53:aload_1
// 28 54:checkcast #143 <Class BaseTransientBottomBar$Behavior>
// 29 57:aload_0
// 30 58:invokestatic #166 <Method void android.support.design.widget.BaseTransientBottomBar$Behavior.a(BaseTransientBottomBar$Behavior, BaseTransientBottomBar)>
((SwipeDismissBehavior) (obj)).a(((ca) (new i(this))));
// 31 61:aload_1
// 32 62:new #168 <Class i>
// 33 65:dup
// 34 66:aload_0
// 35 67:invokespecial #169 <Method void i(BaseTransientBottomBar)>
// 36 70:invokevirtual #174 <Method void android.support.design.widget.SwipeDismissBehavior.a(ca)>
am1.a(((aj) (obj)));
// 37 73:aload_3
// 38 74:aload_1
// 39 75:invokevirtual #177 <Method void android.support.design.widget.am.a(aj)>
am1.g = 80;
// 40 78:aload_3
// 41 79:bipush 80
// 42 81:putfield #179 <Field int am.g>
}
f.addView(((View) (b)));
// 43 84:aload_0
// 44 85:getfield #181 <Field ViewGroup f>
// 45 88:aload_0
// 46 89:getfield #113 <Field s b>
// 47 92:invokevirtual #187 <Method void ViewGroup.addView(View)>
}
b.setOnAttachStateChangeListener(((q) (new j(this))));
// 48 95:aload_0
// 49 96:getfield #113 <Field s b>
// 50 99:new #189 <Class j>
// 51 102:dup
// 52 103:aload_0
// 53 104:invokespecial #190 <Method void j(BaseTransientBottomBar)>
// 54 107:invokevirtual #194 <Method void s.setOnAttachStateChangeListener(q)>
if(ac.x(((View) (b))))
//* 55 110:aload_0
//* 56 111:getfield #113 <Field s b>
//* 57 114:invokestatic #200 <Method boolean ac.x(View)>
//* 58 117:ifeq 137
{
if(f())
//* 59 120:aload_0
//* 60 121:invokevirtual #146 <Method boolean f()>
//* 61 124:ifeq 132
{
d();
// 62 127:aload_0
// 63 128:invokevirtual #202 <Method void d()>
return;
// 64 131:return
} else
{
e();
// 65 132:aload_0
// 66 133:invokevirtual #204 <Method void e()>
return;
// 67 136:return
}
} else
{
b.setOnLayoutChangeListener(((r) (new l(this))));
// 68 137:aload_0
// 69 138:getfield #113 <Field s b>
// 70 141:new #206 <Class l>
// 71 144:dup
// 72 145:aload_0
// 73 146:invokespecial #207 <Method void l(BaseTransientBottomBar)>
// 74 149:invokevirtual #211 <Method void s.setOnLayoutChangeListener(r)>
return;
// 75 152:return
}
}
void c(int k)
{
android.support.design.widget.bs.a().a(c);
// 0 0:invokestatic #132 <Method bs android.support.design.widget.bs.a()>
// 1 3:aload_0
// 2 4:getfield #134 <Field bu c>
// 3 7:invokevirtual #214 <Method void android.support.design.widget.bs.a(bu)>
Object obj = ((Object) (h));
// 4 10:aload_0
// 5 11:getfield #216 <Field List h>
// 6 14:astore_3
if(obj != null)
//* 7 15:aload_3
//* 8 16:ifnull 57
{
for(int i1 = ((List) (obj)).size() - 1; i1 >= 0; i1--)
//* 9 19:aload_3
//* 10 20:invokeinterface #221 <Method int List.size()>
//* 11 25:iconst_1
//* 12 26:isub
//* 13 27:istore_2
//* 14 28:iload_2
//* 15 29:iflt 57
((o)h.get(i1)).a(((Object) (this)), k);
// 16 32:aload_0
// 17 33:getfield #216 <Field List h>
// 18 36:iload_2
// 19 37:invokeinterface #225 <Method Object List.get(int)>
// 20 42:checkcast #227 <Class o>
// 21 45:aload_0
// 22 46:iload_1
// 23 47:invokevirtual #230 <Method void android.support.design.widget.o.a(Object, int)>
// 24 50:iload_2
// 25 51:iconst_1
// 26 52:isub
// 27 53:istore_2
}
//* 28 54:goto 28
obj = ((Object) (b.getParent()));
// 29 57:aload_0
// 30 58:getfield #113 <Field s b>
// 31 61:invokevirtual #157 <Method android.view.ViewParent s.getParent()>
// 32 64:astore_3
if(obj instanceof ViewGroup)
//* 33 65:aload_3
//* 34 66:instanceof #183 <Class ViewGroup>
//* 35 69:ifeq 83
((ViewGroup)obj).removeView(((View) (b)));
// 36 72:aload_3
// 37 73:checkcast #183 <Class ViewGroup>
// 38 76:aload_0
// 39 77:getfield #113 <Field s b>
// 40 80:invokevirtual #233 <Method void ViewGroup.removeView(View)>
// 41 83:return
}
void d()
{
int k = h();
// 0 0:aload_0
// 1 1:invokespecial #70 <Method int h()>
// 2 4:istore_1
if(d)
//* 3 5:getstatic #34 <Field boolean d>
//* 4 8:ifeq 22
ac.e(((View) (b)), k);
// 5 11:aload_0
// 6 12:getfield #113 <Field s b>
// 7 15:iload_1
// 8 16:invokestatic #236 <Method void ac.e(View, int)>
else
//* 9 19:goto 31
b.setTranslationY(k);
// 10 22:aload_0
// 11 23:getfield #113 <Field s b>
// 12 26:iload_1
// 13 27:i2f
// 14 28:invokevirtual #240 <Method void s.setTranslationY(float)>
ValueAnimator valueanimator = new ValueAnimator();
// 15 31:new #66 <Class ValueAnimator>
// 16 34:dup
// 17 35:invokespecial #67 <Method void ValueAnimator()>
// 18 38:astore_2
valueanimator.setIntValues(new int[] {
k, 0
});
// 19 39:aload_2
// 20 40:iconst_2
// 21 41:newarray int[]
// 22 43:dup
// 23 44:iconst_0
// 24 45:iload_1
// 25 46:iastore
// 26 47:dup
// 27 48:iconst_1
// 28 49:iconst_0
// 29 50:iastore
// 30 51:invokevirtual #74 <Method void ValueAnimator.setIntValues(int[])>
valueanimator.setInterpolator(a.b);
// 31 54:aload_2
// 32 55:getstatic #79 <Field android.animation.TimeInterpolator a.b>
// 33 58:invokevirtual #83 <Method void ValueAnimator.setInterpolator(android.animation.TimeInterpolator)>
valueanimator.setDuration(250L);
// 34 61:aload_2
// 35 62:ldc2w #84 <Long 250L>
// 36 65:invokevirtual #89 <Method ValueAnimator ValueAnimator.setDuration(long)>
// 37 68:pop
valueanimator.addListener(((android.animation.Animator.AnimatorListener) (new m(this))));
// 38 69:aload_2
// 39 70:new #242 <Class m>
// 40 73:dup
// 41 74:aload_0
// 42 75:invokespecial #243 <Method void m(BaseTransientBottomBar)>
// 43 78:invokevirtual #98 <Method void ValueAnimator.addListener(android.animation.Animator$AnimatorListener)>
valueanimator.addUpdateListener(((android.animation.ValueAnimator.AnimatorUpdateListener) (new n(this, k))));
// 44 81:aload_2
// 45 82:new #245 <Class n>
// 46 85:dup
// 47 86:aload_0
// 48 87:iload_1
// 49 88:invokespecial #246 <Method void n(BaseTransientBottomBar, int)>
// 50 91:invokevirtual #107 <Method void ValueAnimator.addUpdateListener(android.animation.ValueAnimator$AnimatorUpdateListener)>
valueanimator.start();
// 51 94:aload_2
// 52 95:invokevirtual #110 <Method void ValueAnimator.start()>
// 53 98:return
}
void e()
{
android.support.design.widget.bs.a().b(c);
// 0 0:invokestatic #132 <Method bs android.support.design.widget.bs.a()>
// 1 3:aload_0
// 2 4:getfield #134 <Field bu c>
// 3 7:invokevirtual #248 <Method void bs.b(bu)>
List list = h;
// 4 10:aload_0
// 5 11:getfield #216 <Field List h>
// 6 14:astore_2
if(list != null)
//* 7 15:aload_2
//* 8 16:ifnull 56
{
for(int k = list.size() - 1; k >= 0; k--)
//* 9 19:aload_2
//* 10 20:invokeinterface #221 <Method int List.size()>
//* 11 25:iconst_1
//* 12 26:isub
//* 13 27:istore_1
//* 14 28:iload_1
//* 15 29:iflt 56
((o)h.get(k)).a(((Object) (this)));
// 16 32:aload_0
// 17 33:getfield #216 <Field List h>
// 18 36:iload_1
// 19 37:invokeinterface #225 <Method Object List.get(int)>
// 20 42:checkcast #227 <Class o>
// 21 45:aload_0
// 22 46:invokevirtual #251 <Method void android.support.design.widget.o.a(Object)>
// 23 49:iload_1
// 24 50:iconst_1
// 25 51:isub
// 26 52:istore_1
}
//* 27 53:goto 28
// 28 56:return
}
boolean f()
{
List list = j.getEnabledAccessibilityServiceList(1);
// 0 0:aload_0
// 1 1:getfield #253 <Field AccessibilityManager j>
// 2 4:iconst_1
// 3 5:invokevirtual #259 <Method List AccessibilityManager.getEnabledAccessibilityServiceList(int)>
// 4 8:astore_1
return list != null && list.isEmpty();
// 5 9:aload_1
// 6 10:ifnull 24
// 7 13:aload_1
// 8 14:invokeinterface #262 <Method boolean List.isEmpty()>
// 9 19:ifeq 24
// 10 22:iconst_1
// 11 23:ireturn
// 12 24:iconst_0
// 13 25:ireturn
}
static final Handler a = new Handler(Looper.getMainLooper(), ((android.os.Handler.Callback) (new f())));
private static final boolean d;
private static final int e[];
protected final s b;
final bu c;
private final ViewGroup f;
private final android.support.design.h.a g;
private List h;
private Behavior i;
private final AccessibilityManager j;
static
{
boolean flag;
if(android.os.Build.VERSION.SDK_INT >= 16 && android.os.Build.VERSION.SDK_INT <= 19)
//* 0 0:getstatic #32 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 16
//* 2 5:icmplt 21
//* 3 8:getstatic #32 <Field int android.os.Build$VERSION.SDK_INT>
//* 4 11:bipush 19
//* 5 13:icmpgt 21
flag = true;
// 6 16:iconst_1
// 7 17:istore_0
else
//* 8 18:goto 23
flag = false;
// 9 21:iconst_0
// 10 22:istore_0
d = flag;
// 11 23:iload_0
// 12 24:putstatic #34 <Field boolean d>
e = (new int[] {
c.snackbarStyle
});
// 13 27:iconst_1
// 14 28:newarray int[]
// 15 30:dup
// 16 31:iconst_0
// 17 32:getstatic #39 <Field int c.snackbarStyle>
// 18 35:iastore
// 19 36:putstatic #41 <Field int[] e>
// 20 39:new #43 <Class Handler>
// 21 42:dup
// 22 43:invokestatic #49 <Method Looper Looper.getMainLooper()>
// 23 46:new #51 <Class f>
// 24 49:dup
// 25 50:invokespecial #54 <Method void f()>
// 26 53:invokespecial #57 <Method void Handler(Looper, android.os.Handler$Callback)>
// 27 56:putstatic #59 <Field Handler a>
//* 28 59:return
}
private class Behavior extends SwipeDismissBehavior
{
static void a(Behavior behavior, BaseTransientBottomBar basetransientbottombar)
{
behavior.a(basetransientbottombar);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #23 <Method void a(BaseTransientBottomBar)>
// 3 5:return
}
private void a(BaseTransientBottomBar basetransientbottombar)
{
g.a(basetransientbottombar);
// 0 0:aload_0
// 1 1:getfield #17 <Field p g>
// 2 4:aload_1
// 3 5:invokevirtual #24 <Method void android.support.design.widget.p.a(BaseTransientBottomBar)>
// 4 8:return
}
public boolean a(View view)
{
return g.a(view);
// 0 0:aload_0
// 1 1:getfield #17 <Field p g>
// 2 4:aload_1
// 3 5:invokevirtual #27 <Method boolean android.support.design.widget.p.a(View)>
// 4 8:ireturn
}
public boolean b(CoordinatorLayout coordinatorlayout, View view, MotionEvent motionevent)
{
g.a(coordinatorlayout, view, motionevent);
// 0 0:aload_0
// 1 1:getfield #17 <Field p g>
// 2 4:aload_1
// 3 5:aload_2
// 4 6:aload_3
// 5 7:invokevirtual #32 <Method void android.support.design.widget.p.a(CoordinatorLayout, View, MotionEvent)>
return super.b(coordinatorlayout, view, motionevent);
// 6 10:aload_0
// 7 11:aload_1
// 8 12:aload_2
// 9 13:aload_3
// 10 14:invokespecial #34 <Method boolean SwipeDismissBehavior.b(CoordinatorLayout, View, MotionEvent)>
// 11 17:ireturn
}
private final p g = new p(((SwipeDismissBehavior) (this)));
public Behavior()
{
// 0 0:aload_0
// 1 1:invokespecial #10 <Method void SwipeDismissBehavior()>
// 2 4:aload_0
// 3 5:new #12 <Class p>
// 4 8:dup
// 5 9:aload_0
// 6 10:invokespecial #15 <Method void p(SwipeDismissBehavior)>
// 7 13:putfield #17 <Field p g>
// 8 16:return
}
}
}
|
yinfuquan/file-upload
|
cloud/smthit-fm/smthit-api/src/main/java/com/smthit/framework/api/utils/ServerContext.java
|
<filename>cloud/smthit-fm/smthit-api/src/main/java/com/smthit/framework/api/utils/ServerContext.java
/**
*
*/
package com.smthit.framework.api.utils;
/**
* @author Bean
*
*/
public class ServerContext {
private int port;
private String contextPath;
private String descriptor;
private String resourceBase;
private boolean configurationDiscovered;
private boolean parentLoaderPriority;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public String getDescriptor() {
return descriptor;
}
public void setDescriptor(String descriptor) {
this.descriptor = descriptor;
}
public String getResourceBase() {
return resourceBase;
}
public void setResourceBase(String resourceBase) {
this.resourceBase = resourceBase;
}
public boolean isConfigurationDiscovered() {
return configurationDiscovered;
}
public void setConfigurationDiscovered(boolean configurationDiscovered) {
this.configurationDiscovered = configurationDiscovered;
}
public boolean isParentLoaderPriority() {
return parentLoaderPriority;
}
public void setParentLoaderPriority(boolean parentLoaderPriority) {
this.parentLoaderPriority = parentLoaderPriority;
}
}
|
eZmaxinc/eZmax-SDK-java
|
src/main/java/com/ezmax/api/model/EzsigntemplatepackageGetListV1ResponseMPayload.java
|
<gh_stars>0
/*
* eZmax API Definition
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.3
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.ezmax.api.model;
import java.util.Objects;
import java.util.Arrays;
import com.ezmax.api.model.CommonGetListV1ResponseMPayload;
import com.ezmax.api.model.EzsigntemplatepackageGetListV1ResponseMPayloadAllOf;
import com.ezmax.api.model.EzsigntemplatepackageListElement;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Payload for the /1/object/ezsigntemplatepackage/getList API Request
*/
@ApiModel(description = "Payload for the /1/object/ezsigntemplatepackage/getList API Request")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-12-17T20:11:08.557587Z[Etc/UTC]")
public class EzsigntemplatepackageGetListV1ResponseMPayload {
public static final String SERIALIZED_NAME_A_OBJ_EZSIGNTEMPLATEPACKAGE = "a_objEzsigntemplatepackage";
@SerializedName(SERIALIZED_NAME_A_OBJ_EZSIGNTEMPLATEPACKAGE)
private List<EzsigntemplatepackageListElement> aObjEzsigntemplatepackage = new ArrayList<EzsigntemplatepackageListElement>();
public static final String SERIALIZED_NAME_I_ROW_RETURNED = "iRowReturned";
@SerializedName(SERIALIZED_NAME_I_ROW_RETURNED)
private Integer iRowReturned;
public static final String SERIALIZED_NAME_I_ROW_FILTERED = "iRowFiltered";
@SerializedName(SERIALIZED_NAME_I_ROW_FILTERED)
private Integer iRowFiltered;
public EzsigntemplatepackageGetListV1ResponseMPayload() {
}
public EzsigntemplatepackageGetListV1ResponseMPayload aObjEzsigntemplatepackage(List<EzsigntemplatepackageListElement> aObjEzsigntemplatepackage) {
this.aObjEzsigntemplatepackage = aObjEzsigntemplatepackage;
return this;
}
public EzsigntemplatepackageGetListV1ResponseMPayload addAObjEzsigntemplatepackageItem(EzsigntemplatepackageListElement aObjEzsigntemplatepackageItem) {
this.aObjEzsigntemplatepackage.add(aObjEzsigntemplatepackageItem);
return this;
}
/**
* Get aObjEzsigntemplatepackage
* @return aObjEzsigntemplatepackage
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public List<EzsigntemplatepackageListElement> getaObjEzsigntemplatepackage() {
return aObjEzsigntemplatepackage;
}
public void setaObjEzsigntemplatepackage(List<EzsigntemplatepackageListElement> aObjEzsigntemplatepackage) {
this.aObjEzsigntemplatepackage = aObjEzsigntemplatepackage;
}
public EzsigntemplatepackageGetListV1ResponseMPayload iRowReturned(Integer iRowReturned) {
this.iRowReturned = iRowReturned;
return this;
}
/**
* The number of rows returned
* @return iRowReturned
**/
@javax.annotation.Nonnull
@ApiModelProperty(example = "100", required = true, value = "The number of rows returned")
public Integer getiRowReturned() {
return iRowReturned;
}
public void setiRowReturned(Integer iRowReturned) {
this.iRowReturned = iRowReturned;
}
public EzsigntemplatepackageGetListV1ResponseMPayload iRowFiltered(Integer iRowFiltered) {
this.iRowFiltered = iRowFiltered;
return this;
}
/**
* The number of rows matching your filters (if any) or the total number of rows
* @return iRowFiltered
**/
@javax.annotation.Nonnull
@ApiModelProperty(example = "533", required = true, value = "The number of rows matching your filters (if any) or the total number of rows")
public Integer getiRowFiltered() {
return iRowFiltered;
}
public void setiRowFiltered(Integer iRowFiltered) {
this.iRowFiltered = iRowFiltered;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EzsigntemplatepackageGetListV1ResponseMPayload ezsigntemplatepackageGetListV1ResponseMPayload = (EzsigntemplatepackageGetListV1ResponseMPayload) o;
return Objects.equals(this.aObjEzsigntemplatepackage, ezsigntemplatepackageGetListV1ResponseMPayload.aObjEzsigntemplatepackage) &&
Objects.equals(this.iRowReturned, ezsigntemplatepackageGetListV1ResponseMPayload.iRowReturned) &&
Objects.equals(this.iRowFiltered, ezsigntemplatepackageGetListV1ResponseMPayload.iRowFiltered);
}
@Override
public int hashCode() {
return Objects.hash(aObjEzsigntemplatepackage, iRowReturned, iRowFiltered);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EzsigntemplatepackageGetListV1ResponseMPayload {\n");
sb.append(" aObjEzsigntemplatepackage: ").append(toIndentedString(aObjEzsigntemplatepackage)).append("\n");
sb.append(" iRowReturned: ").append(toIndentedString(iRowReturned)).append("\n");
sb.append(" iRowFiltered: ").append(toIndentedString(iRowFiltered)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
otaviopace/ananas
|
kernel/include/kernel/amd64/dma.h
|
/*-
* SPDX-License-Identifier: Zlib
*
* Copyright (c) 2009-2018 <NAME> <<EMAIL>>
* For conditions of distribution and use, see LICENSE file
*/
#ifndef __ANANAS_AMD64_DMA_H__
#define __ANANAS_AMD64_DMA_H__
typedef uint64_t dma_addr_t;
typedef uint64_t dma_size_t;
#endif /* __ANANAS_AMD64_DMA_H__ */
|
muxanick/scala-native-java-stubs
|
javax/net/ssl/TrustManagerFactorySpi.scala
|
<gh_stars>0
package javax.net.ssl
import java.lang.Object
import java.security.KeyStore
import scala.scalanative.annotation.stub
/** This class defines the Service Provider Interface (SPI)
* for the TrustManagerFactory class.
*
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular trust manager factory.
*/
abstract class TrustManagerFactorySpi extends Object {
/** */
@stub
def this() = ???
/** Returns one trust manager for each type of trust material. */
protected def engineGetTrustManagers(): Array[TrustManager]
/** Initializes this factory with a source of certificate
* authorities and related trust material.
*/
protected def engineInit(ks: KeyStore): Unit
/** Initializes this factory with a source of provider-specific
* key material.
*/
protected def engineInit(spec: ManagerFactoryParameters): Unit
}
|
zealoussnow/chromium
|
chrome/browser/ui/views/frame/browser_frame_view_linux_native.cc
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/browser_frame_view_linux_native.h"
#include "chrome/browser/ui/views/frame/browser_frame_view_layout_linux_native.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/linux_ui/linux_ui.h"
#include "ui/views/window/frame_background.h"
bool BrowserFrameViewLinuxNative::DrawFrameButtonParams::operator==(
const DrawFrameButtonParams& other) const {
return top_area_height == other.top_area_height &&
maximized == other.maximized && active == other.active;
}
BrowserFrameViewLinuxNative::BrowserFrameViewLinuxNative(
BrowserFrame* frame,
BrowserView* browser_view,
BrowserFrameViewLayoutLinux* layout,
std::unique_ptr<views::NavButtonProvider> nav_button_provider,
views::WindowFrameProvider* window_frame_provider)
: BrowserFrameViewLinux(frame, browser_view, layout),
nav_button_provider_(std::move(nav_button_provider)),
window_frame_provider_(window_frame_provider) {}
BrowserFrameViewLinuxNative::~BrowserFrameViewLinuxNative() = default;
float BrowserFrameViewLinuxNative::GetRestoredCornerRadiusDip() const {
return window_frame_provider_->GetTopCornerRadiusDip();
}
void BrowserFrameViewLinuxNative::Layout() {
// Calling MaybeUpdateCachedFrameButtonImages() from Layout() is sufficient to
// catch all cases that could update the appearance, since
// DesktopWindowTreeHostPlatform::On{Window,Activation}StateChanged() does a
// layout any time the maximized and activation state changes, respectively.
MaybeUpdateCachedFrameButtonImages();
OpaqueBrowserFrameView::Layout();
}
BrowserFrameViewLinuxNative::FrameButtonStyle
BrowserFrameViewLinuxNative::GetFrameButtonStyle() const {
return FrameButtonStyle::kImageButton;
}
void BrowserFrameViewLinuxNative::PaintRestoredFrameBorder(
gfx::Canvas* canvas) const {
window_frame_provider_->PaintWindowFrame(
canvas, GetLocalBounds(), GetTopAreaHeight(), ShouldPaintAsActive());
}
void BrowserFrameViewLinuxNative::MaybeUpdateCachedFrameButtonImages() {
DrawFrameButtonParams params{
GetTopAreaHeight() - layout()->FrameEdgeInsets(!IsMaximized()).top(),
IsMaximized(), ShouldPaintAsActive()};
if (cache_ == params)
return;
cache_ = params;
nav_button_provider_->RedrawImages(params.top_area_height, params.maximized,
params.active);
for (auto type : {
views::NavButtonProvider::FrameButtonDisplayType::kMinimize,
IsMaximized()
? views::NavButtonProvider::FrameButtonDisplayType::kRestore
: views::NavButtonProvider::FrameButtonDisplayType::kMaximize,
views::NavButtonProvider::FrameButtonDisplayType::kClose,
}) {
for (size_t state = 0; state < views::Button::STATE_COUNT; state++) {
views::Button::ButtonState button_state =
static_cast<views::Button::ButtonState>(state);
views::Button* button = GetButtonFromDisplayType(type);
DCHECK_EQ(std::string(views::ImageButton::kViewClassName),
button->GetClassName());
static_cast<views::ImageButton*>(button)->SetImage(
button_state, nav_button_provider_->GetImage(type, button_state));
}
}
}
views::Button* BrowserFrameViewLinuxNative::GetButtonFromDisplayType(
views::NavButtonProvider::FrameButtonDisplayType type) {
switch (type) {
case views::NavButtonProvider::FrameButtonDisplayType::kMinimize:
return minimize_button();
case views::NavButtonProvider::FrameButtonDisplayType::kMaximize:
return maximize_button();
case views::NavButtonProvider::FrameButtonDisplayType::kRestore:
return restore_button();
case views::NavButtonProvider::FrameButtonDisplayType::kClose:
return close_button();
default:
NOTREACHED();
return nullptr;
}
}
|
nettee/leetcode
|
solutions/0725.split-linked-list-in-parts/0725.split-linked-list-in-parts.1539592078.cpp
|
/*
* [725] Split Linked List in Parts
*
* https://leetcode.com/problems/split-linked-list-in-parts/description/
*
* algorithms
* Medium (47.26%)
* Total Accepted: 17.8K
* Total Submissions: 37.7K
* Testcase Example: '[1,2,3,4]\n5'
*
* Given a (singly) linked list with head node root, write a function to split
* the linked list into k consecutive linked list "parts".
*
* The length of each part should be as equal as possible: no two parts should
* have a size differing by more than 1. This may lead to some parts being
* null.
*
* The parts should be in order of occurrence in the input list, and parts
* occurring earlier should always have a size greater than or equal parts
*
* Return a List of ListNode's representing the linked list parts that are
* formed.
*
*
* Examples
* 1->2->3->4, k = 5 // 5 equal parts
* [ [1],
* [2],
* [3],
* [4],
* null ]
*
* Example 1:
*
* Input:
* root = [1, 2, 3], k = 5
* Output: [[1],[2],[3],[],[]]
* Explanation:
* The input and each element of the output are ListNodes, not arrays.
* For example, the input root has root.val = 1, root.next.val = 2,
* \root.next.next.val = 3, and root.next.next.next = null.
* The first element output[0] has output[0].val = 1, output[0].next = null.
* The last element output[4] is null, but it's string representation as a
* ListNode is [].
*
*
*
* Example 2:
*
* Input:
* root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
* Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
* Explanation:
* The input has been split into consecutive parts with size difference at most
* 1, and earlier parts are a larger size than the later parts.
*
*
*
* Note:
* The length of root will be in the range [0, 1000].
* Each value of a node in the input will be an integer in the range [0, 999].
* k will be an integer in the range [1, 50].
*
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* root, int k) {
int len = length(root);
vector<int> sizes(k + 1, len / k);
sizes[0] = 0;
for (int i = 0; i < len % k; i++) {
sizes[i+1]++;
}
for (int i = 0; i < k; i++) {
sizes[i+1] += sizes[i];
}
unordered_set<int> indices(sizes.begin(), sizes.end());
vector<ListNode*> res;
ListNode* prev = NULL;
ListNode* p = root;
int j = 0;
while (p != NULL) {
if (indices.find(j) != indices.end()) {
res.push_back(p);
if (prev != NULL) {
prev->next = NULL;
}
}
prev = p;
p = p->next;
j++;
}
while (res.size() < k) {
res.push_back(NULL);
}
return res;
}
private:
int length(ListNode* head) {
int count = 0;
for (ListNode* q = head; q != NULL; q = q->next) {
count++;
}
return count;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.