repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
pchrapka/brain-modelling | external/fieldtrip-20160128/peer/src/smartmem.c | /*
* Copyright (C) 2010, <NAME>
*
* 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 3 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. If not, see <http://www.gnu.org/licenses/
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "peer.h"
#include "extern.h"
#include "platform_includes.h"
/* return value 0 if ok, -1 if error or unsupported platform */
int smartmem_info(UINT64_T *MemTotal, UINT64_T *MemFree, UINT64_T *Buffers, UINT64_T *Cached) {
void *fp;
char str[256];
*MemTotal = UINT32_MAX;
*MemFree = 0;
*Buffers = 0;
*Cached = 0;
#if defined (PLATFORM_LINUX)
/* get the memory information from /proc/meminfo
*
* MemTotal: 32949684 kB
* MemFree: 4200556 kB
* Buffers: 73612 kB
* Cached: 26112456 kB
* SwapCached: 104324 kB
* Active: 10769324 kB
* Inactive: 17096716 kB
* HighTotal: 0 kB
* HighFree: 0 kB
* LowTotal: 32949684 kB
* LowFree: 4200556 kB
* SwapTotal: 62857388 kB
* SwapFree: 62701340 kB
* Dirty: 3110792 kB
* Writeback: 0 kB
* AnonPages: 1677744 kB
* Mapped: 101508 kB
* Slab: 788800 kB
* PageTables: 26740 kB
* NFS_Unstable: 0 kB
* Bounce: 0 kB
* CommitLimit: 79332228 kB
* Committed_AS: 2660040 kB
* VmallocTotal: 34359738367 kB
* VmallocUsed: 293732 kB
* VmallocChunk: 34359443995 kB
* HugePages_Total: 0
* HugePages_Free: 0
* HugePages_Rsvd: 0
* Hugepagesize: 2048 kB
*/
if ((fp = fopen("/proc/meminfo", "r")) == NULL) {
DEBUG(LOG_ERR, "smartmem_info: could not open /proc/meminfo");
return -1;
}
while (fscanf(fp, "%s", str) != EOF) {
if (strcmp(str, "MemTotal:")==0)
fscanf(fp, "%llu", MemTotal);
if (strcmp(str, "MemFree:")==0)
fscanf(fp, "%llu", MemFree);
if (strcmp(str, "Buffers:")==0)
fscanf(fp, "%llu", Buffers);
if (strcmp(str, "Cached:")==0)
fscanf(fp, "%llu", Cached);
} /* while */
fclose(fp);
/* convert from kB into bytes */
(*MemTotal) *= 1024;
(*MemFree) *= 1024;
(*Buffers) *= 1024;
(*Cached) *= 1024;
return 0;
#else
return -1;
#endif
} /* smartmem_info */
/* return value 0 if ok, -1 if error or unsupported platform */
int smartmem_update(void) {
peerlist_t* peer;
unsigned int NumPeers=0;
UINT64_T MemSuggested=0, MemReserved=0;
UINT64_T MemTotal=0, MemFree=0, Buffers=0, Cached=0;
float scale;
int ok;
pthread_mutex_lock(&mutexsmartmem);
if (!smartmem.enabled || smartmem.freeze) {
/* don't update if smartmem is disabled */
/* the freeze flag is enabled during the processing of an incoming job in tcpsocket */
pthread_mutex_unlock(&mutexsmartmem);
return 0;
}
pthread_mutex_lock(&mutexhost);
if (host->status!=STATUS_IDLE) {
/* don't update if the status is something else than IDLE */
pthread_mutex_unlock(&mutexhost);
pthread_mutex_unlock(&mutexsmartmem);
return 0;
}
/* determine the amount of memory available on this computer */
if (smartmem_info(&MemTotal, &MemFree, &Buffers, &Cached) < 0) {
pthread_mutex_unlock(&mutexhost);
pthread_mutex_unlock(&mutexsmartmem);
return -1;
}
DEBUG(LOG_INFO, "smartmem: host->memavail = %llu", host->memavail);
DEBUG(LOG_DEBUG, "smartmem: MemTotal = %llu (%f GB)", MemTotal , ((float)MemTotal )/(1024*1024*1024));
DEBUG(LOG_DEBUG, "smartmem: MemFree = %llu (%f GB)", MemFree , ((float)MemFree )/(1024*1024*1024));
DEBUG(LOG_DEBUG, "smartmem: Buffers = %llu (%f GB)", Buffers , ((float)Buffers )/(1024*1024*1024));
DEBUG(LOG_DEBUG, "smartmem: Cached = %llu (%f GB)", Cached , ((float)Cached )/(1024*1024*1024));
pthread_mutex_lock(&mutexpeerlist);
/* determine the amount of memory that is reserved by the idle slaves on this computer */
peer = peerlist;
while(peer) {
ok = 1;
ok = ok && (strcmp(peer->ipaddr, "127.0.0.1")==0);
ok = ok && (peer->host->id != host->id);
ok = ok && (peer->host->status == STATUS_IDLE);
if (ok) {
MemReserved += peer->host->memavail;
NumPeers++;
}
peer = peer->next ;
}
pthread_mutex_unlock(&mutexpeerlist);
/* include this peer in the count */
NumPeers++;
/* the Buffers and Cached memory are also available to the system */
MemFree += Buffers;
MemFree += Cached;
/* determine the scale of the memory update (for iterative improvements) */
scale = ((float)host->memavail) / ((float)MemFree);
/* apply a heuristic adjustment to improve total memory usage (in case of few peers) and to speed up convergence (in case of many peers) */
switch (NumPeers)
{
case 1:
scale = 0.01 * scale;
break;
case 2:
scale = 0.1 * scale;
break;
case 3:
scale = 0.3 * scale;
break;
case 4:
scale = 0.5 * scale;
break;
default:
scale = 1.0 * scale;
break;
} /* switch */
/* the reserved memory by the other idle slaves should not be more than the available memory */
MemReserved = (MemReserved > MemFree ? MemFree : MemReserved );
/* determine the suggested amount of memory for this slave */
/* this asymptotically approaches the free memory */
MemSuggested = ((float)(MemFree - MemReserved)) / (1.0 + scale);
/* it does not make sense to suggest less than a certain minimum amount */
MemSuggested = (MemSuggested > SMARTMEM_MINIMUM ? MemSuggested : SMARTMEM_MINIMUM );
/* don't exceed the user-specified maximum allowed amount */
MemSuggested = (MemSuggested < smartmem.memavail ? MemSuggested : smartmem.memavail );
DEBUG(LOG_DEBUG, "smartmem: NumPeers = %u", NumPeers);
DEBUG(LOG_DEBUG, "smartmem: MemReserved = %llu (%f GB)", MemReserved , ((float)MemReserved )/(1024*1024*1024));
DEBUG(LOG_DEBUG, "smartmem: MemSuggested = %llu (%f GB)", MemSuggested, ((float)MemSuggested)/(1024*1024*1024));
host->memavail = MemSuggested;
pthread_mutex_unlock(&mutexhost);
pthread_mutex_unlock(&mutexsmartmem);
return 0;
} /* smartmem_update */
|
vcooley/fcc-bookclub | models/Trade.js | <filename>models/Trade.js<gh_stars>0
const bookshelf = require('../config/bookshelf');
require('./User');
require('./Book');
const Trade = bookshelf.Model.extend({
tableName: 'trades',
requester() {
return this.belongsTo('User', 'requester');
},
requestee() {
return this.belongsTo('User', 'requestee');
},
requester_book() {
return this.belongsTo('Book', 'requester_book');
},
requestee_book() {
return this.belongsTo('Book', 'requestee_book');
},
});
module.exports = bookshelf.model('Trade', Trade);
|
quantmind/lux | lux/utils/crypt/__init__.py | <gh_stars>10-100
from os import urandom
import uuid
import string
from random import randint
from hashlib import sha1
from pulsar.utils.string import random_string
digits_letters = string.digits + string.ascii_letters
secret_choices = digits_letters + ''.join(
(p for p in string.punctuation if p != '"')
)
def generate_secret(length=64, allowed_chars=None, hexadecimal=False):
if hexadecimal:
return ''.join((hex(randint(1, 10000)) for _ in range(length)))
return random_string(length, length, allowed_chars or secret_choices)
def digest(value, salt_size=8):
salt = urandom(salt_size)
return sha1(salt+value.encode('utf-8')).hexdigest()
def create_uuid(id=None):
if isinstance(id, uuid.UUID):
return id
return uuid.uuid4()
def create_token():
return create_uuid().hex
def as_hex(value):
if isinstance(value, uuid.UUID):
return value.hex
return value
|
kinarashah/types | apis/authorization.cattle.io/v1/zz_generated_deepcopy.go | <gh_stars>0
package v1
import (
rbac_v1 "k8s.io/api/rbac/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterRoleTemplate) DeepCopyInto(out *ClusterRoleTemplate) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
if in.Rules != nil {
in, out := &in.Rules, &out.Rules
*out = make([]rbac_v1.PolicyRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.ClusterRoleTemplateNames != nil {
in, out := &in.ClusterRoleTemplateNames, &out.ClusterRoleTemplateNames
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterRoleTemplate.
func (in *ClusterRoleTemplate) DeepCopy() *ClusterRoleTemplate {
if in == nil {
return nil
}
out := new(ClusterRoleTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ClusterRoleTemplate) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterRoleTemplateBinding) DeepCopyInto(out *ClusterRoleTemplateBinding) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Subject = in.Subject
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterRoleTemplateBinding.
func (in *ClusterRoleTemplateBinding) DeepCopy() *ClusterRoleTemplateBinding {
if in == nil {
return nil
}
out := new(ClusterRoleTemplateBinding)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ClusterRoleTemplateBinding) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterRoleTemplateBindingList) DeepCopyInto(out *ClusterRoleTemplateBindingList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ClusterRoleTemplateBinding, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterRoleTemplateBindingList.
func (in *ClusterRoleTemplateBindingList) DeepCopy() *ClusterRoleTemplateBindingList {
if in == nil {
return nil
}
out := new(ClusterRoleTemplateBindingList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ClusterRoleTemplateBindingList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterRoleTemplateList) DeepCopyInto(out *ClusterRoleTemplateList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ClusterRoleTemplate, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterRoleTemplateList.
func (in *ClusterRoleTemplateList) DeepCopy() *ClusterRoleTemplateList {
if in == nil {
return nil
}
out := new(ClusterRoleTemplateList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ClusterRoleTemplateList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PodSecurityPolicyTemplate) DeepCopyInto(out *PodSecurityPolicyTemplate) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodSecurityPolicyTemplate.
func (in *PodSecurityPolicyTemplate) DeepCopy() *PodSecurityPolicyTemplate {
if in == nil {
return nil
}
out := new(PodSecurityPolicyTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PodSecurityPolicyTemplate) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PodSecurityPolicyTemplateList) DeepCopyInto(out *PodSecurityPolicyTemplateList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PodSecurityPolicyTemplate, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodSecurityPolicyTemplateList.
func (in *PodSecurityPolicyTemplateList) DeepCopy() *PodSecurityPolicyTemplateList {
if in == nil {
return nil
}
out := new(PodSecurityPolicyTemplateList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PodSecurityPolicyTemplateList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Project) DeepCopyInto(out *Project) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Project.
func (in *Project) DeepCopy() *Project {
if in == nil {
return nil
}
out := new(Project)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Project) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProjectList) DeepCopyInto(out *ProjectList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Project, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectList.
func (in *ProjectList) DeepCopy() *ProjectList {
if in == nil {
return nil
}
out := new(ProjectList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProjectList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProjectRoleTemplate) DeepCopyInto(out *ProjectRoleTemplate) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
if in.Rules != nil {
in, out := &in.Rules, &out.Rules
*out = make([]rbac_v1.PolicyRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.ProjectRoleTemplateNames != nil {
in, out := &in.ProjectRoleTemplateNames, &out.ProjectRoleTemplateNames
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectRoleTemplate.
func (in *ProjectRoleTemplate) DeepCopy() *ProjectRoleTemplate {
if in == nil {
return nil
}
out := new(ProjectRoleTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProjectRoleTemplate) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProjectRoleTemplateBinding) DeepCopyInto(out *ProjectRoleTemplateBinding) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Subject = in.Subject
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectRoleTemplateBinding.
func (in *ProjectRoleTemplateBinding) DeepCopy() *ProjectRoleTemplateBinding {
if in == nil {
return nil
}
out := new(ProjectRoleTemplateBinding)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProjectRoleTemplateBinding) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProjectRoleTemplateBindingList) DeepCopyInto(out *ProjectRoleTemplateBindingList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ProjectRoleTemplateBinding, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectRoleTemplateBindingList.
func (in *ProjectRoleTemplateBindingList) DeepCopy() *ProjectRoleTemplateBindingList {
if in == nil {
return nil
}
out := new(ProjectRoleTemplateBindingList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProjectRoleTemplateBindingList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProjectRoleTemplateList) DeepCopyInto(out *ProjectRoleTemplateList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ProjectRoleTemplate, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectRoleTemplateList.
func (in *ProjectRoleTemplateList) DeepCopy() *ProjectRoleTemplateList {
if in == nil {
return nil
}
out := new(ProjectRoleTemplateList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProjectRoleTemplateList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProjectSpec) DeepCopyInto(out *ProjectSpec) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectSpec.
func (in *ProjectSpec) DeepCopy() *ProjectSpec {
if in == nil {
return nil
}
out := new(ProjectSpec)
in.DeepCopyInto(out)
return out
}
|
adambennett/JustCode | src/main/java/com/zipcode/justcode/clamfortress/ClamFortress/models/game/encounters/miracles/ClericBlessing.java | package com.zipcode.justcode.clamfortress.ClamFortress.models.game.encounters.miracles;
public class ClericBlessing extends AbstractMiracle {
public ClericBlessing(int turns) {
super("Cleric Blessing", "", turns);
}
@Override
public String toString() {
return "Miracle: Blessing";
}
@Override
public ClericBlessing clone() {
return new ClericBlessing(this.turnsActive);
}
}
|
quantumsheep/mickye | server/src/handlers/tcp.c | <gh_stars>1-10
#include "tcp.h"
GuiEnv *env = NULL;
TcpClientChain *clients = NULL;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int server_socket;
/**
* Get a client from its socket (named as id here)
*
* @param id the client's id/socket
*/
TcpClient *
tcp_get_client(int id)
{
TcpClientChain *client = clients;
/**
* Select the right client
*/
while (client != NULL && client->client->socket != id)
{
client = client->next;
}
if (client == NULL)
{
return NULL;
}
else
{
return client->client;
}
}
/**
* Destroy a socket
*
* @param socket the socket
*/
void
tcp_annihilate_socket(int socket)
{
shutdown(socket, SHUT_RDWR);
close(socket);
}
/**
* Create a client object and add it to the clients list
*
* @param socket the socket
* @param storage the TCP server's socket address informations
*/
void
tcp_create_connection(int socket, struct sockaddr_storage *storage)
{
TcpClient *client;
struct sockaddr_in *ipv4;
struct sockaddr_in6 *ipv6;
/**
* Construct the client's structure
*/
client = (TcpClient *)malloc(sizeof(TcpClient));
client->socket = socket;
ipv4 = (struct sockaddr_in *)storage;
ipv6 = (struct sockaddr_in6 *)storage;
memset(client->ipv4, 0x00, INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(ipv4->sin_addr), client->ipv4, INET_ADDRSTRLEN);
memset(client->ipv6, 0x00, INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(ipv6->sin6_addr), client->ipv6, INET6_ADDRSTRLEN);
/**
* Add a client to the global clients
*/
TcpClientChain *new = (TcpClientChain *)malloc(sizeof(TcpClientChain));
new->client = client;
new->next = clients;
clients = new;
/**
* Add the client in the clients list
*/
client_add(env->store, client, CLIENT_CONNECTED);
}
/**
* Create a client object and add it to the clients list
*
* @param socket the socket
* @param sockaddr_in the TCP server's socket address (IPv4)
*/
int
tcp_bind(int socket, struct sockaddr_in *addr)
{
int val = 1;
setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val));
return bind(socket, (struct sockaddr *)addr, sizeof(*addr));
}
/**
* Initialize the TCP server
*/
void *
tcp_init()
{
TcpClientChain *client;
/**
* Server informations
*/
struct sockaddr_in addr;
struct sockaddr_storage storage;
socklen_t storage_size;
/**
* Client socket file descriptors
*/
int client_socket = 0;
// Create the socket.
server_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
/**
* Configure server settings
*
* sin_family is Internet
* sin_port use htons to use the proper byte order
* sin_addr is the IP address (127.0.0.1 for localhost)
*/
addr.sin_family = AF_INET;
addr.sin_port = htons(TCP_SERVER_PORT);
addr.sin_addr.s_addr = inet_addr(TCP_SERVER_HOST);
// Set all bits of the padding field to 0
memset(addr.sin_zero, 0x00, sizeof(addr.sin_zero));
// Bind the address struct to the socket
tcp_bind(server_socket, &addr);
// Listen on the socket, with 64 max connection requests queued
listen(server_socket, 64);
/**
* Listening loop
*/
while (1)
{
storage_size = sizeof storage;
client_socket = accept(server_socket, (struct sockaddr *)&storage, &storage_size);
if (client_socket == -1)
{
break;
}
tcp_create_connection(client_socket, &storage);
}
/**
* Annhilating the sockets
*/
tcp_annihilate_socket(server_socket);
client = clients;
while (client != NULL)
{
tcp_annihilate_socket(client->client->socket);
client = client->next;
}
pthread_exit(NULL);
}
/**
* Event handler that starts the TCP server
*/
void
start_server(GtkWidget *widget, GtkBuilder *builder, GuiEnv *data)
{
pthread_t server_thread;
GObject *stopButton;
if (env == NULL)
{
env = data;
}
gtk_widget_set_sensitive(widget, 0);
stopButton = gtk_builder_get_object(builder, "stop");
gtk_widget_set_sensitive(GTK_WIDGET(stopButton), 1);
pthread_create(&server_thread, NULL, tcp_init, NULL);
log_add(data->text_view, "Started", "Server");
}
/**
* Destroy the TCP server (in a brutal way but hey.. whatever)
*/
void
tcp_stop()
{
tcp_annihilate_socket(server_socket);
}
/**
* Event handler that stops the TCP server
*/
void
stop_server(GtkWidget *widget, GtkBuilder *builder, GuiEnv *data)
{
GObject *startButton;
GtkTreeIter iter;
GtkTreeModel *model;
GtkTreeView *client_tree;
gtk_widget_set_sensitive(widget, 0);
startButton = gtk_builder_get_object(builder, "start");
gtk_widget_set_sensitive(GTK_WIDGET(startButton), 1);
tcp_stop();
log_add(data->text_view, "Stopped", "Server");
log_add(data->text_view, "Removing", "Clients");
// Initialize the client_tree and the model from data
client_tree = GTK_TREE_VIEW(data->client_tree);
model = gtk_tree_view_get_model(client_tree);
// Removes all the clients
while (gtk_tree_model_get_iter_first(model, &iter))
{
gtk_list_store_remove((GtkListStore *)data->store, &iter);
};
log_add(data->text_view, "Clients succesfully", "Removed");
}
|
uk-gov-mirror/hmrc.view-external-guidance-frontend | app/services/SecuredProcessBuilder.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* 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 services
import javax.inject.{Inject, Singleton}
import play.api.i18n.{Lang, MessagesApi}
import core.models.ocelot.{Process, SecuredProcess, Phrase}
import core.models.ocelot.stanzas.{Txt, Equals, Stanza, PageStanza, InputStanza, ChoiceStanza, ChoiceStanzaTest}
@Singleton
class SecuredProcessBuilder @Inject()(messagesApi: MessagesApi) {
lazy val enPassPhrasePrompt: String = messagesApi("passphrase.prompt")(Lang("en"))
lazy val cyPassPhrasePrompt: String = messagesApi("passphrase.prompt")(Lang("cy"))
def secureIfRequired(process: Process): Process =
process.meta.passPhrase.fold(process){passPhrase =>
process.copy(flow = process.flow ++ stanzas(process.phrases.length, passPhrase),
phrases =process.phrases ++ Vector(Phrase(enPassPhrasePrompt, cyPassPhrasePrompt)))
}
import SecuredProcess._
private def stanzas(nextFreePhraseIdx: Int, passPhrase: String): Seq[(String, Stanza)] = Seq(
(PassPhrasePageId, PageStanza(s"/${SecuredProcessStartUrl}", Seq(InputId), false)),
(InputId, InputStanza(Txt,
Seq(ChoiceId),
nextFreePhraseIdx,
None,
PassPhraseResponseLabelName,
None,
false)),
(ChoiceId, ChoiceStanza(
Seq(Process.StartStanzaId, InputId),
Seq(ChoiceStanzaTest(s"[label:${PassPhraseResponseLabelName}]", Equals, passPhrase)), false))
)
}
|
FelixMarin/searchitemsapp-spring-boot-version | src/main/java/com/searchitemsapp/dto/CategoryDto.java | <gh_stars>1-10
package com.searchitemsapp.dto;
import org.springframework.stereotype.Component;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor
@Builder
@Component
public class CategoryDto {
private Long did;
private Boolean bolActivo;
private String desCatEmpresa;
private String nomCatEmpresa;
private CompanyDto empresas;
private BrandsDto marcas;
private LiveSearchDto productos;
}
|
ethmobile/ethdroid | ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/ContractType.java | <gh_stars>10-100
package io.ethmobile.ethdroid.solidity;
/**
* Created by gunicolas on 30/08/16.
*/
public interface ContractType {
}
|
paulahemsi/minishell | sources/hashmap/hashmap_create_table.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* hashmap_create_table.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lcouto <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/07 00:48:28 by user42 #+# #+# */
/* Updated: 2021/07/11 17:07:25 by lcouto ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
t_hashmap *hashmap_create_table(unsigned int size)
{
t_hashmap *new_table;
unsigned int i;
i = 0;
new_table = (t_hashmap *)ft_calloc(sizeof(t_hashmap), 1);
new_table->size = size;
new_table->count = 0;
new_table->pairs = (t_pair **)ft_calloc(sizeof(t_hashmap), size);
while (i < size)
{
new_table->pairs[i] = NULL;
i++;
}
return (new_table);
}
|
houpainansheng/PandaTV | app/src/main/java/com/qianf/ly/pandatv/bean/AllVideoDataBean.java | <reponame>houpainansheng/PandaTV
package com.qianf.ly.pandatv.bean;
/**
* Created by 樊康 on 2017/3/29.
*/
public class AllVideoDataBean {
private AllVideoListBean data;
public AllVideoListBean getData() {
return data;
}
public void setData(AllVideoListBean data) {
this.data = data;
}
}
|
Surya-98/Snapcuit | NGSpice/ngspice-30/src/frontend/com_state.c | #include "ngspice/ngspice.h"
#include "ngspice/bool.h"
#include "ngspice/wordlist.h"
#include "ngspice/ftedefs.h"
#include "ngspice/inpdefs.h"
#include "circuits.h"
#include "com_state.h"
#include "ngspice/cpextern.h"
#include "plotting/plotting.h"
void
com_state(wordlist *wl)
{
NG_IGNORE(wl);
if (!ft_curckt) {
fprintf(cp_err, "Error: no circuit loaded.\n");
return;
}
fprintf(cp_out, "Current circuit: %s\n", ft_curckt->ci_name);
if (!ft_curckt->ci_inprogress) {
fprintf(cp_out, "No run in progress.\n");
return;
}
fprintf(cp_out, "Type of run: %s\n", plot_cur->pl_name);
fprintf(cp_out, "Number of points so far: %d\n",
plot_cur->pl_scale->v_length);
fprintf(cp_out, "(That's all this command does so far)\n");
}
|
karreiro/drools-wb | drools-wb-services/drools-wb-verifier/drools-wb-verifier-core/src/main/java/org/drools/workbench/services/verifier/core/cache/inspectors/FieldInspector.java | <reponame>karreiro/drools-wb<filename>drools-wb-services/drools-wb-verifier/drools-wb-verifier-core/src/main/java/org/drools/workbench/services/verifier/core/cache/inspectors/FieldInspector.java
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.drools.workbench.services.verifier.core.cache.inspectors;
import java.util.Collection;
import org.drools.workbench.services.verifier.api.client.configuration.AnalyzerConfiguration;
import org.drools.workbench.services.verifier.api.client.index.Action;
import org.drools.workbench.services.verifier.api.client.index.Condition;
import org.drools.workbench.services.verifier.api.client.index.Field;
import org.drools.workbench.services.verifier.api.client.index.ObjectField;
import org.drools.workbench.services.verifier.api.client.index.keys.Key;
import org.drools.workbench.services.verifier.api.client.index.keys.UUIDKey;
import org.drools.workbench.services.verifier.api.client.index.select.AllListener;
import org.drools.workbench.services.verifier.api.client.maps.InspectorList;
import org.drools.workbench.services.verifier.api.client.maps.UpdatableInspectorList;
import org.drools.workbench.services.verifier.api.client.maps.util.HasConflicts;
import org.drools.workbench.services.verifier.api.client.maps.util.HasKeys;
import org.drools.workbench.services.verifier.api.client.relations.Conflict;
import org.drools.workbench.services.verifier.api.client.relations.HumanReadable;
import org.drools.workbench.services.verifier.api.client.relations.IsConflicting;
import org.drools.workbench.services.verifier.api.client.relations.IsRedundant;
import org.drools.workbench.services.verifier.api.client.relations.IsSubsuming;
import org.drools.workbench.services.verifier.core.cache.inspectors.action.ActionInspector;
import org.drools.workbench.services.verifier.core.cache.inspectors.action.ActionInspectorFactory;
import org.drools.workbench.services.verifier.core.cache.inspectors.condition.ConditionInspector;
import org.drools.workbench.services.verifier.core.cache.inspectors.condition.ConditionInspectorFactory;
import org.kie.soup.commons.validation.PortablePreconditions;
public class FieldInspector
implements HasConflicts,
IsConflicting,
IsSubsuming,
IsRedundant,
HumanReadable,
HasKeys {
private final ObjectField objectField;
private final UpdatableInspectorList<ActionInspector, Action> actionInspectorList;
private final UpdatableInspectorList<ConditionInspector, Condition> conditionInspectorList;
private final UUIDKey uuidKey;
private final RuleInspectorUpdater ruleInspectorUpdater;
public FieldInspector(final Field field,
final RuleInspectorUpdater ruleInspectorUpdater,
final AnalyzerConfiguration configuration) {
this(field.getObjectField(),
ruleInspectorUpdater,
configuration);
configuration.getUUID(this);
updateActionInspectors(field.getActions()
.where(Action.value()
.any())
.select()
.all());
updateConditionInspectors(field.getConditions()
.where(Condition.value()
.any())
.select()
.all());
setupActionsListener(field);
setupConditionsListener(field);
}
public FieldInspector(final ObjectField field,
final RuleInspectorUpdater ruleInspectorUpdater,
final AnalyzerConfiguration configuration) {
this.objectField = PortablePreconditions.checkNotNull("field",
field);
this.ruleInspectorUpdater = PortablePreconditions.checkNotNull("ruleInspectorUpdater",
ruleInspectorUpdater);
uuidKey = configuration.getUUID(this);
actionInspectorList = new UpdatableInspectorList<>(new ActionInspectorFactory(configuration),
configuration);
conditionInspectorList = new UpdatableInspectorList<>(new ConditionInspectorFactory(configuration),
configuration);
}
private void setupConditionsListener(final Field field) {
field.getConditions()
.where(Condition.value()
.any())
.listen()
.all(new AllListener<Condition>() {
@Override
public void onAllChanged(final Collection<Condition> all) {
updateConditionInspectors(all);
ruleInspectorUpdater.resetConditionsInspectors();
}
});
}
private void setupActionsListener(final Field field) {
field.getActions()
.where(Action.value()
.any())
.listen()
.all(new AllListener<Action>() {
@Override
public void onAllChanged(final Collection<Action> all) {
updateActionInspectors(all);
ruleInspectorUpdater.resetActionsInspectors();
}
});
}
public ObjectField getObjectField() {
return objectField;
}
private void updateConditionInspectors(final Collection<Condition> all) {
conditionInspectorList.update(all);
}
private void updateActionInspectors(final Collection<Action> all) {
actionInspectorList.update(all);
}
public InspectorList<ActionInspector> getActionInspectorList() {
return actionInspectorList;
}
public InspectorList<ConditionInspector> getConditionInspectorList() {
return conditionInspectorList;
}
@Override
public Conflict hasConflicts() {
int index = 1;
for (final ConditionInspector conditionInspector : conditionInspectorList) {
for (int j = index; j < conditionInspectorList.size(); j++) {
if (conditionInspector.conflicts(conditionInspectorList.get(j))) {
return new Conflict(conditionInspector,
conditionInspectorList.get(j));
}
}
index++;
}
return Conflict.EMPTY;
}
@Override
public boolean conflicts(final Object other) {
if (other instanceof FieldInspector && objectField.equals(((FieldInspector) other).objectField)) {
final boolean conflicting = actionInspectorList.conflicts(((FieldInspector) other).actionInspectorList);
if (conflicting) {
return true;
} else {
return conditionInspectorList.conflicts(((FieldInspector) other).conditionInspectorList);
}
} else {
return false;
}
}
@Override
public boolean isRedundant(final Object other) {
if (other instanceof FieldInspector && objectField.equals(((FieldInspector) other).objectField)) {
return actionInspectorList.isRedundant(((FieldInspector) other).actionInspectorList)
&& conditionInspectorList.isRedundant(((FieldInspector) other).conditionInspectorList);
} else {
return false;
}
}
@Override
public boolean subsumes(final Object other) {
if (other instanceof FieldInspector && objectField.equals(((FieldInspector) other).objectField)) {
return actionInspectorList.subsumes(((FieldInspector) other).actionInspectorList)
&& conditionInspectorList.subsumes(((FieldInspector) other).conditionInspectorList);
} else {
return false;
}
}
@Override
public String toHumanReadableString() {
return objectField.getName();
}
@Override
public UUIDKey getUuidKey() {
return uuidKey;
}
@Override
public Key[] keys() {
return new Key[]{
uuidKey
};
}
}
|
ilyayunkin/StocksMonitor | src/WidgetsUi/PopUp/PopUpWindow.h | <gh_stars>0
#ifndef POPUPWINDOW_H
#define POPUPWINDOW_H
#include <QWidget>
#include "AbstractPopUpWindow.h"
class PopUpWindow final : public QWidget, public AbstractPopUpWindow
{
Q_OBJECT
public:
static void showPopUpWindow(const QString &text, int timeMs = 10000);
int width()const override{return QWidget::width();}
int height()const override{return QWidget::height();}
int x()const override{return QWidget::x();}
int y()const override{return QWidget::y();}
void setGeometry(int x, int y, int w, int h) override{QWidget::setGeometry(x, y, w, h);}
private:
explicit PopUpWindow(const QString &text, int timeMs = 10000);
~PopUpWindow();
void mousePressEvent(QMouseEvent *event);
};
#endif // POPUPWINDOW_H
|
tsutterley/model-harmonics | SMB/era5_smb_cumulative.py | #!/usr/bin/env python
u"""
era5_smb_cumulative.py
Written by <NAME> (10/2021)
Reads ERA5 datafiles to calculate monthly cumulative anomalies
in derived surface mass balance products
ERA5 conversion table for accumulated variables
https://confluence.ecmwf.int/pages/viewpage.action?pageId=197702790
COMMAND LINE OPTIONS:
-D X, --directory X: working data directory
-m X, --mean X: Year range for mean
-F X, --format X: input and output data format
ascii
netcdf
HDF5
-M X, --mode X: Permission mode of directories and files
-V, --verbose: Output information for each output file
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python
https://numpy.org
https://numpy.org/doc/stable/user/numpy-for-matlab-users.html
dateutil: powerful extensions to datetime
https://dateutil.readthedocs.io/en/stable/
netCDF4: Python interface to the netCDF C library
https://unidata.github.io/netcdf4-python/netCDF4/index.html
h5py: Python interface for Hierarchal Data Format 5 (HDF5)
https://h5py.org
PROGRAM DEPENDENCIES:
spatial.py: spatial data class for reading, writing and processing data
ncdf_read.py: reads input spatial data from netCDF4 files
hdf5_read.py: reads input spatial data from HDF5 files
ncdf_write.py: writes output spatial data to netCDF4
hdf5_write.py: writes output spatial data to HDF5
time.py: utilities for calculating time operations
UPDATE HISTORY:
Written 10/2021
"""
from __future__ import print_function
import sys
import os
import re
import logging
import netCDF4
import argparse
import numpy as np
import gravity_toolkit.time
import gravity_toolkit.spatial
#-- PURPOSE: read variables from ERA5 P-E files
def read_era5_variables(era5_flux_file):
#-- python dictionary of output variables
dinput = {}
#-- read each variable of interest in ERA5 flux file
with netCDF4.Dataset(era5_flux_file, 'r') as fileID:
#-- extract geolocation variables
dinput['latitude'] = fileID.variables['latitude'][:].copy()
dinput['longitude'] = fileID.variables['longitude'][:].copy()
#-- convert time from netCDF4 units to Julian Days
date_string = fileID.variables['time'].units
epoch,to_secs = gravity_toolkit.time.parse_date_string(date_string)
dinput['time'] = gravity_toolkit.time.convert_delta_time(
to_secs*fileID.variables['time'][:],epoch1=epoch,
epoch2=(1858,11,17,0,0,0), scale=1.0/86400.0) + 2400000.5
#-- read each variable of interest in ERA5 flux file
for key in ['tp','e']:
#-- Getting the data from each NetCDF variable of interest
#-- check dimensions for expver slice
if (fileID.variables[key].ndim == 4):
dinput[key] = ncdf_expver(fileID, key)
else:
dinput[key] = np.ma.array(fileID.variables[key][:].squeeze(),
fill_value=fileID.variables[key]._FillValue)
dinput[key].mask = (dinput[key].data == dinput[key].fill_value)
#-- return the output variables
return dinput
#-- PURPOSE: extract variable from a 4d netCDF4 dataset
#-- ERA5 expver dimension (denotes mix of ERA5 and ERA5T)
def ncdf_expver(fileID, VARNAME):
ntime,nexp,nlat,nlon = fileID.variables[VARNAME].shape
fill_value = fileID.variables[VARNAME]._FillValue
#-- reduced output
output = np.ma.zeros((ntime,nlat,nlon))
output.fill_value = fill_value
for t in range(ntime):
#-- iterate over expver slices to find valid outputs
for j in range(nexp):
#-- check if any are valid for expver
if np.any(fileID.variables[VARNAME][t,j,:,:]):
output[t,:,:] = fileID.variables[VARNAME][t,j,:,:]
#-- update mask variable
output.mask = (output.data == output.fill_value)
#-- return the reduced output variable
return output
#-- PURPOSE: read monthly ERA5 datasets to calculate cumulative anomalies
def era5_smb_cumulative(DIRECTORY,
RANGE=None,
DATAFORM=None,
VERBOSE=False,
MODE=0o775):
#-- create logger for verbosity level
loglevel = logging.INFO if VERBOSE else logging.CRITICAL
logging.basicConfig(level=loglevel)
#-- ERA5 output cumulative subdirectory
cumul_sub = 'ERA5-Cumul-P-E-{0:4d}-{1:4d}'.format(*RANGE)
#-- make cumulative subdirectory
if not os.access(os.path.join(DIRECTORY,cumul_sub), os.F_OK):
os.mkdir(os.path.join(DIRECTORY,cumul_sub), MODE)
#-- regular expression pattern for finding files
rx = re.compile(r'ERA5\-Monthly\-P-E\-(\d{4})\.nc$',re.VERBOSE)
input_files = sorted([f for f in os.listdir(DIRECTORY) if rx.match(f)])
#-- sign for each product to calculate total SMB
smb_sign = {'tp':1.0,'e':-1.0}
#-- output data file format and title
suffix = dict(ascii='txt', netCDF4='nc', HDF5='H5')
output_file_title = 'ERA5 Precipitation minus Evaporation'
#-- output bad value
fill_value = -9999.0
#-- output dimensions and extents
nlat,nlon = (721,1440)
extent = [0.0,359.75,-90.0,90.0]
#-- grid spacing
dlon,dlat = (0.25,0.25)
#-- test that all years are available
start_year, = rx.findall(input_files[0])
end_year, = rx.findall(input_files[-1])
for Y in range(int(start_year),int(end_year)+1):
#-- full path for flux file
f1 = 'ERA5-Monthly-P-E-{0:4d}.nc'.format(Y)
era5_flux_file = os.path.join(DIRECTORY,f1)
if not os.access(era5_flux_file,os.F_OK):
raise Exception('File {0} not in file system'.format(f1))
#-- read mean data from era5_smb_mean.py
args=(RANGE[0], RANGE[1], suffix[DATAFORM])
mean_file = 'ERA5-Mean-P-E-{0:4d}-{1:4d}.{2}'.format(*args)
if (DATAFORM == 'ascii'):
#-- ascii (.txt)
era5_mean = gravity_toolkit.spatial(spacing=[dlon,dlat],
nlat=nlat, nlon=nlon, extent=extent).from_ascii(
os.path.join(DIRECTORY,mean_file),date=False)
elif (DATAFORM == 'netCDF4'):
#-- netcdf (.nc)
era5_mean = gravity_toolkit.spatial().from_netCDF4(
os.path.join(DIRECTORY,mean_file),date=False,
varname='SMB')
elif (DATAFORM == 'HDF5'):
#-- HDF5 (.H5)
era5_mean = gravity_toolkit.spatial().from_HDF5(
os.path.join(DIRECTORY,mean_file),date=False,
varname='SMB')
#-- cumulative mass anomalies calculated by removing mean balance flux
cumul = gravity_toolkit.spatial(nlat=nlat,nlon=nlon,fill_value=fill_value)
cumul.lat = np.copy(era5_mean.lat)
cumul.lon = np.copy(era5_mean.lon)
#-- cumulative data and mask
cumul.data = np.zeros((nlat,nlon))
cumul.mask = np.copy(era5_mean.mask)
#-- for each input file
for f1 in input_files:
#-- full path for flux files
era5_flux_file = os.path.join(DIRECTORY,f1)
Y1, = rx.findall(f1)
#-- days per month in year
dpm = gravity_toolkit.time.calendar_days(int(Y1))
#-- read netCDF4 files for variables of interest
logging.info(era5_flux_file)
var = read_era5_variables(era5_flux_file)
#-- output yearly cumulative mass anomalies
output = gravity_toolkit.spatial(nlat=nlat,nlon=nlon,
fill_value=fill_value)
output.lat = np.copy(era5_mean.lat)
output.lon = np.copy(era5_mean.lon)
#-- output data, mask and time
nt = len(var['time'])
output.data = np.zeros((nlat,nlon,nt))
output.mask = np.zeros((nlat,nlon,nt),dtype=bool)
output.time = np.zeros((nt))
#-- for each month of data
for i,t in enumerate(var['time']):
#-- convert from Julian days to calendar dates
YY,MM,DD,hh,mm,ss = gravity_toolkit.time.convert_julian(t,
FORMAT='tuple')
#-- spatial object for monthly variables
dinput = gravity_toolkit.spatial(nlat=nlat,nlon=nlon,
fill_value=fill_value)
dinput.lat = np.copy(var['latitude'])
dinput.lon = np.copy(var['longitude'])
#-- calculate time in year decimal
dinput.time = gravity_toolkit.time.convert_calendar_decimal(YY,
MM,day=DD,hour=hh,minute=mm,second=ss)
#-- output data and mask
dinput.data = np.zeros((nlat,nlon))
dinput.mask = np.zeros((nlat,nlon),dtype=bool)
for p in ['tp','e']:
dinput.mask |= var[p].mask[i,:,:]
#-- valid indices for all variables
indy,indx = np.nonzero(np.logical_not(dinput.mask))
#-- calculate "SMB" as precipitation minus evaporation
#-- multiply by number of days to get total per month
for p in ['tp','e']:
dinput.data[indy,indx] += dpm[i]*var[p][i,indy,indx]*smb_sign[p]
#-- update masks
dinput.update_mask()
#-- subtract mean and add to cumulative anomalies
cumul.data += dinput.data - era5_mean.data
cumul.mask |= dinput.mask
cumul.update_mask()
#-- copy variables to output yearly data
output.data[:,:,i] = np.copy(cumul.data)
output.mask[:,:,i] = np.copy(cumul.mask)
output.time[i] = np.copy(dinput.time)
#-- output ERA5 cumulative data file
output.update_mask()
FILE = 'ERA5-Cumul-P-E-{0}.{1}'.format(Y1,suffix[DATAFORM])
if (DATAFORM == 'ascii'):
#-- ascii (.txt)
output.to_ascii(os.path.join(DIRECTORY,cumul_sub,FILE),
verbose=VERBOSE)
elif (DATAFORM == 'netCDF4'):
#-- netcdf (.nc)
output.to_netCDF4(os.path.join(DIRECTORY,cumul_sub,FILE),
varname='SMB', UNITS='m w.e.',
LONGNAME='Equivalent_Water_Thickness',
TITLE=output_file_title, verbose=VERBOSE)
elif (DATAFORM == 'HDF5'):
#-- HDF5 (.H5)
output.to_HDF5(os.path.join(DIRECTORY,cumul_sub,FILE),
varname='SMB', UNITS='m w.e.',
LONGNAME='Equivalent_Water_Thickness',
TITLE=output_file_title, verbose=VERBOSE)
#-- change the permissions mode
os.chmod(os.path.join(DIRECTORY,cumul_sub,FILE), MODE)
#-- Main program that calls era5_smb_cumulative()
def main():
#-- Read the system arguments listed after the program
parser = argparse.ArgumentParser(
description="""Reads ERA5 datafiles to calculate
monthly cumulative anomalies in derived surface
mass balance products
"""
)
#-- command line parameters
#-- working data directory
parser.add_argument('--directory','-D',
type=lambda p: os.path.abspath(os.path.expanduser(p)),
default=os.getcwd(),
help='Working data directory')
#-- start and end years to run for mean
parser.add_argument('--mean','-m',
metavar=('START','END'), type=int, nargs=2,
default=[1980,1995],
help='Start and end year range for mean')
#-- input and output data format (ascii, netCDF4, HDF5)
parser.add_argument('--format','-F',
type=str, default='netCDF4', choices=['ascii','netCDF4','HDF5'],
help='Input and output data format')
#-- print information about each output file
parser.add_argument('--verbose','-V',
default=False, action='store_true',
help='Verbose output of run')
#-- permissions mode of the local directories and files (number in octal)
parser.add_argument('--mode','-M',
type=lambda x: int(x,base=8), default=0o775,
help='Permission mode of directories and files')
args,_ = parser.parse_known_args()
#-- run program with parameters
era5_smb_cumulative(args.directory,
RANGE=args.mean,
DATAFORM=args.format,
VERBOSE=args.verbose,
MODE=args.mode)
#-- run main program
if __name__ == '__main__':
main()
|
AhsanSarwar45/OpenGLRenderer | Source/Vertex.cpp | <reponame>AhsanSarwar45/OpenGLRenderer<filename>Source/Vertex.cpp
#include "Vertex.hpp"
bool Vertex::operator==(const Vertex& other) const
{
return Position == other.Position && TexCoord == other.TexCoord && Normal == other.Normal;
} |
ScalablyTyped/SlinkyTyped | a/atom/src/main/scala/typingsSlinky/atom/mod/PreventableExceptionThrownEvent.scala | package typingsSlinky.atom.mod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait PreventableExceptionThrownEvent extends ExceptionThrownEvent {
def preventDefault(): Unit = js.native
}
object PreventableExceptionThrownEvent {
@scala.inline
def apply(
column: Double,
line: Double,
message: String,
originalError: js.Error,
preventDefault: () => Unit,
url: String
): PreventableExceptionThrownEvent = {
val __obj = js.Dynamic.literal(column = column.asInstanceOf[js.Any], line = line.asInstanceOf[js.Any], message = message.asInstanceOf[js.Any], originalError = originalError.asInstanceOf[js.Any], preventDefault = js.Any.fromFunction0(preventDefault), url = url.asInstanceOf[js.Any])
__obj.asInstanceOf[PreventableExceptionThrownEvent]
}
@scala.inline
implicit class PreventableExceptionThrownEventMutableBuilder[Self <: PreventableExceptionThrownEvent] (val x: Self) extends AnyVal {
@scala.inline
def setPreventDefault(value: () => Unit): Self = StObject.set(x, "preventDefault", js.Any.fromFunction0(value))
}
}
|
KillianMeersman/Geometry-wars | Main/src/howest/groep14/game/actor/movement/ISnake.java | package howest.groep14.game.actor.movement;
public interface ISnake {
float getLastX();
float getLastY();
void damage(int damage);
}
|
yesheng86/cpp-utils | include/socket/asioclient.inl | <reponame>yesheng86/cpp-utils<filename>include/socket/asioclient.inl
#pragma once
#include "log/log.hpp"
using namespace util::socket;
using namespace util::log;
inline AsioClient::AsioClient()
: m_io_context(),
m_io_context_thread(),
m_resolver(m_io_context),
m_socket(m_io_context, tcp::v4()) {
}
inline AsioClient::~AsioClient() {
THREAD_SAFE_PRINT("~AsioClient");
m_io_context_thread.join();
}
inline bool AsioClient::connect(const std::string& ip, const std::string& port) {
auto work = asio::require(m_io_context.get_executor(),
asio::execution::outstanding_work.tracked);
asio::error_code error;
tcp::resolver::results_type endpoints = m_resolver.resolve(tcp::v4(), ip, port, error);
if (error) {
THREAD_SAFE_PRINT("resolve end point failed...");
return false;
}
#if 0
auto ep = *endpoints.begin();
m_socket.connect(ep, error);
if (error) {
THREAD_SAFE_PRINT("socket connect failed...");
return false;
}
if (m_on_read_delegate) {
start_read();
}
#else
asio::async_connect(m_socket, endpoints,
[this](std::error_code ec, tcp::endpoint)
{
THREAD_SAFE_PRINT("socket connect ec:%x", ec);
if (!ec)
{
if (m_on_read_delegate) {
start_read();
}
}
});
#endif
m_io_context_thread = std::thread([this]() { m_io_context.run(); });
return true;
}
inline bool AsioClient::disconnect() {
m_io_context.stop();
THREAD_SAFE_PRINT("disconnected...");
return true;
}
inline bool AsioClient::send_block(const BufferDescriptorPtr& buf_desc_ptr) {
m_socket.async_send(asio::buffer(buf_desc_ptr->raw_ptr(), buf_desc_ptr->size()),
asio::use_future);
return true;
}
inline bool AsioClient::write_block(const BufferDescriptorPtr& buf_desc_ptr) {
::asio::write(m_socket, ::asio::buffer(buf_desc_ptr->raw_ptr(), buf_desc_ptr->size()));
return true;
}
inline void AsioClient::register_delegate(const OnReadDelegatePtr& delegate) {
m_on_read_delegate = delegate;
}
inline void AsioClient::unregister_delegate() {
m_on_read_delegate = nullptr;
}
inline void AsioClient::start_read() {
THREAD_SAFE_PRINT("AsioClient::start_read");
m_current_buffer_desc = m_on_read_delegate->prepare_buffer();
if (!m_current_buffer_desc) {
THREAD_SAFE_PRINT("AsioClient::start_read null buffer desc");
return;
}
THREAD_SAFE_PRINT("AsioClient::start_read start async read %d", m_current_buffer_desc->size());
asio::async_read(m_socket,
asio::buffer(m_current_buffer_desc->raw_ptr(),
m_current_buffer_desc->size()),
std::bind(&AsioClient::on_read, this,
std::placeholders::_1,
std::placeholders::_2));
}
inline void AsioClient::on_read(const std::error_code& ec,
std::size_t bytes_transferred) {
THREAD_SAFE_PRINT("AsioClient::on_read %d transferred", bytes_transferred);
if (!ec && m_current_buffer_desc
&& m_on_read_delegate
&& !m_on_read_delegate->is_stopped()) {
if (!m_on_read_delegate->handle_on_read(m_current_buffer_desc, bytes_transferred)) {
return;
}
m_current_buffer_desc = m_on_read_delegate->prepare_buffer();
if (!m_current_buffer_desc) {
return;
} else {
::asio::async_read(m_socket,
::asio::buffer(m_current_buffer_desc->raw_ptr(),
m_current_buffer_desc->size()),
std::bind(&AsioClient::on_read, this,
std::placeholders::_1,
std::placeholders::_2));
}
} else if (ec == ::asio::error::eof) {
THREAD_SAFE_PRINT("asioclient receive eof");
} else {
THREAD_SAFE_PRINT("on read data error %s on connection(0x%x)", ec.message() );
}
}
|
PortalInstruments/athena_health | spec/lib/error_spec.rb | <filename>spec/lib/error_spec.rb
require 'spec_helper'
describe AthenaHealth::ValidationError do
subject { AthenaHealth::ValidationError.new({ error: 'Error message' }) }
let(:error_hash) { { error: 'Error message' } }
it 'returns details' do
expect(subject.details).to eq(error_hash)
end
end
describe AthenaHealth::Error do
let(:error) { AthenaHealth::Error.new(code: code) }
describe '#render' do
context 'when response code is 401' do
let(:code) { 401 }
it 'raise UnauthorizedError' do
expect { error.render }.to raise_error(
AthenaHealth::UnauthorizedError
)
end
end
context 'when response code is 402' do
let(:code) { 402 }
it 'raise IncorrectPermissionsError' do
expect { error.render }.to raise_error(
AthenaHealth::IncorrectPermissionsError
)
end
end
context 'when response code is 403' do
let(:code) { 403 }
it 'raise ForbiddenError' do
expect { error.render }.to raise_error(
AthenaHealth::ForbiddenError
)
end
end
context 'when response code is 404' do
let(:code) { 404 }
it 'raise NotFoundError' do
expect { error.render }.to raise_error(
AthenaHealth::NotFoundError
)
end
end
context 'when response code is 500' do
let(:code) { 500 }
it 'raise InternalServerError,' do
expect { error.render }.to raise_error(
AthenaHealth::InternalServerError
)
end
end
context 'when response code is 503' do
let(:code) { 503 }
it 'raise ServiceUnavailableError' do
expect { error.render }.to raise_error(
AthenaHealth::ServiceUnavailableError
)
end
end
end
end
|
TMarkov98/BindKraft | Scripts/system/globalcommands/keytokenregistry.js | <reponame>TMarkov98/BindKraft<gh_stars>10-100
/**
* This file contains the implementations of commands managing the key/token storage accessible from the LocalAPI as IQueryTokenStorage
*/
System.CommandLibs.TokenStorage = (function() {
function _checkObject(obj) { // Check object if it matches the key storage expectations
if (typeof obj == "object" && obj != null) {
// Existence of other keys is not expected
for (var k in obj) {
if (!obj.hasOwnProperty(k)) continue;
if (k == "key" || k == "token" || k == "servicename") continue;
return false;
}
if (typeof obj.key != "string") return false;
if (obj.key.length == 0) return false;
if ( (typeof obj.token == "string" && obj.token.length > 0) ||
(typeof obj.servicename == "string" && obj.servicename.length > 0)
) {
return true;
}
}
return false;
}
function _registerToken(o) {
var k = o.key;
var t = o.token;
var sn = o.servicename;
if (SystemTokenStorage.Default().storage.registerToken(k,t, (sn?sn:null))) {
return true;
} else {
return false;
}
}
return function(context, api) {
var op = new Operation(null, 20000);
var module = api.pullNextToken();
var lurl = api.pullNextToken();
var bo = new BaseObject();
var actualurl = IPlatformUrlMapper.mapModuleUrl(lurl,module);
bo.ajaxGetXml(actualurl,null, function(result) {
if (result.status.issuccessful) {
var some_err = false;
if (BaseObject.is(result.data, "Array")) {
for (var i = 0; i < result.data.length; i++) {
var r = result.data[i];
if (_checkObject(r)) {
if (!_registerToken(r)) some_err = true;
}
}
if (some_err) {
op.CompleteOperation(false, "Could not register all the returned key/token entries.");
} else {
op.CompleteOperation(true,null);
}
} else {
if (_checkObject(result.data)) { // Single entry
if (_registerToken(result.data)) {
op.CompleteOperation(true,null);
} else {
op.CompleteOperation(false, "Could not register the single entry received.");
}
} else { // Multiple entries in sub-object
for (var k in result.data) {
if (result.data.hasOwnProperty(k)) {
if (_checkObject(result.data[k])) {
if (!_registerToken(result.data[k])) some_err = true;
}
}
}
if (some_err) {
op.CompleteOperation(false, "Could not register all the returned key/token entries.");
} else {
op.CompleteOperation(true,null);
}
}
}
} else {
op.CompleteOperation(false, "Request for the auth token failed.");
}
});
return op;
}
})(); |
Matheus-IT/lang-python-related | python_exercises/39asteriscs.py | <filename>python_exercises/39asteriscs.py<gh_stars>0
n = int(input('Enter a number: '))
print('Using for: ')
for i in range(n):
print('*', end='')
print()
print('Using while: ')
c = n
while c > 0:
print('*', end='')
c -= 1
print()
print('Using the replication operator: ')
print('*' * n)
|
umbreak/lithium | src/main/scala/com/swissborg/lithium/instances/OrderInstances.scala | <reponame>umbreak/lithium
package com.swissborg.lithium
package instances
import akka.cluster.{Member, UniqueAddress}
import cats.Order
import shapeless.tag.@@
object OrderInstances extends OrderInstances
trait OrderInstances {
implicit val memberOrder: Order[Member] = Order.fromOrdering(Member.ordering)
implicit val uniqueAdressOrder: Order[UniqueAddress] = Order.from((a1, a2) => a1.compare(a2))
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
implicit def taggedOrder[A: Order, B]: Order[A @@ B] = Order[A].asInstanceOf[Order[A @@ B]]
}
|
fgallaire/crea | libraries/chain/include/crea/chain/required_action_evaluator.hpp | <reponame>fgallaire/crea<filename>libraries/chain/include/crea/chain/required_action_evaluator.hpp
#pragma once
#include <crea/protocol/crea_required_actions.hpp>
#include <crea/chain/evaluator.hpp>
namespace crea { namespace chain {
using namespace crea::protocol;
#ifdef IS_TEST_NET
CREA_DEFINE_ACTION_EVALUATOR( example_required, required_automated_action )
#endif
} } //crea::chain
|
DanielPDWalker/Astrophoto | frontend/views.py | <gh_stars>0
from django.shortcuts import render, get_object_or_404
from messier_objects.models import MessierObject
from solar_system_objects.models import SolarSystemObject
from asteroids_comets_meteors.models import AsteroidCometMeteorObject
from utils.frontend_view_utils import overview_post_request
def index(request):
return render(request, 'index.html')
def mes_obj_overview(request):
if request.method == 'POST':
list_of_mes_obj = overview_post_request(request)
# else if not post request.
else:
list_of_mes_obj = MessierObject.objects.all()
context = {
"list_of_mes_obj": list_of_mes_obj
}
return render(request,
'api_frontends/messier_objects_overview.html', context)
def mes_obj_detail(request, mes_num):
mes_obj = get_object_or_404(MessierObject, messier_number=mes_num)
context = {
"mes_obj": mes_obj
}
return render(request, 'api_frontends/messier_object_detail.html', context)
def sol_obj_overview(request):
if request.method == 'POST':
list_of_sol_obj = overview_post_request(request)
# else if not post request.
else:
list_of_sol_obj = SolarSystemObject.objects.all()
context = {
"list_of_sol_obj": list_of_sol_obj
}
return render(request,
'api_frontends/solar_system_objects_overview.html',
context)
def sol_obj_detail(request, slug):
sol_obj = get_object_or_404(SolarSystemObject, slug=slug)
context = {
"sol_obj": sol_obj
}
return render(request,
'api_frontends/solar_system_object_detail.html', context)
def acm_obj_overview(request):
if request.method == 'POST':
list_of_acm_obj = overview_post_request(request)
# else if not post request.
else:
list_of_acm_obj = AsteroidCometMeteorObject.objects.all()
context = {
"list_of_acm_obj": list_of_acm_obj
}
return render(request,
'api_frontends/asteroids_comets_meteors_overview.html',
context)
def acm_obj_detail(request, slug):
acm_obj = get_object_or_404(AsteroidCometMeteorObject, slug=slug)
context = {
"acm_obj": acm_obj
}
return render(request,
'api_frontends/asteroids_comets_meteors_detail.html',
context)
|
cjm-ios-sdk/CMKit | CMKit/Classes/AlertView/CMAlertViewController.h | //
// CMAlertViewController.h
// CMAlertViewController
//
// Created by chenjm on 2020/4/14.
//
#import <UIKit/UIKit.h>
@interface CMAlertAction : NSObject
@property (nullable, nonatomic, readonly) NSString *title;
@property (nonatomic, readonly) UIAlertActionStyle style; // 暂时未实现
@property (nonatomic, getter=isEnabled) BOOL enabled; // 是否可用,默认 YES
@property (nullable, nonatomic, strong) UIColor *titleColor; // 标题颜色 blackColor
@property (nullable, nonatomic, strong) UIColor *disableTitleColor; // 默认 grayColor
@property (nullable, nonatomic, strong) UIFont *titleFont; // 标题字体,默认 [UIFont boldSystemFontOfSize:18]
/**
* @brief 生成和初始化一个action
* @param title 标题
* @param style 类型 暂时未实现
* @param handler 回调函数
*/
+ (instancetype _Nonnull )actionWithTitle:(nullable NSString *)title style:(UIAlertActionStyle)style handler:(void (^ __nullable)(UIAlertAction * _Nonnull action))handler;
@end
@interface CMAlertViewController : UIViewController
@property (nonnull, nonatomic, readonly) NSArray<CMAlertAction *> * actions;
@property (nullable, nonatomic, copy) NSString *alertTitle; // 弹框标题
@property (nonatomic, assign) CGFloat alertViewHeight; // 默认 200
@property (nonnull, nonatomic, strong, readonly) UIView *alertView; // 弹框
@property (nonnull, nonatomic, strong, readonly) UILabel *titleLabel; // 标题Label
/**
* @brief 添加一个按钮和事件
*/
- (void)addAction:(CMAlertAction *_Nonnull)action;
/**
* @brief 添加一个label
*/
- (void)addLabelWithConfigurationHandler:(void (^ __nullable)(UILabel *_Nonnull label))configurationHandler;
/**
* @brief 添加一个label
*/
- (void)addTextFieldWithConfigurationHandler:(void (^ __nullable)(UITextField * _Nonnull textField))configurationHandler;
/**
* @brief 添加一个view
*/
- (void)addViewWithHeight:(CGFloat)height configurationHandler:(void (^ __nullable)(UIView *_Nonnull view))configurationHandler;
/**
* @brief 添加一个scrollView
*/
- (void)addScrollViewWithHeight:(CGFloat)height configurationHandler:(void (^ __nullable)(UIScrollView * _Nonnull view))configurationHandler;
@end
|
Grosskopf/openoffice | main/basctl/source/basicide/macrodlg.cxx | <reponame>Grosskopf/openoffice<filename>main/basctl/source/basicide/macrodlg.cxx<gh_stars>100-1000
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basctl.hxx"
#include <memory>
#include <ide_pch.hxx>
#include <macrodlg.hxx>
#include <macrodlg.hrc>
#include <basidesh.hrc>
#include <basidesh.hxx>
#include <baside2.hrc> // ID's fuer Imagese
#include <basobj.hxx>
#include <baside3.hxx>
#include <iderdll.hxx>
#include <iderdll2.hxx>
#include <iderid.hxx>
#include <moduldlg.hxx>
#include <basic/sbx.hxx>
#include <bastypes.hxx>
#include <sbxitem.hxx>
#include <sfx2/minfitem.hxx>
#ifndef _COM_SUN_STAR_SCRIPT_XLIBRYARYCONTAINER2_HPP_
#include <com/sun/star/script/XLibraryContainer2.hpp>
#endif
#include <com/sun/star/document/MacroExecMode.hpp>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
DECLARE_LIST( MacroList, SbMethod* )
MacroChooser::MacroChooser( Window* pParnt, sal_Bool bCreateEntries ) :
SfxModalDialog( pParnt, IDEResId( RID_MACROCHOOSER ) ),
aMacroNameTxt( this, IDEResId( RID_TXT_MACRONAME ) ),
aMacroNameEdit( this, IDEResId( RID_ED_MACRONAME ) ),
aMacroFromTxT( this, IDEResId( RID_TXT_MACROFROM ) ),
aMacrosSaveInTxt( this, IDEResId( RID_TXT_SAVEMACRO ) ),
aBasicBox( this, IDEResId( RID_CTRL_LIB ) ),
aMacrosInTxt( this, IDEResId( RID_TXT_MACROSIN ) ),
aMacroBox( this, IDEResId( RID_CTRL_MACRO ) ),
aRunButton( this, IDEResId( RID_PB_RUN ) ),
aCloseButton( this, IDEResId( RID_PB_CLOSE ) ),
aAssignButton( this, IDEResId( RID_PB_ASSIGN ) ),
aEditButton( this, IDEResId( RID_PB_EDIT ) ),
aNewDelButton( this, IDEResId( RID_PB_DEL ) ),
aOrganizeButton( this, IDEResId( RID_PB_ORG ) ),
aHelpButton( this, IDEResId( RID_PB_HELP ) ),
aNewLibButton( this, IDEResId( RID_PB_NEWLIB ) ),
aNewModButton( this, IDEResId( RID_PB_NEWMOD ) )
{
FreeResource();
nMode = MACROCHOOSER_ALL;
bNewDelIsDel = sal_True;
// Der Sfx fragt den BasicManager nicht, ob modified
// => Speichern anschmeissen, wenn Aenderung, aber kein Sprung in
// die BasicIDE.
bForceStoreBasic = sal_False;
aMacrosInTxtBaseStr = aMacrosInTxt.GetText();
aMacroBox.SetSelectionMode( SINGLE_SELECTION );
aMacroBox.SetHighlightRange(); // ueber ganze Breite selektieren
aRunButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aCloseButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aAssignButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aEditButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aNewDelButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aOrganizeButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
// Buttons only for MACROCHOOSER_RECORDING
aNewLibButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aNewModButton.SetClickHdl( LINK( this, MacroChooser, ButtonHdl ) );
aNewLibButton.Hide(); // default
aNewModButton.Hide(); // default
aMacrosSaveInTxt.Hide(); // default
aMacrosInTxt.SetStyle( WB_NOMULTILINE | WB_PATHELLIPSIS );
aMacroNameEdit.SetModifyHdl( LINK( this, MacroChooser, EditModifyHdl ) );
aBasicBox.SetSelectHdl( LINK( this, MacroChooser, BasicSelectHdl ) );
aMacroBox.SetDoubleClickHdl( LINK( this, MacroChooser, MacroDoubleClickHdl ) );
aMacroBox.SetSelectHdl( LINK( this, MacroChooser, MacroSelectHdl ) );
aBasicBox.SetMode( BROWSEMODE_MODULES );
aBasicBox.SetStyle( WB_TABSTOP | WB_BORDER |
WB_HASLINES | WB_HASLINESATROOT |
WB_HASBUTTONS | WB_HASBUTTONSATROOT |
WB_HSCROLL );
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if( pDispatcher )
{
pDispatcher->Execute( SID_BASICIDE_STOREALLMODULESOURCES );
}
if ( bCreateEntries )
aBasicBox.ScanAllEntries();
}
MacroChooser::~MacroChooser()
{
if ( bForceStoreBasic )
SFX_APP()->SaveBasicAndDialogContainer();
}
void MacroChooser::StoreMacroDescription()
{
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( aBasicBox.FirstSelected() ) );
String aMethodName;
SvLBoxEntry* pEntry = aMacroBox.FirstSelected();
if ( pEntry )
aMethodName = aMacroBox.GetEntryText( pEntry );
else
aMethodName = aMacroNameEdit.GetText();
if ( aMethodName.Len() )
{
aDesc.SetMethodName( aMethodName );
aDesc.SetType( OBJ_TYPE_METHOD );
}
BasicIDEData* pData = IDE_DLL()->GetExtraData();
if ( pData )
pData->SetLastEntryDescriptor( aDesc );
}
void MacroChooser::RestoreMacroDescription()
{
BasicEntryDescriptor aDesc;
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
if ( pIDEShell )
{
IDEBaseWindow* pCurWin = pIDEShell->GetCurWindow();
if ( pCurWin )
aDesc = pCurWin->CreateEntryDescriptor();
}
else
{
BasicIDEData* pData = IDE_DLL()->GetExtraData();
if ( pData )
aDesc = pData->GetLastEntryDescriptor();
}
aBasicBox.SetCurrentEntry( aDesc );
String aLastMacro( aDesc.GetMethodName() );
if ( aLastMacro.Len() )
{
// find entry in macro box
SvLBoxEntry* pEntry = 0;
sal_uLong nPos = 0;
SvLBoxEntry* pE = aMacroBox.GetEntry( nPos );
while ( pE )
{
if ( aMacroBox.GetEntryText( pE ) == aLastMacro )
{
pEntry = pE;
break;
}
pE = aMacroBox.GetEntry( ++nPos );
}
if ( pEntry )
aMacroBox.SetCurEntry( pEntry );
else
{
aMacroNameEdit.SetText( aLastMacro );
aMacroNameEdit.SetSelection( Selection( 0, 0 ) );
}
}
}
short __EXPORT MacroChooser::Execute()
{
RestoreMacroDescription();
aRunButton.GrabFocus();
// #104198 Check if "wrong" document is active
SvLBoxEntry* pSelectedEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pSelectedEntry ) );
const ScriptDocument& rSelectedDoc( aDesc.GetDocument() );
// App Basic is always ok, so only check if shell was found
if( rSelectedDoc.isDocument() && !rSelectedDoc.isActive() )
{
// Search for the right entry
sal_uLong nRootPos = 0;
SvLBoxEntry* pRootEntry = aBasicBox.GetEntry( nRootPos );
while( pRootEntry )
{
BasicEntryDescriptor aCmpDesc( aBasicBox.GetEntryDescriptor( pRootEntry ) );
const ScriptDocument& rCmpDoc( aCmpDesc.GetDocument() );
if ( rCmpDoc.isDocument() && rCmpDoc.isActive() )
{
SvLBoxEntry* pEntry = pRootEntry;
SvLBoxEntry* pLastValid = pEntry;
while ( pEntry )
{
pLastValid = pEntry;
pEntry = aBasicBox.FirstChild( pEntry );
}
if( pLastValid )
aBasicBox.SetCurEntry( pLastValid );
}
pRootEntry = aBasicBox.GetEntry( ++nRootPos );
}
}
CheckButtons();
UpdateFields();
if ( StarBASIC::IsRunning() )
aCloseButton.GrabFocus();
Window* pPrevDlgParent = Application::GetDefDialogParent();
Application::SetDefDialogParent( this );
short nRet = ModalDialog::Execute();
// #57314# Wenn die BasicIDE aktiviert wurde, dann nicht den DefModalDialogParent auf das inaktive Dokument zuruecksetzen.
if ( Application::GetDefDialogParent() == this )
Application::SetDefDialogParent( pPrevDlgParent );
return nRet;
}
void MacroChooser::EnableButton( Button& rButton, sal_Bool bEnable )
{
if ( bEnable )
{
if ( nMode == MACROCHOOSER_CHOOSEONLY || nMode == MACROCHOOSER_RECORDING )
{
// Nur der RunButton kann enabled werden
if ( &rButton == &aRunButton )
rButton.Enable();
else
rButton.Disable();
}
else
rButton.Enable();
}
else
rButton.Disable();
}
SbMethod* MacroChooser::GetMacro()
{
SbMethod* pMethod = 0;
SbModule* pModule = aBasicBox.FindModule( aBasicBox.GetCurEntry() );
if ( pModule )
{
SvLBoxEntry* pEntry = aMacroBox.FirstSelected();
if ( pEntry )
{
String aMacroName( aMacroBox.GetEntryText( pEntry ) );
pMethod = (SbMethod*)pModule->GetMethods()->Find( aMacroName, SbxCLASS_METHOD );
}
}
return pMethod;
}
void MacroChooser::DeleteMacro()
{
SbMethod* pMethod = GetMacro();
DBG_ASSERT( pMethod, "DeleteMacro: Kein Macro !" );
if ( pMethod && QueryDelMacro( pMethod->GetName(), this ) )
{
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if( pDispatcher )
{
pDispatcher->Execute( SID_BASICIDE_STOREALLMODULESOURCES );
}
// Aktuelles Doc als geaendert markieren:
StarBASIC* pBasic = BasicIDE::FindBasic( pMethod );
DBG_ASSERT( pBasic, "Basic?!" );
BasicManager* pBasMgr = BasicIDE::FindBasicManager( pBasic );
DBG_ASSERT( pBasMgr, "BasMgr?" );
ScriptDocument aDocument( ScriptDocument::getDocumentForBasicManager( pBasMgr ) );
if ( aDocument.isDocument() ) // Muss ja nicht aus einem Document kommen...
{
aDocument.setDocumentModified();
SfxBindings* pBindings = BasicIDE::GetBindingsPtr();
if ( pBindings )
pBindings->Invalidate( SID_SAVEDOC );
}
SbModule* pModule = pMethod->GetModule();
DBG_ASSERT( pModule, "DeleteMacro: Kein Modul?!" );
::rtl::OUString aSource( pModule->GetSource32() );
sal_uInt16 nStart, nEnd;
pMethod->GetLineRange( nStart, nEnd );
pModule->GetMethods()->Remove( pMethod );
CutLines( aSource, nStart-1, nEnd-nStart+1, sal_True );
pModule->SetSource32( aSource );
// update module in library
String aLibName = pBasic->GetName();
String aModName = pModule->GetName();
OSL_VERIFY( aDocument.updateModule( aLibName, aModName, aSource ) );
SvLBoxEntry* pEntry = aMacroBox.FirstSelected();
DBG_ASSERT( pEntry, "DeleteMacro: Entry ?!" );
aMacroBox.GetModel()->Remove( pEntry );
bForceStoreBasic = sal_True;
}
}
SbMethod* MacroChooser::CreateMacro()
{
SbMethod* pMethod = 0;
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pCurEntry ) );
ScriptDocument aDocument( aDesc.GetDocument() );
OSL_ENSURE( aDocument.isAlive(), "MacroChooser::CreateMacro: no document!" );
if ( !aDocument.isAlive() )
return NULL;
String aLibName( aDesc.GetLibName() );
if ( !aLibName.Len() )
aLibName = String::CreateFromAscii( "Standard" );
aDocument.getOrCreateLibrary( E_SCRIPTS, aLibName );
::rtl::OUString aOULibName( aLibName );
Reference< script::XLibraryContainer > xModLibContainer( aDocument.getLibraryContainer( E_SCRIPTS ) );
if ( xModLibContainer.is() && xModLibContainer->hasByName( aOULibName ) && !xModLibContainer->isLibraryLoaded( aOULibName ) )
xModLibContainer->loadLibrary( aOULibName );
Reference< script::XLibraryContainer > xDlgLibContainer( aDocument.getLibraryContainer( E_DIALOGS ) );
if ( xDlgLibContainer.is() && xDlgLibContainer->hasByName( aOULibName ) && !xDlgLibContainer->isLibraryLoaded( aOULibName ) )
xDlgLibContainer->loadLibrary( aOULibName );
BasicManager* pBasMgr = aDocument.getBasicManager();
StarBASIC* pBasic = pBasMgr ? pBasMgr->GetLib( aLibName ) : 0;
if ( pBasic )
{
SbModule* pModule = 0;
String aModName( aDesc.GetName() );
if ( aModName.Len() )
{
// extract the module name from the string like "Sheet1 (Example1)"
if( aDesc.GetLibSubName().Equals( String( IDEResId( RID_STR_DOCUMENT_OBJECTS ) ) ) )
{
sal_uInt16 nIndex = 0;
aModName = aModName.GetToken( 0, ' ', nIndex );
}
pModule = pBasic->FindModule( aModName );
}
else if ( pBasic->GetModules()->Count() )
pModule = (SbModule*)pBasic->GetModules()->Get( 0 );
if ( !pModule )
{
pModule = createModImpl( static_cast<Window*>( this ),
aDocument, aBasicBox, aLibName, aModName );
}
String aSubName = aMacroNameEdit.GetText();
DBG_ASSERT( !pModule || !pModule->GetMethods()->Find( aSubName, SbxCLASS_METHOD ), "Macro existiert schon!" );
pMethod = pModule ? BasicIDE::CreateMacro( pModule, aSubName ) : NULL;
}
return pMethod;
}
void MacroChooser::SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry )
{
// Durch das Highlight wird das Edit sonst platt gemacht:
String aSaveText( aMacroNameEdit.GetText() );
Selection aCurSel( aMacroNameEdit.GetSelection() );
rBox.SetCurEntry( pEntry );
aMacroNameEdit.SetText( aSaveText );
aMacroNameEdit.SetSelection( aCurSel );
}
void MacroChooser::CheckButtons()
{
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pCurEntry ) );
SvLBoxEntry* pMacroEntry = aMacroBox.FirstSelected();
SbMethod* pMethod = GetMacro();
// check, if corresponding libraries are readonly
sal_Bool bReadOnly = sal_False;
sal_uInt16 nDepth = pCurEntry ? aBasicBox.GetModel()->GetDepth( pCurEntry ) : 0;
if ( nDepth == 1 || nDepth == 2 )
{
ScriptDocument aDocument( aDesc.GetDocument() );
::rtl::OUString aOULibName( aDesc.GetLibName() );
Reference< script::XLibraryContainer2 > xModLibContainer( aDocument.getLibraryContainer( E_SCRIPTS ), UNO_QUERY );
Reference< script::XLibraryContainer2 > xDlgLibContainer( aDocument.getLibraryContainer( E_DIALOGS ), UNO_QUERY );
if ( ( xModLibContainer.is() && xModLibContainer->hasByName( aOULibName ) && xModLibContainer->isLibraryReadOnly( aOULibName ) ) ||
( xDlgLibContainer.is() && xDlgLibContainer->hasByName( aOULibName ) && xDlgLibContainer->isLibraryReadOnly( aOULibName ) ) )
{
bReadOnly = sal_True;
}
}
if ( nMode != MACROCHOOSER_RECORDING )
{
// Run...
sal_Bool bEnable = pMethod ? sal_True : sal_False;
if ( ( nMode != MACROCHOOSER_CHOOSEONLY ) && StarBASIC::IsRunning() )
bEnable = sal_False;
EnableButton( aRunButton, bEnable );
}
// Organisieren immer moeglich ?
// Assign...
EnableButton( aAssignButton, pMethod ? sal_True : sal_False );
// Edit...
EnableButton( aEditButton, pMacroEntry ? sal_True : sal_False );
// aOrganizeButton
EnableButton( aOrganizeButton, !StarBASIC::IsRunning() && ( nMode == MACROCHOOSER_ALL ));
// aNewDelButton....
bool bProtected = aBasicBox.IsEntryProtected( pCurEntry );
bool bShare = ( aDesc.GetLocation() == LIBRARY_LOCATION_SHARE );
EnableButton( aNewDelButton,
!StarBASIC::IsRunning() && ( nMode == MACROCHOOSER_ALL ) && !bProtected && !bReadOnly && !bShare );
sal_Bool bPrev = bNewDelIsDel;
bNewDelIsDel = pMethod ? sal_True : sal_False;
if ( ( bPrev != bNewDelIsDel ) && ( nMode == MACROCHOOSER_ALL ) )
{
String aBtnText( bNewDelIsDel ? IDEResId( RID_STR_BTNDEL) : IDEResId( RID_STR_BTNNEW ) );
aNewDelButton.SetText( aBtnText );
}
if ( nMode == MACROCHOOSER_RECORDING )
{
// save button
if ( !bProtected && !bReadOnly && !bShare )
aRunButton.Enable();
else
aRunButton.Disable();
// new library button
if ( !bShare )
aNewLibButton.Enable();
else
aNewLibButton.Disable();
// new module button
if ( !bProtected && !bReadOnly && !bShare )
aNewModButton.Enable();
else
aNewModButton.Disable();
}
}
IMPL_LINK_INLINE_START( MacroChooser, MacroDoubleClickHdl, SvTreeListBox *, EMPTYARG )
{
StoreMacroDescription();
if ( nMode == MACROCHOOSER_RECORDING )
{
SbMethod* pMethod = GetMacro();
if ( pMethod && !QueryReplaceMacro( pMethod->GetName(), this ) )
return 0;
}
EndDialog( MACRO_OK_RUN );
return 0;
}
IMPL_LINK_INLINE_END( MacroChooser, MacroDoubleClickHdl, SvTreeListBox *, EMPTYARG )
IMPL_LINK( MacroChooser, MacroSelectHdl, SvTreeListBox *, pBox )
{
// Wird auch gerufen, wenn Deselektiert!
// 2 Funktionsaufrufe in jedem SelectHdl, nur weil Olli
// keinen separatren DeselctHdl einfuehren wollte:
// Also: Feststellen, ob Select oder Deselect:
if ( pBox->IsSelected( pBox->GetHdlEntry() ) )
{
UpdateFields();
CheckButtons();
}
return 0;
}
IMPL_LINK( MacroChooser, BasicSelectHdl, SvTreeListBox *, pBox )
{
static String aSpaceStr = String::CreateFromAscii(" ");
// Wird auch gerufen, wenn Deselektiert!
// 2 Funktionsaufrufe in jedem SelectHdl, nur weil Olli
// keinen separatren DeselctHdl einfuehren wollte:
// Also: Feststellen, ob Select oder Deselect:
if ( !pBox->IsSelected( pBox->GetHdlEntry() ) )
return 0;
SbModule* pModule = aBasicBox.FindModule( aBasicBox.GetCurEntry() );
aMacroBox.Clear();
if ( pModule )
{
String aStr = aMacrosInTxtBaseStr;
aStr += aSpaceStr;
aStr += pModule->GetName();
aMacrosInTxt.SetText( aStr );
// Die Macros sollen in der Reihenfolge angezeigt werden,
// wie sie im Modul stehen.
MacroList aMacros;
sal_uInt16 nMacroCount = pModule->GetMethods()->Count();
sal_uInt16 nRealMacroCount = 0;
sal_uInt16 iMeth;
for ( iMeth = 0; iMeth < nMacroCount; iMeth++ )
{
SbMethod* pMethod = (SbMethod*)pModule->GetMethods()->Get( iMeth );
if( pMethod->IsHidden() )
continue;
++nRealMacroCount;
DBG_ASSERT( pMethod, "Methode nicht gefunden! (NULL)" );
sal_uLong nPos = LIST_APPEND;
// Eventuell weiter vorne ?
sal_uInt16 nStart, nEnd;
pMethod->GetLineRange( nStart, nEnd );
for ( sal_uLong n = 0; n < aMacros.Count(); n++ )
{
sal_uInt16 nS, nE;
SbMethod* pM = aMacros.GetObject( n );
DBG_ASSERT( pM, "Macro nicht in Liste ?!" );
pM->GetLineRange( nS, nE );
if ( nS > nStart )
{
nPos = n;
break;
}
}
aMacros.Insert( pMethod, nPos );
}
aMacroBox.SetUpdateMode( sal_False );
for ( iMeth = 0; iMeth < nRealMacroCount; iMeth++ )
aMacroBox.InsertEntry( aMacros.GetObject( iMeth )->GetName() );
aMacroBox.SetUpdateMode( sal_True );
if ( aMacroBox.GetEntryCount() )
{
SvLBoxEntry* pEntry = aMacroBox.GetEntry( 0 );
DBG_ASSERT( pEntry, "Entry ?!" );
aMacroBox.SetCurEntry( pEntry );
}
}
UpdateFields();
CheckButtons();
return 0;
}
IMPL_LINK( MacroChooser, EditModifyHdl, Edit *, pEdit )
{
(void)pEdit;
// Das Modul, in dem bei Neu das Macro landet, selektieren,
// wenn BasicManager oder Lib selektiert.
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
if ( pCurEntry )
{
sal_uInt16 nDepth = aBasicBox.GetModel()->GetDepth( pCurEntry );
if ( ( nDepth == 1 ) && ( aBasicBox.IsEntryProtected( pCurEntry ) ) )
{
// Dann auf die entsprechende Std-Lib stellen...
SvLBoxEntry* pManagerEntry = aBasicBox.GetModel()->GetParent( pCurEntry );
pCurEntry = aBasicBox.GetModel()->FirstChild( pManagerEntry );
}
if ( nDepth < 2 )
{
SvLBoxEntry* pNewEntry = pCurEntry;
while ( pCurEntry && ( nDepth < 2 ) )
{
pCurEntry = aBasicBox.FirstChild( pCurEntry );
if ( pCurEntry )
{
pNewEntry = pCurEntry;
nDepth = aBasicBox.GetModel()->GetDepth( pCurEntry );
}
}
SaveSetCurEntry( aBasicBox, pNewEntry );
}
if ( aMacroBox.GetEntryCount() )
{
String aEdtText( aMacroNameEdit.GetText() );
sal_Bool bFound = sal_False;
for ( sal_uInt16 n = 0; n < aMacroBox.GetEntryCount(); n++ )
{
SvLBoxEntry* pEntry = aMacroBox.GetEntry( n );
DBG_ASSERT( pEntry, "Entry ?!" );
if ( aMacroBox.GetEntryText( pEntry ).CompareIgnoreCaseToAscii( aEdtText ) == COMPARE_EQUAL )
{
SaveSetCurEntry( aMacroBox, pEntry );
bFound = sal_True;
break;
}
}
if ( !bFound )
{
SvLBoxEntry* pEntry = aMacroBox.FirstSelected();
// If there is the entry ->Select ->Description...
if ( pEntry )
aMacroBox.Select( pEntry, sal_False );
}
}
}
CheckButtons();
return 0;
}
IMPL_LINK( MacroChooser, ButtonHdl, Button *, pButton )
{
// ausser bei New/Record wird die Description durch LoseFocus uebernommen.
if ( pButton == &aRunButton )
{
StoreMacroDescription();
// #116444# check security settings before macro execution
if ( nMode == MACROCHOOSER_ALL )
{
SbMethod* pMethod = GetMacro();
SbModule* pModule = pMethod ? pMethod->GetModule() : NULL;
StarBASIC* pBasic = pModule ? (StarBASIC*)pModule->GetParent() : NULL;
BasicManager* pBasMgr = pBasic ? BasicIDE::FindBasicManager( pBasic ) : NULL;
if ( pBasMgr )
{
ScriptDocument aDocument( ScriptDocument::getDocumentForBasicManager( pBasMgr ) );
if ( aDocument.isDocument() && !aDocument.allowMacros() )
{
WarningBox( this, WB_OK, String( IDEResId( RID_STR_CANNOTRUNMACRO ) ) ).Execute();
return 0;
}
}
}
else if ( nMode == MACROCHOOSER_RECORDING )
{
sal_Bool bValid = BasicIDE::IsValidSbxName( aMacroNameEdit.GetText() );
if ( !bValid )
{
ErrorBox( this, WB_OK | WB_DEF_OK, String( IDEResId( RID_STR_BADSBXNAME ) ) ).Execute();
aMacroNameEdit.SetSelection( Selection( 0, aMacroNameEdit.GetText().Len() ) );
aMacroNameEdit.GrabFocus();
return 0;
}
SbMethod* pMethod = GetMacro();
if ( pMethod && !QueryReplaceMacro( pMethod->GetName(), this ) )
return 0;
}
EndDialog( MACRO_OK_RUN );
}
else if ( pButton == &aCloseButton )
{
StoreMacroDescription();
EndDialog( MACRO_CLOSE );
}
else if ( ( pButton == &aEditButton ) || ( pButton == &aNewDelButton ) )
{
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pCurEntry ) );
ScriptDocument aDocument( aDesc.GetDocument() );
DBG_ASSERT( aDocument.isAlive(), "MacroChooser::ButtonHdl: no document, or document is dead!" );
if ( !aDocument.isAlive() )
return 0;
BasicManager* pBasMgr = aDocument.getBasicManager();
String aLib( aDesc.GetLibName() );
String aMod( aDesc.GetName() );
// extract the module name from the string like "Sheet1 (Example1)"
if( aDesc.GetLibSubName().Equals( String( IDEResId( RID_STR_DOCUMENT_OBJECTS ) ) ) )
{
sal_uInt16 nIndex = 0;
aMod = aMod.GetToken( 0, ' ', nIndex );
}
String aSub( aDesc.GetMethodName() );
SfxMacroInfoItem aInfoItem( SID_BASICIDE_ARG_MACROINFO, pBasMgr, aLib, aMod, aSub, String() );
if ( pButton == &aEditButton )
{
SvLBoxEntry* pEntry = aMacroBox.FirstSelected();
if ( pEntry )
aInfoItem.SetMethod( aMacroBox.GetEntryText( pEntry ) );
StoreMacroDescription();
SfxAllItemSet aArgs( SFX_APP()->GetPool() );
SfxRequest aRequest( SID_BASICIDE_APPEAR, SFX_CALLMODE_SYNCHRON, aArgs );
SFX_APP()->ExecuteSlot( aRequest );
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if( pDispatcher )
pDispatcher->Execute( SID_BASICIDE_EDITMACRO, SFX_CALLMODE_ASYNCHRON, &aInfoItem, 0L );
EndDialog( MACRO_EDIT );
}
else
{
if ( bNewDelIsDel )
{
DeleteMacro();
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if( pDispatcher )
{
pDispatcher->Execute( SID_BASICIDE_UPDATEMODULESOURCE,
SFX_CALLMODE_SYNCHRON, &aInfoItem, 0L );
}
CheckButtons();
UpdateFields();
//if ( aMacroBox.GetCurEntry() ) // OV-Bug ?
// aMacroBox.Select( aMacroBox.GetCurEntry() );
}
else
{
sal_Bool bValid = BasicIDE::IsValidSbxName( aMacroNameEdit.GetText() );
if ( !bValid )
{
ErrorBox( this, WB_OK | WB_DEF_OK, String( IDEResId( RID_STR_BADSBXNAME ) ) ).Execute();
aMacroNameEdit.SetSelection( Selection( 0, aMacroNameEdit.GetText().Len() ) );
aMacroNameEdit.GrabFocus();
return 1;
}
SbMethod* pMethod = CreateMacro();
if ( pMethod )
{
aInfoItem.SetMethod( pMethod->GetName() );
aInfoItem.SetModule( pMethod->GetModule()->GetName() );
aInfoItem.SetLib( pMethod->GetModule()->GetParent()->GetName() );
SfxAllItemSet aArgs( SFX_APP()->GetPool() );
SfxRequest aRequest( SID_BASICIDE_APPEAR, SFX_CALLMODE_SYNCHRON, aArgs );
SFX_APP()->ExecuteSlot( aRequest );
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if ( pDispatcher )
pDispatcher->Execute( SID_BASICIDE_EDITMACRO, SFX_CALLMODE_ASYNCHRON, &aInfoItem, 0L );
StoreMacroDescription();
EndDialog( MACRO_NEW );
}
}
}
}
else if ( pButton == &aAssignButton )
{
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pCurEntry ) );
ScriptDocument aDocument( aDesc.GetDocument() );
DBG_ASSERT( aDocument.isAlive(), "MacroChooser::ButtonHdl: no document, or document is dead!" );
if ( !aDocument.isAlive() )
return 0;
BasicManager* pBasMgr = aDocument.getBasicManager();
String aLib( aDesc.GetLibName() );
String aMod( aDesc.GetName() );
String aSub( aMacroNameEdit.GetText() );
SbMethod* pMethod = GetMacro();
DBG_ASSERT( pBasMgr, "BasMgr?" );
DBG_ASSERT( pMethod, "Method?" );
String aComment( GetInfo( pMethod ) );
SfxMacroInfoItem aItem( SID_MACROINFO, pBasMgr, aLib, aMod, aSub, aComment );
SfxAllItemSet Args( SFX_APP()->GetPool() );
SfxRequest aRequest( SID_CONFIG, SFX_CALLMODE_SYNCHRON, Args );
aRequest.AppendItem( aItem );
SFX_APP()->ExecuteSlot( aRequest );
}
else if ( pButton == &aNewLibButton )
{
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pCurEntry ) );
ScriptDocument aDocument( aDesc.GetDocument() );
createLibImpl( static_cast<Window*>( this ), aDocument, NULL, &aBasicBox );
}
else if ( pButton == &aNewModButton )
{
SvLBoxEntry* pCurEntry = aBasicBox.GetCurEntry();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( pCurEntry ) );
ScriptDocument aDocument( aDesc.GetDocument() );
String aLibName( aDesc.GetLibName() );
String aModName;
createModImpl( static_cast<Window*>( this ), aDocument,
aBasicBox, aLibName, aModName, true );
}
else if ( pButton == &aOrganizeButton )
{
StoreMacroDescription();
BasicEntryDescriptor aDesc( aBasicBox.GetEntryDescriptor( aBasicBox.FirstSelected() ) );
OrganizeDialog* pDlg = new OrganizeDialog( this, 0, aDesc );
sal_uInt16 nRet = pDlg->Execute();
delete pDlg;
if ( nRet ) // Nicht einfach nur geschlossen
{
EndDialog( MACRO_EDIT );
return 0;
}
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
if ( pIDEShell && pIDEShell->IsAppBasicModified() )
bForceStoreBasic = sal_True;
aBasicBox.UpdateEntries();
}
return 0;
}
void MacroChooser::UpdateFields()
{
SvLBoxEntry* pMacroEntry = aMacroBox.GetCurEntry();
String aEmptyStr;
aMacroNameEdit.SetText( aEmptyStr );
if ( pMacroEntry )
aMacroNameEdit.SetText( aMacroBox.GetEntryText( pMacroEntry ) );
}
void MacroChooser::SetMode( sal_uInt16 nM )
{
nMode = nM;
if ( nMode == MACROCHOOSER_ALL )
{
aRunButton.SetText( String( IDEResId( RID_STR_RUN ) ) );
EnableButton( aNewDelButton, sal_True );
EnableButton( aOrganizeButton, sal_True );
}
else if ( nMode == MACROCHOOSER_CHOOSEONLY )
{
aRunButton.SetText( String( IDEResId( RID_STR_CHOOSE ) ) );
EnableButton( aNewDelButton, sal_False );
EnableButton( aOrganizeButton, sal_False );
}
else if ( nMode == MACROCHOOSER_RECORDING )
{
aRunButton.SetText( String( IDEResId( RID_STR_RECORD ) ) );
EnableButton( aNewDelButton, sal_False );
EnableButton( aOrganizeButton, sal_False );
aAssignButton.Hide();
aEditButton.Hide();
aNewDelButton.Hide();
aOrganizeButton.Hide();
aMacroFromTxT.Hide();
aNewLibButton.Show();
aNewModButton.Show();
aMacrosSaveInTxt.Show();
Point aHelpPos = aHelpButton.GetPosPixel();
Point aHelpPosLogic = PixelToLogic( aHelpPos, MapMode(MAP_APPFONT) );
aHelpPosLogic.Y() -= 34;
aHelpPos = LogicToPixel( aHelpPosLogic, MapMode(MAP_APPFONT) );
aHelpButton.SetPosPixel( aHelpPos );
}
CheckButtons();
}
String MacroChooser::GetInfo( SbxVariable* pVar )
{
String aComment;
SbxInfoRef xInfo = pVar->GetInfo();
if ( xInfo.Is() )
aComment = xInfo->GetComment();
return aComment;
}
|
botikasm/lyj-framework | lyj-core/src/org/lyj/commons/io/chunks/FileChunks.java | <gh_stars>1-10
package org.lyj.commons.io.chunks;
import java.util.*;
public class FileChunks {
// ------------------------------------------------------------------------
// c o n s t
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// f i e l d s
// ------------------------------------------------------------------------
private final Set<ChunkInfo> _chunks;
private final String _uid;
// ------------------------------------------------------------------------
// c o n s t r u c t o r
// ------------------------------------------------------------------------
public FileChunks(final String uid) {
_chunks = new HashSet<>();
_uid = uid;
}
// ------------------------------------------------------------------------
// p u b l i c
// ------------------------------------------------------------------------
public String uid() {
return _uid;
}
public int count() {
return _chunks.size();
}
public void clear() {
_chunks.clear();
}
public ChunkInfo add(final String cache_key,
final int index,
final int total) {
final ChunkInfo info = new ChunkInfo(cache_key, index, total);
if (!_chunks.contains(info)) {
_chunks.add(info);
}
return info;
}
public boolean contains(final String cache_key) {
final ChunkInfo info = new ChunkInfo(cache_key);
return _chunks.contains(info);
}
public ChunkInfo remove(final String cache_key) {
final ChunkInfo info = new ChunkInfo(cache_key);
if (_chunks.remove(info)) {
return info;
}
return null;
}
public ChunkInfo[] sort() {
final List<ChunkInfo> list = new ArrayList<>(_chunks);
list.sort(Comparator.comparingInt(ChunkInfo::index));
return list.toArray(new ChunkInfo[0]);
}
public ChunkInfo[] data() {
return _chunks.toArray(new ChunkInfo[0]);
}
// ------------------------------------------------------------------------
// p r i v a t e
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// N E S T E D
// ------------------------------------------------------------------------
public class ChunkInfo {
private final String _cache_key;
private int _index;
private int _total;
public ChunkInfo(final String cache_key,
final int index,
final int total) {
_cache_key = cache_key;
_index = index;
_total = total;
}
public ChunkInfo(final String cache_key) {
_cache_key = cache_key;
_index = 0;
_total = 0;
}
@Override
public int hashCode() {
final int hash = 31 * _cache_key.hashCode();
return hash;
}
@Override
public boolean equals(final Object obj) {
return (this.hashCode() == obj.hashCode());
}
public String cacheKey() {
return _cache_key;
}
public int index() {
return _index;
}
public ChunkInfo index(final int value) {
_index = value;
return this;
}
public int total() {
return _total;
}
public ChunkInfo total(final int value) {
_total = value;
return this;
}
}
}
|
patmbolger/shf-project | spec/mailers/shf_application_mailer_spec.rb | require 'rails_helper'
require 'email_spec/rspec'
require File.join(__dir__, 'shared_email_tests')
require_relative './previews/shf_application_mailer_preview'
# Ensure that the mail can be created
# and the subject, recipient, and greeting are correct
#
RSpec.describe ShfApplicationMailer, type: :mailer do
include EmailSpec::Helpers
include EmailSpec::Matchers
let!(:test_user) { create(:user, email: '<EMAIL>') }
describe '#app_approved' do
let(:approved_text) { 'mailers.shf_application_mailer.app_approved.message_text' }
let(:accepted_app) { create(:shf_application, :accepted, user: test_user) }
let(:email_sent) { ShfApplicationMailer.app_approved(accepted_app) }
it_behaves_like 'a successfully created email to a member',
I18n.t('mailers.shf_application_mailer.app_approved.subject'),
'<EMAIL>',
'<NAME>' do
let(:email_created) { email_sent }
end
it 'says your app is approved' do
expect(email_sent).to have_body_text(I18n.t('app_approved_and_next', scope: approved_text))
end
describe 'has link to where to pay your membership fee' do
it 'html part has correct link' do
unless email_sent.html_part.nil?
expect(email_sent.html_part.body.encoded).to have_link(user_url(accepted_app.user))
end
end
it 'text part has correct link' do
unless email_sent.text_part.nil?
expect(email_sent.text_part).to have_body_text(user_url(accepted_app.user))
end
end
end
it 'closes with a thank you for wanting to be a member' do
expect(email_sent).to have_body_text(I18n.t('thanks', scope: approved_text))
end
context 'branding license fee is not paid' do
it 'says branding license fee payment ' do
expect(email_sent).to have_body_text(I18n.t('h_branding_not_paid', scope: approved_text))
end
end
context 'branding license fee IS paid' do
let(:user1) { create(:user) }
let(:co_branding_paid) {
co = create(:company, name: 'Paid Branding Company')
start_date, _expire_date = Company.next_branding_payment_dates(co.id)
payment_success = Payment.order_to_payment_status('successful')
create(:payment,
user: user1,
status: payment_success,
company: co,
payment_type: Payment::PAYMENT_TYPE_BRANDING,
notes: 'this company has paid their branding licensing fee on time',
start_date: start_date,
expire_date: Time.zone.today + 1.day) # so that is has not expired
co }
def make_branding_payment(a_company)
start_date, _expire_date = Company.next_branding_payment_dates(a_company.id)
create(:payment, user: user1, status: payment_success, company: a_company,
payment_type: Payment::PAYMENT_TYPE_BRANDING,
notes: 'this company has paid their branding licensing fee on time',
start_date: start_date,
expire_date: Time.zone.today + 1.day) # so that is has not expired
end
let(:accepted_app_branding_paid) {
create(:shf_application, :accepted, user: user1)
}
let(:email_sent_branding_paid) { ShfApplicationMailer.app_approved(accepted_app_branding_paid) }
it 'does not say branding license fee must be paid next' do
expect(email_sent_branding_paid).not_to have_body_text(I18n.t('how_to_pay_brandingfee', scope: approved_text))
end
end
end
describe '#acknowledge_received' do
let(:received_app) { create(:shf_application, user: test_user) }
let(:email_sent) { ShfApplicationMailer.acknowledge_received(received_app) }
it_behaves_like 'a successfully created email',
I18n.t('mailers.shf_application_mailer.acknowledge_received.subject'),
'<EMAIL>',
'<NAME>' do
let(:email_created) { email_sent }
end
end
it 'has a previewer' do
expect(ShfApplicationMailerPreview).to be
end
end
|
RedErr404/cprocessing | examples/Basics/Math/DoubleRandom/DoubleRandom.cpp | <gh_stars>10-100
#include <cprocessing/cprocessing.hpp>
using namespace cprocessing;
/**
* Double Random
* by <NAME>.
*
* Using two random() calls and the point() function
* to create an irregular sawtooth line.
*/
int totalPts = 300;
float steps = totalPts + 1;
void setup() {
size(640, 360);
stroke(255);
frameRate(1);
}
void draw() {
background(0);
float rand = 0;
for (int i = 1; i < steps; i++) {
point( (width/steps) * i, (height/2) + random(-rand, rand) );
rand += random(-5, 5);
}
}
|
BullFrog13/ProjectManager | src/app/main/editTimesheet/editTimesheet.controller.js | export default class TimesheetModalController {
constructor(TimesheetService) {
this.TimesheetService = TimesheetService;
}
$onInit() {
this.timesheet = angular.copy(this.resolve.timesheet);
}
cancel() {
this.close();
}
updateTimesheet() {
this.TimesheetService.updateTimesheet(this.timesheet);
this.close({ $value: this.timesheet });
}
} |
erard22/camel | components/camel-jgroups/src/test/java/org/apache/camel/component/jgroups/JGroupsSharedChannelTest.java | <filename>components/camel-jgroups/src/test/java/org/apache/camel/component/jgroups/JGroupsSharedChannelTest.java<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.jgroups;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
/**
* Test for shared channel in JGroups endpoint
*/
public class JGroupsSharedChannelTest extends CamelTestSupport {
private static final String JGROUPS_SHARED_CHANNEL = "jgroups:sharedChannel";
private static final String DIRECT_PRODUCER = "direct:producer";
private static final String MOCK_CONSUMER = "mock:consumer";
private static final String PRODUCER_ROUTE = "producerRoute";
private static final String CONSUMER_ROUTE = "consumerRoute";
private static final String TEST_MESSAGE = "Test Message";
@Test
public void testStopStartProducer() throws Exception {
context().getRouteController().stopRoute(PRODUCER_ROUTE);
context().getRouteController().startRoute(PRODUCER_ROUTE);
testSendReceive();
}
@Test
public void testStopStartConsumer() throws Exception {
context().getRouteController().stopRoute(CONSUMER_ROUTE);
template().sendBody(DIRECT_PRODUCER, TEST_MESSAGE);
context().getRouteController().startRoute(CONSUMER_ROUTE);
testSendReceive();
}
private void testSendReceive() throws InterruptedException {
template().sendBody(DIRECT_PRODUCER, TEST_MESSAGE);
final MockEndpoint mockEndpoint = getMockEndpoint(MOCK_CONSUMER);
mockEndpoint.expectedMinimumMessageCount(1);
mockEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(DIRECT_PRODUCER).routeId(PRODUCER_ROUTE).to(JGROUPS_SHARED_CHANNEL);
from(JGROUPS_SHARED_CHANNEL).routeId(CONSUMER_ROUTE).to(MOCK_CONSUMER);
}
};
}
}
|
JonesRobM/SAPPHIRE | main/Sapphire/CNA/FrameSignature_Ovito.py | <filename>main/Sapphire/CNA/FrameSignature_Ovito.py
# Import OVITO modules.
from ovito.io import *
from ovito.modifiers import *
from ovito.data import *
from ovito.io import import_file
from ovito.modifiers import CreateBondsModifier, CommonNeighborAnalysisModifier
from ovito.data import particles, BondsEnumerator
# Import standard Python and NumPy modules.
import numpy
import datetime
import platform
import getpass
import os
from Sapphire.CNA import Utilities
def cna_init(System = None, Pattern_Input = False):
System = System
if Pattern_Input:
Pattern_Input = Pattern_Input
filename = System['base_dir'] + System['movie_file_name']
if (os.path.exists(System['base_dir']+'CNA_npz/')):
pass
else:
os.mkdir(System['base_dir']+'CNA_npz/')
npz_dir = System['base_dir']+'CNA_npz/'
__version__ = '1.0.0'
Units = 'Angstrom & ev'
if Pattern_Input:
if not os.path.isfile(System['base_dir'] + 'CNA_Pattern_Info.txt'):
with open(System['base_dir'] + 'CNA_Pattern_Info.txt', 'w') as f:
f.write("""
_____ _____ _____ _ _ _____ _____ ______
/ ____| /\ | __ \| __ \| | | |_ _| __ \| ____| ____
| (___ / \ | |__) | |__) | |__| | | | | |__) | |__ /\__/\
\___ \ / /\ \ | ___/| ___/| __ | | | | _ /| __| /_/ \_\
____) / ____ \| | | | | | | |_| |_| | \ \| |____ \ \__/ /
|_____/_/ \_\_| |_| |_| |_|_____|_| \_\______| \/__\/
"""
"\nRunning version -- %s --\n"
"\nCurrent user is [ %s ]\n"
"\nCalculation beginning %s\n"
"\nArchitecture : [ %s ]\n"
"\nUnits : [ %s ]\n"
"\nThis file contains all of the user information regarding\nthe "
"CNA Pattern Recognition and the support vector model.\n"
%(__version__, getpass.getuser(), datetime.datetime.now().strftime("%a %d %b %Y %H:%M:%S"),
platform.machine(), Units)
)
def row_histogram(a):
ca = numpy.ascontiguousarray(a).view([('', a.dtype)] * a.shape[1])
unique, indices, inverse = numpy.unique(ca, return_index=True, return_inverse=True)
counts = numpy.bincount(inverse)
return (a[indices], counts)
class Frame_CNA_Sigs():
"""
Robert:
THIS FUNCTION HAS SINCE BEEN DEPRACATED!
PLEASE INSTEAD USE fRAMEsIGNATURE
This function takes the following input arguments:
frame: int - frame index of a movie.xyz trajectory.
R_Cut: float - Interatomic separation. Can be set manually or read in
by a higher function. It is advised that this is set for each metal individually
to ensure the most accurate and physically meaningful results.
Will default to a value for the most abundant metal in a system otherwise - To be implemented -
Masterkey: Tuple of tuples - Tells the programme which signatures are to be expected.
There will be a mode in which this may be appended to and saved in an external file for reference.
filename: str - self explanatory. where to find the file to be analysed.
Homo: Boolean - Whether or not to search for a single atomic specie. Default of false means that the atoms will
not be doctored prior to analysis.
Metal: str - The name of the specie to be removed.
Will output the following:
signature_cna: a*N array where a is the length of the masterkey & N is the number of atoms considered.
cna_pattern_indices: N dimensional list which tells you which pattern was found for each atom
signature_cna_count: gives the frequency of a given pattern.
May include a mode to write the patterns to a new file.
"""
def __init__(self, System, frame, R_Cut=None, Masterkey=None,
Type = None, Metal = None, Species = None,
Patterns = False, Fingerprint = None):
self.System = System
self.Frame = frame
self.R_Cut = R_Cut
self.Masterkey = Masterkey
self.Type = Type
self.Metal = Metal
self.Patterns = Patterns
self.Fingerprint = Fingerprint
self.Masterkey = ((0,0,0),
(1,0,0),
(2,0,0),(2,1,1),
(3,0,0),(3,1,1),(3,2,2),
(4,0,0),(4,1,1),(4,2,1),(4,2,2),(4,3,3),(4,4,4),
(5,2,1),(5,2,2),(5,3,2),(5,3,3),(5,4,4),(5,5,5),
(6,6,6))
self.Default = True
self.npz_dir = self.System['base_dir']+'CNA_npz/'
self.filename = self.System['base_dir'] + self.System['movie_file_name']
self.Pat_Key = Utilities.Pattern_Key().Key() #Calling dictionary of recognised patterns
self.Keys = list(self.Pat_Key)
self.Max_Label = max(len(str(label)) for label in self.Keys)
self.calculate()
self.write()
def ensure_dir(self, base_dir='', file_path=''):
"""
Robert:
A simple script to verify the existence of a directory
given the path to it. If it does not exist, will create it.
"""
directory = base_dir + file_path
if not os.path.exists(directory):
os.makedirs(directory)
def MakeFile(self, Attributes):
self.out = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']
if not os.path.isfile(self.out):
with open(self.System['base_dir'] + Attributes['Dir'] + Attributes['File'], 'w') as out:
out.close()
else:
pass
def Ascii_Bars(self, Finger):
with open(self.System['base_dir'] + 'CNA_Pattern_Info.txt', 'a', encoding='utf-8') as f:
f.write('\nCNA Pattern distribution for full system at frame %s.\n' %self.Frame)
Temp = numpy.zeros(len(self.Keys), int)
for atom in Finger:
if str(atom) in self.Keys:
Temp[self.Keys.index(str(atom))] += 1
with open(self.System['base_dir'] + 'CNA_Pattern_Info.txt', 'a', encoding='utf-8') as f:
for i, count in enumerate(Temp):
bar_chunks, remainder = divmod(int(count * 8 / (len(Finger) / 50)), 8)
# First draw the full width chunks
bar = '█' * bar_chunks
# Then add the fractional part. The Unicode code points for
# block elements are (8/8), (7/8), (6/8), ... , so we need to
# work backwards.
if remainder > 0:
bar += chr(ord('█')+ (8 - remainder))
# If the bar is empty, add a left one-eighth block
bar = bar or '|'
f.write(f'{self.Keys[i].rjust(self.Max_Label)} | {count:#4d} {bar}\n')
def calculate(self):
"""
if self.Homo:
self.pipeline.modifiers.append( SelectTypeModifier(property='Particle Type',
types={self.Metal}) )
self.pipeline.modifiers.append( DeleteSelectedModifier() )
"""
pipeline = import_file(self.filename)
pipeline.modifiers.append(CreateBondsModifier(cutoff = self.R_Cut))
pipeline.modifiers.append( CommonNeighborAnalysisModifier(
mode = CommonNeighborAnalysisModifier.Mode.BondBased))
data = pipeline.compute(self.Frame)
# The 'CNA Indices' bond property is a a two-dimensional array
# containing the three CNA indices computed for each bond in the system.
cna_indices = data.particles.bonds['CNA Indices']
# Used below for enumerating the bonds of each particle:
bond_enumerator = BondsEnumerator(data.particles.bonds)
particle_cnas = numpy.zeros((data.particles.count, len(self.Masterkey)), dtype=int)
for particle_index in range(data.particles.count):
# Create local list with CNA indices of the bonds of the current particle.
bond_index_list = list(bond_enumerator.bonds_of_particle(particle_index))
local_cna_indices = cna_indices[bond_index_list]
# Count how often each type of CNA triplet occurred.
unique_triplets, triplet_counts = row_histogram(local_cna_indices)
for triplet, count in zip(unique_triplets, triplet_counts):
try:
for index, signature in enumerate(self.Masterkey):
if(signature == tuple(triplet)):
particle_cnas[particle_index,index] = count
except KeyError:
pass
Finger = numpy.zeros(len(particle_cnas), dtype=numpy.ndarray)
for atom in range(len(particle_cnas)):
Temp = []
for i, x in enumerate(particle_cnas[atom]):
if x > 0:
Temp.append((x, self.Masterkey[i]))
Finger[atom] = Temp
Sigs = [ sum(particle_cnas[:,x]) for x in range(len(self.Masterkey)) ]
if (self.Fingerprint and self.Patterns):
if self.Type == 'Homo':
self.Ascii_Bars(Finger, True)
else:
self.Ascii_Bars(Finger)
self.Sigs = Sigs
if self.Patterns:
self.Finger = Finger
def write(self):
if self.Type == 'Full':
from Sapphire.Utilities import OutputInfoFull as Out # Case 1
#Write object for the CoM
Attributes = getattr(Out, str('cna_sigs')) #Loads in the write information for the object
OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']
self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir'])
self.MakeFile(Attributes)
with open(OutFile, 'a') as outfile:
outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Sigs) +'\n')
if self.Patterns:
#Write object for the homo CoM distances
Attributes = getattr(Out, str('pattern_indices')) #Loads in the write information for the object
OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']
self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir'])
self.MakeFile(Attributes)
with open(OutFile, 'a') as outfile:
outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Finger) +'\n') |
sirrah23/AddressBook | frontend/src/services/contact.js | export class ContactService {
constructor(contactNodeConnector, authToken) {
this.contactNodeConnector = contactNodeConnector;
this.authToken = authToken;
}
async getAllContacts() {
const res = await this.contactNodeConnector.sendGetAllContactsRequest(
this.authToken
);
return res;
}
}
|
jhh67/chapel | third-party/llvm/llvm-src/lib/CodeGen/PreISelIntrinsicLowering.cpp | //===- PreISelIntrinsicLowering.cpp - Pre-ISel intrinsic lowering pass ----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This pass implements IR lowering for the llvm.load.relative and llvm.objc.*
// intrinsics.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
using namespace llvm;
static bool lowerLoadRelative(Function &F) {
if (F.use_empty())
return false;
bool Changed = false;
Type *Int32Ty = Type::getInt32Ty(F.getContext());
Type *Int32PtrTy = Int32Ty->getPointerTo();
Type *Int8Ty = Type::getInt8Ty(F.getContext());
for (auto I = F.use_begin(), E = F.use_end(); I != E;) {
auto CI = dyn_cast<CallInst>(I->getUser());
++I;
if (!CI || CI->getCalledOperand() != &F)
continue;
IRBuilder<> B(CI);
Value *OffsetPtr =
B.CreateGEP(Int8Ty, CI->getArgOperand(0), CI->getArgOperand(1));
Value *OffsetPtrI32 = B.CreateBitCast(OffsetPtr, Int32PtrTy);
Value *OffsetI32 = B.CreateAlignedLoad(Int32Ty, OffsetPtrI32, Align(4));
Value *ResultPtr = B.CreateGEP(Int8Ty, CI->getArgOperand(0), OffsetI32);
CI->replaceAllUsesWith(ResultPtr);
CI->eraseFromParent();
Changed = true;
}
return Changed;
}
// ObjCARC has knowledge about whether an obj-c runtime function needs to be
// always tail-called or never tail-called.
static CallInst::TailCallKind getOverridingTailCallKind(const Function &F) {
objcarc::ARCInstKind Kind = objcarc::GetFunctionClass(&F);
if (objcarc::IsAlwaysTail(Kind))
return CallInst::TCK_Tail;
else if (objcarc::IsNeverTail(Kind))
return CallInst::TCK_NoTail;
return CallInst::TCK_None;
}
static bool lowerObjCCall(Function &F, const char *NewFn,
bool setNonLazyBind = false) {
if (F.use_empty())
return false;
// If we haven't already looked up this function, check to see if the
// program already contains a function with this name.
Module *M = F.getParent();
FunctionCallee FCache = M->getOrInsertFunction(NewFn, F.getFunctionType());
if (Function *Fn = dyn_cast<Function>(FCache.getCallee())) {
Fn->setLinkage(F.getLinkage());
if (setNonLazyBind && !Fn->isWeakForLinker()) {
// If we have Native ARC, set nonlazybind attribute for these APIs for
// performance.
Fn->addFnAttr(Attribute::NonLazyBind);
}
}
CallInst::TailCallKind OverridingTCK = getOverridingTailCallKind(F);
for (auto I = F.use_begin(), E = F.use_end(); I != E;) {
auto *CI = cast<CallInst>(I->getUser());
assert(CI->getCalledFunction() && "Cannot lower an indirect call!");
++I;
IRBuilder<> Builder(CI->getParent(), CI->getIterator());
SmallVector<Value *, 8> Args(CI->args());
CallInst *NewCI = Builder.CreateCall(FCache, Args);
NewCI->setName(CI->getName());
// Try to set the most appropriate TailCallKind based on both the current
// attributes and the ones that we could get from ObjCARC's special
// knowledge of the runtime functions.
//
// std::max respects both requirements of notail and tail here:
// * notail on either the call or from ObjCARC becomes notail
// * tail on either side is stronger than none, but not notail
CallInst::TailCallKind TCK = CI->getTailCallKind();
NewCI->setTailCallKind(std::max(TCK, OverridingTCK));
if (!CI->use_empty())
CI->replaceAllUsesWith(NewCI);
CI->eraseFromParent();
}
return true;
}
static bool lowerIntrinsics(Module &M) {
bool Changed = false;
for (Function &F : M) {
if (F.getName().startswith("llvm.load.relative.")) {
Changed |= lowerLoadRelative(F);
continue;
}
switch (F.getIntrinsicID()) {
default:
break;
case Intrinsic::objc_autorelease:
Changed |= lowerObjCCall(F, "objc_autorelease");
break;
case Intrinsic::objc_autoreleasePoolPop:
Changed |= lowerObjCCall(F, "objc_autoreleasePoolPop");
break;
case Intrinsic::objc_autoreleasePoolPush:
Changed |= lowerObjCCall(F, "objc_autoreleasePoolPush");
break;
case Intrinsic::objc_autoreleaseReturnValue:
Changed |= lowerObjCCall(F, "objc_autoreleaseReturnValue");
break;
case Intrinsic::objc_copyWeak:
Changed |= lowerObjCCall(F, "objc_copyWeak");
break;
case Intrinsic::objc_destroyWeak:
Changed |= lowerObjCCall(F, "objc_destroyWeak");
break;
case Intrinsic::objc_initWeak:
Changed |= lowerObjCCall(F, "objc_initWeak");
break;
case Intrinsic::objc_loadWeak:
Changed |= lowerObjCCall(F, "objc_loadWeak");
break;
case Intrinsic::objc_loadWeakRetained:
Changed |= lowerObjCCall(F, "objc_loadWeakRetained");
break;
case Intrinsic::objc_moveWeak:
Changed |= lowerObjCCall(F, "objc_moveWeak");
break;
case Intrinsic::objc_release:
Changed |= lowerObjCCall(F, "objc_release", true);
break;
case Intrinsic::objc_retain:
Changed |= lowerObjCCall(F, "objc_retain", true);
break;
case Intrinsic::objc_retainAutorelease:
Changed |= lowerObjCCall(F, "objc_retainAutorelease");
break;
case Intrinsic::objc_retainAutoreleaseReturnValue:
Changed |= lowerObjCCall(F, "objc_retainAutoreleaseReturnValue");
break;
case Intrinsic::objc_retainAutoreleasedReturnValue:
Changed |= lowerObjCCall(F, "objc_retainAutoreleasedReturnValue");
break;
case Intrinsic::objc_retainBlock:
Changed |= lowerObjCCall(F, "objc_retainBlock");
break;
case Intrinsic::objc_storeStrong:
Changed |= lowerObjCCall(F, "objc_storeStrong");
break;
case Intrinsic::objc_storeWeak:
Changed |= lowerObjCCall(F, "objc_storeWeak");
break;
case Intrinsic::objc_unsafeClaimAutoreleasedReturnValue:
Changed |= lowerObjCCall(F, "objc_unsafeClaimAutoreleasedReturnValue");
break;
case Intrinsic::objc_retainedObject:
Changed |= lowerObjCCall(F, "objc_retainedObject");
break;
case Intrinsic::objc_unretainedObject:
Changed |= lowerObjCCall(F, "objc_unretainedObject");
break;
case Intrinsic::objc_unretainedPointer:
Changed |= lowerObjCCall(F, "objc_unretainedPointer");
break;
case Intrinsic::objc_retain_autorelease:
Changed |= lowerObjCCall(F, "objc_retain_autorelease");
break;
case Intrinsic::objc_sync_enter:
Changed |= lowerObjCCall(F, "objc_sync_enter");
break;
case Intrinsic::objc_sync_exit:
Changed |= lowerObjCCall(F, "objc_sync_exit");
break;
}
}
return Changed;
}
namespace {
class PreISelIntrinsicLoweringLegacyPass : public ModulePass {
public:
static char ID;
PreISelIntrinsicLoweringLegacyPass() : ModulePass(ID) {}
bool runOnModule(Module &M) override { return lowerIntrinsics(M); }
};
} // end anonymous namespace
char PreISelIntrinsicLoweringLegacyPass::ID;
INITIALIZE_PASS(PreISelIntrinsicLoweringLegacyPass,
"pre-isel-intrinsic-lowering", "Pre-ISel Intrinsic Lowering",
false, false)
ModulePass *llvm::createPreISelIntrinsicLoweringPass() {
return new PreISelIntrinsicLoweringLegacyPass;
}
PreservedAnalyses PreISelIntrinsicLoweringPass::run(Module &M,
ModuleAnalysisManager &AM) {
if (!lowerIntrinsics(M))
return PreservedAnalyses::all();
else
return PreservedAnalyses::none();
}
|
zd938780519/YiDaoProject | yidao-system/src/main/java/com/ruoyi/system/mapper/YdUserAppealMapper.java | <filename>yidao-system/src/main/java/com/ruoyi/system/mapper/YdUserAppealMapper.java
package com.ruoyi.system.mapper;
import com.ruoyi.system.domain.YdUserAppeal;
/**
* 申诉数据访问层
*/
public interface YdUserAppealMapper {
/**
* 新增申诉数据
* @param ydUserAppeal
* @return
*/
public int insertUserAppeal(YdUserAppeal ydUserAppeal);
/**
* 修改申诉数据
* @param ydUserAppeal
* @return
*/
public int updateUserAppeal(YdUserAppeal ydUserAppeal);
/**
* 根据userId查询是否有未处理的申诉记录
* @param userId
* @return
*/
public int selectUserAppeal(long userId);
}
|
ckamtsikis/cmssw | Calibration/Tools/interface/TrackDetMatchInfoCollection.h | <filename>Calibration/Tools/interface/TrackDetMatchInfoCollection.h<gh_stars>10-100
#ifndef HTrackAssociator_HTrackDetMatchInfoCollection_h
#define HTrackAssociator_HTrackDetMatchInfoCollection_h
#include <vector>
#include "Calibration/Tools/interface/TrackDetMatchInfo.h"
typedef std::vector<HTrackDetMatchInfo> HTrackDetMatchInfoCollection;
#endif
|
fredemmott/jp | examples/simple/TextConsumer.rb | <reponame>fredemmott/jp<gh_stars>1-10
#!/usr/bin/env ruby
$LOAD_PATH.push '../../lib/rb'
require 'jp/consumer'
c = Jp::TextConsumer.new 'text' do |message|
print "I consumed a %s.\n" % message
true # must return something that evalutes to true in a boolean context, or purge() isn't called.
end
c.run
|
redNixon/eland | eland/client.py | <reponame>redNixon/eland<filename>eland/client.py
# Copyright 2019 Elasticsearch BV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from elasticsearch import Elasticsearch
from elasticsearch import helpers
class Client:
"""
eland client - implemented as facade to control access to Elasticsearch methods
"""
def __init__(self, es=None):
if isinstance(es, Elasticsearch):
self._es = es
elif isinstance(es, Client):
self._es = es._es
else:
self._es = Elasticsearch(es)
def index_create(self, **kwargs):
return self._es.indices.create(**kwargs)
def index_delete(self, **kwargs):
return self._es.indices.delete(**kwargs)
def index_exists(self, **kwargs):
return self._es.indices.exists(**kwargs)
def get_mapping(self, **kwargs):
return self._es.indices.get_mapping(**kwargs)
def bulk(self, actions, refresh=False):
return helpers.bulk(self._es, actions, refresh=refresh)
def scan(self, **kwargs):
return helpers.scan(self._es, **kwargs)
def search(self, **kwargs):
return self._es.search(**kwargs)
def field_caps(self, **kwargs):
return self._es.field_caps(**kwargs)
def count(self, **kwargs):
count_json = self._es.count(**kwargs)
return count_json["count"]
def perform_request(self, method, url, headers=None, params=None, body=None):
return self._es.transport.perform_request(method, url, headers, params, body)
|
nename0/moshi-java-codegen | test-adapters/src/test/java/com/github/nename0/moshi/java/codegen/SingleFieldTest.java | package com.github.nename0.moshi.java.codegen;
import com.github.nename0.moshi.java.codegen.model.simple.*;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonClass;
import com.squareup.moshi.JsonDataException;
import com.squareup.moshi.Moshi;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SingleFieldTest {
private final Moshi moshi = new Moshi.Builder()
.build();
@Test
public void singleFieldString() throws IOException {
assertThat(SingleFieldString.class.getAnnotation(JsonClass.class)).isNotNull();
JsonAdapter<SingleFieldString> adapter = moshi.adapter(SingleFieldString.class);
SingleFieldString fromModel = adapter.fromJson("{\"aString\": \"value\"}");
assertThat(fromModel).isNotNull();
assertThat(fromModel.aString).isEqualTo("value");
SingleFieldString toModel = new SingleFieldString();
toModel.aString = "Value2";
String json = adapter.toJson(toModel);
assertThat(json).isEqualTo("{\"aString\":\"Value2\"}");
// test serializeNulls
toModel.aString = null;
json = adapter.serializeNulls().toJson(toModel);
assertThat(json).isEqualTo("{\"" + "aString" + "\":null}");
// test non - serializeNulls
json = adapter.toJson(toModel);
assertThat(json).isEqualTo("{}");
JsonDataException failure = assertThrows(JsonDataException.class, () -> {
adapter.fromJson("{\"aString\": []}");
});
assertThat(failure).hasMessageThat().contains("Expected a string but was BEGIN_ARRAY");
}
@Test()
public void singleFieldInt() throws IOException {
assertThat(SingleFieldInt.class.getAnnotation(JsonClass.class)).isNotNull();
JsonAdapter<SingleFieldInt> adapter = moshi.adapter(SingleFieldInt.class);
SingleFieldInt fromModel = adapter.fromJson("{\"anInt\": 555}");
assertThat(fromModel).isNotNull();
assertThat(fromModel.anInt).isEqualTo(555);
SingleFieldInt toModel = new SingleFieldInt();
toModel.anInt = 345;
String json = adapter.toJson(toModel);
assertThat(json).isEqualTo("{\"anInt\":345}");
JsonDataException failure = assertThrows(JsonDataException.class, () -> {
adapter.fromJson("{\"anInt\": \"A\"}");
});
assertThat(failure).hasMessageThat().contains("Expected an int but was A");
failure = assertThrows(JsonDataException.class, () -> {
adapter.fromJson("{\"anInt\": null}");
});
assertThat(failure).hasMessageThat().contains("Expected an int but was NULL");
}
@Test()
public void singlePrivateField() throws IOException {
assertThat(SinglePrivateField.class.getAnnotation(JsonClass.class)).isNotNull();
JsonAdapter<SinglePrivateField> adapter = moshi.adapter(SinglePrivateField.class);
SinglePrivateField fromModel = adapter.fromJson("{\"anInt\": 987}");
assertThat(fromModel).isNotNull();
assertThat(fromModel.getAnInt()).isEqualTo(987);
SinglePrivateField toModel = new SinglePrivateField();
toModel.setAnInt(4711);
String json = adapter.toJson(toModel);
assertThat(json).isEqualTo("{\"anInt\":4711}");
JsonDataException failure = assertThrows(JsonDataException.class, () -> {
adapter.fromJson("{\"anInt\": \"A\"}");
});
assertThat(failure).hasMessageThat().contains("Expected an int but was A");
}
@Test()
public void singleRenamedField() throws IOException {
assertThat(SingleRenamedField.class.getAnnotation(JsonClass.class)).isNotNull();
JsonAdapter<SingleRenamedField> adapter = moshi.adapter(SingleRenamedField.class);
SingleRenamedField fromModel = adapter.fromJson("{\"boolean\": true}");
assertThat(fromModel).isNotNull();
assertThat(fromModel.aBoolean).isEqualTo(true);
SingleRenamedField toModel = new SingleRenamedField();
toModel.aBoolean = false;
String json = adapter.toJson(toModel);
assertThat(json).isEqualTo("{\"boolean\":false}");
JsonDataException failure = assertThrows(JsonDataException.class, () -> {
adapter.fromJson("{\"boolean\": 5555}");
});
assertThat(failure).hasMessageThat().contains("Expected a boolean but was NUMBER");
}
@Test()
public void singleRenamedPrivateField() throws IOException {
assertThat(SingleRenamedPrivateField.class.getAnnotation(JsonClass.class)).isNotNull();
JsonAdapter<SingleRenamedPrivateField> adapter = moshi.adapter(SingleRenamedPrivateField.class);
SingleRenamedPrivateField fromModel = adapter.fromJson("{\"byte\": 42}");
assertThat(fromModel).isNotNull();
assertThat(fromModel.getaByte()).isEqualTo(42);
SingleRenamedPrivateField toModel = new SingleRenamedPrivateField();
toModel.setaByte((byte) 127);
String json = adapter.toJson(toModel);
assertThat(json).isEqualTo("{\"byte\":127}");
JsonDataException failure = assertThrows(JsonDataException.class, () -> {
adapter.fromJson("{\"byte\": 5555}");
});
assertThat(failure).hasMessageThat().contains("Expected a byte but was 5555");
}
}
|
Traap/amber | lib/amber/tof/writers/latex/utility.rb | <reponame>Traap/amber
# LaTeX_Utility assembles the strings listed below which represent macros
# autodoc expands into the locations of files created by amber.
#
# (tpo) Test Plan Output
# (tso) Test Suite Output
# (tco) Test Case Output
#
# When browser and language are present:
# Note C: three parameters. C is third letter of English alphabet.
# \tpoC{Chrome}{en}{full-path-to/factory/plan/About/About.tex}
# \tsoC{Chrome}{en}{full-path-to/factory/suite/About/About.tex}
# \tcoC{Chrome}{en}{full-path-to/factory/case/About/About.tex}
#
# When browser and language are NOT present:
# \tpo{full-path-to/factory/plan/About/About.tex}
# \tso{full-path-to/factory/suite/About/About.tex}
# \tco{full-path-to/factory/case/About/About.tex}
#
# ------------------------------------------------------------------------------
require 'amber/cli/language'
require 'amber/cli/options'
require 'amber/tof/writers/latex/test'
module Amber
module LaTeXUtility
# --------------------------------------------------------------------------
def self.get_plan_macro(decoratee)
macro = ""
macro << '\\tpo' \
<< LaTeXUtility.append_browser_and_language(decoratee) \
<< LaTeXUtility.append_filename(decoratee)
end
# --------------------------------------------------------------------------
def self.get_suite_macro(decoratee)
macro = ""
macro << '\\tso' \
<< LaTeXUtility.append_browser_and_language(decoratee) \
<< LaTeXUtility.append_filename(decoratee)
end
# --------------------------------------------------------------------------
def self.get_case_macro(decoratee)
macro = ""
macro << '\\tco' \
<< LaTeXUtility.append_browser_and_language(decoratee) \
<< LaTeXUtility.append_filename(decoratee)
end
# --------------------------------------------------------------------------
def self.gather_browser_and_language(decoratee)
if decoratee.options.has_browser? && decoratee.options.has_language?
browser = decoratee.options.browser
language = decoratee.options.language
code = Amber::Language::CODE.key(language)
[browser, code]
end
end
# --------------------------------------------------------------------------
# def self.append_browser_and_language(macro, decoratee)
def self.append_browser_and_language(decoratee)
browser, code = Amber::LaTeXUtility.gather_browser_and_language(decoratee)
macro = ""
unless browser.nil? && code.nil? then
macro << 'C{' << browser << '}{' << code << '}'
end
macro
end
# --------------------------------------------------------------------------
# def self.append_filename(macro, decoratee)
def self.append_filename(decoratee)
pwd = FileUtils.pwd()
browser, code = Amber::LaTeXUtility.gather_browser_and_language(decoratee)
macro = ""
macro << '{' \
<< pwd << File::SEPARATOR \
<< TestEvidence::TEST_OUTPUT_DIR << File::SEPARATOR
macro << "#{browser}" << File::SEPARATOR unless browser.nil?
macro << "#{code}" << File::SEPARATOR unless code.nil?
macro << File.dirname(decoratee.filename) << File::SEPARATOR \
<< File.basename(decoratee.filename, '.*') \
<< '}' \
<< "\n"
end
# --------------------------------------------------------------------------
end
end
|
samuelcouch/the-blue-alliance | helpers/matchstats_helper.py | # Calculates OPR/DPR/CCWM
# For implementation details, see
# http://www.chiefdelphi.com/forums/showpost.php?p=484220&postcount=19
# M is n x n where n is # of teams
# s is n x 1 where n is # of teams
# solve [M][x]=[s] for [x]
# x is OPR and should be n x 1
import numpy as np
class MatchstatsHelper(object):
@classmethod
def calculate_matchstats(cls, matches):
parsed_matches_by_type, team_list, team_id_map = cls._parse_matches(matches)
oprs_dict = cls._calculate_stat(parsed_matches_by_type['opr'], team_list, team_id_map)
dprs_dict = cls._calculate_stat(parsed_matches_by_type['dpr'], team_list, team_id_map)
ccwms_dict = cls._calculate_stat(parsed_matches_by_type['ccwm'], team_list, team_id_map)
return {'oprs': oprs_dict, 'dprs': dprs_dict, 'ccwms': ccwms_dict}
@classmethod
def _calculate_stat(cls, parsed_matches, team_list, team_id_map):
"""
Returns: a dict where
key: a string representing a team number (Example: "254", "254B", "1114")
value: a float representing the stat (OPR/DPR/CCWM) for that team
"""
n = len(team_list)
M = np.zeros([n, n])
s = np.zeros([n, 1])
# Constructing M and s
for teams, score in parsed_matches:
for team1 in teams:
team1_id = team_id_map[team1]
for team2 in teams:
M[team1_id, team_id_map[team2]] += 1
s[team1_id] += score
# Solving M*x = s for x
try:
x = np.linalg.solve(M, s)
except (np.linalg.LinAlgError, ValueError):
return {}
stat_dict = {}
for team, stat in zip(team_list, x):
stat_dict[team] = stat[0]
return stat_dict
@classmethod
def _parse_matches(cls, matches):
"""
Returns:
parsed_matches_by_type: list of matches as the tuple ([team, team, team], <score/opposingscore/scoremargin>) for each key ('opr', 'dpr', 'ccwm')
team_list: list of strings representing team numbers. Example: "254", "254B", "1114"
team_id_map: dict that maps a team to a unique integer from 0 to n-1
"""
team_list = set()
parsed_matches_by_type = {
'opr': [],
'dpr': [],
'ccwm': [],
}
for match in matches:
if not match.has_been_played or match.comp_level != 'qm': # only calculate OPRs for played quals matches
continue
alliances = match.alliances
for alliance_color, opposing_color in zip(['red', 'blue'], ['blue', 'red']):
match_team_list = []
for team in alliances[alliance_color]['teams']:
team = team[3:] # turns "frc254B" into "254B"
team_list.add(team)
match_team_list.append(team)
alliance_score = int(alliances[alliance_color]['score'])
opposing_score = int(alliances[opposing_color]['score'])
parsed_matches_by_type['opr'].append((match_team_list, alliance_score))
parsed_matches_by_type['dpr'].append((match_team_list, opposing_score))
parsed_matches_by_type['ccwm'].append((match_team_list, alliance_score - opposing_score))
team_list = list(team_list)
team_id_map = {}
for i, team in enumerate(team_list):
team_id_map[team] = i
return parsed_matches_by_type, team_list, team_id_map
|
GaloisInc/BESSPIN-BSC | src/hdl/rtl_edit/ApplyChanges.cxx | // Copyright 2010 Bluespec Inc. All rights reserved
#include <dirent.h>
#include <sys/stat.h>
#include "ApplyChanges.h"
#include "HdlUtils.h"
#include "VeriModule.h"
#include "VeriLibrary.h"
#include "VeriExpression.h"
#include "VeriMisc.h"
#include "VeriId.h"
#include "veri_tokens.h"
#include "VeriConstVal.h"
#include "VeriScope.h"
#include "VeriModuleItem.h"
#include "VeriUtil_Stat.h"
#include "VeriNodeInfo.h"
#include "string.h"
#include <boost/regex.hpp>
int ApplyChanges::visit(class CktMod *) { return -1; }
int ApplyChanges::visit(class ChangeModuleName *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class ChangeInstModuleName *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class AddPort *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class AddInstanceConnection *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RenameInstanceConnection *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class AddNet *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class AddSimpleAssign *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class AddInstance *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RmInstance *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RmBody *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RmReg *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RmNet *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RmSimpleAssign *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class ChangeAssignRHS *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class RmCode *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class UpdateParam *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::visit(class ChangeFragmentFile *m)
{
if (!currentPassIs(3)) return 0;
//"sed -e 's/top./top.fpgaA.top_mkBridge_EDITED./' vlog_dut/scemilink.vlog_fragment > vlog_edited/scemilink.vlog_fragment"}}
BString ifilename( m->getInputDir());
ifilename += "/";
ifilename += "scemilink.vlog_fragment";
ifstream infile(ifilename.c_str());
if (infile.fail()) {
cerr << "ChageFragmentFile:: unable to open input file " << ifilename << endl;
return 1;
}
BString ofilename( m_output_dir);
ofilename += "/";
ofilename += "scemilink.vlog_fragment";
ofstream outfile(ofilename.c_str());
if (outfile.fail()) {
cerr << "ChageFragmentFile:: unable to open output file " << ofilename << endl;
return 1;
}
BString oldname (m->getOldName());
size_t oldlen = oldname.length();
BString linestr;
getline(infile,linestr); // Get the frist line from the file, if any.
while ( infile ) {
size_t pos = linestr.find(oldname);
if (pos != string::npos) {
// replace oldname with new name
linestr.replace(pos, oldlen, m->getNewName());
}
outfile << linestr << std::endl ;
linestr.clear();
getline(infile,linestr); // next line
}
infile.close();
outfile.close();
return 0;
}
// Collect info for the scan.map file
// this is the same either TextedBased or ParsedTree
int ApplyChanges::visit(class AddCosim *m)
{
char buf[1024];
if (!currentPassIs(1)) return 0;
cerr << "Adding scan chain info for cosim probe " << m->getName() << endl;
ScanDataList* datalist = m->getData();
for (ScanDataList::iterator iter = (*datalist).begin(); iter != (*datalist).end(); ++iter) {
ScanData & data = (**iter);
sprintf(buf, "p: %d %d %d\n", m->getKey(), data.getChain(), data.getWidth());
// sprintf(buf, "p: %d %d\n", data.getChain(), data.getWidth());
addPathInfo(buf);
sprintf(buf, "d: %d %s\n", m->getKey(), m->getDef().c_str());
// sprintf(buf, "d: %s\n", m->getDef().c_str());
addPathInfo(buf);
sprintf(buf, "i: %d %s\n", m->getKey(), m->getInst().c_str());
// sprintf(buf, "i: %d %s\n", m->getKey(), "/top");
addPathInfo(buf);
if (data.getFlavor() == Inputs || data.getFlavor() == InputsBB) {
sprintf(buf, "c: /%s\n", m->getClock().c_str());
addPathInfo(buf);
}
ScanPath* path = data.getPath();
addPathInfo(path->ToString("", "\n", "r: "));
}
return 0;
}
// this is the same either TextedBased or ParsedTree
int ApplyChanges::visit(class ReplaceModule *m)
{
if (!currentPassIs(0)) return 0;
VeriModule* module = veri_file::GetModule(m->getName().c_str());
if (!module) {
cerr << "Unable to resolve module " << m->getName().c_str() << endl;
return 0;
}
if (m_module == NULL) {
cerr << "Error ApplyChanges::visit(ReplaceModule): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
std::string new_module_name = m_new_modname[m_module];
m_module = module;
setLastPortLinefile();
clearModifications(m_module);
m_new_modname[m_module] = new_module_name;
return 1;
}
int ApplyChanges::visit(class RenameSignal *m)
{
return (m_textbased ? textBasedApply(m) : parsedTreeApply(m));
}
int ApplyChanges::parsedTreeApply(class ChangeModuleName *modification)
{
if (!currentPassIs(1)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(ChangeModuleName): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
//printf("Change Module Name: from %s to %s\n", m_module->Name(),
// modification->getName().c_str());
VeriIdDef *id = m_module->GetId();
if (id == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(ChangeModuleName): module "
<< modification->getInstName().c_str() << " has no VeriIdDef."
<< endl;
return 0;
}
VeriLibrary *lib = m_module->GetLibrary() ;
VeriScope *scope = m_module->GetScope() ;
VeriScope *container_scope = (scope) ? scope->Upper() : 0 ;
// First remove the module/id from its container:
if (lib) {
(void) lib->DetachModule(m_module) ;
} else if (container_scope) {
// Nested module:
(void) container_scope->Undeclare(id) ;
}
id->SetName(Strings::save(modification->getName().c_str()));
// Then, back insert into its container:
if (lib) {
(void) lib->AddModule(m_module) ;
} else if (container_scope) {
// Nested module:
(void) container_scope->Declare(id) ;
}
if (scope) {
scope->Declare(id);
id->SetLocalScope(scope);
}
return 1;
}
int ApplyChanges::textBasedApply(class ChangeModuleName *modification)
{
if (!currentPassIs(1)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(ChangeModuleName): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
std::string new_module_name = m_new_modname[m_module];
//printf("Change Module Name: from %s to %s\n", m_module->Name(), modification->getName().c_str());
if (0 == new_module_name.compare(modification->getName())) {
// printf("SKIP\n");
// return 1;
}
VeriIdDef *id = m_module->GetId();
// Form a pattern for replacing
/*
string modname_tmp = m_module->Name();
size_t pos = modname_tmp.find("_orig");
string modname = modname_tmp.substr(0,pos);
//cout << "modname " << modname << endl;
string pat("(\\s*)(");
pat += modname;
pat += ")(\\s*.*)";
cout << "Replace pattern " << pat << endl;
const boost::regex rpattern(pat,
boost::regex_constants::icase|boost::regex_constants::perl);
std::string newpat("\\1");
newpat += modification->getName();
newpat += "\\3";
cout << "New pattern " << newpat << endl;
*/
// Get the file position
linefile_type start_linefile = id->StartingLinefile();
// Get the text
//string linetext = m_tbdm.GetText(start_linefile, 1);
// Make substitution
//string newline = boost::regex_replace(linetext, rpattern, newpat);
// Replace the text in the file
m_tbdm.Replace(start_linefile, modification->getName().c_str());
m_new_modname[m_module] = modification->getName();
ModSetPath pair = ModSetPath(modification->getInstName(), modification->getModSet());
m_path_map[pair] = modification->rangeKey();
return 1;
}
int ApplyChanges::parsedTreeApply(class ChangeInstModuleName *modification)
{
if (!currentPassIs(2)) return 0;
unsigned ret = 1;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(ChangeInstModuleName): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
//printf("Change ModuleInst Name: from %s to %s\n", modification->getContainingInst().c_str(),
// modification->getName().c_str());
// Get the instance identifier
VeriIdDef *instance_id = m_module->FindDeclared(modification->getContainingInst().c_str());
// No instance named 'instance_name' exists
if (!instance_id || !instance_id->IsInst()) {
cerr << "Error ApplyChanges::parsedTreeApply(ChangeInstModuleName): instance "
<< modification->getContainingInst().c_str()
<< " of module "
<< modification->getInstName().c_str() << " is not found."
<< endl;
return 0 ;
}
VeriModuleInstantiation *moduleInst = instance_id->GetModuleInstance();
if (moduleInst == NULL) ret = 0;
if (ret) {
VeriName *vname = moduleInst->GetModuleNameRef();
if (vname == NULL)
ret = 0;
else
vname->SetName(Strings::save(modification->getName().c_str()));
}
if (ret == 0) {
cerr << "Error ApplyChanges::parsedTreeApply(ChangeInstModuleName): name change of instance "
<< modification->getInstName().c_str()
<< " failed."
<< endl;
return 0;
}
return ret;
}
int ApplyChanges::textBasedApply(class ChangeInstModuleName *modification)
{
if (!currentPassIs(2)) return 0;
unsigned ret = 1;
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(ChangeInstModuleName): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// printf("Change ModuleInst Name: from %s to %s\n", modification->getContainingInst().c_str(),
// modification->getName().c_str());
// Get the instance identifier
VeriIdDef *instance_id = m_module->FindDeclared(modification->getContainingInst().c_str());
if (modification->newInst()){
BString key = modification->getInstName();
key += "/";
key += modification->getContainingInst();
m_change_map[key] = modification;
}
// No instance named 'instance_name' exists
if (!instance_id || !instance_id->IsInst()) {
if (!modification->newInst()) {
cerr << "Error ApplyChanges::textBasedApply(ChangeInstModuleName): instance "
<< modification->getContainingInst().c_str()
<< " of module "
<< modification->getInstName().c_str() << " is not found."
<< endl;
}
return 0 ;
}
VeriModuleInstantiation *moduleInst = instance_id->GetModuleInstance();
if (moduleInst == NULL) ret = 0;
if (ret) {
VeriName *vname = moduleInst->GetModuleNameRef();
if (vname == NULL)
ret = 0;
else {
/*
// Form a pattern for replacing
string modname = vname->GetName();
//cout << "modname " << modname << endl;
string pat("(\\s*)(");
pat += modname;
pat += ")(\\s*.*)";
//cout << "Replace pattern " << pat << endl;
const boost::regex rpattern(pat,
boost::regex_constants::icase|boost::regex_constants::perl);
std::string newpat("\\1");
newpat += modification->getName();
newpat += "\\3";
//cout << "New pattern " << newpat << endl;
*/
// Get the file position
linefile_type start_linefile = vname->StartingLinefile();
//linefile_type end_linefile = vname->EndingLinefile();
// Get the text
//string linetext = m_tbdm.GetText(start_linefile, end_linefile, 1);
// Make substitution
//string newline = boost::regex_replace(linetext, rpattern, newpat);
unsigned int suffix = modification->getSuffix();
std::string name_new = modification->getName();
if (suffix > 0) {
std::map<unsigned int, unsigned int>::iterator iter = m_key_map.find(suffix);
if(iter == m_key_map.end())
{
name_new += "_";
name_new += itoa(suffix);
}
else
{
unsigned int mapped = (*iter).second;
name_new += "_";
name_new += itoa(mapped);
}
}
// Replace the text in the file
m_tbdm.Replace(start_linefile, name_new.c_str());
}
}
if (ret == 0) {
cerr << "Error ApplyChanges::textBasedApply(ChangeInstModuleName): name change of instance "
<< modification->getInstName().c_str()
<< " failed."
<< endl;
return 0;
}
return ret;
}
int ApplyChanges::parsedTreeApply(class AddPort *port)
{
if (!currentPassIs(1)) return 0;
unsigned portdir;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddPort): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
printf("AddPort1\n");
switch (port->getDirection()) {
case d_input:
portdir = VERI_INPUT;
break;
case d_output:
portdir = VERI_OUTPUT;
break;
case d_inout:
portdir = VERI_INOUT;
break;
default:
cerr << "Warning ApplyChanges::parsedTreeApply(AddPort): unknown port direction: "
<< port->getDirection()
<< endl;
break;
}
VeriRange *range = HdlUtils::mkVeriRangeFromWidth(port->getWidth());
VeriDataType *type = new VeriDataType(0, 0, range);
VeriIdDef *vport = m_module->AddPort(port->getPortName().c_str(), portdir, type);
if (vport) {
m_module_list.push_back(m_module);
}
else {
cerr << "Error ApplyChanges::parsedTreeApply(AddPort): failed adding port "
<< port->getPortName().c_str() << " to module "
<< m_module->Name() << endl;
return 0;
}
return 1;
}
int ApplyChanges::textBasedApply(class AddPort *port)
{
string portdir;
if (!currentPassIs(1)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(AddPort): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the port connection array of the first top level module.
Array *port_connects = m_module->GetPortConnects() ;
VeriExpression *last_port = (port_connects && port_connects->Size()) ? (VeriExpression*)port_connects->GetLast() : 0 ;
if (!last_port) {
cerr << "Warning ApplyChanges::parsedTreeApply(AddPort): Cannot find any port on module"
<< m_module->Name()
<< endl;
return 0;
}
linefile_type ending_linefile = last_port->EndingLinefile() ;
switch (port->getDirection()) {
case d_input:
portdir = "input";
break;
case d_output:
portdir = "output";
break;
case d_inout:
portdir = "inout";
break;
default:
cerr << "Warning ApplyChanges::parsedTreeApply(AddPort): unknown port direction: "
<< port->getDirection()
<< endl;
return 0;
}
// Here we are inserting a port reference after a specific port, so we have to insert a ','
// before the new port name. Please note that we don't check whether a port with this name
// (new_port) is already there in the module or not.
//cerr << "AddPort " << port->getPortName() << " module: " << m_module->Name() << endl;
if (last_port->IsAnsiPortDecl()) {
string portdecl = ", ";
portdecl += portdir;
portdecl += " ";
if (port->getWidth() > 1) {
std::stringstream out;
out << (port->getWidth()-1);
portdecl += "[" + out.str() + ":0] ";
}
portdecl += port->getPortName();
// It's an ANSI port declaration, so just insert another ANSI port
m_tbdm.InsertAfter(ending_linefile, portdecl.c_str());
} else {
string portdecl = ", ";
portdecl += port->getPortName();
// Its a non-ANSI port declaration, so insert the declaration both in port list and module item
m_tbdm.InsertAfter(ending_linefile, portdecl.c_str());
// Call InsertBefore of 'DesignModDir' utility
portdecl = portdir;
portdecl += " ";
if (port->getWidth() > 1) {
std::stringstream out;
out << (port->getWidth()-1);
portdecl += "[" + out.str() + ":0] ";
}
portdecl += port->getPortName();
portdecl += ";\n";
m_tbdm.InsertBefore(m_last_port_linefile, portdecl.c_str());
}
return 1;
}
int ApplyChanges::parsedTreeApply(class AddNet *net)
{
if (!currentPassIs(2)) return 0;
VeriIdDef *signal;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddNet): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
VeriRange *range = HdlUtils::mkVeriRangeFromWidth(net->getWidth());
signal = m_module->AddSignal(net->getName().c_str(), new VeriDataType(VERI_WIRE, 0, range), 0);
if (signal) {
m_module_list.push_back(m_module);
}
else {
cerr << "Error ApplyChanges::parsedTreeApply(AddNet): failed adding net "
<< net->getName().c_str() << " to module "
<< m_module->Name() << endl;
return 0;
}
return 1;
}
int ApplyChanges::textBasedApply(class AddNet *net)
{
string netdecl;
if (!currentPassIs(2)) return 0;
//cerr << "AddNet " << net->getName() << " module: " << m_module->Name() << endl;
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(AddNet): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
if (HdlUtils::findSignalInModuleByName(m_module, net->getName()))
return 1;
// Get the port connection array of the first top level module.
Array *port_connects = m_module->GetPortConnects() ;
VeriExpression *last_port = (port_connects && port_connects->Size()) ? (VeriExpression*)port_connects->GetLast() : 0 ;
// Conditional means that the port declaration in the module definition already
// has input/output declaraion, we cannot add a wire here or it would be syntax error.
if (!net->getConditional() || (last_port && !last_port->IsAnsiPortDecl())) {
linefile_type lf = m_module->Linefile();
linefile_type end_lf = (lf) ? lf->Copy() : 0 ;
if (end_lf) {
// Set the start line/col to be at 'e' of "endmodule" keyword:
end_lf->SetLeftLine(end_lf->GetRightLine()) ;
end_lf->SetLeftCol(end_lf->GetRightCol()-9) ;
}
// Call InsertBefore of 'DesignModDir' utility
netdecl += "wire ";
if (net->getWidth() > 1) {
std::stringstream out;
out << (net->getWidth()-1);
netdecl += "[" + out.str() + ":0] ";
}
netdecl += net->getName();
netdecl += ";\n";
m_tbdm.InsertBefore(m_last_port_linefile, netdecl.c_str());
//m_tbdm.InsertBefore(end_lf, netdecl.c_str());
}
return 1;
}
int ApplyChanges::parsedTreeApply(class AddInstanceConnection *modification)
{
unsigned ret;
if (!currentPassIs(2)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstanceConnection): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the instance identifier
VeriIdDef *instance_id = m_module->FindDeclared(modification->getContainingInst().c_str());
VeriInstId *inst;
// No instance named 'instance_name' exists
if (!instance_id || !instance_id->IsInst()) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstanceConnection): instance "
<< modification->getContainingInst().c_str()
<< " of module "
<< m_module->Name() << " is not found."
<< endl;
return 0 ;
}
else
inst = static_cast<class VeriInstId*>(instance_id);
string value = modification->getPortExpr();
string portname = modification->getPortName();
// Get the style of the port print
VariablePrintStyle style = HdlUtils::getPortConnectsPrintStyle(inst);
if (style == HdlKeyValuePairStyle) {
ret = HdlUtils::addPortRefKeyValue(m_module, inst, portname,
value);
}
else if (style == HdlPositionalStyle) {
ret = HdlUtils::addPortRefPositional(m_module, inst, value);
}
if (ret == 0) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstanceConnection): add portref to instance "
<< modification->getInstName().c_str()
<< " failed."
<< endl;
return 0;
}
return 1;
}
int ApplyChanges::textBasedApply(class AddInstanceConnection *modification)
{
string portdecl;
VeriInstId *inst;
if (!currentPassIs(2)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstanceConnection): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the instance identifier
VeriIdDef *instance_id = m_module->FindDeclared(modification->getContainingInst().c_str());
// No instance named 'instance_name' exists
if (!instance_id || !instance_id->IsInst()) {
cerr << "Error ApplyChanges::textBasedApply(AddInstanceConnection): instance "
<< modification->getContainingInst().c_str()
<< " of module "
<< modification->getInstName().c_str() << " is not found."
<< endl;
return 0 ;
} else {
inst = static_cast<class VeriInstId*>(instance_id);
}
Array *port_connects = inst->GetPortConnects();
VeriExpression *last_port = (port_connects && port_connects->Size()) ? (VeriExpression*)port_connects->GetLast() : 0 ;
if (!last_port) {
cerr << "Warning ApplyChanges::textBasedApply(AddInstanceConnection): Cannot find any port on instance"
<< modification->getContainingInst().c_str()
<< endl;
return 0;
}
// Get the starting location of first module item
linefile_type ending_linefile = last_port->EndingLinefile() ;
// Get the style of the port print
VariablePrintStyle style = HdlUtils::getPortConnectsPrintStyle(inst);
string value = modification->getPortExpr();
string portname = modification->getPortName();
if (style == HdlKeyValuePairStyle) {
portdecl = ", .";
portdecl = portdecl+portname+"("+value+")";
}
else if (style == HdlPositionalStyle) {
portdecl = ", ";
portdecl += value;
}
// Call InsertBefore of 'DesignModDir' utility
m_tbdm.InsertAfter(ending_linefile, portdecl.c_str());
return 1;
}
int ApplyChanges::parsedTreeApply(class RenameInstanceConnection *modification)
{
return 0;
}
int ApplyChanges::textBasedApply(class RenameInstanceConnection *modification)
{
string portdecl;
VeriInstId *inst;
if (!currentPassIs(2)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstanceConnection): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the instance identifier
VeriIdDef *instance_id = m_module->FindDeclared(modification->getContainingInst().c_str());
// No instance named 'instance_name' exists
if (!instance_id || !instance_id->IsInst()) {
cerr << "Error ApplyChanges::textBasedApply(AddInstanceConnection): instance "
<< modification->getContainingInst().c_str()
<< " of module "
<< modification->getInstName().c_str() << " is not found."
<< endl;
return 0 ;
} else {
inst = static_cast<class VeriInstId*>(instance_id);
}
Array *port_connects = inst->GetPortConnects();
VeriExpression *last_port = 0;
unsigned it;
VeriExpression *expr;
BString instportname;
FOREACH_ARRAY_ITEM(port_connects, it, expr) {
if (expr->GetClassId() == ID_VERIPORTCONNECT) {
instportname = expr->NamedFormal();
if (instportname == modification->getPortName()) {
last_port = expr;
}
}
}
if (!last_port) {
cerr << "Warning ApplyChanges::textBasedApply(AddInstanceConnection): Cannot find any port on instance"
<< modification->getContainingInst().c_str()
<< endl;
return 0;
}
// Get the starting location of first module item
linefile_type start_linefile = last_port->StartingLinefile() ;
// Get the style of the port print
VariablePrintStyle style = HdlUtils::getPortConnectsPrintStyle(inst);
string value = modification->getPortExpr();
string portname = modification->getPortName();
if (style == HdlKeyValuePairStyle) {
portdecl = ".";
portdecl = portdecl+portname+"("+value+")";
}
else if (style == HdlPositionalStyle) {
portdecl = "";
portdecl += value;
}
// Call InsertBefore of 'DesignModDir' utility
m_tbdm.Replace(start_linefile, portdecl.c_str());
return 1;
}
int ApplyChanges::parsedTreeApply(class AddSimpleAssign *assignment)
{
if (!currentPassIs(2)) return 0;
Array *assign_list = new Array (1) ;
//printf("AddSimpleAssign\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddSimpleAssign): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
VeriExpression *lhs = new VeriIdRef(Strings::save(assignment->getLeftHandSide().c_str()));
VeriExpression *rhs = new VeriIdRef(Strings::save(assignment->getRightHandSide().c_str()));
VeriNetRegAssign *assign = new VeriNetRegAssign(lhs, rhs);
assign_list->InsertLast(assign);
VeriContinuousAssign *continuous_assignment = new VeriContinuousAssign(0, 0, assign_list) ;
// Resolve reference, links VeriIdRef to VeriIdDef
continuous_assignment->Resolve(m_module->GetScope(), VeriTreeNode::VERI_UNDEF_ENV) ;
m_module->AddModuleItem(continuous_assignment);
return 1;
}
int ApplyChanges::textBasedApply(class AddSimpleAssign *assignment)
{
if (!currentPassIs(2)) return 0;
//printf("AddSimpleAssign\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddSimpleAssign): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
string assign = " assign " + assignment->getLeftHandSide() + " = " +
assignment->getRightHandSide() + ";\n";
linefile_type lf = m_module->Linefile();
linefile_type end_lf = (lf) ? lf->Copy() : 0 ;
if (end_lf) {
// Set the start line/col to be at 'e' of "endmodule" keyword:
end_lf->SetLeftLine(end_lf->GetRightLine()) ;
end_lf->SetLeftCol(end_lf->GetRightCol()-9) ;
}
m_tbdm.InsertBefore(end_lf, assign.c_str());
return 1;
}
int ApplyChanges::parsedTreeApply(class AddInstance *instAction)
{
if (!currentPassIs(2)) return 0;
VeriModuleInstantiation *moduleInst;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstance): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Construct the param values array
ParameterListIterator pit;
ParameterList &list = instAction->getParamList();
Array *param_values = new Array;
for(pit = list.begin(); pit != list.end(); pit++) {
VeriExpression *newparam = new VeriPortConnect(Strings::save((*pit).m_name.c_str()),
new VeriIntVal(atoi((*pit).m_value.c_str())));
if (newparam == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstance): cannot add param "
<< (*pit).m_name.c_str() << " on module "
<< m_module->Name() << "."
<< endl;
return 0;
}
param_values->InsertLast(newparam);
}
// Construct the inst (VeriInstId)
VeriInstId *inst;
inst = new VeriInstId(Strings::save(instAction->getLocalInstanceName().c_str()), 0, 0);
// Convert 'instantiated_component_name' into a VeriName
VeriIdRef *instantiated_module =
new VeriIdRef(Strings::save(instAction->getModuleName().c_str()));
// Construct VeriModuleInstantiation
moduleInst = new VeriModuleInstantiation(instantiated_module, 0,
param_values, inst, 0);
if (moduleInst) {
m_module->AddModuleItem(moduleInst);
m_module_list.push_back(m_module); // Put module in a list to be written out later
}
else {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstance): failed adding instance "
<< instAction->getLocalInstanceName().c_str() << " to module "
<< instAction->getModuleName().c_str() << endl;
return 0;
}
// Add new terminal from modification specifications
ModuleTerminalIterator mterm_it;
unsigned ret;
// Get the style of the port print
VariablePrintStyle style = HdlUtils::getPortConnectsPrintStyle(inst);
ModuleTerminalList &mterm_list = instAction->getPortList();
for(mterm_it = mterm_list.begin(); mterm_it != mterm_list.end(); mterm_it++) {
string portname = (*mterm_it).m_portName;
string netname = (*mterm_it).m_netName;
if (style == HdlKeyValuePairStyle) {
ret = HdlUtils::addPortRefKeyValue(m_module, inst, portname,
netname);
}
else if (style == HdlPositionalStyle) {
ret = HdlUtils::addPortRefPositional(m_module, inst, netname);
}
else ret = 0;
if (!ret)
cerr << "Error ApplyChanges::parsedTreeApply(AddInstance): failed adding portref "
<< (*mterm_it).m_portName.c_str() << " to instance "
<< instAction->getLocalInstanceName().c_str() << " in module "
<< instAction->getModuleName().c_str() << endl;
}
return 1;
}
int ApplyChanges::textBasedApply(class AddInstance *instAction)
{
if (!currentPassIs(3)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(AddInstance): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
BString key = instAction->getInstName();
key += "/";
key += instAction->getLocalInstanceName();
AddInstanceMap::iterator add_iter = m_add_map.find(key);
if(add_iter != m_add_map.end()) {
printf("Instance %s already added. Skipping AddInstance.\n", key.c_str());
return 0;
}
m_add_map[key] = instAction;
ChangeInstModuleNameMap::iterator iter = m_change_map.find(key);
string modname = instAction->getModuleName();
unsigned int suffix = instAction->getSuffix();
if(iter == m_change_map.end()) {
} else {
ChangeInstModuleName* c = (*iter).second;
modname = c->getName();
suffix = c->getSuffix();
}
if (suffix > 0) {
std::map<unsigned int, unsigned int>::iterator iter = m_key_map.find(suffix);
if(iter == m_key_map.end())
{
modname += "_";
modname += itoa(suffix);
}
else
{
unsigned int mapped = (*iter).second;
modname += "_";
modname += itoa(mapped);
}
}
// Module instantiation statement
string addinst = "\n " + modname;
// Add new terminal from modification specifications
ModuleTerminalIterator mterm_it;
ParameterListIterator param_it;
unsigned ret = 1;
// Get the style of the port print
VariablePrintStyle style = HdlKeyValuePairStyle;
// Parameter list
ParameterList ¶m_list = instAction->getParamList();
int firstTime = 1;
for(param_it = param_list.begin(); param_it != param_list.end(); param_it++) {
string paramname = (*param_it).m_name;
string paramvalue = (*param_it).m_value;
if (firstTime) {
addinst += " #(";
firstTime = 0;
} else {
addinst += ", ";
}
if (instAction->getOnePortPerLine() == true)
addinst += "\n ";
if (style == HdlKeyValuePairStyle) {
addinst += "." + paramname + "(" + paramvalue + ")";
}
else if (style == HdlPositionalStyle) {
addinst += paramvalue;
}
else ret = 0;
if (!ret)
cerr << "Error ApplyChanges::textBasedApply(AddInstance): failed adding parameter "
<< (*param_it).m_name.c_str() << " to instance "
<< instAction->getLocalInstanceName().c_str() << " in module "
<< instAction->getModuleName().c_str() << endl;
}
if (firstTime == 0)
addinst += ")";
addinst += " " + instAction->getLocalInstanceName();
// Terminal list
ModuleTerminalList &mterm_list = instAction->getPortList();
firstTime = 1;
for(mterm_it = mterm_list.begin(); mterm_it != mterm_list.end(); mterm_it++) {
string portname = (*mterm_it).m_portName;
string netname = (*mterm_it).m_netName;
if (firstTime) {
addinst += " (";
firstTime = 0;
} else {
addinst += ", ";
}
if (instAction->getOnePortPerLine() == true)
addinst += "\n ";
if (style == HdlKeyValuePairStyle) {
addinst += "." + portname + "(" + netname + ")";
}
else if (style == HdlPositionalStyle) {
addinst += netname;
}
else ret = 0;
if (!ret)
cerr << "Error ApplyChanges::textBasedApply(AddInstance): failed adding portref "
<< (*mterm_it).m_portName.c_str() << " to instance "
<< instAction->getLocalInstanceName().c_str() << " in module "
<< instAction->getModuleName().c_str() << endl;
}
if (firstTime == 0)
addinst += ");\n\n";
else
addinst += "();\n\n";
linefile_type lf = m_module->Linefile();
linefile_type end_lf = (lf) ? lf->Copy() : 0 ;
if (end_lf) {
// Set the start line/col to be at 'e' of "endmodule" keyword:
end_lf->SetLeftLine(end_lf->GetRightLine()) ;
end_lf->SetLeftCol(end_lf->GetRightCol()-9) ;
}
m_tbdm.InsertBefore(end_lf, addinst.c_str());
return 1;
}
linefile_type ApplyChanges::getLastComment(VeriModule *module)
{
Array *comments = module->GetComments();
VeriCommentNode *last_comment = (comments && comments->Size()) ?
(VeriCommentNode*)comments->GetLast() : 0 ;
if (!last_comment)
return 0;
linefile_type comment_linefile = last_comment->EndingLinefile();
// Get the starting location of first module item
linefile_type ending_linefile = module->EndingLinefile() ;
//cerr << "comment lineno: " << comment_linefile->GetRightLine() << " moduleitem lineno: "
// << ending_linefile->GetRightLine() << endl;
//cerr << "comments size: " << comments->Size() << endl;
//cerr << "comment: " << m_tbdm.GetText(comment_linefile, 1);
if (comment_linefile->GetRightLine() >= ending_linefile->GetRightLine())
if (comments->Size() >= 2) {
//cerr << "here" << endl;
last_comment = (VeriCommentNode*)comments->At(comments->Size()-2);
//cerr << "last comment address " << (void*)last_comment << endl;
//cerr << "last comment lineno: " << last_comment->EndingLinefile()->GetRightLine()
// << endl;
}
if (last_comment)
return last_comment->EndingLinefile();
return 0;
}
int ApplyChanges::parsedTreeApply(class RmInstance *instAction)
{
if (!currentPassIs(2)) return 0;
unsigned val;
//printf("RmInstance\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(RmInstance): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
val = m_module->RemoveInstance(instAction->getLocalInstanceName().c_str());
if (val) {
m_module_list.push_back(m_module);
}
else {
cerr << "Error ApplyChanges::parsedTreeApply(RmInstance): failed removing instance "
<< instAction->getLocalInstanceName().c_str() << " to module "
<< m_module->Name() << endl;
return 0;
}
return 1;
}
int ApplyChanges::textBasedApply(class RmInstance *instAction)
{
if (!currentPassIs(2)) return 0;
//printf("RmInstance\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(RmInstance): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the instance identifier
VeriIdDef *instance_id = m_module->FindDeclared(instAction->getLocalInstanceName().c_str());
//VeriInstId *inst;
// No instance named 'instance_name' exists
if (!instance_id || !instance_id->IsInst()) {
cerr << "Error ApplyChanges::textBasedApply(RmInstance): instance "
<< instAction->getLocalInstanceName().c_str()
<< " of module "
<< m_module->Name() << " is not found."
<< endl;
return 0 ;
}
//else
// inst = static_cast<class VeriInstId*>(instance_id);
VeriModuleInstantiation *moduleInst = instance_id->GetModuleInstance();
// Get the file position
linefile_type start_linefile = moduleInst->StartingLinefile();
//linefile_type end_linefile = moduleInst->EndingLinefile();
// Remove the statement
m_tbdm.Remove(start_linefile);
return 1;
}
int ApplyChanges::parsedTreeApply(class RmBody *action)
{
if (!currentPassIs(2)) return 0;
return 0;
}
int ApplyChanges::textBasedApply(class RmBody *action)
{
if (!currentPassIs(3)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(RmBody): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
linefile_type lf = m_module->Linefile();
linefile_type end_lf = (lf) ? lf->Copy() : 0 ;
if (end_lf) {
end_lf->SetLeftLine(end_lf->GetRightLine()) ;
}
m_tbdm.InsertBefore(end_lf, "");
lf = m_module->Linefile();
end_lf = (lf) ? lf->Copy() : 0 ;
if (end_lf) {
// Set the start line/col to be at 'e' of "endmodule" keyword:
end_lf->SetRightCol(0) ;
}
m_tbdm.Remove(m_last_port_linefile, end_lf);
m_tbdm.InsertAfter(end_lf, "endmodule");
return 1;
}
int ApplyChanges::parsedTreeApply(class RmReg *action)
{
if (!currentPassIs(2)) return 0;
return 0;
}
int ApplyChanges::textBasedApply(class RmReg *action)
{
if (!currentPassIs(2)) return 0;
//printf("In textBasedApply for RmReg\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(RmReg): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
//printf("MODULE %s\n", m_module->Name());
//printf("Now looking for signal %s\n", action->getRegName().c_str());
VeriIdDef *id = HdlUtils::findSignalInModuleByName(m_module, action->getRegName());
if (id && id->IsReg()) {
linefile_type start_linefile = id->StartingLinefile();
linefile_type end_linefile = start_linefile->Copy();
start_linefile->SetLeftCol(0);
end_linefile->SetRightLine(end_linefile->GetRightLine()+1);
end_linefile->SetRightCol(1);
m_tbdm.Remove(start_linefile, end_linefile);
}
else
printf("Not found\n");
return 1;
}
int ApplyChanges::parsedTreeApply(class RmNet *action)
{
if (!currentPassIs(2)) return 0;
return 0;
}
int ApplyChanges::parsedTreeApply(class RmSimpleAssign *action)
{
if (!currentPassIs(2)) return 0;
return 0;
}
int ApplyChanges::textBasedApply(class RmSimpleAssign *action)
{
if (!currentPassIs(2)) return 0;
//printf("In textBasedApply for RmNet\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(RmSimpleAssign): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
Array *items = m_module->GetModuleItems() ;
unsigned it;
VeriModuleItem *item;
//VeriIdRef *ref ;
BString lstring, rstring, expstring;
std::stringstream st;
FOREACH_ARRAY_ITEM(items, it, item) {
if (item->GetClassId() == ID_VERICONTINUOUSASSIGN) {
VeriContinuousAssign *cont_assign = dynamic_cast<VeriContinuousAssign *>(item) ;
Array *assigns = (cont_assign) ? cont_assign->GetNetAssigns() : 0 ;
if (!assigns) continue;
SignalVisitor v ;
unsigned i ;
VeriNetRegAssign *assign ;
FOREACH_ARRAY_ITEM(assigns, i, assign) {
if (!assign) continue ;
//printf("\nAssign statement: ");
//assign->PrettyPrint(cout, 0);
//cout << endl;
VeriExpression *lval = assign->GetLValExpr() ;
VeriExpression *rval = assign->GetRValExpr() ;
if ((lval == NULL) || (rval == NULL))
continue;
// Get the lhs value
lval->Accept(v);
st.str("");
lval->PrettyPrint(st, 0);
lstring = st.str();
v.ResetSignals();
if (lstring == action->getNetName()) {
linefile_type start_linefile = item->StartingLinefile();
linefile_type end_linefile = start_linefile->Copy();
start_linefile->SetLeftCol(0);
end_linefile->SetRightLine(end_linefile->GetRightLine()+1);
end_linefile->SetRightCol(1);
m_tbdm.Remove(start_linefile, end_linefile);
}
}
}
}
return 0;
}
int ApplyChanges::textBasedApply(class RmNet *action)
{
if (!currentPassIs(2)) return 0;
//printf("In textBasedApply for RmNet\n");
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(RmNet): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the scope of this module :
VeriScope *module_scope = m_module->GetScope() ;
// Now iterate over the declared identifiers ((VeriIdDef*s) in the hash table (scope->DeclArea()) in this scope :
MapIter mi ;
VeriIdDef *id ;
char *id_name ;
FOREACH_MAP_ITEM(module_scope->DeclArea(), mi, &id_name, &id) {
// Rule out all identifiers declared here, except for 'nets' :
if (!(id->IsNet() || id->IsReg())) continue ;
if (action->getNetName() == id->Name()) {
printf("RmNet Found signal %s\n", action->getNetName().c_str());
linefile_type start_linefile = id->StartingLinefile();
linefile_type end_linefile = start_linefile->Copy();
start_linefile->SetLeftCol(0);
end_linefile->SetRightLine(end_linefile->GetRightLine()+1);
end_linefile->SetRightCol(1);
m_tbdm.Remove(start_linefile, end_linefile);
}
}
Array *items = m_module->GetModuleItems() ;
unsigned it;
VeriModuleItem *item;
//VeriIdRef *ref ;
BString lstring, rstring, expstring;
std::stringstream st;
FOREACH_ARRAY_ITEM(items, it, item) {
if (item->GetClassId() == ID_VERICONTINUOUSASSIGN) {
VeriContinuousAssign *cont_assign = dynamic_cast<VeriContinuousAssign *>(item) ;
Array *assigns = (cont_assign) ? cont_assign->GetNetAssigns() : 0 ;
if (!assigns) continue;
SignalVisitor v ;
unsigned i ;
VeriNetRegAssign *assign ;
FOREACH_ARRAY_ITEM(assigns, i, assign) {
if (!assign) continue ;
//printf("\nAssign statement: ");
//assign->PrettyPrint(cout, 0);
//cout << endl;
VeriExpression *lval = assign->GetLValExpr() ;
VeriExpression *rval = assign->GetRValExpr() ;
if ((lval == NULL) || (rval == NULL))
continue;
// Get the lhs value
lval->Accept(v);
st.str("");
lval->PrettyPrint(st, 0);
lstring = st.str();
v.ResetSignals();
if (lstring == action->getNetName()) {
linefile_type start_linefile = item->StartingLinefile();
linefile_type end_linefile = start_linefile->Copy();
start_linefile->SetLeftCol(0);
end_linefile->SetRightLine(end_linefile->GetRightLine()+1);
end_linefile->SetRightCol(1);
m_tbdm.Remove(start_linefile, end_linefile);
}
}
}
}
return 0;
}
int ApplyChanges::parsedTreeApply(class ChangeAssignRHS *action)
{
if (!currentPassIs(2)) return 0;
return 0;
}
int ApplyChanges::textBasedApply(class ChangeAssignRHS *action)
{
if (!currentPassIs(2)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(RmNet): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
Array *items = m_module->GetModuleItems() ;
unsigned it;
VeriModuleItem *item;
VeriIdRef *ref ;
BString lstring, rstring, expstring;
std::stringstream st;
FOREACH_ARRAY_ITEM(items, it, item) {
if (item->GetClassId() == ID_VERICONTINUOUSASSIGN) {
VeriContinuousAssign *cont_assign = dynamic_cast<VeriContinuousAssign *>(item) ;
Array *assigns = (cont_assign) ? cont_assign->GetNetAssigns() : 0 ;
if (!assigns) continue;
SignalVisitor v ;
unsigned i ;
VeriNetRegAssign *assign ;
FOREACH_ARRAY_ITEM(assigns, i, assign) {
if (!assign) continue ;
VeriExpression *lval = assign->GetLValExpr() ;
VeriExpression *rval = assign->GetRValExpr() ;
if ((lval == NULL) || (rval == NULL))
continue;
// Get the lhs value
lval->Accept(v);
st.str("");
lval->PrettyPrint(st, 0);
lstring = st.str();
v.ResetSignals();
// If left hand side is not the one we want then go to the next
if (lstring != action->getLHS()) continue;
// Now do the rhs
rval->Accept(v);
if (v.NumSignals() < 1) { // Const case
if (rval->IsConst() || rval->IsConstExpr()) {
st.str("");
rval->PrettyPrint(st, 0);
rstring = st.str();
if (rstring == action->getRHS()) {
linefile_type start_linefile = rval->StartingLinefile();
m_tbdm.Replace(start_linefile, action->getNewRHS().c_str());
}
}
else {
st.str("");
assign->PrettyPrint(st, 0);
assign->Info("Something wrong, unrecognized Assignment Statement: %s",
st.str().c_str());
}
}
else if (v.NumSignals() == 1) { //
FOREACH_ARRAY_ITEM(v.GetSignals(), i, ref) {
st.str("");
ref->PrettyPrint(st, 0);
rstring = st.str();
}
}
else {
st.str("");
rval->PrettyPrint(st, 0);
expstring = st.str();
printf("RHS multiple signals\n");
FOREACH_ARRAY_ITEM(v.GetSignals(), i, ref) {
st.str("");
ref->PrettyPrint(st, 0);
rstring = st.str();
}
}
v.ResetSignals() ;
}
}
}
//linefile_type start_linefile = id->StartingLinefile();
//m_tbdm.Replace(start_linefile, action->getNewRHS().c_str());
return 0;
}
int ApplyChanges::parsedTreeApply(class RmCode *instAction)
{
if (!currentPassIs(2)) return 0;
return 0;
}
int ApplyChanges::textBasedApply(class RmCode *instAction)
{
if (!currentPassIs(2)) return 0;
const VeriModuleItem* item = instAction->getItem();
linefile_type start_linefile = item->StartingLinefile();
m_tbdm.InsertBefore(start_linefile, "/* ");
m_tbdm.InsertAfter(start_linefile, "*/ ");
return 0;
}
int ApplyChanges::parsedTreeApply(class UpdateParam *modification)
{
if (!currentPassIs(2)) return 0;
//printf("UpdateParam: %s %s\n", modification->getName().c_str(),
//modification->getValue().c_str());
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(UpdateParam): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the module item list of the module
VeriIdDef *param = m_module->GetParam(modification->getName().c_str());
if (param == 0) {
cerr << "Error ApplyChanges::parsedTreeApply(UpdateParam): something wrong, "
<< "param " << modification->getName() << " does not exist in module "
<< m_module->Name() << "." << endl;
return 0;
}
VeriConst *expr = HdlUtils::mkVeriConst(modification->getValue());
if (expr)
param->SetInitialValue(expr);
else
return 0;
return 1;
}
int ApplyChanges::textBasedApply(class UpdateParam *modification)
{
if (!currentPassIs(2)) return 0;
//printf("UpdateParam: %s %s\n", modification->getName().c_str(),
// modification->getValue().c_str());
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(UpdateParam): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// Get the module item list of the module
VeriIdDef *param = m_module->GetParam(modification->getName().c_str());
if (param == 0) {
cerr << "Error ApplyChanges::parsedTreeApply(UpdateParam): param "
<< modification->getName() << " does not exist in module "
<< m_module->Name() << "." << endl;
return 0;
}
VeriExpression *expr = param->GetInitialValue();
// Get the file position
linefile_type start_linefile = expr->StartingLinefile();
linefile_type end_linefile = expr->EndingLinefile();
// Replace the text in the file
m_tbdm.Replace(start_linefile, end_linefile, modification->getValue().c_str());
return 1;
}
void ApplyChanges::clearModifications(VeriModule *module)
{
linefile_type start_linefile = module->StartingLinefile();
unsigned file_id = start_linefile->GetFileId();
m_tbdm.ClearModifications(file_id);
}
string ApplyChanges::writeTextBasedChanges(VeriModule *module, BString & path, ModSet & modset, bool & is_top)
{
string out_filename;
std::ofstream out_file;
// If this is not text based mode then return
if (m_textbased == 0)
return "";
// First try to open the directory
DIR *dp;
if((dp = opendir(m_output_dir.c_str())) == NULL) {
if(mkdir(m_output_dir.c_str(), 0777) != 0) {
cerr << "Error opening directory " << m_output_dir << endl;
return "";
}
}
else
closedir(dp);
string new_module_name = m_new_modname[m_module];
linefile_type module_lf = module->StartingLinefile();
linefile_type begin_lf;
linefile_type prev_mod_lf = module->GetPreviousModuleLineFile();
if (prev_mod_lf) {
begin_lf = prev_mod_lf->Copy();
//Set the start line/col to be at the end of prev module:
if (prev_mod_lf->GetRightLine() == 1)
begin_lf->SetLeftLine(1);
else
begin_lf->SetLeftLine(prev_mod_lf->GetRightLine()+1);
begin_lf->SetLeftCol(1);
begin_lf->SetRightLine(module_lf->GetLeftLine());
begin_lf->SetRightCol(1);
//cerr << "Here is content from the end of prev module to this module: " << module->Name() << endl;
//cerr << m_tbdm.GetText(begin_lf, 0);
//cerr << "End of content\n";
} else { // This is the first module in the file
begin_lf = module_lf->Copy();
//Set to the start of the file
begin_lf->SetLeftLine(1);
begin_lf->SetLeftCol(1);
begin_lf->SetRightLine(module_lf->GetLeftLine());
begin_lf->SetRightCol(1);
//cerr << "Here is content from the beginning of the file to this module: " << module->Name() << endl;
//cerr << m_tbdm.GetText(begin_lf, 0);
//cerr << "End of beginning section\n";
}
VeriIdDef *id = m_module->GetId();
linefile_type id_linefile = id->StartingLinefile();
ModSetPath pair = ModSetPath(path, modset);
std::map<ModSetPath, unsigned int>::iterator iter = m_path_map.find(pair);
unsigned int key;
if (iter == m_path_map.end())
key = 0;
else
key = (*iter).second;
// printf("MOD: %d %s\n", key, name_current);
// const boost::regex rpattern(name_current);
// m_tbdm.Remove(id_linefile);
char *comment = m_tbdm.GetText(begin_lf, 0);
//printf("writeTextBasedChanges comment: %s\n", comment);
//printf("writeTextBasedChanges %s\n", out_filename.c_str());
char *file_content = m_tbdm.GetText(module_lf, 1);
// string generic = boost::regex_replace(string(file_content), rpattern, string(" module_|XXX"));
bool is_new = true;
if (key != 0) {
is_new = false;
std::map<string, unsigned int>::iterator iter = m_content_map.find(file_content);
if(iter == m_content_map.end())
{
is_new = true;
m_content_map[file_content] = key;
if (!is_top) {
std::string suffix = "_";
suffix += itoa(key);
m_tbdm.Replace(id_linefile, suffix.c_str());
}
// printf("MISS: %d\n", key);
}
else
{
int match_key = (*iter).second;
// printf("HIT! %d\n", match_key);
m_key_map[key] = match_key;
}
}
if (is_new)
{
char *file_content = m_tbdm.GetText(module_lf, 1);
out_filename = m_output_dir + "/" + new_module_name;
if (!is_top && key != 0) {
out_filename += "_";
out_filename += itoa(key);
}
BString fn = module_lf->GetFileName();
if (fn.find(".sv") != string::npos) {
out_filename += ".sv";
}
else {
out_filename += ".v";
}
// Write out the new content
out_file.open(out_filename.c_str(), ios_base::out);
out_file << comment;
out_file << file_content;
out_file << "\n";
out_file.close();
return out_filename;
}
else
{
return string("");
}
}
void ApplyChanges::writeParsedTreeChanges(BStringList &written_filenames,
const char *suffix)
{
VeriModule *module;
string outfile_name;
std::ofstream out_file;
//printf("writeChanges\n");
// If this is not parsed tree mode then return
if (m_textbased)
return;
// First try to open the directory
DIR *dp;
if((dp = opendir(m_output_dir.c_str())) == NULL) {
if(mkdir(m_output_dir.c_str(), 0777) != 0) {
cerr << "Error opening directory " << m_output_dir << endl;
return;
}
}
else
closedir(dp);
// Delete duplicate VeriModule in the list
m_module_list.unique();
VeriModuleListIterator it;
for (it = m_module_list.begin(); it != m_module_list.end(); it++) {
module = (*it);
if (out_file.is_open())
out_file.close();
outfile_name = m_output_dir;
outfile_name += "/";
outfile_name += module->GetName();
if (suffix)
outfile_name += suffix;
if (module->IsSystemVeri())
outfile_name += ".sv";
else {
outfile_name += ".v";
}
// Pass back the filename
written_filenames.push_back(outfile_name);
if (already_written[module] == 0) {
out_file.open(outfile_name.c_str(), ios_base::out);
already_written[module] = 1;
} else
out_file.open(outfile_name.c_str(), ios_base::app);
if (!out_file.is_open())
cerr << "Output file " << outfile_name.c_str() << " cannot be opened." << endl;
module->PrettyPrint(out_file, 0);
out_file.close();
}
//} else { // Text based manipulation
// Overwrite all the modified files: if they do not belong to the secure diretory this
// will not overwrite the file, instead will generate an warning message, otherwise it
// will overwrite the file as usual.
//m_tbdm.WriteDesign(0, m_output_dir.c_str());
// Remove all analyzed modules
//veri_file::RemoveAllModules() ;
//}
}
void ApplyChanges::setModuleContext(VeriModule *module)
{
m_module = module;
m_pass = 0;
setLastPortLinefile();
//Array *comments = module->GetComments();
//VeriCommentNode *c;
//unsigned i;
//c = (VeriCommentNode*)comments->GetFirst();
//linefile_type begin_lf = c->StartingLinefile();
//linefile_type module_lf = module->StartingLinefile();
//linefile_type end_lf = begin_lf->Copy();
// Set the start line/col to be at 'e' of "endmodule" keyword:
//end_lf->SetRightLine(module_lf->GetLeftLine()) ;
//end_lf->SetRightCol(module_lf->GetLeftCol()) ;
//cerr << m_tbdm.GetText(end_lf, 1);
//FOREACH_ARRAY_ITEM(comments, i, c) {
// if (c) {
// linefile_type lf = c->Linefile();
// cerr << endl;
// cerr << "comment " << i << ": " << m_tbdm.GetText(lf, 1);
// }
//}
}
void ApplyChanges::setLastPortLinefile()
{
// To insert input declaration in file as the first module item we have to get handle
// to module items and location of starting point of existing first module item.
if (m_module == NULL) {
cerr << "Error ApplyChanges::setLastPortLinefile(): something wrong, "
<< "module was not previously set."
<< endl;
return;
}
m_last_port_linefile = m_last_declare_linefile = NULL;
Array *ports = m_module->GetPorts();
VeriIdDef *portid;
unsigned lineno;
unsigned maxportlineno = 0;
unsigned lastmodlineno;
int i;
linefile_type port_linefile;
linefile_type module_linefile;
//linefile_type item_linefile;
module_linefile = m_module->EndingLinefile();
lastmodlineno = module_linefile->GetRightLine();
// Find the line number of the last port
FOREACH_ARRAY_ITEM(ports, i, portid) {
if (portid) {
port_linefile = portid->StartingLinefile() ;
if (port_linefile) {
lineno = port_linefile->GetLeftLine();
if ((lineno < lastmodlineno) && (lineno > maxportlineno))
maxportlineno = lineno;
}
}
}
// Find the line number of the last declaration
// Declaration is either; Port, Net, Reg, or Param.
Array *items = m_module->GetModuleItems() ;
VeriModuleItem *item = NULL;
/*
FOREACH_ARRAY_ITEM(items, i, item) {
if (item->GetId()->IsPort() || item->GetId()->IsNet() || item->GetId()->IsReg()
|| item->GetId()->IsParam()) {
item_linefile = item->StartingLinefile() ;
lineno = item_linefile->GetLeftLine();
if (lineno > maxdeclarelineno)
maxdeclarelineno = lineno;
}
}
*/
unsigned min_item_lineno = 99999999;
//unsigned min_declare_lineno = 99999999;
FOREACH_ARRAY_ITEM(items, i, item) {
// Find the linefile right after the last port
if ((lineno = item->StartingLinefile()->GetLeftLine()) > maxportlineno) {
if (lineno < min_item_lineno) {
min_item_lineno = lineno;
// This is the location of first item after the last existing ports
m_last_port_linefile = item->StartingLinefile() ;
break;
}
}
// Now find the linefile right after last declaration
/*
if ((item->GetId()->IsPort() || item->GetId()->IsNet() || item->GetId()->IsReg()
|| item->GetId()->IsParam()) && (lineno > maxdeclarelineno)) {
if (lineno < min_declare_lineno) {
min_declare_lineno = lineno;
// This is the location of first item after the last existing ports
m_last_declare_linefile = item->StartingLinefile() ;
}
}
*/
}
if (!item) {
cerr << "Error ApplyChanges::setLastPortLinefile(): "
<< "cannot find any module item in this module "
<< m_module->Name() << "." << endl;
return;
}
}
int ApplyChanges::parsedTreeApply(class RenameSignal *instAction)
{
if (!currentPassIs(2)) return 0;
// unsigned val;
if (m_module == NULL) {
cerr << "Error ApplyChanges::parsedTreeApply(RenameSignal): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
// no-op for now
// val = m_module->RemoveAssignment(instAction->getLocalAssignmentName().c_str());
// if (val) {
// m_module_list.push_back(m_module);
// }
// else {
// cerr << "Error ApplyChanges::parsedTreeApply(RenameSignal): failed removing instance "
// << instAction->getLocalAssignmentName().c_str() << " to module "
// << m_module->Name() << endl;
// return 0;
// }
return 1;
}
int ApplyChanges::textBasedApply(class RenameSignal *instAction)
{
if (!currentPassIs(2)) return 0;
if (m_module == NULL) {
cerr << "Error ApplyChanges::textBasedApply(RenameSignal): something wrong, "
<< "module was not previously set."
<< endl;
return 0;
}
if (instAction->includeDecls()) {
textRenameSignal(m_module, instAction->getName(), instAction->getNameNew());
} else {
Array *items = m_module->GetModuleItems() ;
VeriModuleItem *item = NULL;
int i;
FOREACH_ARRAY_ITEM(items, i, item) {
if (item->IsDataDecl()) continue;
textRenameSignal(item, instAction->getName(), instAction->getNameNew());
}
VeriIdDef* def = HdlUtils::findSignalInModuleByName(m_module, instAction->getName());
unsigned int size = HdlUtils::getSignalSize(def);
if (def->IsReg()) {
textAddSignal(m_module, instAction->getNameNew(), size, VERI_REG);
} else {
textAddSignal(m_module, instAction->getNameNew(), size, VERI_WIRE);
}
}
return 1;
}
void ApplyChanges::textRenameSignal(VeriTreeNode* node, const BString & name, const BString & name_new)
{
IdRefVisitor ref_visitor(name);
node->Accept(ref_visitor);
VeriIdRef* ref;
foreachSetRef(ref_visitor._refs, it) {
ref = (VeriIdRef*) *it;
printf("REF: %s\n", HdlUtils::getImage(ref));
linefile_type start_linefile = ref->StartingLinefile();
m_tbdm.Replace(start_linefile, name_new.c_str());
}
}
void ApplyChanges::textAddSignal(VeriModule* module, const BString & name, const unsigned & size, const unsigned & type)
{
BString netdecl = "";
linefile_type lf = module->Linefile();
linefile_type end_lf = (lf) ? lf->Copy() : 0 ;
if (end_lf) {
// Set the start line/col to be at 'e' of "endmodule" keyword:
end_lf->SetLeftLine(end_lf->GetRightLine()) ;
end_lf->SetLeftCol(end_lf->GetRightCol()-9) ;
}
// Call InsertBefore of 'DesignModDir' utility
if (type == VERI_REG) {
netdecl += "reg ";
} else {
netdecl += "wire ";
}
if (size > 1) {
netdecl += "[";
netdecl += itoa(size-1);
netdecl += ":0] ";
}
netdecl += name;
netdecl += ";\n";
m_tbdm.InsertBefore(m_last_port_linefile, netdecl.c_str());
}
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
int ApplyChanges::addPathInfo(BString info)
{
m_path_info += info;
return 0;
}
int ApplyChanges::writePathInfo()
{
std::string out_filename;
std::ofstream out_file;
// First try to open the directory
DIR *dp;
if((dp = opendir(m_output_dir.c_str())) == NULL) {
if(mkdir(m_output_dir.c_str(), 0777) != 0) {
cerr << "Error opening directory " << m_output_dir << endl;
return 1;
}
}
else
closedir(dp);
out_filename = m_output_dir + "/path.map";
out_file.open(out_filename.c_str(), ios_base::out);
out_file << m_path_info.c_str();
out_file << "\n";
out_file.close();
return 0;
}
|
imalpasha/meV2 | rhymecity/src/main/java/com/metech/firefly/api/ApiEndpoint.java | <filename>rhymecity/src/main/java/com/metech/firefly/api/ApiEndpoint.java
package com.metech.firefly.api;
import retrofit.Endpoint;
public class ApiEndpoint implements Endpoint {
@Override
public String getUrl() {
return "https://m.fireflyz.com.my/api";
//return "http://fyapidev.me-tech.com.my/api";
}
@Override
public String getName() {
return "Production Endpoint";
}
//
}
//http://sheetsu.com/apis/c4182617 |
faraz891/gitlabhq | spec/lib/bulk_imports/pipeline/context_spec.rb | <reponame>faraz891/gitlabhq
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe BulkImports::Pipeline::Context do
let_it_be(:user) { create(:user) }
let_it_be(:group) { create(:group) }
let_it_be(:bulk_import) { create(:bulk_import, user: user) }
let_it_be(:entity) do
create(
:bulk_import_entity,
source_full_path: 'source/full/path',
destination_name: 'My Destination Group',
destination_namespace: group.full_path,
group: group,
bulk_import: bulk_import
)
end
let_it_be(:tracker) do
create(
:bulk_import_tracker,
entity: entity,
pipeline_name: described_class.name
)
end
subject { described_class.new(tracker, extra: :data) }
describe '#entity' do
it { expect(subject.entity).to eq(entity) }
end
describe '#group' do
it { expect(subject.group).to eq(group) }
end
describe '#bulk_import' do
it { expect(subject.bulk_import).to eq(bulk_import) }
end
describe '#current_user' do
it { expect(subject.current_user).to eq(user) }
end
describe '#configuration' do
it { expect(subject.configuration).to eq(bulk_import.configuration) }
end
describe '#extra' do
it { expect(subject.extra).to eq(extra: :data) }
end
end
|
djangojeng-e/TIL | javascript/useful_javascript_syntax/part_06_structure_assignment.js | // objects
//
// const object = { a: 1, b: 2 };
// // const { a, b } = object;
// // console.log(a);
// // console.log(b);
// //
// // function print({a, b = 2}) {
// // console.log(a);
// // console.log(b || 2);
// // }
//
//
//
// const { a, b = 2 } = object;
// console.log(a);
// console.log(b);
//
//
// const animal = {
// name: '멍멍이',
// type: '개'
// };
//
// const { name: nickname } = animal;
//
// console.log(nickname);
// console.log(animal);
// const array = [ 1, 2 ];
//
// // const one = array[0];
// // const two = array[1];
//
// const [one, two = 2] = array;
//
// console.log(one);
// console.log(two);
//
const deepObject = {
state: {
information: {
name: 'django',
languages: ['korean', 'english', 'chinese']
}
},
value: 5
}
const { name, languages } = deepObject.state.information;
const { value } = deepObject;
const extracted = {
name,
languages,
value
};
console.log(extracted)
|
lucassaldanha/gpact | sdk/java/src/main/java/net/consensys/gpact/functioncall/gpact/GpactCrossControlManagerGroup.java | <filename>sdk/java/src/main/java/net/consensys/gpact/functioncall/gpact/GpactCrossControlManagerGroup.java<gh_stars>0
/*
* Copyright 2021 ConsenSys Software Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package net.consensys.gpact.functioncall.gpact;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.consensys.gpact.common.BlockchainConfig;
import net.consensys.gpact.common.BlockchainId;
import net.consensys.gpact.functioncall.CallExecutionTree;
import net.consensys.gpact.functioncall.CrossControlManager;
import net.consensys.gpact.functioncall.CrossControlManagerGroup;
import net.consensys.gpact.functioncall.CrosschainCallResult;
import net.consensys.gpact.functioncall.CrosschainFunctionCallException;
import net.consensys.gpact.functioncall.gpact.engine.ExecutionEngine;
import net.consensys.gpact.functioncall.gpact.engine.ParallelExecutionEngine;
import net.consensys.gpact.functioncall.gpact.engine.SerialExecutionEngine;
import net.consensys.gpact.messaging.MessagingVerificationInterface;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.web3j.crypto.Credentials;
public class GpactCrossControlManagerGroup implements CrossControlManagerGroup {
private static final Logger LOG = LogManager.getLogger(GpactCrossControlManagerGroup.class);
private final Map<BlockchainId, BcHolder> blockchains = new HashMap<>();
@Override
public void addBlockchainAndDeployContracts(
Credentials creds,
BlockchainConfig bcInfo,
MessagingVerificationInterface messageVerification)
throws Exception {
BlockchainId blockchainId = bcInfo.bcId;
if (this.blockchains.containsKey(blockchainId)) {
return;
}
LOG.debug("Deploying Cross-Blockchain Control contract for blockchain id {}", blockchainId);
BcHolder holder = new BcHolder();
holder.cbc =
new GpactCrossControlManager(
creds, bcInfo.bcId, bcInfo.uri, bcInfo.gasPriceStrategy, bcInfo.period);
holder.cbc.deployContract();
holder.cbcContractAddress = holder.cbc.getCbcContractAddress();
holder.ver = messageVerification;
this.blockchains.put(blockchainId, holder);
}
@Override
public void addBlockchainAndLoadCbcContract(
Credentials creds,
BlockchainConfig bcInfo,
String cbcAddress,
MessagingVerificationInterface messageVerification)
throws Exception {
BlockchainId blockchainId = bcInfo.bcId;
if (this.blockchains.containsKey(blockchainId)) {
return;
}
BcHolder holder = new BcHolder();
holder.cbc =
new GpactCrossControlManager(
creds, bcInfo.bcId, bcInfo.uri, bcInfo.gasPriceStrategy, bcInfo.period);
holder.cbc.loadContract(cbcAddress);
holder.cbcContractAddress = cbcAddress;
holder.ver = messageVerification;
this.blockchains.put(blockchainId, holder);
}
@Override
public CrosschainCallResult executeCrosschainCall(
String executionEngine, CallExecutionTree callTree, long timeout)
throws CrosschainFunctionCallException {
GpactCrosschainExecutor executor = new GpactCrosschainExecutor(this);
ExecutionEngine engine = null;
if (executionEngine.equalsIgnoreCase("SERIAL")) {
engine = new SerialExecutionEngine(executor);
} else if (executionEngine.equalsIgnoreCase("PARALLEL")) {
engine = new ParallelExecutionEngine(executor);
} else {
throw new CrosschainFunctionCallException("Unknown execution engine: " + executionEngine);
}
try {
return engine.execute(callTree, timeout);
} catch (Exception ex) {
throw new CrosschainFunctionCallException("Exception while executing crosschain call", ex);
}
}
@Override
public CrossControlManager getCbcManager(BlockchainId bcId)
throws CrosschainFunctionCallException {
if (!this.blockchains.containsKey(bcId)) {
throw new CrosschainFunctionCallException("Unknown blockchain: " + bcId);
}
return this.blockchains.get(bcId).cbc;
}
@Override
public MessagingVerificationInterface getMessageVerification(BlockchainId bcId)
throws CrosschainFunctionCallException {
if (!this.blockchains.containsKey(bcId)) {
throw new CrosschainFunctionCallException("Unknown blockchain: " + bcId);
}
return this.blockchains.get(bcId).ver;
}
@Override
public String getCbcAddress(BlockchainId bcId) throws CrosschainFunctionCallException {
if (!this.blockchains.containsKey(bcId)) {
throw new CrosschainFunctionCallException("Unknown blockchain: " + bcId);
}
return this.blockchains.get(bcId).cbcContractAddress;
}
@Override
public ArrayList<BlockchainId> getAllBlockchainIds() {
ArrayList<BlockchainId> bcIds = new ArrayList<>();
bcIds.addAll(this.blockchains.keySet());
return bcIds;
}
private static class BcHolder {
GpactCrossControlManager cbc;
String cbcContractAddress;
MessagingVerificationInterface ver;
}
}
|
jasonfan1997/threeML | threeML/config/fitting_structure.py | <reponame>jasonfan1997/threeML
from dataclasses import dataclass, field
from enum import Enum, Flag
from typing import Any, Dict, List, Optional
import numpy as np
import matplotlib.pyplot as plt
from omegaconf import II, MISSING, SI, OmegaConf
from .plotting_structure import CornerStyle, MPLCmap
class Sampler(Enum):
emcee = "emcee"
multinest = "multinest"
zeus = "zeus"
dynesty_nested = "dynesty_nested"
dynesty_dynamic = "dynesty_dynamic"
ultranest = "ultranest"
autoemcee = "autoemcee"
_sampler_default = {'emcee': {'n_burnin': 1}}
class Optimizer(Enum):
minuit = "minuit"
scipy = "scipy"
ROOT = "ROOT"
@dataclass
class BayesianDefault:
default_sampler: Sampler = Sampler.emcee
emcee_setup: Optional[Dict[str, Any]] = field(
default_factory=lambda: {'n_burnin': None,
'n_iterations': 500,
"n_walkers": 50,
"seed": 5123})
multinest_setup: Optional[Dict[str, Any]] = field(
default_factory=lambda: {'n_live_points': 400,
'chain_name': "chains/fit-",
"resume": False,
"importance_nested_sampling": False,
"auto_clean": False,
})
ultranest_setup: Optional[Dict[str, Any]] = field(
default_factory=lambda: { "min_num_live_points":400,
"dlogz":0.5,
"dKL": 0.5,
"frac_remain": 0.01,
"Lepsilon": 0.001,
"min_ess": 400,
"update_interval_volume_fraction":0.8,
"cluster_num_live_points":40,
"use_mlfriends": True,
"resume": 'overwrite' }
)
zeus_setup: Optional[Dict[str, Any]] = field(
default_factory=lambda: {'n_burnin': None,
'n_iterations': 500,
"n_walkers": 50,
"seed": 5123})
dynesty_nested_setup: Optional[Dict[str, Any]] = field(
default_factory=lambda: { "n_live_points": 400,
"maxiter": None,
"maxcall": None,
"dlogz": None,
"logl_max": np.inf,
"n_effective": None,
"add_live": True,
"print_func": None,
"save_bounds":True,
"bound":"multi",
"wrapped_params": None,
"sample": "auto",
"periodic": None,
"reflective": None,
"update_interval": None,
"first_update": None,
"npdim": None,
"rstate": None,
"use_pool": None,
"live_points": None,
"logl_args": None,
"logl_kwargs": None,
"ptform_args": None,
"ptform_kwargs": None,
"gradient": None,
"grad_args": None,
"grad_kwargs": None,
"compute_jac": False,
"enlarge": None,
"bootstrap": 0,
"vol_dec": 0.5,
"vol_check": 2.0,
"walks": 25,
"facc": 0.5,
"slices": 5,
"fmove": 0.9,
"max_move": 100,
"update_func": None,
})
dynesty_dynmaic_setup: Optional[Dict[str, Any]] = field(
default_factory=lambda: {
"nlive_init": 500,
"maxiter_init": None,
"maxcall_init": None,
"dlogz_init": 0.01,
"logl_max_init": np.inf,
"n_effective_init": np.inf,
"nlive_batch": 500,
"wt_function": None,
"wt_kwargs": None,
"maxiter_batch": None,
"maxcall_batch": None,
"maxiter": None,
"maxcall": None,
"maxbatch": None,
"n_effective": np.inf,
"stop_function": None,
"stop_kwargs": None,
"use_stop": True,
"save_bounds": True,
"print_func": None,
"live_points": None,
"bound":"multi",
"wrapped_params": None,
"sample":"auto",
"periodic": None,
"reflective": None,
"update_interval": None,
"first_update": None,
"npdim": None,
"rstate": None,
"use_pool": None,
"logl_args": None,
"logl_kwargs": None,
"ptform_args": None,
"ptform_kwargs": None,
"gradient": None,
"grad_args": None,
"grad_kwargs": None,
"compute_jac": False,
"enlarge": None,
"bootstrap": 0,
"vol_dec": 0.5,
"vol_check": 2.0,
"walks": 25,
"facc": 0.5,
"slices": 5,
"fmove": 0.9,
"max_move": 100,
"update_func": None,
})
corner_style: CornerStyle =CornerStyle()
@dataclass
class MLEDefault:
default_minimizer: Optimizer = Optimizer.minuit
default_minimizer_algorithm: Optional[str] = None
default_minimizer_callback: Optional[str] = None
contour_cmap: MPLCmap = MPLCmap.Pastel1
contour_background: str = 'white'
contour_level_1: str = '#ffa372'
contour_level_2: str = '#ed6663'
contour_level_3: str = '#0f4c81'
profile_color: str = 'k'
profile_level_1: str = '#ffa372'
profile_level_2: str = '#ed6663'
profile_level_3: str = '#0f4c81'
|
nikolaymatrosov/yc-ts-sdk | lib/generated/yandex/cloud/compute/v1/disk_placement_group_service.js | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiskPlacementGroupServiceClient = exports.DiskPlacementGroupServiceService = exports.ListDiskPlacementGroupOperationsResponse = exports.ListDiskPlacementGroupOperationsRequest = exports.ListDiskPlacementGroupDisksResponse = exports.ListDiskPlacementGroupDisksRequest = exports.DeleteDiskPlacementGroupMetadata = exports.DeleteDiskPlacementGroupRequest = exports.UpdateDiskPlacementGroupMetadata = exports.UpdateDiskPlacementGroupRequest_LabelsEntry = exports.UpdateDiskPlacementGroupRequest = exports.CreateDiskPlacementGroupMetadata = exports.CreateDiskPlacementGroupRequest_LabelsEntry = exports.CreateDiskPlacementGroupRequest = exports.ListDiskPlacementGroupsResponse = exports.ListDiskPlacementGroupsRequest = exports.GetDiskPlacementGroupRequest = exports.protobufPackage = void 0;
/* eslint-disable */
const field_mask_1 = require("../../../../google/protobuf/field_mask");
const typeRegistry_1 = require("../../../../typeRegistry");
const disk_1 = require("../../../../yandex/cloud/compute/v1/disk");
const disk_placement_group_1 = require("../../../../yandex/cloud/compute/v1/disk_placement_group");
const operation_1 = require("../../../../yandex/cloud/operation/operation");
const grpc_js_1 = require("@grpc/grpc-js");
const long_1 = __importDefault(require("long"));
const minimal_1 = __importDefault(require("protobufjs/minimal"));
exports.protobufPackage = 'yandex.cloud.compute.v1';
const baseGetDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.GetDiskPlacementGroupRequest',
diskPlacementGroupId: '',
};
exports.GetDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.GetDiskPlacementGroupRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseGetDiskPlacementGroupRequest,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseGetDiskPlacementGroupRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
return obj;
},
fromPartial(object) {
const message = {
...baseGetDiskPlacementGroupRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.GetDiskPlacementGroupRequest.$type, exports.GetDiskPlacementGroupRequest);
const baseListDiskPlacementGroupsRequest = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupsRequest',
folderId: '',
pageSize: 0,
pageToken: '',
filter: '',
};
exports.ListDiskPlacementGroupsRequest = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupsRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.folderId !== '') {
writer.uint32(10).string(message.folderId);
}
if (message.pageSize !== 0) {
writer.uint32(16).int64(message.pageSize);
}
if (message.pageToken !== '') {
writer.uint32(26).string(message.pageToken);
}
if (message.filter !== '') {
writer.uint32(34).string(message.filter);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseListDiskPlacementGroupsRequest,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.folderId = reader.string();
break;
case 2:
message.pageSize = longToNumber(reader.int64());
break;
case 3:
message.pageToken = reader.string();
break;
case 4:
message.filter = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseListDiskPlacementGroupsRequest,
};
if (object.folderId !== undefined && object.folderId !== null) {
message.folderId = String(object.folderId);
}
else {
message.folderId = '';
}
if (object.pageSize !== undefined && object.pageSize !== null) {
message.pageSize = Number(object.pageSize);
}
else {
message.pageSize = 0;
}
if (object.pageToken !== undefined && object.pageToken !== null) {
message.pageToken = String(object.pageToken);
}
else {
message.pageToken = '';
}
if (object.filter !== undefined && object.filter !== null) {
message.filter = String(object.filter);
}
else {
message.filter = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.folderId !== undefined && (obj.folderId = message.folderId);
message.pageSize !== undefined && (obj.pageSize = message.pageSize);
message.pageToken !== undefined && (obj.pageToken = message.pageToken);
message.filter !== undefined && (obj.filter = message.filter);
return obj;
},
fromPartial(object) {
const message = {
...baseListDiskPlacementGroupsRequest,
};
if (object.folderId !== undefined && object.folderId !== null) {
message.folderId = object.folderId;
}
else {
message.folderId = '';
}
if (object.pageSize !== undefined && object.pageSize !== null) {
message.pageSize = object.pageSize;
}
else {
message.pageSize = 0;
}
if (object.pageToken !== undefined && object.pageToken !== null) {
message.pageToken = object.pageToken;
}
else {
message.pageToken = '';
}
if (object.filter !== undefined && object.filter !== null) {
message.filter = object.filter;
}
else {
message.filter = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.ListDiskPlacementGroupsRequest.$type, exports.ListDiskPlacementGroupsRequest);
const baseListDiskPlacementGroupsResponse = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupsResponse',
nextPageToken: '',
};
exports.ListDiskPlacementGroupsResponse = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupsResponse',
encode(message, writer = minimal_1.default.Writer.create()) {
for (const v of message.diskPlacementGroups) {
disk_placement_group_1.DiskPlacementGroup.encode(v, writer.uint32(10).fork()).ldelim();
}
if (message.nextPageToken !== '') {
writer.uint32(18).string(message.nextPageToken);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseListDiskPlacementGroupsResponse,
};
message.diskPlacementGroups = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroups.push(disk_placement_group_1.DiskPlacementGroup.decode(reader, reader.uint32()));
break;
case 2:
message.nextPageToken = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseListDiskPlacementGroupsResponse,
};
message.diskPlacementGroups = [];
if (object.diskPlacementGroups !== undefined &&
object.diskPlacementGroups !== null) {
for (const e of object.diskPlacementGroups) {
message.diskPlacementGroups.push(disk_placement_group_1.DiskPlacementGroup.fromJSON(e));
}
}
if (object.nextPageToken !== undefined &&
object.nextPageToken !== null) {
message.nextPageToken = String(object.nextPageToken);
}
else {
message.nextPageToken = '';
}
return message;
},
toJSON(message) {
const obj = {};
if (message.diskPlacementGroups) {
obj.diskPlacementGroups = message.diskPlacementGroups.map((e) => e ? disk_placement_group_1.DiskPlacementGroup.toJSON(e) : undefined);
}
else {
obj.diskPlacementGroups = [];
}
message.nextPageToken !== undefined &&
(obj.nextPageToken = message.nextPageToken);
return obj;
},
fromPartial(object) {
const message = {
...baseListDiskPlacementGroupsResponse,
};
message.diskPlacementGroups = [];
if (object.diskPlacementGroups !== undefined &&
object.diskPlacementGroups !== null) {
for (const e of object.diskPlacementGroups) {
message.diskPlacementGroups.push(disk_placement_group_1.DiskPlacementGroup.fromPartial(e));
}
}
if (object.nextPageToken !== undefined &&
object.nextPageToken !== null) {
message.nextPageToken = object.nextPageToken;
}
else {
message.nextPageToken = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.ListDiskPlacementGroupsResponse.$type, exports.ListDiskPlacementGroupsResponse);
const baseCreateDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupRequest',
folderId: '',
name: '',
description: '',
zoneId: '',
};
exports.CreateDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.folderId !== '') {
writer.uint32(10).string(message.folderId);
}
if (message.name !== '') {
writer.uint32(18).string(message.name);
}
if (message.description !== '') {
writer.uint32(26).string(message.description);
}
Object.entries(message.labels).forEach(([key, value]) => {
exports.CreateDiskPlacementGroupRequest_LabelsEntry.encode({
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupRequest.LabelsEntry',
key: key,
value,
}, writer.uint32(34).fork()).ldelim();
});
if (message.zoneId !== '') {
writer.uint32(42).string(message.zoneId);
}
if (message.spreadPlacementStrategy !== undefined) {
disk_placement_group_1.DiskSpreadPlacementStrategy.encode(message.spreadPlacementStrategy, writer.uint32(50).fork()).ldelim();
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseCreateDiskPlacementGroupRequest,
};
message.labels = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.folderId = reader.string();
break;
case 2:
message.name = reader.string();
break;
case 3:
message.description = reader.string();
break;
case 4:
const entry4 = exports.CreateDiskPlacementGroupRequest_LabelsEntry.decode(reader, reader.uint32());
if (entry4.value !== undefined) {
message.labels[entry4.key] = entry4.value;
}
break;
case 5:
message.zoneId = reader.string();
break;
case 6:
message.spreadPlacementStrategy =
disk_placement_group_1.DiskSpreadPlacementStrategy.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseCreateDiskPlacementGroupRequest,
};
message.labels = {};
if (object.folderId !== undefined && object.folderId !== null) {
message.folderId = String(object.folderId);
}
else {
message.folderId = '';
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
}
else {
message.name = '';
}
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
}
else {
message.description = '';
}
if (object.labels !== undefined && object.labels !== null) {
Object.entries(object.labels).forEach(([key, value]) => {
message.labels[key] = String(value);
});
}
if (object.zoneId !== undefined && object.zoneId !== null) {
message.zoneId = String(object.zoneId);
}
else {
message.zoneId = '';
}
if (object.spreadPlacementStrategy !== undefined &&
object.spreadPlacementStrategy !== null) {
message.spreadPlacementStrategy =
disk_placement_group_1.DiskSpreadPlacementStrategy.fromJSON(object.spreadPlacementStrategy);
}
else {
message.spreadPlacementStrategy = undefined;
}
return message;
},
toJSON(message) {
const obj = {};
message.folderId !== undefined && (obj.folderId = message.folderId);
message.name !== undefined && (obj.name = message.name);
message.description !== undefined &&
(obj.description = message.description);
obj.labels = {};
if (message.labels) {
Object.entries(message.labels).forEach(([k, v]) => {
obj.labels[k] = v;
});
}
message.zoneId !== undefined && (obj.zoneId = message.zoneId);
message.spreadPlacementStrategy !== undefined &&
(obj.spreadPlacementStrategy = message.spreadPlacementStrategy
? disk_placement_group_1.DiskSpreadPlacementStrategy.toJSON(message.spreadPlacementStrategy)
: undefined);
return obj;
},
fromPartial(object) {
const message = {
...baseCreateDiskPlacementGroupRequest,
};
message.labels = {};
if (object.folderId !== undefined && object.folderId !== null) {
message.folderId = object.folderId;
}
else {
message.folderId = '';
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
}
else {
message.name = '';
}
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
}
else {
message.description = '';
}
if (object.labels !== undefined && object.labels !== null) {
Object.entries(object.labels).forEach(([key, value]) => {
if (value !== undefined) {
message.labels[key] = String(value);
}
});
}
if (object.zoneId !== undefined && object.zoneId !== null) {
message.zoneId = object.zoneId;
}
else {
message.zoneId = '';
}
if (object.spreadPlacementStrategy !== undefined &&
object.spreadPlacementStrategy !== null) {
message.spreadPlacementStrategy =
disk_placement_group_1.DiskSpreadPlacementStrategy.fromPartial(object.spreadPlacementStrategy);
}
else {
message.spreadPlacementStrategy = undefined;
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.CreateDiskPlacementGroupRequest.$type, exports.CreateDiskPlacementGroupRequest);
const baseCreateDiskPlacementGroupRequest_LabelsEntry = {
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupRequest.LabelsEntry',
key: '',
value: '',
};
exports.CreateDiskPlacementGroupRequest_LabelsEntry = {
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupRequest.LabelsEntry',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.key !== '') {
writer.uint32(10).string(message.key);
}
if (message.value !== '') {
writer.uint32(18).string(message.value);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseCreateDiskPlacementGroupRequest_LabelsEntry,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseCreateDiskPlacementGroupRequest_LabelsEntry,
};
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
}
else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
}
else {
message.value = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object) {
const message = {
...baseCreateDiskPlacementGroupRequest_LabelsEntry,
};
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
}
else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
}
else {
message.value = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.CreateDiskPlacementGroupRequest_LabelsEntry.$type, exports.CreateDiskPlacementGroupRequest_LabelsEntry);
const baseCreateDiskPlacementGroupMetadata = {
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupMetadata',
diskPlacementGroupId: '',
};
exports.CreateDiskPlacementGroupMetadata = {
$type: 'yandex.cloud.compute.v1.CreateDiskPlacementGroupMetadata',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseCreateDiskPlacementGroupMetadata,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseCreateDiskPlacementGroupMetadata,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
return obj;
},
fromPartial(object) {
const message = {
...baseCreateDiskPlacementGroupMetadata,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.CreateDiskPlacementGroupMetadata.$type, exports.CreateDiskPlacementGroupMetadata);
const baseUpdateDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupRequest',
diskPlacementGroupId: '',
name: '',
description: '',
};
exports.UpdateDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
if (message.updateMask !== undefined) {
field_mask_1.FieldMask.encode(message.updateMask, writer.uint32(18).fork()).ldelim();
}
if (message.name !== '') {
writer.uint32(26).string(message.name);
}
if (message.description !== '') {
writer.uint32(34).string(message.description);
}
Object.entries(message.labels).forEach(([key, value]) => {
exports.UpdateDiskPlacementGroupRequest_LabelsEntry.encode({
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupRequest.LabelsEntry',
key: key,
value,
}, writer.uint32(42).fork()).ldelim();
});
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUpdateDiskPlacementGroupRequest,
};
message.labels = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
case 2:
message.updateMask = field_mask_1.FieldMask.decode(reader, reader.uint32());
break;
case 3:
message.name = reader.string();
break;
case 4:
message.description = reader.string();
break;
case 5:
const entry5 = exports.UpdateDiskPlacementGroupRequest_LabelsEntry.decode(reader, reader.uint32());
if (entry5.value !== undefined) {
message.labels[entry5.key] = entry5.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseUpdateDiskPlacementGroupRequest,
};
message.labels = {};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
if (object.updateMask !== undefined && object.updateMask !== null) {
message.updateMask = field_mask_1.FieldMask.fromJSON(object.updateMask);
}
else {
message.updateMask = undefined;
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
}
else {
message.name = '';
}
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
}
else {
message.description = '';
}
if (object.labels !== undefined && object.labels !== null) {
Object.entries(object.labels).forEach(([key, value]) => {
message.labels[key] = String(value);
});
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
message.updateMask !== undefined &&
(obj.updateMask = message.updateMask
? field_mask_1.FieldMask.toJSON(message.updateMask)
: undefined);
message.name !== undefined && (obj.name = message.name);
message.description !== undefined &&
(obj.description = message.description);
obj.labels = {};
if (message.labels) {
Object.entries(message.labels).forEach(([k, v]) => {
obj.labels[k] = v;
});
}
return obj;
},
fromPartial(object) {
const message = {
...baseUpdateDiskPlacementGroupRequest,
};
message.labels = {};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
if (object.updateMask !== undefined && object.updateMask !== null) {
message.updateMask = field_mask_1.FieldMask.fromPartial(object.updateMask);
}
else {
message.updateMask = undefined;
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
}
else {
message.name = '';
}
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
}
else {
message.description = '';
}
if (object.labels !== undefined && object.labels !== null) {
Object.entries(object.labels).forEach(([key, value]) => {
if (value !== undefined) {
message.labels[key] = String(value);
}
});
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.UpdateDiskPlacementGroupRequest.$type, exports.UpdateDiskPlacementGroupRequest);
const baseUpdateDiskPlacementGroupRequest_LabelsEntry = {
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupRequest.LabelsEntry',
key: '',
value: '',
};
exports.UpdateDiskPlacementGroupRequest_LabelsEntry = {
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupRequest.LabelsEntry',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.key !== '') {
writer.uint32(10).string(message.key);
}
if (message.value !== '') {
writer.uint32(18).string(message.value);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUpdateDiskPlacementGroupRequest_LabelsEntry,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseUpdateDiskPlacementGroupRequest_LabelsEntry,
};
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
}
else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
}
else {
message.value = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object) {
const message = {
...baseUpdateDiskPlacementGroupRequest_LabelsEntry,
};
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
}
else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
}
else {
message.value = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.UpdateDiskPlacementGroupRequest_LabelsEntry.$type, exports.UpdateDiskPlacementGroupRequest_LabelsEntry);
const baseUpdateDiskPlacementGroupMetadata = {
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupMetadata',
diskPlacementGroupId: '',
};
exports.UpdateDiskPlacementGroupMetadata = {
$type: 'yandex.cloud.compute.v1.UpdateDiskPlacementGroupMetadata',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUpdateDiskPlacementGroupMetadata,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseUpdateDiskPlacementGroupMetadata,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
return obj;
},
fromPartial(object) {
const message = {
...baseUpdateDiskPlacementGroupMetadata,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.UpdateDiskPlacementGroupMetadata.$type, exports.UpdateDiskPlacementGroupMetadata);
const baseDeleteDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.DeleteDiskPlacementGroupRequest',
diskPlacementGroupId: '',
};
exports.DeleteDiskPlacementGroupRequest = {
$type: 'yandex.cloud.compute.v1.DeleteDiskPlacementGroupRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDeleteDiskPlacementGroupRequest,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseDeleteDiskPlacementGroupRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
return obj;
},
fromPartial(object) {
const message = {
...baseDeleteDiskPlacementGroupRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.DeleteDiskPlacementGroupRequest.$type, exports.DeleteDiskPlacementGroupRequest);
const baseDeleteDiskPlacementGroupMetadata = {
$type: 'yandex.cloud.compute.v1.DeleteDiskPlacementGroupMetadata',
diskPlacementGroupId: '',
};
exports.DeleteDiskPlacementGroupMetadata = {
$type: 'yandex.cloud.compute.v1.DeleteDiskPlacementGroupMetadata',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDeleteDiskPlacementGroupMetadata,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseDeleteDiskPlacementGroupMetadata,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
return obj;
},
fromPartial(object) {
const message = {
...baseDeleteDiskPlacementGroupMetadata,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.DeleteDiskPlacementGroupMetadata.$type, exports.DeleteDiskPlacementGroupMetadata);
const baseListDiskPlacementGroupDisksRequest = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupDisksRequest',
diskPlacementGroupId: '',
pageSize: 0,
pageToken: '',
};
exports.ListDiskPlacementGroupDisksRequest = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupDisksRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
if (message.pageSize !== 0) {
writer.uint32(16).int64(message.pageSize);
}
if (message.pageToken !== '') {
writer.uint32(26).string(message.pageToken);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseListDiskPlacementGroupDisksRequest,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
case 2:
message.pageSize = longToNumber(reader.int64());
break;
case 3:
message.pageToken = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseListDiskPlacementGroupDisksRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
if (object.pageSize !== undefined && object.pageSize !== null) {
message.pageSize = Number(object.pageSize);
}
else {
message.pageSize = 0;
}
if (object.pageToken !== undefined && object.pageToken !== null) {
message.pageToken = String(object.pageToken);
}
else {
message.pageToken = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
message.pageSize !== undefined && (obj.pageSize = message.pageSize);
message.pageToken !== undefined && (obj.pageToken = message.pageToken);
return obj;
},
fromPartial(object) {
const message = {
...baseListDiskPlacementGroupDisksRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
if (object.pageSize !== undefined && object.pageSize !== null) {
message.pageSize = object.pageSize;
}
else {
message.pageSize = 0;
}
if (object.pageToken !== undefined && object.pageToken !== null) {
message.pageToken = object.pageToken;
}
else {
message.pageToken = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.ListDiskPlacementGroupDisksRequest.$type, exports.ListDiskPlacementGroupDisksRequest);
const baseListDiskPlacementGroupDisksResponse = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupDisksResponse',
nextPageToken: '',
};
exports.ListDiskPlacementGroupDisksResponse = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupDisksResponse',
encode(message, writer = minimal_1.default.Writer.create()) {
for (const v of message.disks) {
disk_1.Disk.encode(v, writer.uint32(10).fork()).ldelim();
}
if (message.nextPageToken !== '') {
writer.uint32(18).string(message.nextPageToken);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseListDiskPlacementGroupDisksResponse,
};
message.disks = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.disks.push(disk_1.Disk.decode(reader, reader.uint32()));
break;
case 2:
message.nextPageToken = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseListDiskPlacementGroupDisksResponse,
};
message.disks = [];
if (object.disks !== undefined && object.disks !== null) {
for (const e of object.disks) {
message.disks.push(disk_1.Disk.fromJSON(e));
}
}
if (object.nextPageToken !== undefined &&
object.nextPageToken !== null) {
message.nextPageToken = String(object.nextPageToken);
}
else {
message.nextPageToken = '';
}
return message;
},
toJSON(message) {
const obj = {};
if (message.disks) {
obj.disks = message.disks.map((e) => e ? disk_1.Disk.toJSON(e) : undefined);
}
else {
obj.disks = [];
}
message.nextPageToken !== undefined &&
(obj.nextPageToken = message.nextPageToken);
return obj;
},
fromPartial(object) {
const message = {
...baseListDiskPlacementGroupDisksResponse,
};
message.disks = [];
if (object.disks !== undefined && object.disks !== null) {
for (const e of object.disks) {
message.disks.push(disk_1.Disk.fromPartial(e));
}
}
if (object.nextPageToken !== undefined &&
object.nextPageToken !== null) {
message.nextPageToken = object.nextPageToken;
}
else {
message.nextPageToken = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.ListDiskPlacementGroupDisksResponse.$type, exports.ListDiskPlacementGroupDisksResponse);
const baseListDiskPlacementGroupOperationsRequest = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupOperationsRequest',
diskPlacementGroupId: '',
pageSize: 0,
pageToken: '',
};
exports.ListDiskPlacementGroupOperationsRequest = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupOperationsRequest',
encode(message, writer = minimal_1.default.Writer.create()) {
if (message.diskPlacementGroupId !== '') {
writer.uint32(10).string(message.diskPlacementGroupId);
}
if (message.pageSize !== 0) {
writer.uint32(16).int64(message.pageSize);
}
if (message.pageToken !== '') {
writer.uint32(26).string(message.pageToken);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseListDiskPlacementGroupOperationsRequest,
};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.diskPlacementGroupId = reader.string();
break;
case 2:
message.pageSize = longToNumber(reader.int64());
break;
case 3:
message.pageToken = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseListDiskPlacementGroupOperationsRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = String(object.diskPlacementGroupId);
}
else {
message.diskPlacementGroupId = '';
}
if (object.pageSize !== undefined && object.pageSize !== null) {
message.pageSize = Number(object.pageSize);
}
else {
message.pageSize = 0;
}
if (object.pageToken !== undefined && object.pageToken !== null) {
message.pageToken = String(object.pageToken);
}
else {
message.pageToken = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.diskPlacementGroupId !== undefined &&
(obj.diskPlacementGroupId = message.diskPlacementGroupId);
message.pageSize !== undefined && (obj.pageSize = message.pageSize);
message.pageToken !== undefined && (obj.pageToken = message.pageToken);
return obj;
},
fromPartial(object) {
const message = {
...baseListDiskPlacementGroupOperationsRequest,
};
if (object.diskPlacementGroupId !== undefined &&
object.diskPlacementGroupId !== null) {
message.diskPlacementGroupId = object.diskPlacementGroupId;
}
else {
message.diskPlacementGroupId = '';
}
if (object.pageSize !== undefined && object.pageSize !== null) {
message.pageSize = object.pageSize;
}
else {
message.pageSize = 0;
}
if (object.pageToken !== undefined && object.pageToken !== null) {
message.pageToken = object.pageToken;
}
else {
message.pageToken = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.ListDiskPlacementGroupOperationsRequest.$type, exports.ListDiskPlacementGroupOperationsRequest);
const baseListDiskPlacementGroupOperationsResponse = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupOperationsResponse',
nextPageToken: '',
};
exports.ListDiskPlacementGroupOperationsResponse = {
$type: 'yandex.cloud.compute.v1.ListDiskPlacementGroupOperationsResponse',
encode(message, writer = minimal_1.default.Writer.create()) {
for (const v of message.operations) {
operation_1.Operation.encode(v, writer.uint32(10).fork()).ldelim();
}
if (message.nextPageToken !== '') {
writer.uint32(18).string(message.nextPageToken);
}
return writer;
},
decode(input, length) {
const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseListDiskPlacementGroupOperationsResponse,
};
message.operations = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.operations.push(operation_1.Operation.decode(reader, reader.uint32()));
break;
case 2:
message.nextPageToken = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = {
...baseListDiskPlacementGroupOperationsResponse,
};
message.operations = [];
if (object.operations !== undefined && object.operations !== null) {
for (const e of object.operations) {
message.operations.push(operation_1.Operation.fromJSON(e));
}
}
if (object.nextPageToken !== undefined &&
object.nextPageToken !== null) {
message.nextPageToken = String(object.nextPageToken);
}
else {
message.nextPageToken = '';
}
return message;
},
toJSON(message) {
const obj = {};
if (message.operations) {
obj.operations = message.operations.map((e) => e ? operation_1.Operation.toJSON(e) : undefined);
}
else {
obj.operations = [];
}
message.nextPageToken !== undefined &&
(obj.nextPageToken = message.nextPageToken);
return obj;
},
fromPartial(object) {
const message = {
...baseListDiskPlacementGroupOperationsResponse,
};
message.operations = [];
if (object.operations !== undefined && object.operations !== null) {
for (const e of object.operations) {
message.operations.push(operation_1.Operation.fromPartial(e));
}
}
if (object.nextPageToken !== undefined &&
object.nextPageToken !== null) {
message.nextPageToken = object.nextPageToken;
}
else {
message.nextPageToken = '';
}
return message;
},
};
typeRegistry_1.messageTypeRegistry.set(exports.ListDiskPlacementGroupOperationsResponse.$type, exports.ListDiskPlacementGroupOperationsResponse);
/** A set of methods for managing DiskPlacementGroup resources. */
exports.DiskPlacementGroupServiceService = {
/** Returns the specified placement group. */
get: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/Get',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.GetDiskPlacementGroupRequest.encode(value).finish()),
requestDeserialize: (value) => exports.GetDiskPlacementGroupRequest.decode(value),
responseSerialize: (value) => Buffer.from(disk_placement_group_1.DiskPlacementGroup.encode(value).finish()),
responseDeserialize: (value) => disk_placement_group_1.DiskPlacementGroup.decode(value),
},
/** Retrieves the list of placement groups in the specified folder. */
list: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/List',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.ListDiskPlacementGroupsRequest.encode(value).finish()),
requestDeserialize: (value) => exports.ListDiskPlacementGroupsRequest.decode(value),
responseSerialize: (value) => Buffer.from(exports.ListDiskPlacementGroupsResponse.encode(value).finish()),
responseDeserialize: (value) => exports.ListDiskPlacementGroupsResponse.decode(value),
},
/** Creates a placement group in the specified folder. */
create: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/Create',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.CreateDiskPlacementGroupRequest.encode(value).finish()),
requestDeserialize: (value) => exports.CreateDiskPlacementGroupRequest.decode(value),
responseSerialize: (value) => Buffer.from(operation_1.Operation.encode(value).finish()),
responseDeserialize: (value) => operation_1.Operation.decode(value),
},
/** Updates the specified placement group. */
update: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/Update',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.UpdateDiskPlacementGroupRequest.encode(value).finish()),
requestDeserialize: (value) => exports.UpdateDiskPlacementGroupRequest.decode(value),
responseSerialize: (value) => Buffer.from(operation_1.Operation.encode(value).finish()),
responseDeserialize: (value) => operation_1.Operation.decode(value),
},
/** Deletes the specified placement group. */
delete: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/Delete',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.DeleteDiskPlacementGroupRequest.encode(value).finish()),
requestDeserialize: (value) => exports.DeleteDiskPlacementGroupRequest.decode(value),
responseSerialize: (value) => Buffer.from(operation_1.Operation.encode(value).finish()),
responseDeserialize: (value) => operation_1.Operation.decode(value),
},
/** Lists disks for the specified placement group. */
listDisks: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/ListDisks',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.ListDiskPlacementGroupDisksRequest.encode(value).finish()),
requestDeserialize: (value) => exports.ListDiskPlacementGroupDisksRequest.decode(value),
responseSerialize: (value) => Buffer.from(exports.ListDiskPlacementGroupDisksResponse.encode(value).finish()),
responseDeserialize: (value) => exports.ListDiskPlacementGroupDisksResponse.decode(value),
},
/** Lists operations for the specified placement group. */
listOperations: {
path: '/yandex.cloud.compute.v1.DiskPlacementGroupService/ListOperations',
requestStream: false,
responseStream: false,
requestSerialize: (value) => Buffer.from(exports.ListDiskPlacementGroupOperationsRequest.encode(value).finish()),
requestDeserialize: (value) => exports.ListDiskPlacementGroupOperationsRequest.decode(value),
responseSerialize: (value) => Buffer.from(exports.ListDiskPlacementGroupOperationsResponse.encode(value).finish()),
responseDeserialize: (value) => exports.ListDiskPlacementGroupOperationsResponse.decode(value),
},
};
exports.DiskPlacementGroupServiceClient = (0, grpc_js_1.makeGenericClientConstructor)(exports.DiskPlacementGroupServiceService, 'yandex.cloud.compute.v1.DiskPlacementGroupService');
var globalThis = (() => {
if (typeof globalThis !== 'undefined')
return globalThis;
if (typeof self !== 'undefined')
return self;
if (typeof window !== 'undefined')
return window;
if (typeof global !== 'undefined')
return global;
throw 'Unable to locate global object';
})();
function longToNumber(long) {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER');
}
return long.toNumber();
}
if (minimal_1.default.util.Long !== long_1.default) {
minimal_1.default.util.Long = long_1.default;
minimal_1.default.configure();
}
|
scraiber/scraiber-api | src/app/api/routes/namespaces.py | <reponame>scraiber/scraiber-api
from typing import List
from asyncpg.exceptions import UniqueViolationError
from fastapi import APIRouter, HTTPException, Depends
from app.api.crud import project2user, projects, namespaces, namespace2projecttransfer
from app.api.kubernetes import namespace, users
from app.api.models.projects import Project2UserDB, ProjectPrimaryKeyUserID, ProjectPrimaryKey
from app.api.models.namespaces import NamespacePrimaryKey, NamespaceSchema, NamespacePrimaryKeyEmail, NamespacePrimaryKeyProjectID
from app.api.models.auth0 import Auth0User
from app.api.auth0.users import get_user_by_id, get_user_list_by_id
from app.api.email.namespaces import *
from app.auth0 import current_user, check_email_verified
from app.kubernetes_setup import clusters
router = APIRouter()
@router.post("/", response_model=NamespaceSchema, status_code=201)
async def create_namespace(payload: NamespaceSchema, user: Auth0User = Depends(current_user)):
await check_email_verified(user)
await project2user.admin_check(ProjectPrimaryKeyUserID(project_id=payload.project_id, user_id=user.user_id))
if payload.name in clusters[payload.region]["blacklist"]:
raise HTTPException(status_code=403, detail="Namespace already exists")
project = await projects.get(payload.project_id)
if not project:
raise HTTPException(status_code=404, detail="Project not found")
project_deserialized = ProjectPrimaryKeyName(**project)
try:
await namespaces.post(payload)
except UniqueViolationError:
raise HTTPException(status_code=403, detail="Namespace already exists")
await namespace.create_namespace(payload)
creator = await get_user_by_id(user.user_id)
users_res = await project2user.get_by_project(payload.project_id)
user_ids = [Project2UserDB(**user_item).user_id for user_item in users_res]
auth0_users = await get_user_list_by_id(user_ids)
for auth0_user in auth0_users:
await users.add_user_to_namespace(NamespacePrimaryKeyEmail(name=payload.name, region=payload.region, e_mail=auth0_user.email))
await mail_namespace_post(NamespacePrimaryKeyEmailInfo(name=payload.name, region=payload.region, e_mail=auth0_user.email,
project_id=payload.project_id, project_name=project_deserialized.name, creator=creator.nickname))
return payload
@router.get("/", response_model=NamespaceSchema)
async def get_namespace(primary_key: NamespacePrimaryKey, user: Auth0User = Depends(current_user)):
await check_email_verified(user)
namespace_res = await namespaces.get(primary_key)
if not namespace_res:
raise HTTPException(status_code=404, detail="Namespace not found")
namespace_item = NamespaceSchema(**namespace_res)
user_namespace_check = await project2user.get(ProjectPrimaryKeyUserID(project_id=namespace_item.project_id, user_id=user.user_id))
if not user_namespace_check:
raise HTTPException(status_code=404, detail="Project/Namespace for user not found")
return namespace_res
@router.get("/by_project", response_model=List[NamespaceSchema])
async def get_namespaces_by_project(primary_key: ProjectPrimaryKey, user: Auth0User = Depends(current_user)):
await check_email_verified(user)
project2user_res = await project2user.get(ProjectPrimaryKeyUserID(project_id=primary_key.project_id, user_id=user.user_id))
if not project2user_res:
raise HTTPException(status_code=404, detail="Project for user not found")
return await namespaces.get_by_project(primary_key.project_id)
@router.get("/by_user", response_model=List[NamespaceSchema])
async def get_namespaces_by_user(user: Auth0User = Depends(current_user)):
await check_email_verified(user)
project2user_res = await project2user.get_by_user(user.user_id)
if not project2user_res:
raise HTTPException(status_code=404, detail="No Project found for user")
output_list = []
for item in project2user_res:
item_deserialized = Project2UserDB(**item)
namespace_list_res = await namespaces.get_by_project(item_deserialized.project_id)
namespace_list = [NamespaceSchema(**ns_item) for ns_item in namespace_list_res]
output_list.extend(namespace_list)
return output_list
@router.put("/update_cpu_memory", response_model=NamespaceSchema, status_code=200)
async def update_cpu_memory(update: NamespaceSchema, user: Auth0User = Depends(current_user)):
await check_email_verified(user)
await project2user.admin_check(ProjectPrimaryKeyUserID(project_id=update.project_id, user_id=user.user_id))
namespace_res = await namespaces.get(update)
if not namespace_res:
raise HTTPException(status_code=404, detail="Namespace not found")
namespace_item = NamespaceSchema(**namespace_res)
if namespace_item.project_id != update.project_id:
raise HTTPException(status_code=404, detail="Namespace does not belong to the project outlined")
await namespaces.put_cpu_mem(update)
await namespace.update_namespace(update)
project_res = await projects.get(update.project_id)
project_info = ProjectPrimaryKeyName(**project_res)
admins = await project2user.get_admins_by_project(update.project_id)
admin_ids = [Project2UserDB(**admin).user_id for admin in admins]
auth0_admins = await get_user_list_by_id(admin_ids)
for auth0_admin in auth0_admins:
mail_payload = NamespaceSchemaProjectNameEmailInfo(
name=update.name, region=update.region,
max_namespace_cpu=update.max_namespace_cpu, max_namespace_mem=update.max_namespace_mem,
default_limit_pod_cpu=update.default_limit_pod_cpu, default_limit_pod_mem=update.default_limit_pod_mem,
project_id=update.project_id, project_name=project_info.name,
e_mail=auth0_admin.email, creator=user.nickname
)
await mail_namespace_put_resources(mail_payload)
return update
@router.delete("/", status_code=200)
async def delete_namespace(primary_key: NamespacePrimaryKey, user: Auth0User = Depends(current_user)):
await check_email_verified(user)
namespace_res = await namespaces.get(primary_key)
if not namespace_res:
raise HTTPException(status_code=404, detail="Namespace not found")
namespace_item = NamespaceSchema(**namespace_res)
user_namespace_check = await project2user.get(ProjectPrimaryKeyUserID(project_id=namespace_item.project_id, user_id=user.user_id))
if not user_namespace_check:
raise HTTPException(status_code=404, detail="Project/Namespace for user not found")
await project2user.admin_check(ProjectPrimaryKeyUserID(project_id=namespace_item.project_id, user_id=user.user_id))
namespace_info_res = await namespaces.get(primary_key)
namespace_info = NamespaceSchema(**namespace_info_res)
project_res = await projects.get(namespace_item.project_id)
project_info = ProjectPrimaryKeyName(**project_res)
await namespace.delete_namespace(primary_key)
await namespaces.delete(primary_key)
await namespace2projecttransfer.delete(primary_key)
admins = await project2user.get_admins_by_project(namespace_info.project_id)
admin_ids = [Project2UserDB(**admin).user_id for admin in admins]
auth0_admins = await get_user_list_by_id(admin_ids)
for auth0_admin in auth0_admins:
await mail_namespace_delete(NamespacePrimaryKeyEmailInfo(name=primary_key.name, region=primary_key.region, e_mail=auth0_admin.email,
project_id=project_info.project_id, project_name=project_info.name, creator=user.nickname))
return primary_key
|
whwu123/zf | src/main/java/com/active4j/hr/system/dao/SysLogDao.java | package com.active4j.hr.system.dao;
import com.active4j.hr.system.entity.SysLogEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface SysLogDao extends BaseMapper<SysLogEntity>{
}
|
Tiankx1003/Scala | spark-demo/spark-core/src/main/scala/com/tian/day04/hbase/HBaseWrite.scala | package com.tian.day04.hbase
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.client.Put
import org.apache.hadoop.hbase.io.ImmutableBytesWritable
import org.apache.hadoop.hbase.mapreduce.TableOutputFormat
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.mapreduce.Job
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
/**
* @author tian
* @date 2019/9/17 20:54
* @version 1.0.0
*/
object HBaseWrite {
def main(args: Array[String]): Unit = {
val conf: SparkConf = new SparkConf().setAppName("Practice").setMaster("local[2]")
val sc: SparkContext = new SparkContext(conf)
val hbaseConf: Configuration = HBaseConfiguration.create()
hbaseConf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104")
hbaseConf.set(TableOutputFormat.OUTPUT_TABLE, "student")
//通过job来设置输出的格式的类
val job: Job = Job.getInstance(hbaseConf)
job.setOutputFormatClass(classOf[TableOutputFormat[ImmutableBytesWritable]])
job.setOutputKeyClass(classOf[ImmutableBytesWritable])
job.setOutputValueClass(classOf[Put])
val initialRDD: RDD[(String, String, String)] =
sc.parallelize(List(("10", "apple", "11"), ("20", "banana", "21")))
val hbaseRDD: RDD[(ImmutableBytesWritable, Put)] = initialRDD.map {
case (row, name, weight) =>
//封装rowKey
val rowKey: ImmutableBytesWritable = new ImmutableBytesWritable()
rowKey.set(Bytes.toBytes(row))
val put: Put = new Put(Bytes.toBytes(row))
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes(name))
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("weight"), Bytes.toBytes(weight))
(rowKey, put)
}
hbaseRDD.saveAsNewAPIHadoopDataset(job.getConfiguration)
sc.stop()
}
}
|
neekon91/Ilera-health | server/models/patient_medication-helpers.js | <filename>server/models/patient_medication-helpers.js
'use strict'
const db = require('../db/dbConnect/connection.js');
module.exports = {
//added params here and miodified queryString
new_medication: (params, cb) => {
console.log("I'm reached", params);
let data = [params.drug_name, params.dosage, params.id_medication,
params.id_physician, params.id_patient, params.start_date, params.end_date];
const queryString = 'INSERT INTO patient_medication \
(drug_name, dosage, id_medication, id_physician, id_patient, \
start_date, end_date) \
value (?,?,?,?,?,?,?)';
db.query(queryString, data, (error, results) => cb(error, results) );
},
// added
getAll_patientMeds: (params, cb) => {
let data = [params.userid];
const queryString = 'SELECT * \
FROM patient_medication \
WHERE id_patient=? \
LIMIT 40';
db.query(queryString, data, (error, results) => cb(error, results) );
},
getAll_patient_medicationAndPhysician_info: (params, cb) => {
let data = [params.userid];
const queryString = 'SELECT m.id, m.drug_name, m.dosage, m.id_medication, \
m.id_physician, m.id_patient, m.start_date, m.end_date, \
py.id, py.betterDoctorUID, py.first, py.last, py.email, py.phone_number, \
py.photo_path, py.specialty \
FROM patient_medication m \
JOIN physician py \
ON py.id = m.id_physician \
WHERE m.id_patient=? \
LIMIT 40';
db.query(queryString, data, (error, results) => cb(error, results) );
}
// (params, cb)=>{
// let data = [params.userid];
// const queryString = 'SELECT * FROM patient_medication WHERE \
// id_patient=? LIMIT 40';
// db.query(queryString, data, (error, results) => cb(error, results) );
// }
};
// medication
// med.id, med.drug_name, med.details
// physician
// py.id, py.betterDoctorUID, py.first, py.last, py.email, py.phone_number, py.photo_path, py.specialty
// patient_medication
// m.id, m.drug_name, m.dosage, m.id_medication, m.id_physician, m.id_patient, m.start_date, m.end_date
// SELECT m.id, m.drug_name, m.dosage, m.id_medication,
// m.id_physician, m.id_patient, m.start_date, m.end_date, py.id,
// py.betterDoctorUID, py.first, py.last, py.email, py.phone_number,
// py.photo_path, py.specialty
// FROM patient_medication m
// JOIN physician py ON py.id = m.id_physician
// WHERE m.id_patient=7 LIMIT 40;
// 'use strict'
//
// const db = require('../db/dbConnect/connection.js');
//
// module.exports = {
//
// getAll_patientMeds: (params, cb) => {
// let data = [params.userid];
// const queryString = 'SELECT * FROM patient_medication \
// WHERE id_patient=?';
// db.query(queryString, data, (error, results) => cb(error, results) );
// }
//
// };
|
anaya-world/BuzzApp | app/src/main/java/com/example/myapplication/OpenChats/OpenChatFragment.java | <filename>app/src/main/java/com/example/myapplication/OpenChats/OpenChatFragment.java
package com.example.myapplication.OpenChats;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.Activities.AllContacts;
import com.example.myapplication.Activities.Main3Activity;
import com.example.myapplication.Activities.MapsActivity;
import com.example.myapplication.Activities.MediaPlayerActivity;
import com.example.myapplication.Activities.PhotoViewerActivity;
import com.example.myapplication.Adapter.FileListAdapter;
import com.example.myapplication.GroupChats.GroupChatAdapter;
import com.example.myapplication.GroupChats.GroupParticipantActivity;
import com.example.myapplication.Intefaces.OnBackPressedListener;
import com.example.myapplication.Intefaces.OnStartFileDownloadListener;
import com.example.myapplication.R;
import com.example.myapplication.Utils.FileUtils;
import com.example.myapplication.Utils.MimeType;
import com.example.myapplication.Utils.PreferenceUtils;
import com.example.myapplication.Utils.UrlPreviewInfo;
import com.google.android.material.snackbar.Snackbar;
import com.jaiselrahman.filepicker.model.MediaFile;
import com.kevalpatel2106.emoticongifkeyboard.EmoticonGIFKeyboardFragment;
import com.kevalpatel2106.emoticongifkeyboard.emoticons.Emoticon;
import com.kevalpatel2106.emoticongifkeyboard.emoticons.EmoticonSelectListener;
import com.kevalpatel2106.emoticongifkeyboard.gifs.Gif;
import com.kevalpatel2106.emoticongifkeyboard.gifs.GifSelectListener;
import com.kevalpatel2106.emoticonpack.android8.Android8EmoticonProvider;
import com.kevalpatel2106.gifpack.giphy.GiphyGifProvider;
import com.sendbird.android.AdminMessage;
import com.sendbird.android.BaseChannel;
import com.sendbird.android.BaseMessage;
import com.sendbird.android.FileMessage;
import com.sendbird.android.OpenChannel;
import com.sendbird.android.ParticipantListQuery;
import com.sendbird.android.PreviousMessageListQuery;
import com.sendbird.android.SendBird;
import com.sendbird.android.SendBirdException;
import com.sendbird.android.User;
import com.sendbird.android.UserListQuery;
import com.sendbird.android.UserMessage;
import com.sendbird.syncmanager.MessageCollection;
import com.sendbird.syncmanager.MessageFilter;
import com.sendbird.syncmanager.handler.CompletionHandler;
import com.sendbird.syncmanager.handler.FetchCompletionHandler;
import org.json.JSONException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import br.com.safety.audio_recorder.AudioListener;
import br.com.safety.audio_recorder.AudioRecordButton;
import br.com.safety.audio_recorder.AudioRecording;
import br.com.safety.audio_recorder.RecordingItem;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class OpenChatFragment extends Fragment {
List<BaseMessage> messagelist = new ArrayList();
public static final int CAMERA_PIC_REQUEST = 100;
public static final int INTENT_REQUEST_CHOOSE_MEDIA = 301;
public int REQUEST_CODE_DOC = 404;
final MessageFilter mMessageFilter = new MessageFilter(BaseChannel.MessageTypeFilter.ALL, null, null);
private long mLastRead;
static final String EXTRA_CHANNEL_URL = "CHANNEL_URL";
private static final String LOG_TAG = OpenChatFragment.class.getSimpleName();
private static final int CHANNEL_LIST_LIMIT = 30;
private static final String CONNECTION_HANDLER_ID = "CONNECTION_HANDLER_OPEN_CHAT";
private static final String CHANNEL_HANDLER_ID = "CHANNEL_HANDLER_OPEN_CHAT";
private static final int STATE_NORMAL = 0;
private static final int STATE_EDIT = 1;
private static final int INTENT_REQUEST_CHOOSE_IMAGE = 300;
private static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 13;
private final static int FILE_REQUEST_CODE = 1;
EmoticonGIFKeyboardFragment emoticonGIFKeyboardFragment;
FrameLayout attachment_container, keyboard_container;
EditText chatsearchbar;
AudioRecordButton audio_record_button;
FrameLayout recordcontainer, searchframe;
ImageView chat_backarrow, iv_chatsearch;
private InputMethodManager mIMM;
private RecyclerView mRecyclerView;
private OpenChatAdapter mChatAdapter;
private LinearLayoutManager mLayoutManager;
private View mRootLayout;
private EditText mMessageEditText;
private Button mMessageSendButton;
private ImageButton mUploadFileButton;
private View mCurrentEventLayout;
private TextView mCurrentEventText, tv_chatperson_name;
private ImageView emoj, iv_chat_more;
private OpenChannel mChannel;
private String mChannelUrl;
private PreviousMessageListQuery mPrevMessageListQuery;
private int mCurrentState = STATE_NORMAL;
private BaseMessage mEditingMessage = null;
private ImageView iv_document, iv_camera, iv_gallery, iv_record, iv_audio, iv_location, iv_contact, iv_schedule;
private AudioRecordButton mAudioRecordButton;
private AudioRecording audioRecording;
private MessageCollection mMessageCollection;
private FileListAdapter fileListAdapter;
private ArrayList<MediaFile> mediaFiles = new ArrayList<>();
private List<BaseMessage> mMessageList;
private String urls;
private HashMap<BaseChannel.SendFileMessageWithProgressHandler, FileMessage> mFileProgressHandlerMap;
private String contactname;
private String phonenum;
private OnStartFileDownloadListener onStartFileDownloadListener;
private boolean mIsTyping;
/**
* To create an instance of this fragment, a Channel URL should be passed.
*/
public static OpenChatFragment newInstance(@NonNull String channelUrl) {
OpenChatFragment fragment = new OpenChatFragment();
Bundle args = new Bundle();
args.putString(OpenChannelListFragment.EXTRA_OPEN_CHANNEL_URL, channelUrl);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIMM = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
((Main3Activity) getActivity()).setOnBackPressedListener(new OnBackPressedListener() {
@Override
public void doBack() {
try {
if (attachment_container.getVisibility() == View.VISIBLE) {
attachment_container.setVisibility(View.GONE);
} else if (emoticonGIFKeyboardFragment.isAdded()) {
if (emoticonGIFKeyboardFragment.isOpen()) {
emoticonGIFKeyboardFragment.close();
} else {
getActivity().finish();
}
} else {
getActivity().finish();
}
} catch (Exception e) {
}
}
});
this.mFileProgressHandlerMap = new HashMap<>();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_open_chat, container, false);
// getActivity().getWindow().setSoftInputMode(SOFT_INPUT_ADJUST_PAN);
setRetainInstance(true);
setHasOptionsMenu(true);
attachment_container = rootView.findViewById(R.id.attachment_container);
keyboard_container = rootView.findViewById(R.id.keyboard_container);
mRootLayout = rootView.findViewById(R.id.layout_open_chat_root);
//comment
ImageView chat_backarrow = rootView.findViewById(R.id.chat_backarrow);
iv_document = (ImageView) rootView.findViewById(R.id.iv_document);
iv_camera = (ImageView) rootView.findViewById(R.id.iv_camera);
iv_gallery = (ImageView) rootView.findViewById(R.id.iv_gallery);
iv_record = (ImageView) rootView.findViewById(R.id.ic_recorder);
iv_audio = (ImageView) rootView.findViewById(R.id.iv_audio);
iv_contact = (ImageView) rootView.findViewById(R.id.iv_contact);
iv_location = (ImageView) rootView.findViewById(R.id.iv_location);
iv_schedule = (ImageView) rootView.findViewById(R.id.iv_schedule);
iv_chatsearch = (ImageView) rootView.findViewById(R.id.iv_chatsearch);
chat_backarrow = (ImageView) ((Main3Activity) getActivity()).findViewById(R.id.chat_backarrow);
recordcontainer = (FrameLayout) rootView.findViewById(R.id.recordcontainer);
searchframe = (FrameLayout) rootView.findViewById(R.id.searchframe);
//audio_record_button
audio_record_button = (AudioRecordButton) rootView.findViewById(R.id.audio_record_button);
chatsearchbar = (EditText) rootView.findViewById(R.id.searchbar);
setUpChatListAdapter();
/*this.audio_record_button.setOnAudioListener(new AudioListener() {
public void onStop(RecordingItem recordingItem) {
audioRecording.play(recordingItem);
urls = recordingItem.getFilePath();
recordcontainer.setVisibility(View.GONE);
sendRecordedFile(urls);
}
public void onCancel() {
recordcontainer.setVisibility(View.GONE);
Toast.makeText(getContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
public void onError(Exception e) {
StringBuilder sb = new StringBuilder();
sb.append("Error: ");
sb.append(e.getMessage());
Log.d("MainActivity", sb.toString());
}
});
*/
this.audio_record_button.setOnAudioListener(new AudioListener() {
public void onStop(RecordingItem recordingItem) {
OpenChatFragment.this.audioRecording.play(recordingItem);
OpenChatFragment.this.urls = recordingItem.getFilePath();
OpenChatFragment.this.recordcontainer.setVisibility(View.GONE);
OpenChatFragment.this.sendRecordedFile(OpenChatFragment.this.urls);
}
public void onCancel() {
OpenChatFragment.this.recordcontainer.setVisibility(View.GONE);
Toast.makeText(OpenChatFragment.this.getContext(),
"Cancel", Toast.LENGTH_SHORT).show();
}
public void onError(Exception e) {
StringBuilder sb = new StringBuilder();
sb.append("Error: ");
sb.append(e.getMessage());
Log.d("MainActivity", sb.toString());
}
});
iv_chatsearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
searchframe.setVisibility(View.VISIBLE);
}
});
//comment
// sendUserMessage(chatsearchbar.getText().toString());
chatsearchbar.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
sendUserMessage(chatsearchbar.getText().toString());
}
});
audioRecording = new AudioRecording(getActivity());
initView();
ActivityCompat.requestPermissions(getActivity(), new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO, READ_EXTERNAL_STORAGE}, 0);
ActivityCompat.requestPermissions(getActivity(), new String[]{WRITE_EXTERNAL_STORAGE}, 0);
chat_backarrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((Main3Activity) getActivity()).finish();
}
});
iv_record.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* recordcontainer.setVisibility(View.VISIBLE);
attachment_container.setVisibility(View.GONE);*/
OpenChatFragment.this.recordcontainer.setVisibility(View.VISIBLE);
OpenChatFragment.this.attachment_container.setVisibility(View.GONE);
}
});
//comment
/* this.mAudioRecordButton.setOnAudioListener(new AudioListener() {
@Override
public void onStop(RecordingItem recordingItem) {
Toast.makeText(getContext(), "Audio..", Toast.LENGTH_SHORT).show();
audioRecording.play(recordingItem);
}
@Override
public void onCancel() {
recordcontainer.setVisibility(View.GONE);
Toast.makeText(getContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Exception e) {
Log.d("MainActivity", "Error: " + e.getMessage());
} //comment
});*/
iv_audio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload, 101);
// startActivityForResult(new Intent("android.intent.action.PICK",
// Media.EXTERNAL_CONTENT_URI), 101);
attachment_container.setVisibility(View.GONE);
}
});
this.iv_document.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent("android.intent.action.OPEN_DOCUMENT");
intent.addCategory("android.intent.category.OPENABLE");
intent.setType("*/*");
intent.putExtra("android.intent.extra.MIME_TYPES", new String[]{"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/plain", "application/pdf", "application/zip", "application/apk", "application/txt"});
OpenChatFragment.this.startActivityForResult(intent, OpenChatFragment.this.REQUEST_CODE_DOC);
OpenChatFragment.this.attachment_container.setVisibility(View.GONE);
}
});
// camera click
iv_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//comment
startActivity(cameraIntent);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
iv_contact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(getActivity(), AllContacts.class), 3);
attachment_container.setVisibility(View.GONE);
}
});
iv_location.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(getActivity(), MapsActivity.class), 44);
attachment_container.setVisibility(View.GONE);
}
});
iv_gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestMedia();
attachment_container.setVisibility(View.GONE);
}
});
chat_backarrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getFragmentManager().popBackStack();
getActivity().finish();
}
});
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_open_channel_chat);
mCurrentEventLayout = rootView.findViewById(R.id.layout_open_chat_current_event);
mCurrentEventText = (TextView) rootView.findViewById(R.id.text_open_chat_current_event);
tv_chatperson_name = (TextView) ((Main3Activity) getActivity()).findViewById(R.id.tv_chatperson_name);
iv_chat_more = (ImageView) rootView.findViewById(R.id.iv_chat_more);
tv_chatperson_name.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ParticipantListQuery participantListQuery = mChannel.createParticipantListQuery();
participantListQuery.next(new UserListQuery.UserListQueryResultHandler() {
@SuppressLint("SetTextI18n")
@Override
public void onResult(List<User> list, SendBirdException e) {
if (e != null) {
e.printStackTrace();// Error.
return;
}
Log.d("OpenChat", " Total members : " + list.size());
//if (OpenChatFragment.this.mChannel.getMembers().size() > 2) {
Intent intent = new Intent(OpenChatFragment.this.getActivity(), OpenParticipantActivity.class);
intent.putExtra("members_key", OpenChatFragment.this.mChannelUrl);
intent.putExtra("groupname_key", OpenChatFragment.this.mChannel.getName());
OpenChatFragment.this.startActivity(intent);
//}
}
});
}
});
// ((Main3Activity) getActivity()).setActionBarTitle(mChannel.getName());//comment
setUpRecyclerView();
mMessageSendButton = (Button) rootView.findViewById(R.id.button_open_channel_chat_send);
mMessageEditText = (EditText) rootView.findViewById(R.id.edittext_chat_message);
this.mIsTyping = false;
this.mMessageEditText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!mIsTyping) {
setTypingStatus(true);
}
if (s.length() == 0) {
setTypingStatus(false);
}
}
public void afterTextChanged(Editable s) {
String s1 = s.toString().trim();
if (s1.length() <= 0 || s1.equals("")) {
mMessageSendButton.setEnabled(false);
} else {
mMessageSendButton.setEnabled(true);
}
}
});
// if(!Common.isConnected(getContext())){
// createMessageCollection(mChannelUrl);
// }
this.mMessageEditText.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// attachment_container.setVisibility(View.VISIBLE);
keyboard_container.setVisibility(View.GONE);
}
});
mUploadFileButton = (ImageButton) rootView.findViewById(R.id.button_open_channel_chat_upload);
mUploadFileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attachment_container.setVisibility(View.VISIBLE);
keyboard_container.setVisibility(View.GONE);
}
});
mMessageSendButton.setEnabled(false);
mMessageSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mCurrentState == STATE_EDIT) {
String userInput = mMessageEditText.getText().toString();
if (userInput.length() > 0) {
if (mEditingMessage != null) {
editMessage(mEditingMessage, mMessageEditText.getText().toString());
}
}
setState(STATE_NORMAL, null, -1);
} else {
String userInput = mMessageEditText.getText().toString().trim();
if (userInput.length() > 0) {
sendUserMessage(userInput);
mMessageEditText.setText("");
}
}
}
});
// Gets channel from URL user requested
mChannelUrl = getArguments().getString(OpenChannelListFragment.EXTRA_OPEN_CHANNEL_URL);
refreshFirst();
EmoticonGIFKeyboardFragment.EmoticonConfig emoticonConfig = new EmoticonGIFKeyboardFragment.EmoticonConfig()
.setEmoticonProvider(Android8EmoticonProvider.create())
/*
NOTE: The process of removing last character when user preses back space will handle
by library if your edit text is in focus.
*/
.setEmoticonSelectListener(new EmoticonSelectListener() {
@Override
public void emoticonSelected(Emoticon emoticon) {
//Do something with new emoticon.
// Log.d(TAG, "emoticonSelected: " + emoticon.getUnicode());
// editText.append(emoticon.getUnicode(),
// editText.getSelectionStart(),
// editText.getSelectionEnd());
mMessageEditText.append(emoticon.getUnicode());
}
@Override
public void onBackSpace() {
//Do something here to handle backspace event.
//The process of removing last character when user preses back space will handle
//by library if your edit text is in focus.
}
});
EmoticonGIFKeyboardFragment.GIFConfig gifConfig = new EmoticonGIFKeyboardFragment
/*
Here we are using GIPHY to provide GIFs. Create Giphy GIF provider by passing your key.
It is required to set GIF provider before adding fragment into container.
*/
.GIFConfig(GiphyGifProvider.create(getActivity(), "564ce7370bf347f2b7c0e4746593c179"))
.setGifSelectListener(new GifSelectListener() {
@Override
public void onGifSelected(@NonNull Gif gif) {
//Do something with the selected GIF.
Log.d("GUF", "onGifSelected: " + gif.getGifUrl());
//sendUserMessage(gif.getGifUrl());
showUploadConfirmDialog(/*null,*/ gif /*,REQUEST_CODE_SHARE_GIF*/);
}
});
emoticonGIFKeyboardFragment = EmoticonGIFKeyboardFragment
.getNewInstance(rootView.findViewById(R.id.keyboard_container), emoticonConfig, gifConfig);
emoj = (ImageView) rootView.findViewById(R.id.emoji_open_close_btn);
emoj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* getActivity().getWindow().setSoftInputMode(
SOFT_INPUT_ADJUST_PAN);*/
keyboard_container.setVisibility(View.VISIBLE);
attachment_container.setVisibility(View.GONE);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//Adding the keyboard fragment to keyboard_container.
getFragmentManager()
.beginTransaction()
.replace(R.id.keyboard_container, emoticonGIFKeyboardFragment)
.commit();
emoticonGIFKeyboardFragment.open();
}
});
return rootView;
}
/**
* This upload alert will be used as confirmation
* when user want to upload contact and Gif images.
*/
private void showUploadConfirmDialog(/*Intent data, */Gif gif/*, int requestCode*/) {
new AlertDialog.Builder(getActivity()).setMessage((CharSequence) "Upload file?").setPositiveButton((int) R.string.upload,
(DialogInterface.OnClickListener) new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/* if (requestCode == REQUEST_CODE_SHARE_CONTACT && data != null) {
contactname = data.getStringExtra("contactname_key");
phonenum = data.getStringExtra("phonenum_key");
sendContact(contactname, phonenum);
} else if (requestCode == REQUEST_CODE_SHARE_GIF) {*/
StringBuilder sb = new StringBuilder();
sb.append("onGifSelected: ");
sb.append(gif.getGifUrl());
Log.d("GUF", sb.toString());
OpenChatFragment.this.sendUserMessage(gif.getGifUrl());
/* }*/
}
}).setNegativeButton((int) R.string.cancel, (DialogInterface.OnClickListener) null).show();
}
private void fetchInitialMessages() {
if (mMessageCollection == null) {
return;
}
mMessageCollection.fetchSucceededMessages(MessageCollection.Direction.PREVIOUS, new FetchCompletionHandler() {
@Override
public void onCompleted(boolean hasMore, SendBirdException e) {
mMessageCollection.fetchSucceededMessages(MessageCollection.Direction.NEXT, new FetchCompletionHandler() {
@Override
public void onCompleted(boolean hasMore, SendBirdException e) {
mMessageCollection.fetchFailedMessages(new CompletionHandler() {
@Override
public void onCompleted(SendBirdException e) {
if (getActivity() == null) {
return;
}
}
});
}
});
}
});
}
// public void createMessageCollection(final String channelUrl) {
// Log.d("SyncManagerUtils","msg-"+channelUrl);
// GroupChannel.getChannel(channelUrl, new GroupChannel.GroupChannelGetHandler() {
// @Override
// public void onResult(GroupChannel groupChannel, SendBirdException e) {
// Log.d("SyncManagerUtils","msg-"+groupChannel);
// if (e != null) {
// MessageCollection.create(channelUrl, mMessageFilter, mLastRead, new MessageCollectionCreateHandler() {
// @Override
// public void onResult(MessageCollection messageCollection, SendBirdException e) {
// if (e == null) {
// if (mMessageCollection != null) {
// mMessageCollection.remove();
// }
//
// mMessageCollection = messageCollection;
// mMessageCollection.setCollectionHandler(mMessageCollectionHandler);
//
// mChannel = mMessageCollection.getChannel();
// mChatAdapter.setChannel(mChannel);
//
// if (getActivity() == null) {
// return;
// }
//
// getActivity().runOnUiThread(new Runnable() {
// @Override
// public void run() {
// mChatAdapter.clear();
// updateActionBarTitle();
// }
// });
//
// fetchInitialMessages();
// } else {
// //Toast.makeText(getContext(), getString(R.string.get_channel_failed), Toast.LENGTH_SHORT).show();
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// getActivity().onBackPressed();
// }
// }, 1000);
// }
// }
// });
// } else {
// if (mMessageCollection != null) {
// mMessageCollection.remove();
// }
// Log.d("SyncManagerUtils","msg1");
// mMessageCollection = new MessageCollection(groupChannel, mMessageFilter, mLastRead);
// mMessageCollection.setCollectionHandler(mMessageCollectionHandler);
//
// mChannel = groupChannel;
// mChatAdapter.setChannel(mChannel);
// mChatAdapter.clear();
// updateActionBarTitle();
//
// fetchInitialMessages();
// }
// }
// });
// }
// private void updateLastSeenTimestamp(List<BaseMessage> messages) {
// long lastSeenTimestamp = mLastRead == Long.MAX_VALUE ? 0 : mLastRead;
// for (BaseMessage message : messages) {
// if (lastSeenTimestamp < message.getCreatedAt()) {
// lastSeenTimestamp = message.getCreatedAt();
// }
// }
//
// if (lastSeenTimestamp > mLastRead) {
// PreferenceUtils.setLastRead(mChannelUrl, lastSeenTimestamp);
// mLastRead = lastSeenTimestamp;
// }
// }
// private MessageCollectionHandler mMessageCollectionHandler = new MessageCollectionHandler() {
// @Override
// public void onMessageEvent(MessageCollection collection, final List<BaseMessage> messages, final MessageEventAction action) {
// }
//
// @Override
// public void onSucceededMessageEvent(MessageCollection collection, final List<BaseMessage> messages, final MessageEventAction action) {
// Log.d("SyncManager", "onSucceededMessageEvent: size = " + messages.size() + ", action = " + action);
//
// if (getActivity() == null) {
// return;
// }
//
// getActivity().runOnUiThread(new Runnable() {
// @Override
// public void run() {
// switch (action) {
// case INSERT:
// mChatAdapter.insertSucceededMessages(messages);
// mChatAdapter.markAllMessagesAsRead();
// break;
//
// case REMOVE:
// mChatAdapter.removeSucceededMessages(messages);
// break;
//
// case UPDATE:
// mChatAdapter.updateSucceededMessages(messages);
// break;
//
// case CLEAR:
// mChatAdapter.clear();
// break;
// }
// }
// });
//
// updateLastSeenTimestamp(messages);
// }
// @Override
// public void onPendingMessageEvent(MessageCollection collection, final List<BaseMessage> messages, final MessageEventAction action) {
// Log.d("SyncManager", "onPendingMessageEvent: size = " + messages.size() + ", action = " + action);
// if (getActivity() == null) {
// return;
// }
//
// getActivity().runOnUiThread(new Runnable() {
// @Override
// public void run() {
// switch (action) {
// case INSERT:
// List<BaseMessage> pendingMessages = new ArrayList<>();
// for (BaseMessage message : messages) {
// if (!mChatAdapter.failedMessageListContains(message)) {
// pendingMessages.add(message);
// }
// }
// mChatAdapter.insertSucceededMessages(pendingMessages);
// break;
//
// case REMOVE:
// mChatAdapter.removeSucceededMessages(messages);
// break;
// }
// }
// });
// }
//
// @Override
// public void onFailedMessageEvent(MessageCollection collection, final List<BaseMessage> messages, final MessageEventAction action, final FailedMessageEventActionReason reason) {
// Log.d("SyncManager", "onFailedMessageEvent: size = " + messages.size() + ", action = " + action);
// if (getActivity() == null) {
// return;
// }
//
// getActivity().runOnUiThread(new Runnable()
// {
// @Override
// public void run() {
// switch (action) {
// case INSERT:
// mChatAdapter.insertFailedMessages(messages);
// break;
//
// case REMOVE:
// mChatAdapter.removeFailedMessages(messages);
// break;
// case UPDATE:
// if (reason == FailedMessageEventActionReason.UPDATE_RESEND_FAILED) {
// mChatAdapter.updateFailedMessages(messages);
// }
// break;
// }
// }
// });
// }
//
// @Override
// public void onNewMessage(MessageCollection collection, BaseMessage message) {
// Log.d("SyncManager", "onNewMessage: message = " + message);
// //show when the scroll position is bottom ONLY.
// if (mLayoutManager.findFirstVisibleItemPosition() != 0) {
// if (message instanceof UserMessage) {
// if (!((UserMessage) message).getSender().getUserId().equals(PreferenceUtils.getUserId())) {
// // mNewMessageText.setText("New Message = " + ((UserMessage) message).getSender().getNickname() + " : " + ((UserMessage) message).getMessage());
// // mNewMessageText.setVisibility(View.VISIBLE);
// }
// } else if (message instanceof FileMessage) {
// if (!((FileMessage) message).getSender().getUserId().equals(PreferenceUtils.getUserId())) {
// // mNewMessageText.setText("New Message = " + ((FileMessage) message).getSender().getNickname() + "Send a File");
// // mNewMessageText.setVisibility(View.VISIBLE);
// }
// }
// }
// }
// };
private void retryFailedMessage(final BaseMessage message) {
new AlertDialog.Builder(getActivity())
.setMessage("Retry")
.setPositiveButton(R.string.resend_message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
if (message instanceof UserMessage) {
mChannel.resendUserMessage((UserMessage) message, new BaseChannel.ResendUserMessageHandler() {
@Override
public void onSent(UserMessage userMessage, SendBirdException e) {
mMessageCollection.handleSendMessageResponse(userMessage, e);
}
});
} else if (message instanceof FileMessage) {
Uri uri = mChatAdapter.getTempFileMessageUri(message);
sendFileWithThumbnail(uri);
// mChatAdapter.removeFailedMessages(Collections.singletonList(message));
}
}
}
})
.setNegativeButton(R.string.delete_message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
if (message instanceof UserMessage) {
mMessageCollection.deleteMessage(message);
} else if (message instanceof FileMessage) {
// mChatAdapter.removeFailedMessages(Collections.singletonList(message));
}
}
}
}).show();
}
public void sendFileWithThumbnail(Uri uri) {
Log.d("datain", "1" + uri + "--");
Uri uri2 = uri;
ArrayList arrayList = new ArrayList();
arrayList.add(new FileMessage.ThumbnailSize(240, 240));
arrayList.add(new FileMessage.ThumbnailSize(320, 320));
Hashtable<String, Object> info = FileUtils.getFileInfo(getActivity(), uri2);
// for (Map.Entry<String,Object> entry : info.entrySet()) {
// Log.d("datain","2"+uri+"--");
// String key = entry.getKey();
// Log.e("key doc", key);
// Object value = entry.getValue();
// // do stuff
// }
if (info == null) {
Log.d("datain", "3" + uri + "--");
Toast.makeText(getActivity(), "Extracting file information failed.", Toast.LENGTH_LONG).show();
return;
}
Log.d("datain", "4" + uri + "--");
String path = (String) info.get("path");
File file = new File(path);
String name = (String) info.get("name");
String mime = (String) info.get("mime");
int size = ((Integer) info.get("size")).intValue();
Log.e("key doc", name + " " + mime + " " + size + " " + path);
if (path.equals("")) {
Toast.makeText(getActivity(), "File must be located in local storage.", Toast.LENGTH_LONG).show();
} else {
Log.d("datain", "5" + uri + "--");
BaseChannel.SendFileMessageWithProgressHandler r11 = new BaseChannel.SendFileMessageWithProgressHandler() {
public void onProgress(int bytesSent, int totalBytesSent, int totalBytesToSend) {
Log.d("datain", "6" + uri + "--");
if (mFileProgressHandlerMap != null) {
Log.d("datain", "7" + uri + "--");
FileMessage fileMessage = (FileMessage) mFileProgressHandlerMap.get(this);
if (fileMessage != null && totalBytesToSend > 0) {
Log.d("datain", "8" + uri + "--");
mChatAdapter.setFileProgressPercent(fileMessage, (totalBytesSent * 100) / totalBytesToSend);
}
}
}
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
Log.e("onSent doc", String.valueOf(e));
try {
FragmentActivity activity = getActivity();
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(e.getCode());
sb.append(":");
sb.append(e.getMessage());
Toast.makeText(activity, sb.toString(), Toast.LENGTH_SHORT).show();
mChatAdapter.markMessageFailed(fileMessage.getRequestId());
} catch (Exception e2) {
}
return;
}
Log.e("onSent doc", fileMessage.getName());
mChatAdapter.markMessageSent(fileMessage);
}
};
if (this.mChannel != null) {
BaseChannel.SendFileMessageWithProgressHandler sendFileMessageWithProgressHandler = r11;
FileMessage tempFileMessage = this.mChannel.sendFileMessage(file, name, mime, size, "", (String) null, (List<FileMessage.ThumbnailSize>) arrayList, r11);
this.mFileProgressHandlerMap.put(sendFileMessageWithProgressHandler, tempFileMessage);
this.mChatAdapter.addTempFileMessageInfo(tempFileMessage, uri2);
this.mChatAdapter.addFirst(tempFileMessage);
}
}
}
public void setTypingStatus(boolean typing) {
if (this.mChannel != null) {
if (typing) {
this.mIsTyping = true;
// this.mChannel.startTyping();
} else {
this.mIsTyping = false;
// this.mChannel.endTyping();
}
}
}
private void setUpChatListAdapter() {
mChatAdapter = new OpenChatAdapter(getActivity(), mChannelUrl);
mChatAdapter.setItemClickListener(new OpenChatAdapter.OnItemClickListener() {
@Override
public void onUserMessageItemClick(UserMessage message) {
if (mChatAdapter.isFailedMessage(message) && !mChatAdapter.isResendingMessage(message)) {
retryFailedMessage(message);
return;
}
// Message is sending. Do nothing on click event.
if (mChatAdapter.isTempMessage(message)) {
return;
}
if (message.getCustomType().equals(GroupChatAdapter.URL_PREVIEW_CUSTOM_TYPE)) {
try {
UrlPreviewInfo info = new UrlPreviewInfo(message.getData());
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.getUrl()));
startActivity(browserIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onFileMessageItemClick(FileMessage message) {
// Load media chooser and removeSucceededMessages the failed message from list.
if (mChatAdapter.isFailedMessage(message)) {
retryFailedMessage(message);
return;
}
// Message is sending. Do nothing on click event.
if (mChatAdapter.isTempMessage(message)) {
return;
}
onFileMessageClicked(message);
}
@Override
public void onAdminMessageItemClick(AdminMessage message) {
}
});
mChatAdapter.setItemLongClickListener(new OpenChatAdapter.OnItemLongClickListener() {
@Override
public void onUserMessageItemLongClick(UserMessage message, int position) {
if (message.getSender().getUserId().equals(PreferenceUtils.getUserId())) {
showMessageOptionsDialog(message, position);
}
}
@Override
public void onAdminMessageItemLongClick(AdminMessage message) {
}
@Override
public void onFileMessageItemLongClick(FileMessage fileMessage, int i) {
}
});
}
/*public void sendRecordedFile(String uri) {
File file = new File(uri);
ArrayList arrayList = new ArrayList();
arrayList.add(new FileMessage.ThumbnailSize(240, 240));
arrayList.add(new FileMessage.ThumbnailSize(320, 320));
if (uri.equals("")) {
Toast.makeText(getActivity(), "File must be located in local storage.", Toast.LENGTH_LONG).show();
return;
}
BaseChannel.SendFileMessageWithProgressHandler r10 = new BaseChannel.SendFileMessageWithProgressHandler() {
public void onProgress(int bytesSent, int totalBytesSent, int totalBytesToSend) {
FileMessage fileMessage = (FileMessage) mFileProgressHandlerMap.get(this);
if (fileMessage != null && totalBytesToSend > 0) {
mChatAdapter.setFileProgressPercent(fileMessage, (totalBytesSent * 100) / totalBytesToSend);
}
}
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
FragmentActivity activity = getActivity();
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append("Send Failed with an error");
sb.append(":");
sb.append(e.getMessage());
Toast.makeText(activity, sb.toString(), Toast.LENGTH_SHORT).show();
// mChatAdapter.markMessageFailed(fileMessage.getRequestId());
return;
}
mChatAdapter.markMessageSent(fileMessage);
}
};
if (this.mChannel != null) {
FileMessage tempFileMessage = this.mChannel.sendFileMessage(file, "Recording", "audio/mpeg", 346923, "", (String) null, (List<FileMessage.ThumbnailSize>) arrayList, (BaseChannel.SendFileMessageWithProgressHandler) r10);
this.mFileProgressHandlerMap.put(r10, tempFileMessage);
this.mChatAdapter.addTempFileMessageInfo(tempFileMessage, Uri.parse(uri));
this.mChatAdapter.addFirst(tempFileMessage);
}
}*/
public void sendRecordedFile(String uri) {
File file = new File(uri);
ArrayList<FileMessage.ThumbnailSize> arrayList = new ArrayList<>();
arrayList.add(new FileMessage.ThumbnailSize(240, 240));
arrayList.add(new FileMessage.ThumbnailSize(320, 320));
if (uri.equals("")) {
Toast.makeText(getActivity(), "File must be located in local storage.", Toast.LENGTH_LONG).show();
return;
}
BaseChannel.SendFileMessageWithProgressHandler r10 = new BaseChannel.SendFileMessageWithProgressHandler() {
public void onProgress(int bytesSent, int totalBytesSent, int totalBytesToSend) {
FileMessage fileMessage = (FileMessage) OpenChatFragment.this.mFileProgressHandlerMap.get(this);
if (fileMessage != null && totalBytesToSend > 0) {
OpenChatFragment.this.mChatAdapter.setFileProgressPercent(fileMessage, (totalBytesSent * 100) / totalBytesToSend);
}
}
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
FragmentActivity activity = OpenChatFragment.this.getActivity();
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(e.getCode());
sb.append(":");
sb.append(e.getMessage());
Toast.makeText(activity, sb.toString(), Toast.LENGTH_SHORT).show();
OpenChatFragment.this.mChatAdapter.markMessageFailed(fileMessage.getRequestId());
return;
}
OpenChatFragment.this.mChatAdapter.markMessageSent(fileMessage);
}
};
if (this.mChannel != null) {
FileMessage tempFileMessage = this.mChannel.sendFileMessage(file, "Recording", "audio/mpeg", 346923, "", (String) null, arrayList, (BaseChannel.SendFileMessageWithProgressHandler) r10);
this.mFileProgressHandlerMap.put(r10, tempFileMessage);
this.mChatAdapter.addTempFileMessageInfo(tempFileMessage, Uri.parse(uri));
this.mChatAdapter.addFirst(tempFileMessage);
}
}
public void requestMedia() {
if (ContextCompat.checkSelfPermission(getActivity(), "android.permission.WRITE_EXTERNAL_STORAGE") != 0) {
requestStoragePermissions();
return;
}
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= 19) {
intent.setType("*/*");
intent.putExtra("android.intent.extra.MIME_TYPES", new String[]{MimeType.IMAGE_MIME, "video/*"});
} else {
intent.setType("image/* video/*");
}
intent.setAction("android.intent.action.GET_CONTENT");
startActivityForResult(Intent.createChooser(intent, "Select Media"), 301);
SendBird.setAutoBackgroundDetection(false);
}
private void initView() {
//this.mAudioRecordButton = audio_record_button;//comment
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_WRITE_EXTERNAL_STORAGE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
Snackbar.make(mRootLayout, "Storage permissions granted. You can now upload or download files.",
Snackbar.LENGTH_LONG)
.show();
} else {
// Permission denied.
Snackbar.make(mRootLayout, "Permissions denied.",
Snackbar.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SendBird.setAutoBackgroundDetection(true);
if (requestCode == 301 && resultCode == -1) {
if (data == null) {
Log.d(LOG_TAG, "data is null!");
return;
}
showUploadConfirmDialog(data.getData());
} else if (requestCode == 100 && resultCode == -1) {
if (data == null) {
Log.d(LOG_TAG, "data is null!");
} else {
showUploadConfirmDialog(getImageUri(getActivity(), (Bitmap) data.getExtras().get("data")));
}
} else if (requestCode == this.REQUEST_CODE_DOC && resultCode == -1) {
if (data == null) {
Log.d(LOG_TAG, "data is null!");
return;
}
Log.d("DOC DATA", data + "" + data.getData());
showUploadConfirmDialog(data.getData());
} else if (requestCode == 101 && resultCode == -1) {
if (data == null) {
Log.d(LOG_TAG, "data is null!");
return;
}
showUploadConfirmDialog(data.getData());
} else if (requestCode == 3 && resultCode == -1) {
if (data == null) {
Log.d(LOG_TAG, "data is null!");
return;
}
this.contactname = data.getStringExtra("contactname_key");
this.phonenum = data.getStringExtra("phonenum_key");
sendContact(this.contactname, this.phonenum);
} else if (requestCode == 44 && resultCode == -1) {
if (data == null) {
Log.d(LOG_TAG, "data is null!");
return;
}
sendUserMessage(data.getStringExtra("latlong_key"));
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
inImage.compress(Bitmap.CompressFormat.JPEG, 100, new ByteArrayOutputStream());
return Uri.parse(MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null));
}
private void sendContact(String name, String number) {
this.mChatAdapter.addFirst(this.mChannel.sendUserMessage(name, number, "Contact", null, new BaseChannel.SendUserMessageHandler() {
public void onSent(UserMessage userMessage, SendBirdException e) {
if (e != null) {
Log.e(OpenChatFragment.LOG_TAG, e.toString());
FragmentActivity activity = getActivity();
StringBuilder sb = new StringBuilder();
sb.append("Send failed with error ");
sb.append(e.getCode());
sb.append(": ");
sb.append(e.getMessage());
Toast.makeText(activity, sb.toString(), Toast.LENGTH_SHORT).show();
// mChatAdapter.markMessageFailed(userMessage.getRequestId());
return;
}
mChatAdapter.markMessageSent(userMessage);
}
}));
}
@Override
public void onResume() {
super.onResume();
refresh();
refreshFirst();
/* ConnectionManager.addConnectionManagementHandler(CONNECTION_HANDLER_ID, new ConnectionManager.ConnectionManagementHandler() {
@Override
public void onConnected(boolean reconnect) {
if (reconnect) {
refresh();
} else {
refreshFirst();
}
}
});*/
SendBird.addChannelHandler(CHANNEL_HANDLER_ID, new SendBird.ChannelHandler() {
@Override
public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
// Add new message to view
if (baseChannel.getUrl().equals(mChannelUrl)) {
mChatAdapter.addFirst(baseMessage);
}
}
@Override
public void onMessageDeleted(BaseChannel baseChannel, long msgId) {
super.onMessageDeleted(baseChannel, msgId);
if (baseChannel.getUrl().equals(mChannelUrl)) {
mChatAdapter.delete(msgId);
}
}
@Override
public void onMessageUpdated(BaseChannel channel, BaseMessage message) {
super.onMessageUpdated(channel, message);
if (channel.getUrl().equals(mChannelUrl)) {
mChatAdapter.update(message);
}
}
});
}
@Override
public void onPause() {
// ConnectionManager.removeConnectionManagementHandler(CONNECTION_HANDLER_ID);
SendBird.removeChannelHandler(CHANNEL_HANDLER_ID);
super.onPause();
}
@Override
public void onDestroyView() {
if (mChannel != null) {
mChannel.exit(new OpenChannel.OpenChannelExitHandler() {
@Override
public void onResult(SendBirdException e) {
if (e != null) {
// Error!
e.printStackTrace();
return;
}
}
});
}
super.onDestroyView();
}
//
// private void setUpChatAdapter() {
// mChatAdapter = new OpenChatAdapter(getActivity(),mChannelUrl);
// mChatAdapter.setOnItemClickListener(new OpenChatAdapter.OnItemClickListener() {
// @Override
// public void onUserMessageItemClick(UserMessage message) {
// }
//
// @Override
// public void onFileMessageItemClick(FileMessage message) {
// onFileMessageClicked(message);
// }
//
// @Override
// public void onAdminMessageItemClick(AdminMessage message) {
// }
// });
//
// mChatAdapter.setOnItemLongClickListener(new OpenChatAdapter.OnItemLongClickListener() {
// @Override
// public void onBaseMessageLongClick(final BaseMessage message, int position) {
// showMessageOptionsDialog(message, position);
// }
// });
// }
private void showMessageOptionsDialog(final BaseMessage message, final int position) {
String[] options = new String[]{"Edit message", "Delete message"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
setState(STATE_EDIT, message, position);
} else if (which == 1) {
deleteMessage(message);
}
}
});
builder.create().show();
}
private void setState(int state, BaseMessage editingMessage, final int position) {
switch (state) {
case STATE_NORMAL:
mCurrentState = STATE_NORMAL;
mEditingMessage = null;
mUploadFileButton.setVisibility(View.VISIBLE);
mMessageSendButton.setText("SEND");
mMessageEditText.setText("");
break;
case STATE_EDIT:
mCurrentState = STATE_EDIT;
mEditingMessage = editingMessage;
mUploadFileButton.setVisibility(View.GONE);
mMessageSendButton.setText("SAVE");
String messageString = ((UserMessage) editingMessage).getMessage();
if (messageString == null) {
messageString = "";
}
mMessageEditText.setText(messageString);
if (messageString.length() > 0) {
mMessageEditText.setSelection(0, messageString.length());
}
mMessageEditText.requestFocus();
mMessageEditText.postDelayed(new Runnable() {
@Override
public void run() {
mIMM.showSoftInput(mMessageEditText, 0);
mRecyclerView.postDelayed(new Runnable() {
@Override
public void run() {
mRecyclerView.scrollToPosition(position);
}
}, 500);
}
}, 100);
break;
}
}
/* @Override
public void onAttach(Context context) {
super.onAttach(context);
*//* getActivity().setOnBackPressedListener(new OpenChannelActivity.onBackPressedListener() {
@Override
public boolean onBack() {
if (mCurrentState == STATE_EDIT) {
setState(STATE_NORMAL, null, -1);
return true;
}
mIMM.hideSoftInputFromWindow(mMessageEditText.getWindowToken(), 0);
return false;
}
});*//*
}*/
private void setUpRecyclerView() {
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mChatAdapter);
// Load more messages when user reaches the top of the current message list.
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// if (mLayoutManager.findFirstVisibleItemPosition() <= 0) {
// mMessageCollection.fetchSucceededMessages(MessageCollection.Direction.NEXT, null);
// // mNewMessageText.setVisibility(View.GONE);
// }
//
// if (mLayoutManager.findLastVisibleItemPosition() == mChatAdapter.getItemCount() - 1) {
// mMessageCollection.fetchSucceededMessages(MessageCollection.Direction.PREVIOUS, null);
// }
//
// }
if (mLayoutManager.findLastVisibleItemPosition() == mChatAdapter.getItemCount() - 1) {
loadNextMessageList(CHANNEL_LIST_LIMIT);
}
Log.v(LOG_TAG, "onScrollStateChanged");
}
});
}
private void onFileMessageClicked(FileMessage message) {
String type = message.getType().toLowerCase();
if (type.startsWith("image")) {
Intent i = new Intent(getActivity(), PhotoViewerActivity.class);
i.putExtra("url", message.getUrl());
i.putExtra("type", message.getType());
startActivity(i);
} else if (type.startsWith("video")) {
Intent intent = new Intent(getActivity(), MediaPlayerActivity.class);
intent.putExtra("url", message.getUrl());
startActivity(intent);
} else {
showDownloadConfirmDialog(message);
}
}
private void showDownloadConfirmDialog(final FileMessage message) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// If storage permissions are not granted, request permissions at run-time,
// as per < API 23 guidelines.
requestStoragePermissions();
} else {
new AlertDialog.Builder(getActivity())
.setMessage("Download file?")
.setPositiveButton(R.string.download, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// FileUtils.downloadFile(getActivity(), message.getUrl(), message.getName());
onStartFileDownloadListener.onStartFileDownload(message);
}
}
})
.setNegativeButton(R.string.cancel, null).show();
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.onStartFileDownloadListener = (OnStartFileDownloadListener) context;
}
private void showUploadConfirmDialog(final Uri uri) {
new AlertDialog.Builder(getActivity())
.setMessage("Upload file?")
.setPositiveButton(R.string.upload, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// Specify two dimensions of thumbnails to generate
List<FileMessage.ThumbnailSize> thumbnailSizes = new ArrayList<>();
thumbnailSizes.add(new FileMessage.ThumbnailSize(240, 240));
thumbnailSizes.add(new FileMessage.ThumbnailSize(320, 320));
sendImageWithThumbnail(uri, thumbnailSizes);
}
}
})
.setNegativeButton(R.string.cancel, null).show();
}
private void requestImage() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// If storage permissions are not granted, request permissions at run-time,
// as per < API 23 guidelines.
requestStoragePermissions();
} else {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/* video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Media"), INTENT_REQUEST_CHOOSE_IMAGE);
// Set this as false to maintain connection
// even when an external Activity is started.
SendBird.setAutoBackgroundDetection(false);
}
}
@SuppressLint("NewApi")
private void requestStoragePermissions() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
Snackbar.make(mRootLayout, "Storage access permissions are required to upload/download files.",
Snackbar.LENGTH_LONG)
.setAction("Okay", new View.OnClickListener() {
@Override
public void onClick(View view) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_WRITE_EXTERNAL_STORAGE);
}
})
.show();
} else {
// Permission has not been granted yet. Request it directly.
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_WRITE_EXTERNAL_STORAGE);
}
}
private void refreshFirst() {
enterChannel(mChannelUrl);
}
/**
* Enters an Open Channel.
* <p>
* A user must successfully enter a channel before being able to load or send messages
* within the channel.
*
* @param channelUrl The URL of the channel to enter.
*/
private void enterChannel(String channelUrl) {
OpenChannel.getChannel(channelUrl, new OpenChannel.OpenChannelGetHandler() {
@Override
public void onResult(final OpenChannel openChannel, SendBirdException e) {
if (e != null) {
// Error!
e.printStackTrace();
return;
}
// Enter the channel
openChannel.enter(new OpenChannel.OpenChannelEnterHandler() {
@Override
public void onResult(SendBirdException e) {
if (e != null) {
// Error!
e.printStackTrace();
return;
}
mChannel = openChannel;
if (getActivity() != null) {
// Set action bar title to name of channel
// ((Main3Activity) getActivity()).setActionBarTitle(mChannel.getName());
((Main3Activity) getActivity()).setActionBarTitle(mChannel.getName());
//Toast.makeText(getContext(), ""+mChannel.getName(), Toast.LENGTH_SHORT).show();
tv_chatperson_name.setText(mChannel.getName());
}
refresh();
}
});
}
});
}
private void sendUserMessage(String text) {
mChannel.sendUserMessage(text, new BaseChannel.SendUserMessageHandler() {
@Override
public void onSent(UserMessage userMessage, SendBirdException e) {
if (e != null) {
// Error!
Log.e(LOG_TAG, e.toString());
Toast.makeText(
getActivity(),
"Send failed with error " + e.getCode() + ": " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
return;
}
// Display sent message to RecyclerView
mChatAdapter.addFirst(userMessage);
}
});
}
/**
* Sends a File Message containing an image file.
* Also requests thumbnails to be generated in specified sizes.
*
* @param uri The URI of the image, which in this case is received through an Intent request.
*/
private void sendImageWithThumbnail(Uri uri, List<FileMessage.ThumbnailSize> thumbnailSizes) {
Hashtable<String, Object> info = FileUtils.getFileInfo(getActivity(), uri);
final String path = (String) info.get("path");
final File file = new File(path);
final String name = file.getName();
final String mime = (String) info.get("mime");
final int size = (Integer) info.get("size");
if (path.equals("")) {
Toast.makeText(getActivity(), "File must be located in local storage.", Toast.LENGTH_LONG).show();
} else {
// Send image with thumbnails in the specified dimensions
mChannel.sendFileMessage(file, name, mime, size, "", null, thumbnailSizes, new BaseChannel.SendFileMessageHandler() {
@Override
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
Toast.makeText(getActivity(), "" + e.getCode() + ":" + e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
mChatAdapter.addFirst(fileMessage);
}
});
}
}
private void refresh() {
if (this.mChannel == null) {
OpenChannel.getChannel(mChannelUrl, new OpenChannel.OpenChannelGetHandler() {
@Override
public void onResult(OpenChannel openChannel, SendBirdException e) {
if (e != null) {
e.printStackTrace();
return;
}
mChannel = openChannel;
OpenChatFragment.this.mChatAdapter.setChannel(OpenChatFragment.this.mChannel);
OpenChatFragment.this.mChatAdapter.loadLatestMessages(30, new BaseChannel.GetMessagesHandler() {
public void onResult(List<BaseMessage> list, SendBirdException e) {
OpenChatFragment.this.messagelist = list;
//OpenChatFragment.this.mChatAdapter.markAllMessagesAsRead();
OpenChatFragment.this.mChatAdapter.notifyDataSetChanged();
}
});
try {
tv_chatperson_name.setText(mChannel.getName());
// OpenChatFragment.this.chat_personimg.setImageResource(R.drawable.ic_logo_pink);
} catch (Exception e2) {
}
// Op
}
});
}
}
/**
* Replaces current message list with new list.
* Should be used only on initial load.
*/
private void loadInitialMessageList(int numMessages) {
mPrevMessageListQuery = mChannel.createPreviousMessageListQuery();
mPrevMessageListQuery.load(numMessages, true, new PreviousMessageListQuery.MessageListQueryResult() {
@Override
public void onResult(List<BaseMessage> list, SendBirdException e) {
if (e != null) {
// Error!
e.printStackTrace();
return;
}
mChatAdapter.setMessageList(list);
}
});
}
/**
* Loads messages and adds them to current message list.
* <p>
* A PreviousMessageListQuery must have been already initialized through {@link #loadInitialMessageList(int)}
*/
private void loadNextMessageList(int numMessages) throws NullPointerException {
if (mChannel == null) {
Log.d("OpenChatFragment", "No more Channel ");
}
// mPrevMessageListQuery.load(numMessages, true, new PreviousMessageListQuery.MessageListQueryResult() {
// @Override
// public void onResult(List<BaseMessage> list, SendBirdException e) {
// if (e != null) {
// // Error!
// e.printStackTrace();
// return;
// }
//
// for (BaseMessage message : list) {
// mChatAdapter.addLast((message));
// }
// }
// });
OpenChatFragment.this.mChatAdapter.loadLatestMessages(numMessages, new BaseChannel.GetMessagesHandler() {
public void onResult(List<BaseMessage> list, SendBirdException e) {
OpenChatFragment.this.messagelist = list;
//OpenChatFragment.this.mChatAdapter.markAllMessagesAsRead();
OpenChatFragment.this.mChatAdapter.notifyDataSetChanged();
}
});
}
private void editMessage(final BaseMessage message, String editedMessage) {
mChannel.updateUserMessage(message.getMessageId(), editedMessage, null, null, new BaseChannel.UpdateUserMessageHandler() {
@Override
public void onUpdated(UserMessage userMessage, SendBirdException e) {
if (e != null) {
// Error!
Toast.makeText(getActivity(), "Error " + e.getCode() + ": " + e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
refresh();
}
});
}
/**
* Deletes a message within the channel.
* Note that users can only delete messages sent by oneself.
*
* @param message The message to delete.
*/
private void deleteMessage(final BaseMessage message) {
mChannel.deleteMessage(message, new BaseChannel.DeleteMessageHandler() {
@Override
public void onResult(SendBirdException e) {
if (e != null) {
// Error!
Toast.makeText(getActivity(), "Error " + e.getCode() + ": " + e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
refresh();
}
});
}
public void notifyAdapter() {
this.mChatAdapter.notifyDataSetChanged();
}
}
|
schimmelpfeng-dmlr/azure-service-operator | v2/internal/controllers/operatormode_test.go | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package controllers_test
import (
"testing"
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
resources "github.com/Azure/azure-service-operator/v2/api/microsoft.resources/v1alpha1api20200601"
"github.com/Azure/azure-service-operator/v2/internal/config"
"github.com/Azure/azure-service-operator/v2/internal/testcommon"
)
func TestOperatorMode_Webhooks(t *testing.T) {
t.Parallel()
tc := globalTestContext.ForTestWithConfig(t, config.Values{
OperatorMode: config.OperatorModeWebhooks,
})
rg := resources.ResourceGroup{
ObjectMeta: metav1.ObjectMeta{
Name: tc.Namer.GenerateName("rg"),
Namespace: tc.Namespace,
},
Spec: resources.ResourceGroupSpec{
Location: tc.AzureRegion,
Tags: testcommon.CreateTestResourceGroupDefaultTags(),
},
}
tc.Expect(rg.Spec.AzureName).To(Equal(""))
_, err := tc.CreateResourceGroup(&rg)
tc.Expect(err).ToNot(HaveOccurred())
// AzureName should have been defaulted on the group on the
// way in (it doesn't require waiting for a reconcile).
tc.Expect(rg.Spec.AzureName).To(Equal(rg.ObjectMeta.Name))
checkNeverGetsFinalizer(tc, &rg,
"instance got a finalizer when operator mode is webhooks")
}
func TestOperatorMode_Watchers(t *testing.T) {
t.Parallel()
tc := globalTestContext.ForTestWithConfig(t, config.Values{
OperatorMode: config.OperatorModeWatchers,
})
rg := resources.ResourceGroup{
ObjectMeta: metav1.ObjectMeta{
Name: tc.Namer.GenerateName("rg"),
Namespace: tc.Namespace,
},
Spec: resources.ResourceGroupSpec{
Location: tc.AzureRegion,
Tags: testcommon.CreateTestResourceGroupDefaultTags(),
},
}
tc.Expect(rg.Spec.AzureName).To(Equal(""))
_, err := tc.CreateResourceGroup(&rg)
// We should fail because the webhook isn't registered (in a real
// multi-operator deployment it would be routed to a different
// operator running in webhook-only mode).
tc.Expect(err.Error()).To(MatchRegexp(`failed calling webhook .* connection refused`))
// Nothing else to check since we can't create the resource
// without a webhook.
}
func TestOperatorMode_Both(t *testing.T) {
t.Parallel()
tc := globalTestContext.ForTestWithConfig(t, config.Values{
OperatorMode: config.OperatorModeBoth,
})
rg := resources.ResourceGroup{
ObjectMeta: metav1.ObjectMeta{
Name: tc.Namer.GenerateName("rg"),
Namespace: tc.Namespace,
},
Spec: resources.ResourceGroupSpec{
Location: tc.AzureRegion,
Tags: testcommon.CreateTestResourceGroupDefaultTags(),
},
}
tc.Expect(rg.Spec.AzureName).To(Equal(""))
_, err := tc.CreateResourceGroup(&rg)
tc.Expect(err).NotTo(HaveOccurred())
// AzureName should have been defaulted on the group on the
// way in (it doesn't require waiting for a reconcile).
tc.Expect(rg.Spec.AzureName).To(Equal(rg.ObjectMeta.Name))
tc.Eventually(&rg).Should(tc.Match.BeProvisioned())
}
|
pavechernyshev/job4j | chapter_005/src/main/java/ru/job4j/generics/AbstractStore.java | package ru.job4j.generics;
/***
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public abstract class AbstractStore<T extends Base> implements Store<T> {
protected SimpleArray<T> simpleArray;
public AbstractStore(SimpleArray<T> simpleArray) {
this.simpleArray = simpleArray;
}
protected int findPosById(String id) {
int result = -1;
for (int index = 0; index < simpleArray.getSize(); index++) {
T u = simpleArray.get(index);
if (u != null && u.getId().equals(id)) {
result = index;
break;
}
}
return result;
}
@Override
public void add(T model) {
this.simpleArray.add(model);
}
@Override
public boolean replace(String id, T model) {
int pos = findPosById(id);
boolean result = pos >= 0;
if (result) {
this.simpleArray.set(pos, model);
}
return result;
}
@Override
public boolean delete(String id) {
int pos = findPosById(id);
boolean result = pos >= 0;
if (result) {
simpleArray.delete(pos);
}
return result;
}
@Override
public T findById(String id) {
T result = null;
for (T u : simpleArray) {
if (u != null && u.getId().equals(id)) {
result = u;
break;
}
}
return result;
}
}
|
dspjlj/wsp | src/com/jlj/model/Wscpscenter.java | package com.jlj.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Wscpscenter entity.
*
* @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "wscpscenter", catalog = "wsp")
public class Wscpscenter implements java.io.Serializable {
// Fields
private Integer id;
private Whymember whymember;
private Wsc wsc;
private String phone;
private String password;
private Integer sypoint;
private Float xfmoney;
private Float symoney;
private String username;
private Date birthday;
private String email;
private String publicaccount;
private Set<Wscaddress> wscaddresses = new HashSet<Wscaddress>(0);
private Set<Whdscratchcardrecord> whdscratchcardrecords = new HashSet<Whdscratchcardrecord>(
0);
private Set<Whdstandingrecord> whdstandingrecords = new HashSet<Whdstandingrecord>(
0);
private Set<Wscprodiscount> wscprodiscounts = new HashSet<Wscprodiscount>(0);
private Set<Wscprocollect> wscprocollects = new HashSet<Wscprocollect>(0);
private Set<Whdgoldeneggrecord> whdgoldeneggrecords = new HashSet<Whdgoldeneggrecord>(
0);
private Set<Wdyrecord> wdyrecords = new HashSet<Wdyrecord>(0);
private Set<Wtgrecord> wtgrecords = new HashSet<Wtgrecord>(0);
private Set<Wtprecord> wtprecords = new HashSet<Wtprecord>(0);
private Set<Whdcouponrecord> whdcouponrecords = new HashSet<Whdcouponrecord>(
0);
private Set<Whdbigwheelrecord> whdbigwheelrecords = new HashSet<Whdbigwheelrecord>(
0);
private Set<Whdluckyrecord> whdluckyrecords = new HashSet<Whdluckyrecord>(0);
// Constructors
/** default constructor */
public Wscpscenter() {
}
/** full constructor */
public Wscpscenter(Whymember whymember, Wsc wsc, String phone,
String password, Integer sypoint, Float xfmoney, Float symoney,
String username, Date birthday, String email, String publicaccount,
Set<Wscaddress> wscaddresses,
Set<Whdscratchcardrecord> whdscratchcardrecords,
Set<Whdstandingrecord> whdstandingrecords,
Set<Wscprodiscount> wscprodiscounts,
Set<Wscprocollect> wscprocollects,
Set<Whdgoldeneggrecord> whdgoldeneggrecords,
Set<Wdyrecord> wdyrecords, Set<Wtgrecord> wtgrecords,
Set<Wtprecord> wtprecords, Set<Whdcouponrecord> whdcouponrecords,
Set<Whdbigwheelrecord> whdbigwheelrecords,
Set<Whdluckyrecord> whdluckyrecords) {
this.whymember = whymember;
this.wsc = wsc;
this.phone = phone;
this.password = password;
this.sypoint = sypoint;
this.xfmoney = xfmoney;
this.symoney = symoney;
this.username = username;
this.birthday = birthday;
this.email = email;
this.publicaccount = publicaccount;
this.wscaddresses = wscaddresses;
this.whdscratchcardrecords = whdscratchcardrecords;
this.whdstandingrecords = whdstandingrecords;
this.wscprodiscounts = wscprodiscounts;
this.wscprocollects = wscprocollects;
this.whdgoldeneggrecords = whdgoldeneggrecords;
this.wdyrecords = wdyrecords;
this.wtgrecords = wtgrecords;
this.wtprecords = wtprecords;
this.whdcouponrecords = whdcouponrecords;
this.whdbigwheelrecords = whdbigwheelrecords;
this.whdluckyrecords = whdluckyrecords;
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "whymemberid")
public Whymember getWhymember() {
return this.whymember;
}
public void setWhymember(Whymember whymember) {
this.whymember = whymember;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "wscid")
public Wsc getWsc() {
return this.wsc;
}
public void setWsc(Wsc wsc) {
this.wsc = wsc;
}
@Column(name = "phone", length = 20)
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "password", length = 20)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "sypoint")
public Integer getSypoint() {
return this.sypoint;
}
public void setSypoint(Integer sypoint) {
this.sypoint = sypoint;
}
@Column(name = "xfmoney", precision = 12, scale = 0)
public Float getXfmoney() {
return this.xfmoney;
}
public void setXfmoney(Float xfmoney) {
this.xfmoney = xfmoney;
}
@Column(name = "symoney", precision = 12, scale = 0)
public Float getSymoney() {
return this.symoney;
}
public void setSymoney(Float symoney) {
this.symoney = symoney;
}
@Column(name = "username", length = 20)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Temporal(TemporalType.DATE)
@Column(name = "birthday", length = 10)
public Date getBirthday() {
return this.birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Column(name = "email", length = 30)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "publicaccount", length = 30)
public String getPublicaccount() {
return this.publicaccount;
}
public void setPublicaccount(String publicaccount) {
this.publicaccount = publicaccount;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Wscaddress> getWscaddresses() {
return this.wscaddresses;
}
public void setWscaddresses(Set<Wscaddress> wscaddresses) {
this.wscaddresses = wscaddresses;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Whdscratchcardrecord> getWhdscratchcardrecords() {
return this.whdscratchcardrecords;
}
public void setWhdscratchcardrecords(
Set<Whdscratchcardrecord> whdscratchcardrecords) {
this.whdscratchcardrecords = whdscratchcardrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Whdstandingrecord> getWhdstandingrecords() {
return this.whdstandingrecords;
}
public void setWhdstandingrecords(Set<Whdstandingrecord> whdstandingrecords) {
this.whdstandingrecords = whdstandingrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Wscprodiscount> getWscprodiscounts() {
return this.wscprodiscounts;
}
public void setWscprodiscounts(Set<Wscprodiscount> wscprodiscounts) {
this.wscprodiscounts = wscprodiscounts;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Wscprocollect> getWscprocollects() {
return this.wscprocollects;
}
public void setWscprocollects(Set<Wscprocollect> wscprocollects) {
this.wscprocollects = wscprocollects;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Whdgoldeneggrecord> getWhdgoldeneggrecords() {
return this.whdgoldeneggrecords;
}
public void setWhdgoldeneggrecords(
Set<Whdgoldeneggrecord> whdgoldeneggrecords) {
this.whdgoldeneggrecords = whdgoldeneggrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Wdyrecord> getWdyrecords() {
return this.wdyrecords;
}
public void setWdyrecords(Set<Wdyrecord> wdyrecords) {
this.wdyrecords = wdyrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Wtgrecord> getWtgrecords() {
return this.wtgrecords;
}
public void setWtgrecords(Set<Wtgrecord> wtgrecords) {
this.wtgrecords = wtgrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Wtprecord> getWtprecords() {
return this.wtprecords;
}
public void setWtprecords(Set<Wtprecord> wtprecords) {
this.wtprecords = wtprecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Whdcouponrecord> getWhdcouponrecords() {
return this.whdcouponrecords;
}
public void setWhdcouponrecords(Set<Whdcouponrecord> whdcouponrecords) {
this.whdcouponrecords = whdcouponrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Whdbigwheelrecord> getWhdbigwheelrecords() {
return this.whdbigwheelrecords;
}
public void setWhdbigwheelrecords(Set<Whdbigwheelrecord> whdbigwheelrecords) {
this.whdbigwheelrecords = whdbigwheelrecords;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "wscpscenter")
public Set<Whdluckyrecord> getWhdluckyrecords() {
return this.whdluckyrecords;
}
public void setWhdluckyrecords(Set<Whdluckyrecord> whdluckyrecords) {
this.whdluckyrecords = whdluckyrecords;
}
} |
muparkkra/mup | tools/test/reggen2.c | /*
Copyright (c) 1995-2021 by Arkkra Enterprises.
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that
the following conditions are met:
1. Redistributions of source code must retain
the above copyright notice, this list of conditions
and the following DISCLAIMER.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and
the following DISCLAIMER in the documentation and/or
other materials provided with the distribution.
3. Any additions, deletions, or changes to the original files
must be clearly indicated in accompanying documentation,
including the reasons for the changes,
and the names of those who made the modifications.
DISCLAIMER
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This program generate random Mup input files and runs Mup on them, as a
* way to do regression testing. If the program runs to completion before
* a timeout value, and without generating a core dump, the input is discarded.
* Otherwise, the file is kept as a way to potentially reproduce a bug.
* On a reasonably fast machine, it is possible to run over a million test
* cases in less than a day.
* Arguments:
* -d use mupdisp instead of mup
* -i iterations generate this many tests. Default is ITERATIONS
* (ITERATIONS is #defined below)
* -n also save files that give non-zero exit codes
* -t timeout timeout value in seconds. Default is TIMEOUT
* (TIMEOUT is #defined below)
* -p prefix use this prefix for generated files
* -v verbose
* If compiled with GENONLY defined, it will only generate files, not run
* mup, useful for non-UNIX-like systems, since this uses fork/exec and
* expects to be able to run "sh -c"
* With GENONLY, -i and -p are the only valid options.
* GENONLY gets defined if __TURBOC__ or __WATCOMC__ or __DOS__ are defined.
*
* Typically, more than 90% of the generated files are not completely legal
* Mup input, and the rest tend to have things no sane musician would actually
* input, but that is a very good thing,
* because we have found that most of the bugs
* that remain in Mup after normal functional testing with good examples
* are in obscure error cases, or interactions of strange combinations of
* features that we would never think of testing.
* It even randomly throws in a few typos.
* So if this program runs through a million test cases without triggering any
* core dumps or infinite loops, that means the code is probably pretty solid.
*
* Each input is run both for PostScript and MIDI output, since those go
* through somewhat different code, and a -x option is used a random percentage
* of the time, since that tends to interact with many other things.
*/
#ifdef __TURBOC__
#define __DOS__ 1
#endif
#ifdef __WATCOMC__
#define __DOS__ 1
#endif
#ifdef __DOS__
#define GENONLY 1
#endif
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#ifndef GENONLY
#include <sys/wait.h>
#endif
#include <signal.h>
#include <time.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include "rational.h"
/* default values */
#define ITERATIONS 100
#define TIMEOUT 10
#define YES 1
#define NO 0
/* special flag to mark octave. Must be different from YES and NO */
#define OCTSTR 2
/* special flag to mark chord with grid.
* Must be different than YES, NO, and OCTSTR */
#define GRIDCHORD 3
/* Values to control how mup input is generated */
short use1; /* % of time to explicitly state voice 1,
* when it will default to 1 anyway */
short measrest; /* % of time to use measure rest */
short measspace; /* % of time to use measure space */
short measrpt; /* % of time to use measure repeat */
short sylposition; /* % of time to specific sylposition parameter */
short staffpad; /* % of time to specific staffpad parameter */
short scorepad; /* % of time to specific scorepad parameter */
short rehstyle; /* % of time to specific rehstyle parameter */
short brack; /* % of time to use [ ] things */
short whitebefore; /* % of time to put white space before token */
short whiteafter; /* % of time to put white space after token */
short extranl; /* % of time to add extra newline */
short swingunit; /* % of time to use swingunit */
short stemlen; /* % of time to use stemlen */
short stemshorten; /* % of time to use stemshorten */
short staffmult; /* % of time to have an SSV apply to multiple staffs */
short crnl; /* % of time to use \r\n */
short cr_only; /* % of time to use \r alone as line separator */
short midmeas; /* % of time to make mid-measure param chgs */
short noteheads; /* % of time to use noteheads parameter */
short typo; /* % of time to add a "typo" to the input */
short scorefeed; /* % of time to use newscore */
short pagefeed; /* % of time to use newpage */
short marginoverride; /* % of time to override margin on feeds */
short restart; /* % of time to use restart */
short samescore; /* % of time to use samescore zone */
short samepage; /* % of time to use samepage zone */
short dotted; /* % of time to use dotted notes */
short dbldotted; /* % of time to use double dotted notes */
short timedflt; /* % of time to use time default value if possible */
short wrongtime; /* % of time to use incorrect amount of time in meas */
short rest; /* % of time to use rest */
short space; /* % of time to use space */
short uncompressible; /* % of time use make space uncompressible */
short subdivide; /* % of time to subdivide notes */
short accidental; /* % of time to use accidental */
short rehlet; /* % of time to use reh let */
short rehnum; /* % of time to use reh num */
short rehmnum; /* % of time to use reh mnum */
short rehstr; /* % of time to use reh "string" */
short multirest; /* % of time to use multirest */
short restsymmult; /* % of time to use restsymmult */
short printedtime; /* % of time to use printedtime */
short additive_time; /* % of time to use additive time */
short cross_staff_stems; /* % of time to use cross-staff stems */
short phrase; /* % of time to generate phrase marks */
short octavesbeyond; /* how many octave beyond default to use for notes */
short alt; /* % of time to use alt */
short numalt; /* argument to alt */
short custombeam; /* % of time to do custom beaming */
short autobeaming; /* % of time to do abm / eabm */
short esbm; /* % of time to do esbm */
short ph_eph; /* % of time to do ph - eph */
short slope; /* % of time to specify slope on beam */
short compoundts; /* % of time to use time sig with additive numerator */
short comments; /* % of time to add comments */
short vcombine; /* % of time to use vcombine parameter */
short pagesize; /* % of time to use pagesize parameter */
short pedal; /* % of time to use pedal */
short endped; /* % of time to use endped */
short pedpermeas; /* max pedal per measure */
short margins; /* % of time to set margin */
short dist; /* % of time to set dist/chorddist/crescdist */
short aligntag; /* % of time to use align tag on STUFF */
short division; /* % of time to set division parameter */
short endingstyle; /* % of time to set endingstyle */
short label; /* % of time to set label */
short measnum; /* % of time to specify measnum */
short maxmeasures; /* % of time to specify maxmeasures */
short maxscores; /* % of time to specify maxscores */
short slashesbetween; /* % of time to specify slashesbetween */
short bracketrepeats; /* % of time to specify bracketrepeats */
short repeatdots; /* % of time to specify repeatdots */
short withfont; /* % of time to specify with font/familly/size */
short pack; /* % of time to specify packfact or packexp */
short transpose; /* % of time to transpose */
short chordtranslation; /* % of time to use chordtranslation */
short useaccs; /* % of time to use useaccs */
short carryaccs; /* % of time to use carryaccs */
short emptymeas; /* % of time to use emptymeas */
short alignped; /* % of time to use alignped */
short alignlabels; /* % of time to use alignlabels */
short extendlyrics; /* % of time to use extendlyrics */
short tag; /* % of time to add tag */
short abstag; /* % of time to use absolute tag */
short prints; /* % of time to generate print commands */
short dd_bar; /* % of time to do dashed/dotted bar lines */
short string_escapes; /* % of time to do things like \v \s \f etc */
short modifier; /* % of time to use chord/analysis/figbass */
short box; /* % of time to do boxed string */
short staffscale; /* % of time to use staffscale */
short multi_brack; /* % of time to do more than one [] on group */
short gtc; /* % of time to use ... (good til canceled) */
short unsetparam; /* % of time to use use unset */
short viswhereused; /* % of time to use visible=whereused */
short paragraph; /* % of time to use paragraph */
short block; /* % of time to use block */
short restcombine; /* % of time to use restcombine param */
short firstpage; /* % of time to use firstpage param */
short fretx, freto, fretdash; /* % of time to use x, o, and - in grids */
short grids; /* % of time to generate grids */
short gridfret; /* % of time to use gridfret param */
short gridscale; /* % of time to use gridscale param */
short gridparen; /* % of time to use parentheses in grid definitions */
short mingridheight; /* % of time to use mingridheight param */
short minalignscale; /* % of time to use minalignscale param */
short orderlist; /* % of time to use aboveorder, etc */
short phrasemod; /* % of time to use dotted or dashed phrase */
short xoption; /* % of time to use -x comand line argument */
short print; /* % of time to generate print (x,y) "xxx" */
short line; /* % of time to generate lines */
short curve; /* % of time to generate curves (not bulge) */
short bulgecurve; /* % of time to generate curves (using bulge) */
short keymaps; /* % of time generate keymaps */
short tuning; /* % of time to use tuning parameter */
short midi; /* % of time to put midi things */
short midi_to; /* % of time to add "to" to midi things */
short control; /* % of time to use control context */
short saveparms; /* % of time to use saveparms */
short restoreparms; /* % of time to use restoreparms */
short barstyle; /* % of time to generate barstyle parameter */
short subbarstyle; /* % of time to generate subbarstyle parameter */
short midlinestemfloat; /* % of the time to generate midlinestemfloat parameter */
short beamslope; /* % of the time to generate beamslope parameter */
short tupletslope; /* % of the time to generate tupletslope parameter */
short numbermultrpt; /* % of the time to generate numbermultrpt parameter */
short defaultphraseside; /* % of the time to generate defaultphraseside param */
short maxnotes; /* notes per voice */
short maxsize; /* maxsize to actually use */
/* constants that control how mup input is generated */
#define BEAMSTYLE 60 /* % of time to use beamstyle */
#define BEAMRESTS 50 /* % of time to use "r" on beamstyle */
#define STAFFTHINGS 60 /* % of time to use staff contexts */
#define KEY 30 /* % of time to set key */
#define MAJMIN 50 /* % of time to set maj/min */
#define CLEF 30 /* % of time to set clef */
#define VSCHEME2o 20 /* % of time to use 2o */
#define VSCHEME2f 20 /* % of time to use 2f */
#define VSCHEME3o 20 /* % of time to use 3o */
#define VSCHEME3f 20 /* % of time to use 3f */
#define VSCHEME1 20 /* % of time to explicitly use 1 */
#define ABSOCT 15 /* % of time to use absolute octave */
#define LYRICS 20 /* % of time to generate lyrics */
#define LYRABOVE 15 /* % of time to use lyrics above */
#define LYRBETWEEN 15 /* % of time to use lyrics between */
#define LYRBELOW 15 /* % of time to use explicit lyrics below */
#define LYRSPACE 15 /* % of time to use s on lyrics */
#define LYRDASH 20 /* % of time to use - between syllables */
#define UNDERSCORE 10 /* % of time to use underscore on syllables */
#define SMALL 5 /* % of time to use ? (small) notes */
#define STUFFABOVE 40 /* % of time to put stuff above */
#define STUFFBELOW 25 /* % of time to put stuff below */
#define STUFFBETWEEN 20 /* % of time to put stuff between */
#define CRESC 5 /* % of time to do cresc */
#define TILSAMEMEAS 30 /* % of time to do til within same measure */
#define TILMEASONLY 20 /* % of time to do til with just # nmeasures */
#define FAMILY 25 /* % of time to use explicit font family */
#define FNTSIZE 20 /* % of time to specify font size */
#define TILTEXT 10 /* % of time to use til clause on text stuff */
#define TEXTSTUFF 15 /* % of time to add text stuff items */
#define OCTSTUFF 5 /* % of time to generate octave marks */
#define HDFTFONT 15 /* % of time to use font in header/footer */
#define HDFTSIZE 15 /* % of time to use size in header/footer */
#define FNT 20 /* % of time to specify font on titles */
#define TITLE2 25 /* % of time to generate 2nd title string */
#define TITLE3 20 /* % of time to generate 2nd title string */
#define HDFT 20 /* % of time to generate a header/footer */
#define GRACE 5 /* % of time to add grace notes */
#define GRACETIME 30 /* % of time to explicitly specify time value on grace groups after the first */
#define SLASHGRACE 25 /* % of time to use slash on grace notes */
#define DFLTGRP 30 /* % of time to default pitches if possible */
#define BARPAD 5 /* % of time to add bar padding */
#define ENDING 15 /* % of time to use ending */
#define ENDENDING 30 /* % of time to end ending */
#define ONELETTAG 15 /* % of time to generate 1-letter tags */
#define TABSTRING 25 /* % of time to use each tab string */
#define MAXMEAS 12 /* how many measures max to generate */
#define MAXSTAFFS 8 /* how many staffs max to generate */
#define MINNUMERATOR 1 /* minimum time sig numerator */
#define MAXNUMERATOR 24 /* maximum time sig numerator */
#define MAXREHSTR 10 /* # characters in rehearsal string */
#define MAXSTR 12 /* max chars in stuff string */
#define MAXPARASTR 200 /* max chars in a paragraph */
#define MINSIZE 1 /* min point size to use */
#define MAXSIZE 100 /* max point size to use */
#define MINHDFTITEMS 0 /* minimum number of items in header/footer */
#define MAXHDFTITEMS 10 /* maximum number of items in header/footer */
#define MAXTITLE 30 /* maximum chars in a title string */
#define MAXGRACE 4 /* max # of grace groups before a real group */
#define MAXBRACK 3 /* max number of items in [] before group */
#define MINPAD 1 /* minimum padding */
#define MAXPAD 10 /* maximum padding */
#define MAXENDSTR 5 /* max size for ending string */
#define MAXLABEL 9 /* max strlen of label */
#define MAXTAGS 100 /* max number of tags */
#define MAXTAGLEN 7 /* max length of a tag */
#define MAXSTRINGS 9 /* maximum number of tablature strings */
#define MAX_KEYMAPS 5 /* maximum number of keymap contexts to generate */
#define MAX_KEYMAP_NAME_LEN 10 /* longest keymap name */
/* kinds of groups */
typedef enum { None, Rest, Space, Uspace, Notes } GTYPE;
/* handy rational constants */
RATIONAL Three_halves = { 3, 2 }; /* for dotted notes */
RATIONAL Seven_fourths = { 7, 4 }; /* for double-dotted notes */
RATIONAL Three_fourths = { 3, 4 };
RATIONAL Five_fourths = { 5, 4 };
RATIONAL Eighth = { 1, 8 };
RATIONAL One = { 1, 1 };
RATIONAL Two = { 2, 1 };
RATIONAL Four = { 4, 1 };
RATIONAL Eight = { 8, 1 };
RATIONAL Zero = { 0, 1};
RATIONAL N64 = { 1, 64 };
RATIONAL N128 = { 1, 128 };
/* the time value for a group. Enough for a measure are linked in a list */
struct GRP {
RATIONAL basictime;
int dots;
int do_alt; /* 0 = no alt, 1 = first of alt, 2 = second */
int custbeam; /* 0 = no custom beam, 1 = bm, 2 =
* inside, 3 = ebm, 4 = esbm */
int autobeam; /* 0 = none, 1 = abm, 2 = eabm */
struct GRP *next;
};
/* struct for list of items to choose from */
struct LIST {
char *str; /* value to be printed */
int used; /* set to the current "generation." If this
* field is the same as the current generation
* number, this item will not be used. This
* will ensure that a value will only get used
* once */
};
/* The following are various lists of tiny snippets of Mup input that
* we randomly choose from when we want to generate a particular type
* of token that can have various values. When the number of valid choices
* is small, it will be an exhastive list of those, otherwise a sampling.
*/
struct LIST Notelist[] = {
{ "a0", 0 },
{ "b0", 0 },
{ "c0", 0 },
{ "d0", 0 },
{ "e0", 0 },
{ "f0", 0 },
{ "g0", 0 },
{ "a1", 0 },
{ "b1", 0 },
{ "c1", 0 },
{ "d1", 0 },
{ "e1", 0 },
{ "f1", 0 },
{ "g1", 0 },
{ "a2", 0 },
{ "b2", 0 },
{ "c2", 0 },
{ "d2", 0 },
{ "e2", 0 },
{ "f2", 0 },
{ "g2", 0 },
{ "a3", 0 },
{ "b3", 0 },
{ "c3", 0 },
{ "d3", 0 },
{ "e3", 0 },
{ "f3", 0 },
{ "g3", 0 },
{ "a4", 0 },
{ "b4", 0 },
{ "c4", 0 },
{ "d4", 0 },
{ "e4", 0 },
{ "f4", 0 },
{ "g4", 0 },
{ "a5", 0 },
{ "b5", 0 },
{ "c5", 0 },
{ "d5", 0 },
{ "e5", 0 },
{ "f5", 0 },
{ "g5", 0 },
{ "a6", 0 },
{ "b6", 0 },
{ "c6", 0 },
{ "d6", 0 },
{ "e6", 0 },
{ "f6", 0 },
{ "g6", 0 },
{ "a7", 0 },
{ "b7", 0 },
{ "c7", 0 },
{ "d7", 0 },
{ "e7", 0 },
{ "f7", 0 },
{ "g7", 0 },
{ "a8", 0 },
{ "b8", 0 },
{ "c8", 0 },
{ "d8", 0 },
{ "e8", 0 },
{ "f8", 0 },
{ "g8", 0 },
{ "a9", 0 },
{ "b9", 0 },
{ "c9", 0 },
{ "d9", 0 },
{ "e9", 0 },
{ "f9", 0 },
{ "g9", 0 },
};
struct LIST Acclist[] = {
{ "", 0 },
{ "#", 0 },
{ "&", 0 },
{ "x", 0 },
{ "&&", 0 },
{ "n", 0 }
};
struct LIST Useaccslist[] = {
{ "n", 0 },
{ "y", 0 },
{ "y none", 0 },
{ "y all", 0 },
{ "y nonnat", 0 },
};
struct LIST Barlist[] = {
{ "bar", 0 },
{ "dblbar", 0 },
{ "invisbar", 0 },
{ "repeatstart", 0 },
{ "repeatend", 0 },
{ "repeatboth", 0 },
{ "endbar", 0 }
};
struct LIST Barstylelist[] = {
{ "all", 0 },
{ "between all", 0 },
{ "1-2", 0 }
};
struct LIST Cleflist[] = {
{ "treble", 0 },
{ "bass", 0 },
{ "soprano", 0 },
{ "alto", 0 },
{ "tenor", 0},
{ "baritone", 0 },
{ "mezzosoprano", 0 },
{ "frenchviolin", 0 },
{ "8treble", 0},
{ "treble8", 0},
{ "8bass", 0 },
{ "bass8", 0 },
{ "subbass", 0 },
};
struct LIST Familylist [] = {
{ "times", 0 },
{ "helvetica", 0 },
{ "avantgarde", 0 },
{ "newcentury", 0 },
{ "courier", 0 },
{ "bookman", 0 },
{ "palatino", 0 }
};
struct LIST Fontlist[] = {
{ "rom", 0 },
{ "bold", 0 },
{ "ital", 0 },
{ "boldital", 0 }
};
struct LIST Stylelist[] = {
{ "plain", 0 },
{ "boxed", 0 },
{ "circled", 0 }
};
struct LIST Headfootlist[] = {
{ "top", 0 },
{ "top2", 0 },
{ "bottom", 0 },
{ "bottom2", 0 },
{ "header", 0 },
{ "header2", 0 },
{ "footer", 0 },
{ "footer2", 0 }
};
struct LIST Pagesidelist[] = {
{ "leftpage", 0 },
{ "rightpage", 0 },
{ "", 0 }
};
struct LIST Bracklist[] = {
{ "cue", 0 },
{ "xnote", 0 },
{ "slash 1", 0 },
{ "with .", 0 },
{ "with \"sfz\"", 0 },
{ "ho 2", 0 },
{ "ho -", 0 },
{ "hs \"semicirc\"", 0 },
{ "hs \"allslash\"", 0 },
{ "len 4" },
{ "up", 0 },
{ "down", 0 },
{ "pad 2", 0 }
};
struct LIST Endingstylelist[] = {
{ "top", 0 },
{ "barred", 0 },
{ "grouped", 0 }
};
struct LIST Xposelist[] = {
{ "per 1", 0 },
{ "min 2", 0 },
{ "maj 2", 0 },
{ "dim 2", 0 },
{ "aug 2", 0 },
{ "min 3", 0 },
{ "maj 3", 0 },
{ "dim 3", 0 },
{ "aug 3", 0 },
{ "perfect 4", 0 },
{ "diminished 4", 0 },
{ "augmented 4", 0 },
{ "perfect 5", 0 },
{ "diminished 5", 0 },
{ "augmented 5", 0 },
{ "min 6", 0 },
{ "maj 6", 0 },
{ "dim 6", 0 },
{ "aug 6", 0 },
{ "min 7", 0 },
{ "maj 7", 0 },
{ "dim 7", 0 },
{ "aug 7", 0 }
};
struct LIST Chordtranslationlist[] = {
{ "", 0 },
{ "\"German\"", 0 },
{ "\"do re mi fa sol la si\"", 0 },
{ "\"foo Hjk zz89 345k+ o9ee MMMuy qw\"", 0 }
};
struct LIST Printcmdslist[] = {
{ "print", 0 },
{ "center", 0 },
{ "left", 0 },
{ "right", 0 }
};
struct LIST Paramlist[] = {
{ "a4freq", 0 },
{ "aboveorder", 0 },
{ "acctable", 0 },
{ "addtranspose", 0 },
{ "alignlabels", 0 },
{ "alignped", 0 },
{ "barstyle", 0 },
{ "beamslope", 0 },
{ "beamstyle", 0 },
{ "beloworder", 0 },
{ "betweenorder", 0 },
{ "bottommargin", 0 },
{ "brace", 0 },
{ "bracket", 0 },
{ "bracketrepeats", 0 },
{ "cancelkey", 0 },
{ "chorddist", 0 },
{ "chordtranslation", 0 },
{ "clef", 0 },
{ "cue", 0 },
{ "defaultkeymap", 0 },
{ "defaultphraseside", 0 },
{ "defoct", 0 },
{ "dist", 0 },
{ "division", 0 },
{ "dyndist", 0 },
{ "emptymeas", 0 },
{ "endingkeymap", 0 },
{ "endingstyle", 0 },
{ "extendlyrics", 0 },
{ "firstpage", 0 },
{ "flipmargins", 0 },
{ "font", 0 },
{ "fontfamily", 0 },
{ "gridfret", 0 },
{ "gridsatend", 0 },
{ "gridswhereused", 0 },
{ "gridscale", 0 },
{ "key", 0 },
{ "labelkeymap", 0 },
{ "label2", 0 },
{ "label", 0 },
{ "leftmargin", 0 },
{ "lyricsalign", 0 },
{ "lyricsdist", 0 },
{ "lyricsfont", 0 },
{ "lyricsfontfamily", 0 },
{ "lyricskeymap", 0 },
{ "lyricssize", 0 },
{ "maxmeasures", 0 },
{ "maxscores", 0 },
{ "measnum", 0 },
{ "measnumfont", 0 },
{ "measnumfontfamily", 0 },
{ "measnumsize", 0 },
{ "midlinestemfloat", 0 },
{ "minalignscale", 0 },
{ "mingridheight", 0 },
{ "numbermrpt", 0 },
{ "numbermultrpt", 0 },
{ "ontheline", 0 },
{ "packexp", 0 },
{ "packfact", 0 },
{ "pad", 0 },
{ "pageheight", 0 },
{ "pagewidth", 0 },
{ "panelsperpage", 0 },
{ "pedstyle", 0 },
{ "printkeymap", 0 },
{ "printmultnum", 0 },
{ "rehearsalkeymap", 0 },
{ "rehstyle", 0 },
{ "release", 0 },
{ "repeatdots", 0 },
{ "restcombine", 0 },
{ "rightmargin", 0 },
{ "scale", 0 },
{ "scorepad", 0 },
{ "scoresep", 0 },
{ "size", 0 },
{ "slashesbetween", 0 },
{ "stafflines", 0 },
{ "staffpad", 0 },
{ "staffs", 0 },
{ "staffscale", 0 },
{ "staffsep", 0 },
{ "stemlen", 0 },
{ "stemshorten", 0 },
{ "subbarstyle", 0 },
{ "swingunit", 0 },
{ "sylposition", 0 },
{ "tabwhitebox", 0 },
{ "time", 0 },
{ "timeunit", 0 },
{ "topmargin", 0 },
{ "transpose", 0 },
{ "tuning", 0 },
{ "tupletslope", 0 },
{ "units", 0 },
{ "useaccs", 0 },
{ "carryaccs", 0 },
{ "visible", 0 },
{ "vcombine", 0 },
{ "pagesize", 0 },
{ "vscheme", 0 },
{ "warn", 0 },
{ "withfont", 0 },
{ "withfontfamily", 0 },
{ "withkeymap", 0 },
{ "withsize", 0 }
};
struct LIST Vcombinelist[] = {
{ "1,2", 0 },
{ "1-3", 0 },
{ "3, 2, 1 ", 0 },
{ "2,1,3", 0 },
{ "2", 0 }
};
struct LIST Vcombquallist[] = {
{ "", 0 },
{ "nooverlap", 0 },
{ "shareone", 0 },
{ "overlap", 0 },
{ "restsonly", 0 }
};
struct LIST Pagesizelist[] = {
{ "letter", 0 },
{ "legal landscape", 0 },
{ "legal portrait", 0 },
{ "a4 landscape", 0 },
{ "a5", 0 },
{ "a6 portrait", 0 }
};
struct LIST Abovelist[] = {
{ "mussym", 0 },
{ "othertext", 0 },
{ "chord", 0 },
{ "ending", 0 },
{ "rehearsal", 0 },
{ "octave", 0 },
{ "lyrics", 0 },
{ "dyn", 0 },
};
struct LIST Belowlist[] = {
{ "mussym", 0 },
{ "othertext", 0 },
{ "chord", 0 },
{ "pedal", 0 },
{ "octave", 0 },
{ "lyrics", 0 },
{ "dyn", 0 },
};
struct LIST Betweenlist[] = {
{ "mussym", 0 },
{ "othertext", 0 },
{ "chord", 0 },
{ "lyrics", 0 },
{ "dyn", 0 },
};
struct LIST Keymaplist[] = {
{ "defaultkeymap", 0 },
{ "textkeymap", 0 },
{ "lyricskeymap", 0 },
{ "endingkeymap", 0 },
{ "labelkeymap", 0 },
{ "printkeymap", 0 },
{ "rehearsalkeymap", 0 },
{ "withkeymap", 0 },
};
struct LIST Tuninglist[] = {
{ "equal", 0 },
{ "meantone", 0 },
{ "pythagorean", 0 }
};
struct LIST Noteheadlist[] = {
{ "norm", 0 },
{ "x", 0 },
{ "allx", 0 },
{ "diam", 0 },
{ "blank", 0 },
{ "righttri", 0 },
{ "isostri", 0 },
{ "rect", 0 },
{ "pie", 0 },
{ "semicirc", 0 },
{ "slash", 0 },
{ "allslash", 0 },
{ "ILLEGAL", 0 } /* to cause error cases */
};
struct LIST Noteshapeslist[] = {
{ "octwhole", 0 },
{ "quadwhole", 0 },
{ "dblwhole", 0 },
{ "1n", 0 },
{ "2n", 0 },
{ "4n", 0 },
{ "xnote", 0 },
{ "dwhdiamond", 0 },
{ "diamond", 0 },
{ "filldiamond", 0 },
{ "dwhrighttriangle", 0 },
{ "righttriangle", 0 },
{ "fillrighttriangle", 0 },
{ "udwhrighttriangle", 0 },
{ "urighttriangle", 0 },
{ "ufillrighttriangle", 0 },
{ "dwhrectangle", 0 },
{ "rectangle", 0 },
{ "fillrectangle", 0 },
{ "dwhisostriangle", 0 },
{ "isostriangle", 0 },
{ "fillisostriangle", 0 },
{ "dwhpiewedge", 0 },
{ "piewedge", 0 },
{ "fillpiewedge", 0 },
{ "dwhsemicircle", 0 },
{ "semicircle", 0 },
{ "fillsemicircle", 0 },
{ "blankhead", 0 },
{ "slashhead", 0 },
{ "fillslashhead", 0 },
{ "dwhslashhead", 0 },
{ "INVALID", 0 } /* to cause error cases */
};
struct LIST Midi_list[] = {
{ "channel", 0 },
{ "chanpressure", 0 },
{ "cue", 0 },
{ "hex", 0 },
{ "instrument", 0 },
{ "marker", 0 },
{ "name", 0 },
{ "offvelocity", 0 },
{ "onvelocity", 0 },
{ "parameter", 0 },
{ "port", 0 },
{ "program", 0 },
{ "seqnum", 0 },
{ "tempo", 0 },
{ "text", 0 }
};
/* list of grid chords to use */
struct LIST *Gridlist; /* malloc-ed */
int Numgrids;
char Keymapnames[MAX_KEYMAPS][MAX_KEYMAP_NAME_LEN + 1];
int Numkeymaps;
/* For save/restore. The names are for testing a typical name, a name with a
* space, and a ridiculous but legal name. */
char *saveparms_names[] = { "xx", "a name", "!@,)& +" };
#define MAX_SAVEPARMS (sizeof(saveparms_names) / sizeof(saveparms_names[0]))
short saveparms_used[MAX_SAVEPARMS];
/* info about each staff */
struct STAFFINFO {
int voices; /* 1, 2, or 3 */
int defoct; /* default octave */
} Staffinfo[MAXSTAFFS + 1];
struct STRINGDATA {
char pitch;
char accidental;
short nticks;
short octave; /* greater than 9 means use default */
};
/* tag information */
char Tagtable[MAXTAGS][MAXTAGLEN+1] = {
"_win", "_page", "_cur", "_score", "_staff.1" } ;
int Numtags = 3;
/* statistics */
int num_killed, num_core_dumped, num_exited_nonzero, num_midi_nonzero, num_nans;
int num_huge_nums;
int num_non_midi_tests, num_midi_tests;
short savenonzero = NO; /* if to save files than cause non-zero exit */
int child; /* PID of child process */
FILE *outf; /* output file */
int In_ending; /* if currently doing an ending */
short Pedstate[MAXSTAFFS + 1]; /* ped state, 0 off, 1 on */
short Samescore_inprog = NO;
short Samepage_inprog = NO;
/* argv processing globals */
extern int optind;
extern char *optarg;
/* function templates */
void gen(void);
void genmeas(int num, int den, int staff, int voice, int staffs);
struct GRP * gen_music(int num, int den, int staff);
int sometimes(int percent);
int myrandom(int min, int max);
void out(char *str);
void outfmt(char *fmt, ...);
void newline(void);
void genbar(int);
struct GRP *picktimes(struct GRP *grplist_p, RATIONAL remtime);
struct GRP *scramble_times(struct GRP *grplist_p);
void freegrps(struct GRP *g_p);
void picknotes(int n, int defoct);
void genbrack(void);
char *picklist(struct LIST *list_p, int leng, int generation);
void genstring(int leng);
char * create_a_string(int minleng, int leng);
char *create_a_name(int minleng, int leng);
void prtime(struct GRP *g_p);
void usage(char *pname);
void run_test(int index, char *command, char *suffix, char *prefix, int timeout, int verbose);
int exectest(char *cmd, int timeout, int verbose, int doing_midi, int *ret_p);
void alarmhandler(int sig);
void genlyrics(struct GRP *grplist_p, int staff, int staffs);
void gensyl(int mid);
void scramble_lines(long foffset, char repchar);
void cresc(int staff, int staffs, int meas, int measures, int num);
void place(int staff, int staffs, int between_ok, int req);
void stuff(int num, int str, int til, int measrem);
void textstuff(int staff, int staffs, int meas, int measures, int num);
void phrasestuff(int staff, int staffs, int meas, int measures, int num);
void octstuff(int staff, int staffs, int meas, int measures, int num);
void pedalstuff(int staff, int num);
void betweenbars(void);
void headfoot(void);
void initvals(void);
char *create_tag(void);
void genprint(void);
char *gettag(void);
struct STRINGDATA *tabstafflines(int *nstrings_p);
void picktabnotes(int nstrings, struct STRINGDATA *stringdata_p);
void do_a_tab_note(struct STRINGDATA *stringdata_p, int n);
void gen_grid(int gridlist_index);
void adjust_defoct(char * clefname, int staff);
void gen_coord_things(void);
void gen_keymaps(void);
void gen_til(int count100, int num, int measrem);
void gen_to(int minval, int maxval, int start, int ts_num, int measrem, int multi);
void gen_midi(int staffs, int ts_num, int measrem);
void gen_barstyle(void);
void gen_subbarstyle(void);
int
main(int argc, char **argv)
{
int a; /* cmd line arg */
int iterations = ITERATIONS; /* how many tests to run */
int timeout = TIMEOUT; /* how long to wait before assuming
* program is stuck in a loop */
char *command = "mup"; /* what program to run and its args */
char *suffix = "> RegGen2.out"; /* end of command after file name */
char *prefix = "RGtest"; /* prefix for file names */
int verbose = 0;
int index; /* loop index */
#ifdef __DOS__
extern int _fmode;
#endif
#ifdef __DOS__
_fmode = O_BINARY;
#endif
#ifdef GENONLY
while ((a = getopt(argc, argv, "i:p:")) != EOF) {
#else
while ((a = getopt(argc, argv, "di:np:t:v")) != EOF) {
#endif
switch(a) {
#ifndef GENONLY
case 'd':
command = "mupdisp";
suffix = "";
timeout = 0;
break;
#endif
case 'i':
iterations = atoi(optarg);
break;
#ifndef GENONLY
case 'n':
savenonzero = YES;
break;
#endif
case 'p':
prefix = optarg;
break;
#ifndef GENONLY
case 't':
timeout = atoi(optarg);
break;
case 'v':
verbose = 1;
break;
#endif
default:
usage(argv[0]);
break;
}
}
if (optind != argc) {
usage(argv[0]);
}
/* seed random number generator */
srand(time((long *) 0));
/* Turn on malloc flag to make certain error blatant that might
* otherwise get through. */
setenv("MALLOC_PERTURB_", "29", 1);
/* run as many tests as specified */
for (index = 1; index <= iterations; index++) {
run_test(index, command, suffix, prefix, timeout, verbose);
/* clean up */
if (Numgrids > 0) {
int g;
for (g = 0; g < Numgrids; g++) {
free(Gridlist[g].str);
}
free(Gridlist);
Gridlist = 0;
Numgrids = 0;
}
Numtags = 3; /* _cur, _win, and _page */
}
#ifndef GENONLY
fprintf(stderr, "\n%d non-midi and %d midi tests run.\n %d core dumps, %d killed, %d contained 'nan', %d contained huge numbers,\n%d exited non-zero (%d non-midi / %d midi)\n",
num_non_midi_tests, num_midi_tests, num_core_dumped,
num_killed, num_nans, num_huge_nums, num_exited_nonzero,
num_exited_nonzero - num_midi_nonzero, num_midi_nonzero);
#endif
unlink("RegGen2.out");
/* core dumps is a definite bug. Killed due to timeout is almost
* certainly a bug. Seeing a "nan" can have
* false positives, so we'll let them go. */
return(num_core_dumped + num_killed);
}
/* Generate various score level SSV things */
void
gen_score_ssv()
{
int val;
if (sometimes(dist)) {
out("dist=");
if (sometimes(dist)) {
outfmt("%d", myrandom(0, 10));
}
else {
/* use floating point */
outfmt("%d.%d", myrandom(0, 10), myrandom(0,999));
}
newline();
}
if (sometimes(dist)) {
out("chorddist=");
if (sometimes(dist)) {
outfmt("%d", myrandom(0, 10));
}
else {
/* use floating point */
outfmt("%d.%d", myrandom(0, 10), myrandom(0,999));
}
newline();
}
if (sometimes(dist)) {
out("dyndist=");
if (sometimes(dist)) {
outfmt("%d", myrandom(0, 10));
}
else {
/* use floating point */
outfmt("%d.%d", myrandom(0, 10), myrandom(0,999));
}
newline();
}
if (sometimes(dist)) {
out("lyricsdist=");
if (sometimes(dist)) {
outfmt("%d", myrandom(0, 10));
}
else {
/* use floating point */
outfmt("%d.%d", myrandom(0, 10), myrandom(0,999));
}
newline();
}
if (sometimes(endingstyle)) {
out("endingstyle=");
out(picklist(Endingstylelist,
sizeof(Endingstylelist) / sizeof(struct LIST), -1));
newline();
}
if (sometimes(label)) {
out("label=");
genstring(MAXLABEL);
newline();
}
if (sometimes(label)) {
out("label2=");
genstring(MAXLABEL);
newline();
}
if (sometimes(measnum)) {
out("measnum=");
out(sometimes(50) ? "y" : "n");
newline();
if (sometimes(50)) {
outfmt("measnumsize=%d", myrandom(1, 20));
newline();
}
if (sometimes(50)) {
out("measnumfont=");
out(picklist(Fontlist, sizeof(Fontlist)
/ sizeof(struct LIST), -1));
newline();
}
if (sometimes(50)) {
out("measnumfontfamily=");
out(picklist(Familylist, sizeof(Familylist)
/ sizeof(struct LIST), -1));
newline();
}
if (sometimes(50)) {
out("measnumstyle=");
out(picklist(Stylelist, sizeof(Stylelist)
/ sizeof(struct LIST), -1));
newline();
}
}
if (sometimes(maxmeasures)) {
outfmt("maxmeasures=%d", myrandom(1, 10));
newline();
}
if (sometimes(maxscores)) {
outfmt("maxscores=%d", myrandom(1, 5));
newline();
}
if (sometimes(slashesbetween)) {
out("slashesbetween=");
out(sometimes(50) ? "y" : "n");
newline();
}
if (sometimes(bracketrepeats)) {
out("bracketrepeats=");
out(sometimes(50) ? "y" : "n");
newline();
}
if (sometimes(repeatdots)) {
out("repeatdots=");
out(sometimes(50) ? "all" : "standard");
newline();
}
if (sometimes(withfont)) {
out("withfontfamily=");
out(picklist(Familylist, sizeof(Familylist)
/ sizeof(struct LIST), -1));
newline();
}
if (sometimes(withfont)) {
out("withfont=");
out(picklist(Fontlist, sizeof(Fontlist)
/ sizeof(struct LIST), -1));
newline();
}
if (sometimes(withfont)) {
outfmt("withsize=%d", myrandom(1, 20));
newline();
}
if (sometimes(pack)) {
out("packexp=");
val = myrandom(0, 100);
outfmt("%d.%02d", val / 100, val % 100);
newline();
}
if (sometimes(pack)) {
out("packfact=");
val = myrandom(0, 100);
outfmt("%d.%1d", val / 10, val % 10);
newline();
}
if (sometimes(transpose)) {
out("transpose=");
out(sometimes(50) ? "up " : "down ");
out(picklist(Xposelist, sizeof(Xposelist) / sizeof(struct LIST),
-1));
newline();
}
if (sometimes(chordtranslation)) {
out("chordtranslation=");
out(picklist(Chordtranslationlist,
sizeof(Chordtranslationlist) / sizeof(struct LIST), -1));
newline();
}
if (sometimes(useaccs)) {
out("useaccs=");
out(picklist(Useaccslist, sizeof(Useaccslist) / sizeof(struct LIST), -1));
newline();
}
if (sometimes(carryaccs)) {
out("carryaccs=");
out(sometimes(50) ? "y" : "n");
newline();
}
if (sometimes(alignped)) {
out("alignped=");
out(sometimes(50) ? "y" : "n");
newline();
}
if (sometimes(alignlabels)) {
out("alignlabels=");
out(sometimes(50) ? "left" : "center");
newline();
}
if (sometimes(extendlyrics)) {
out("extendlyrics=");
out(sometimes(75) ? "y" : "n");
newline();
}
if (sometimes(orderlist)) {
static int ordergeneration;
int i;
int items;
int use; /* how many items to actually use */
ordergeneration++;
if (sometimes(75)) {
items = sizeof(Abovelist) / sizeof(struct LIST);
use = myrandom(items - 3, items);
outfmt("aboveorder=");
for (i = 0; i < use; i++) {
outfmt( "%s", picklist(Abovelist, items, ordergeneration));
if (i < use - 1) {
outfmt(",");
}
}
newline();
}
ordergeneration++;
if (sometimes(75)) {
items = sizeof(Belowlist) / sizeof(struct LIST);
use = myrandom(items - 2, items);
outfmt("beloworder=");
for (i = 0; i < use; i++) {
outfmt( "%s", picklist(Belowlist, items, ordergeneration));
if (i < use - 1) {
outfmt(",");
}
}
newline();
}
ordergeneration++;
if (sometimes(75)) {
items = sizeof(Betweenlist) / sizeof(struct LIST);
use = myrandom(items - 1, items);
outfmt("betweenorder=");
for (i = 0; i < use; i++) {
outfmt( "%s", picklist(Betweenlist, items, ordergeneration));
if (i < use - 1) {
outfmt(",");
}
}
newline();
}
}
if (sometimes(noteheads)) {
int i;
out("noteheads =\"");
for (i = 0; i < 7; i++) {
outfmt("%s ",picklist(Noteheadlist, sizeof(Noteheadlist) /
sizeof(struct LIST), -1));
}
out("\"");
newline();
}
if (sometimes(sylposition)) {
outfmt("sylposition = %d", myrandom(0, 30) - 15);
newline();
}
if (sometimes(staffpad)) {
outfmt("staffpad = %d", myrandom(0, 12) - 6);
newline();
}
if (sometimes(scorepad)) {
if (sometimes(50)) {
outfmt("scorepad = %d", myrandom(0, 12) - 6);
}
else {
outfmt("scorepad = %d, %d", myrandom(0, 12) - 6,
myrandom(0, 20) - 2);
}
newline();
}
if (sometimes(rehstyle)) {
out("rehstyle = ");
out(picklist(Stylelist, sizeof(Stylelist)
/ sizeof(struct LIST), -1));
newline();
}
if (sometimes(stemlen)) {
outfmt("stemlen= %d", myrandom(0,10));
if (sometimes(stemlen)) {
outfmt(".%d", myrandom(0,9));
}
out("\n");
}
if (sometimes(stemshorten)) {
outfmt("stemshorten=%d", myrandom(0,2));
if (sometimes(stemshorten)) {
outfmt(".%d", myrandom(0,9));
}
if (sometimes(stemshorten)) {
outfmt(",%d", myrandom(0,6));
if (sometimes(stemshorten)) {
outfmt(".%d", myrandom(0,9));
}
if (sometimes(stemshorten)) {
outfmt(",%d,%d", myrandom(-4, 50), myrandom(-4, 50));
}
}
out("\n");
}
if (sometimes(swingunit)) {
switch (myrandom(0, 3)) {
case 0:
outfmt("swingunit = 8\n");
break;
case 1:
outfmt("swingunit = 4\n");
break;
case 2:
outfmt("swingunit = 4.\n");
break;
case 3:
outfmt("swingunit = 2\n");
break;
}
}
if (sometimes(barstyle)) {
gen_barstyle();
}
if (sometimes(subbarstyle)) {
gen_subbarstyle();
}
if (sometimes(midlinestemfloat)) {
out("midlinestemfloat=");
out(sometimes(50) ? "y" : "n");
newline();
}
if (sometimes(beamslope)) {
out("beamslope=");
outfmt("0.%d, %d", myrandom(1, 9), myrandom(0, 45));
newline();
}
if (sometimes(tupletslope)) {
out("tupletslope=");
outfmt("0.%d, %d", myrandom(1, 9), myrandom(0, 45));
newline();
}
if (sometimes(numbermultrpt)) {
out("numbermultrpt=");
out(sometimes(50) ? "y" : "n");
newline();
}
if (sometimes(defaultphraseside)) {
out("defaultphraseside=");
out(sometimes(50) ? "above" : "below");
newline();
}
}
/* generate a test file */
void
gen()
{
int measures; /* how many measures to generate */
int staffs; /* how many staffs */
int voices;
int num; /* time signature */
int den;
int s; /* staff index */
int i; /* index in saveparms_used */
RATIONAL meastime;
struct GRP *grplist_p, *g_p;
long f_offset; /* file offset */
int meas; /* current measure number */
int marg; /* margin in 100th of an inch */
int val; /* value for parameters */
short otherstaffs[MAXSTAFFS+1]; /* for doing multiple SSVs */
int extrastaff; /* when doing multiple SSVs */
int set_vscheme; /* YES or NO */
int ss; /* another staff index */
/* initialize to not having done any saves */
for (i = 0; i < MAX_SAVEPARMS; i++) {
saveparms_used[i] = NO;
}
/* decide some fundamental things */
measures = myrandom(1, MAXMEAS);
staffs = myrandom(1, MAXSTAFFS);
num = myrandom(MINNUMERATOR, MAXNUMERATOR);
den = (int) (pow(2.0, (double) myrandom(0, 6)));
In_ending = NO;
if (sometimes(noteheads)) {
int i, j;
/* generate a headshapes context */
out("headshapes");
newline();
for (i = myrandom(0,4); i > 0; i--) {
/* usually do user-defines,
* but sometimes override builtin */
if (sometimes(70)) {
genstring(30);
}
else {
outfmt("%s ",picklist(Noteheadlist, sizeof(Noteheadlist) /
sizeof(struct LIST), -1));
}
out("\"");
for (j = 0; j < 4; j++) {
out(picklist(Noteshapeslist, sizeof(Noteshapeslist) /
sizeof(struct LIST), -1));
if (j < 3) {
out(" ");
}
}
out("\"");
newline();
}
}
if (sometimes(keymaps)) {
gen_keymaps();
}
else {
Numkeymaps = 0;
}
/* do the score things */
out("score");
newline();
out("staffs=");
outfmt("%d\ntime=", staffs);
if (sometimes(compoundts)) {
int remaining, part;
for (remaining = num; remaining > 2; remaining -= part) {
part = myrandom(1, remaining - 1);
outfmt("%d+", part);
}
outfmt("%d/%d\n", remaining, den);
}
else {
outfmt("%d/%d\n", num, den);
}
/* save file offset for scrambling */
f_offset = ftell(outf);
out("scale=");
outfmt("0.%d", myrandom(4,9));
newline();
/* establish a beamstyle */
if (sometimes(BEAMSTYLE)) {
meastime.n = num; meastime.d = den;
rred ( &meastime);
grplist_p = picktimes( (struct GRP *) 0, meastime);
grplist_p = scramble_times(grplist_p);
out("beamstyle=");
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
prtime(g_p);
while (sometimes(additive_time) && g_p->next != 0) {
out("+");
g_p = g_p->next;
prtime(g_p);
}
if (g_p->next != (struct GRP *) 0) {
out(",");
}
}
if (sometimes(BEAMRESTS)) {
out(" r");
}
newline();
freegrps(grplist_p);
}
/* establish global vscheme */
if (sometimes(VSCHEME2o)) {
out("vscheme=");
out("2o");
newline();
voices = 2;
}
else if (sometimes(VSCHEME2f)) {
out("vscheme=");
out("2f");
newline();
voices = 2;
}
else if (sometimes(VSCHEME1)) {
out("vscheme=");
out("1");
newline();
voices = 1;
}
else if (sometimes(VSCHEME3f)) {
out("vscheme=");
out("3f");
newline();
voices = 3;
}
else if (sometimes(VSCHEME3o)) {
out("vscheme=");
out("3o");
newline();
voices = 3;
}
else {
voices = 1;
}
/* sometimes set margins */
if (sometimes(margins)) {
marg = myrandom(0, 110);
out("topmargin=");
outfmt("%d.%d", marg / 100, marg % 100);
newline();
}
if (sometimes(margins)) {
marg = myrandom(0, 110);
out(sometimes(50) ? "bottommargin" : "botmargin=");
outfmt("%d.%d", marg / 100, marg % 100);
newline();
}
if (sometimes(margins)) {
marg = myrandom(0, 110);
out("leftmargin=");
outfmt("%d.%d", marg / 100, marg % 100);
newline();
}
if (sometimes(margins)) {
marg = myrandom(0, 110);
out("rightmargin=");
outfmt("%d.%d", marg / 100, marg % 100);
newline();
}
if (sometimes(margins)) {
outfmt("flipmargins=%s", (sometimes(50) ? "y" : "n"));
newline();
}
gen_score_ssv();
if (sometimes(division)) {
out("division=");
outfmt("%d", 96 * myrandom(1, 4));
newline();
}
if (Numkeymaps > 0) {
while (sometimes(60)) {
outfmt("%s=\"%s\"", picklist(Keymaplist,
sizeof(Keymaplist) / sizeof(struct LIST), -1),
Keymapnames[myrandom(0, Numkeymaps-1)]);
newline();
}
}
if (sometimes(tuning)) {
outfmt("tuning = %s\n",
picklist(Tuninglist, sizeof(Tuninglist)
/ sizeof(struct LIST), -1));
}
if (sometimes(emptymeas)) {
struct GRP *grplist_p;
out("emptymeas = \"");
grplist_p = gen_music(num, den, 1);
out("\"");
newline();
if (grplist_p != 0) {
freegrps(grplist_p);
}
}
if (sometimes(restsymmult)) {
out("restsymmult=y");
newline();
}
if (sometimes(printedtime)) {
out("printedtime=");
genstring(4);
if (myrandom(1, 10) > 3) {
genstring(4);
}
newline();
}
if (sometimes(vcombine)) {
outfmt("vcombine = %s", picklist(Vcombinelist,
sizeof(Vcombinelist) / sizeof(struct LIST), -1));
outfmt(" %s ", picklist(Vcombquallist,
sizeof(Vcombquallist) / sizeof(struct LIST), -1));
if (sometimes(10)) {
out(" bymeas");
}
newline();
}
if (sometimes(pagesize)) {
outfmt("pagesize = %s", picklist(Pagesizelist,
sizeof(Pagesizelist) / sizeof(struct LIST), -1));
newline();
}
if (sometimes(restcombine)) {
outfmt("restcombine=%d", myrandom(2, 10));
newline();
}
if (sometimes(firstpage)) {
outfmt("firstpage=%d", myrandom(1, 400));
newline();
}
if (sometimes(gridfret)) {
outfmt("gridfret=%d", myrandom(2, 30));
newline();
}
if (sometimes(gridscale)) {
outfmt("gridscale=%d.%d", myrandom(0, 1), myrandom(1,9));
newline();
}
if (sometimes(mingridheight)) {
outfmt("mingridheight=%d\n", myrandom(3,15));
newline();
}
if (sometimes(minalignscale)) {
outfmt("minalignscale=0.%d\n", myrandom(1,99));
newline();
}
if (sometimes(grids)) {
if (sometimes(75)) {
outfmt("gridswhereused=y");
newline();
}
if (sometimes(75)) {
outfmt("gridsatend=y");
newline();
}
}
/* rearrange the score parameters */
scramble_lines(f_offset, '\n');
/* pick clefs, keys, etc for each staff */
for (s = 1; s <= staffs; s++) {
Staffinfo[s].voices = voices;
Staffinfo[s].defoct = 4;
if(sometimes(STAFFTHINGS)) {
out("staff ");
outfmt("%d", s);
for (ss = 1; ss <= staffs; ss++) {
otherstaffs[ss] = NO;
}
if (sometimes(staffmult)) {
extrastaff = myrandom(1, staffs);
outfmt(",%d", extrastaff);
otherstaffs[extrastaff] = YES;
}
if (sometimes(staffmult)) {
extrastaff = myrandom(1, staffs);
outfmt(" & %d", extrastaff);
otherstaffs[extrastaff] = YES;
}
newline();
if(sometimes(KEY)) {
out("key=");
outfmt("%d", myrandom(0,7));
out(sometimes(50) ? "#" : "&");
if (sometimes(MAJMIN)) {
out(sometimes(50) ? "maj" : "min");
}
newline();
}
if (sometimes(CLEF)) {
char *str;
out("clef=");
str = picklist(Cleflist, sizeof(Cleflist) /
sizeof(struct LIST), -1);
out(str);
adjust_defoct(str, s);
for (ss = 1; ss <= staffs; ss++) {
if (otherstaffs[ss] == YES) {
adjust_defoct(str, ss);
}
}
newline();
}
/* per staff vscheme */
set_vscheme = NO;
if (sometimes(VSCHEME2o)) {
out("vscheme=");
out("2o");
newline();
Staffinfo[s].voices = 2;
set_vscheme = YES;
}
else if (sometimes(VSCHEME2f)) {
out("vscheme=");
out("2f");
newline();
Staffinfo[s].voices = 2;
set_vscheme = YES;
}
else if (sometimes(VSCHEME1)) {
out("vscheme=");
out("1");
newline();
Staffinfo[s].voices = 1;
set_vscheme = YES;
}
else if (sometimes(VSCHEME3f)) {
out("vscheme=");
out("3f");
newline();
Staffinfo[s].voices = 3;
set_vscheme = YES;
}
else if (sometimes(VSCHEME3o)) {
out("vscheme=");
out("3o");
newline();
Staffinfo[s].voices = 3;
set_vscheme = YES;
}
if (set_vscheme == YES) {
for (ss = 1; ss <= staffs; ss++) {
if (otherstaffs[ss] == YES) {
Staffinfo[ss].voices = Staffinfo[s].voices;
}
}
}
if (sometimes(unsetparam)) {
out("unset ");
out(picklist(Paramlist, sizeof(Paramlist) / sizeof(struct LIST), -1));
newline();
}
if (sometimes(viswhereused)) {
out("visible=whereused");
newline();
}
if (sometimes(label)) {
out("label=");
genstring(MAXLABEL);
newline();
}
if (sometimes(label)) {
out("label2=");
genstring(MAXLABEL);
newline();
}
if (sometimes(staffscale)) {
out("staffscale=");
outfmt("%d.%d", myrandom(0,1), myrandom(0, 9));
newline();
}
}
}
/* generate some grids */
if (sometimes(grids)) {
int g;
out("grids");
newline();
Numgrids = myrandom(0, 50);
/* get space to save the names for use in chord statements */
if ((Gridlist = (struct LIST *) malloc(Numgrids * sizeof(struct LIST))) == 0) {
fprintf(stderr, "failed to malloc grid memory\n");
exit(1);
}
for (g = 0; g < Numgrids; g++) {
gen_grid(g);
}
}
/* go into music context */
out("music");
newline();
/* generate as many measures as needed for this test */
for (meas = 1; meas <= measures; meas++) {
if (sometimes(multirest)) {
out("multirest ");
outfmt("%d", myrandom(2, 100));
newline();
}
else {
/* save file offset for scrambling lines later */
f_offset = ftell(outf);
/* generate everything for this measure */
for (s = 1; s <= staffs; s++) {
genmeas(num, den, s, 1, staffs);
if (Staffinfo[s].voices > 1) {
genmeas(num, den, s, 2, staffs);
}
if (Staffinfo[s].voices > 2) {
genmeas(num, den, s, 3, staffs);
}
if (sometimes(CRESC)) {
cresc(s, staffs, meas, measures, num);
}
if (sometimes(TEXTSTUFF)) {
textstuff(s, staffs, meas,
measures, num);
}
if (sometimes(phrase)) {
phrasestuff(s, staffs, meas,
measures, num);
}
if (sometimes(OCTSTUFF)) {
octstuff(s, staffs, meas,
measures, num);
}
if (sometimes(pedal)) {
pedalstuff(s, num);
}
if (sometimes(midi)) {
gen_midi(staffs, num, measures - meas);
}
if (sometimes(prints)) {
genprint();
}
if (sometimes(comments)) {
out("//");
genstring(100);
newline();
}
}
/* rearrange the lines */
scramble_lines(f_offset, '\n');
}
gen_coord_things();
genbar(meas == measures ? NO : YES);
betweenbars();
}
newline();
if (sometimes(typo)) {
/* "mistype" one random byte in the file */
fseek(outf, myrandom(0, ftell(outf) - 1), SEEK_SET);
outfmt("%c", myrandom(32, 127));
}
}
/* generate a measure for a given staff and voice */
void
genmeas(num, den, staff, voice, staffs)
int num;
int den;
int staff;
int voice;
int staffs; /* total number of staffs */
{
struct GRP *grplist_p, *g_p;
/* generate stuff before colon */
outfmt("%d", staff);
if (voice == 1) {
if( sometimes(use1)) {
outfmt(" %d", voice);
}
}
else {
outfmt(" %d", voice);
}
out(":");
grplist_p = gen_music(num, den, staff);
newline();
if (grplist_p == 0) {
return;
}
/* for testing it might be nice to have lyrics with time unrelated to
* note times, but that very quickly makes thing too wide to fit, and
* is not normal, so for now, reuse note times */
if (sometimes(LYRICS) && voice == 1) {
/* put back the original time values of alt groups, since
* lyrics don't have alt */
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
if (g_p->do_alt != 0) {
g_p->basictime = rdiv(g_p->basictime, Two);
}
}
genlyrics(grplist_p, staff, staffs);
}
/* free info */
freegrps(grplist_p);
}
/* generate a measure worth of music, either for normal music input
* of for an emptymeas parameter value. */
struct GRP *
gen_music(num, den, staff)
int num;
int den;
int staff;
{
struct GRP *grplist_p, *g_p;
RATIONAL meastime;
struct GRP lastgrp;
GTYPE type;
int ngrace; /* number of grace chords */
int g; /* grace loop counter */
GTYPE lasttype = None;
char * clefname;
int need_comma; /* if did an inter-group thing */
int need_eph = 0; /* did a ph that needs a matching eph */
int doing_autobeam; /* abm / eadm */
/* sometimes do measure rest or space or rpt */
if (sometimes(measrest)) {
out("mr;");
return(0);
}
if (sometimes(measspace)) {
out("ms;");
return(0);
}
if (sometimes(measrpt)) {
if (sometimes(20)) {
out("dbl");
}
else if (sometimes(15)) {
out("quad");
}
out("mrpt;");
return(0);
}
/* figure out time values first */
meastime.n = num; meastime.d = den;
rred ( &meastime);
grplist_p = picktimes( (struct GRP *) 0, meastime);
grplist_p = scramble_times(grplist_p);
/* set up beginning default time value */
/* TODO: really should be based on timeunit */
lastgrp.basictime.n = 1;
lastgrp.basictime.d = den;
lastgrp.dots = 0;
/* figure out which ones to make alt pairs. If consecutive groups
* have same time value, can make into alt */
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
if (g_p->next != (struct GRP *) 0 &&
EQ(g_p->basictime, g_p->next->basictime) &&
g_p->dots == g_p->next->dots &&
LT(g_p->basictime, Two) &&
sometimes(alt)) {
g_p->basictime = rmul(g_p->basictime, Two);
g_p->next->basictime = g_p->basictime;
g_p->do_alt = 1;
g_p = g_p->next;
g_p->do_alt = 2;
}
else {
g_p->do_alt = 0;
}
}
/* figure out which to connect with custom beams */
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
/* assume no custom beaming */
g_p->custbeam = 0;
/* if there is a run of eighth or shorter, sometimes beam */
if (LE(g_p->basictime, Eighth) && sometimes(custombeam)) {
if (g_p->next != (struct GRP *) 0 &&
LE(g_p->next->basictime, Eighth)) {
g_p->custbeam = 1;
for (g_p = g_p->next; g_p->next != (struct GRP *) 0
&& LE(g_p->next->basictime, Eighth) &&
sometimes(custombeam);
g_p = g_p->next) {
if (sometimes(esbm)) {
g_p->custbeam = 4;
}
else {
g_p->custbeam = 2;
}
}
g_p->custbeam = 3;
}
}
}
doing_autobeam = NO;
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
if (doing_autobeam == YES) {
/* Need to stop if at end of measure, or will be
* hitting custom beam in next group,
* or sometimes stop, even if we could go on */
if (g_p->next == 0 || g_p->next->custbeam != 0 || sometimes(20)) {
g_p->autobeam = 2;
doing_autobeam = NO;
}
}
else if (sometimes(autobeaming)) {
if (g_p->next != 0 && g_p->next->custbeam == 0) {
/* We can do autobeaming */
g_p->autobeam = 1;
doing_autobeam = YES;
}
}
}
/* do each group */
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
need_comma = 0;
/* do mid-measure changes */
if (sometimes(midmeas)) {
char * contxt, param[100];
switch (myrandom(0, 4)) {
default:
case 0:
case 3:
contxt = "score";
break;
case 1:
case 4:
contxt = "staff";
break;
case 2:
/* clef can't be on voice, so use less often */
contxt = "voice";
break;
}
switch (myrandom(0, 2)) {
default:
case 0:
clefname = picklist(Cleflist,
sizeof(Cleflist) / sizeof(struct LIST), -1);
sprintf(param, "clef=%s", clefname);
if (strcmp(contxt, "score") == 0) {
int st;
for (st = 1; st <= MAXSTAFFS; st++) {
adjust_defoct(clefname, st);
}
}
else {
adjust_defoct(clefname, staff);
}
break;
case 1:
/* This won't really work right for "voice"
* level changes to defoct. Oh well. */
Staffinfo[staff].defoct = myrandom(0, 9);
if (strcmp(contxt, "score") == 0) {
int st;
for (st = 1; st <= MAXSTAFFS; st++) {
Staffinfo[st].defoct = Staffinfo[staff].defoct;
}
}
sprintf(param, "defoct=%d", Staffinfo[staff].defoct);
break;
case 2:
sprintf(param, "release=%d", myrandom(0,400));
break;
}
outfmt("<<%s %s>>", contxt, param);
}
/* choose rest, space, or notes */
if (sometimes(rest) && g_p->do_alt == 0 && g_p->custbeam == 0) {
type = Rest;
}
else if (sometimes(space) && g_p->do_alt == 0
&& g_p->custbeam == 0) {
if (sometimes(uncompressible)) {
type = Uspace;
}
else {
type = Space;
}
}
else {
type = Notes;
/* sometimes add some grace notes */
if (sometimes(GRACE) && g_p->do_alt != 2) {
ngrace = myrandom(1, MAXGRACE);
for (g = 0; g < ngrace; g++) {
out("[");
/* explicitly say "grace" on first group,
* and half the time on
* subsequent grace groups.
* Otherwise just use [] */
if (g == 0 || sometimes(50)) {
out("grace");
if (sometimes(SLASHGRACE) &&
ngrace == 1) {
out(";slash 1");
}
}
/* sometime force stem direction */
if (sometimes(GRACE)) {
if (sometimes(50)) {
out(";up");
}
else {
out(";down");
}
}
out("]");
/* on first grace group and some others,
* give a time value from 8 to 256 */
if (g == 0 || sometimes(GRACETIME)) {
lastgrp.basictime.n = 1;
lastgrp.basictime.d
= (8 << myrandom(0, 5));
lastgrp.dots = 0;
outfmt("%d", lastgrp.basictime.d);
}
picknotes(myrandom(1, maxnotes),
Staffinfo[staff].defoct);
out(";");
}
}
/* sometimes add [] things */
if (sometimes(brack)) {
genbrack();
}
}
/* do time value */
if ( EQ(lastgrp.basictime, g_p->basictime)
&& lastgrp.dots == g_p->dots
&& sometimes(timedflt)) {
/* use default value */
out("");
}
else {
prtime(g_p);
while (sometimes(additive_time) && g_p->next != 0) {
g_p = g_p->next;
out("+");
prtime(g_p);
}
}
lastgrp = *g_p;
switch (type) {
case Rest:
if (lasttype == Rest && sometimes(DFLTGRP)) {
out("");
}
else {
out("r");
}
break;
case Uspace:
if (lasttype == Uspace && sometimes(DFLTGRP)) {
out("");
}
else {
out("us");
}
break;
case Space:
if (lasttype == Space && sometimes(DFLTGRP)) {
out("");
}
else {
out("s");
}
break;
default:
if (lasttype == Notes && sometimes(DFLTGRP)) {
out("");
}
else {
/* do some random notes */
picknotes(myrandom(1, maxnotes),
Staffinfo[staff].defoct);
}
/* sometimes do alt */
if (g_p->do_alt == 1) {
out(" alt");
outfmt("%d", myrandom(1, numalt));
if (sometimes(slope)) {
outfmt(", slope %d", myrandom(-30, 30));
}
need_comma = 1;
}
/* do any custom beaming */
if (g_p->custbeam == 1) {
if (need_comma == 1) {
out(",");
}
need_comma = 1;
out(" bm ");
if (sometimes(slope)) {
outfmt(", slope %d", myrandom(-30, 30));
}
}
else if (g_p->custbeam == 3) {
if (need_comma == 1) {
out(",");
}
need_comma = 1;
out(" ebm ");
}
else if (g_p->custbeam == 4) {
if (need_comma == 1) {
out(",");
}
need_comma = 1;
out(" esbm ");
}
if (g_p->autobeam == 1) {
out("abm");
}
else if (g_p->autobeam == 2) {
out("eabm");
}
/* This will only test non-nested ph - eph inside a
* single measure, but is better than no test at all...
*/
if (need_eph && (g_p->next == 0 || sometimes(30))) {
if (need_comma == 1) {
out(",");
}
need_comma = 1;
out("eph");
need_eph = 0;
}
if (sometimes(ph_eph) && g_p->next != 0 && need_eph == 0) {
char *phside;
if (need_comma == 1) {
out(",");
}
need_comma = 1;
if (sometimes(30)) {
phside = "above";
}
else if (sometimes(30)) {
phside = "below";
}
else {
phside = "";
}
outfmt("ph %s", phside);
need_eph = 1;
}
/* TODO: could sometimes do tie */
}
out(";");
lasttype = type;
}
return(grplist_p);
}
/* return YES or NO randomly according to percentage YES */
int
sometimes(percent)
int percent;
{
return ((rand() % 100) < percent ? YES : NO);
}
/* return random number between min and max inclusive */
int
myrandom(min, max)
int min;
int max;
{
return ((rand() % (max - min + 1)) + min);
}
/* output a string, with random white space on either side */
void
out(str)
char *str;
{
if (sometimes(whitebefore)) {
fprintf(outf, " ");
}
fprintf(outf, "%s", str);
if (sometimes(whiteafter)) {
fprintf(outf, " ");
}
}
/* printf-like output, without white space padding */
void
outfmt(char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(outf, fmt, args);
va_end(args);
}
/* do newline, sometimes with an extra one */
void
newline()
{
if (sometimes(crnl)) {
out("\r\n");
}
else if (sometimes(cr_only)) {
out("\r");
}
else {
out("\n");
}
if (sometimes(extranl)) {
out("\n");
}
}
/* generate bar line */
void
genbar(int feed_ok)
{
long f_off; /* offset in file */
if (sometimes(dd_bar)) {
out( sometimes(50) ? " dashed " : " dotted " );
}
out(picklist(Barlist, sizeof(Barlist) / sizeof(struct LIST), -1));
/* save file location for scrambling */
f_off = ftell(outf);
/* add optional things. End each with newline for scrambling */
/* sometimes add a rehearsal mark */
if (sometimes(rehlet)) {
out(" reh ");
outfmt("let\n");
}
else if (sometimes(rehnum)) {
out(" reh ");
outfmt("num\n");
}
else if (sometimes(rehmnum)) {
out(" reh ");
outfmt("mnum\n");
}
else if (sometimes(rehstr)) {
out(" reh ");
genstring(MAXREHSTR);
outfmt("\n");
}
/* add padding sometimes */
if(sometimes(BARPAD)) {
outfmt(" pad %d\n", myrandom(MINPAD, MAXPAD));
}
/* sometimes do ending */
if (sometimes(ENDING)) {
if (In_ending == YES && sometimes(ENDENDING)) {
outfmt(" endending\n");
In_ending = NO;
}
else if (feed_ok) {
out(" ending ");
genstring(MAXENDSTR);
outfmt("\n");
In_ending = YES;
}
}
scramble_lines(f_off, ' ');
newline();
if (feed_ok) {
/* adds feeds and similar things sometimes */
if (Samescore_inprog == YES && sometimes(55)) {
out("samescoreend");
newline();
Samescore_inprog = NO;
}
if (Samepage_inprog == YES && sometimes(55)) {
out("samepageend");
newline();
Samepage_inprog = NO;
}
else if (sometimes(scorefeed)) {
out("newscore");
if (sometimes(marginoverride)) {
outfmt(" rightmargin %d.%d", myrandom(0, 2), myrandom(0,100) );
}
else if (sometimes(marginoverride)) {
outfmt(" rightmargin = auto");
}
if (sometimes(marginoverride)) {
outfmt(" leftmargin %d.%d", myrandom(0, 2), myrandom(0,100) );
}
newline();
}
else if (sometimes(pagefeed)) {
out("newpage");
if (sometimes(marginoverride)) {
outfmt(" leftmargin %d.%d", myrandom(0, 2), myrandom(0,100) );
}
if (sometimes(marginoverride)) {
outfmt(" rightmargin %d.%d", myrandom(0, 2), myrandom(0,100) );
}
else if (sometimes(marginoverride)) {
outfmt(" rightmargin = auto");
}
newline();
}
else if (sometimes(restart)) {
out("restart");
newline();
}
else {
if (sometimes(samescore)) {
out("samescorebegin");
newline();
Samescore_inprog = YES;
}
if (sometimes(samepage)) {
out("samepagebegin");
newline();
Samepage_inprog = YES;
}
}
}
if (sometimes(control)) {
out("control");
newline();
if (sometimes(saveparms)) {
int spi;
spi = myrandom(0, MAX_SAVEPARMS - 1);
outfmt("saveparms \"%s\"\n", saveparms_names[spi]);
saveparms_used[spi] = YES;
}
if (sometimes(restoreparms)) {
int spi;
int count;
/* Start at a random place in the saveparms list,
* and look for one that has been used. */
spi = myrandom(0, MAX_SAVEPARMS - 1);
for(count = 0; count < MAX_SAVEPARMS; count++) {
if (saveparms_used[spi] == YES) {
/* Found one. restore from it */
outfmt("restoreparms \"%s\"\n", saveparms_names[spi]);
break;
}
/* move to next in list, wrapping if needed */
if (++spi >= MAX_SAVEPARMS) {
spi = 0;
}
}
}
/* Change some parameters */
if (sometimes(50)) {
out("score");
gen_score_ssv();
}
newline();
/* return to music context */
out("music");
newline();
}
}
/* create a list of GRPs that add up to remtime. Return pointer to list */
struct GRP *
picktimes(grplist_p, remtime)
struct GRP *grplist_p;
RATIONAL remtime;
{
RATIONAL basictime;
RATIONAL fulltime;
int dots;
struct GRP *grp_p;
/* Start with oct whole note, optionally with dots.
* Go shorter from there if necessary to fit in the remaining
* time in the measure. */
fulltime = basictime = Eight;
dots = 0;
if (sometimes(dotted)) {
dots = 1;
fulltime = rmul(basictime, Three_halves);
if (sometimes(dbldotted)) {
dots = 2;
fulltime = rmul(basictime, Seven_fourths);
}
}
/* keep shortening til no longer than remaining time */
while (GT(fulltime, remtime)) {
/* undo dots sometimes, if any, to shorten */
/* also undo dots if they might cause us to need notes
* shorter than a 256th */
if (dots == 2 && (sometimes(dbldotted) || LE(basictime, N64))) {
dots = 1;
fulltime = rmul(basictime, Three_halves);
}
else if (dots == 1 && (sometimes(dotted) || LE(basictime, N128))) {
dots = 0;
fulltime = basictime;
}
else {
basictime = rdiv(basictime, Two);
fulltime = rdiv(fulltime, Two);
}
}
/* save info about the amount of time chosen */
if ((grp_p = (struct GRP *) malloc(sizeof(struct GRP))) ==
(struct GRP *) 0) {
fprintf(stderr, "malloc failed\n");
exit(1);
}
grp_p->basictime = basictime;
grp_p->dots = dots;
grp_p->next = grplist_p;
grplist_p = grp_p;
/* find out how much time is left */
remtime = rsub(remtime, fulltime);
/* Sometimes introduce a "bug" in the input, with too much time,
* or use the auto padding feature with too little */
if (sometimes(wrongtime) && remtime.d < 16) {
if (GE(remtime, Three_fourths)) {
remtime = rmul(remtime, Three_fourths);
}
else {
remtime = rmul(remtime, Five_fourths);
}
}
/* if still time left, recurse to create more groups */
if (GT(remtime, Zero)) {
grplist_p = picktimes(grplist_p, remtime);
}
return(grplist_p);
}
/* recursively free list of GRP structs */
void
freegrps(g_p)
struct GRP *g_p;
{
if (g_p == (struct GRP *) 0) {
return;
}
freegrps(g_p->next);
free(g_p);
}
/* given a list of group times, rearrange them and subdivide some of the
* times, etc */
struct GRP *
scramble_times(grplist_p)
struct GRP *grplist_p;
{
struct GRP *g_p;
struct GRP *grp_p;
/* go down list, take some groups and subdivide */
for (g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
if (sometimes(subdivide)) {
if (g_p->basictime.d < 256) {
g_p->basictime = rdiv(g_p->basictime, Two);
if ((grp_p = (struct GRP *) malloc(sizeof(struct GRP))) ==
(struct GRP *) 0) {
fprintf(stderr, "malloc failed\n");
exit(1);
}
grp_p->basictime = g_p->basictime;
grp_p->dots = g_p->dots;
grp_p->next = g_p->next;
g_p->next = grp_p;
}
}
}
/* TODO: could shuffle them around */
return(grplist_p);
}
/* pick random notes to make up a chord */
void
picknotes(n, defoct)
int n;
int defoct;
{
static int notegeneration = 0;
char *str;
int octave;
struct LIST *list_p;
int listleng;
int css_index; /* cross-staff stem index */
/* calculate subset of notelist to use, based on octave range. Constrain
* to be within valid range */
octave = defoct - octavesbeyond;
if (octave < 0) {
octave = 0;
}
list_p = &(Notelist[octave * 7]);
listleng = (octavesbeyond * 2 + 1) * 7;
if (defoct + octavesbeyond > 9) {
listleng -= 7 * (defoct + octavesbeyond - 9);
}
/* pick appropriate number of notes, some with accidentals */
notegeneration++;
if (sometimes(cross_staff_stems)) {
css_index = myrandom(1, n);
}
else {
css_index = -1;
}
for ( ; n > 0; n--) {
str = picklist(list_p, listleng, notegeneration);
if (str != (char *) 0) {
if (css_index == n) {
outfmt(" with ");
}
outfmt("%c", str[0]);
}
else {
break;
}
octave = str[1] - '0';
if (sometimes(accidental)) {
str = picklist(Acclist,
sizeof(Acclist) / sizeof(struct LIST), -1);
if (str != (char *) 0) {
out(str);
}
}
/* handle octave */
if (sometimes(ABSOCT)) {
outfmt("%d", octave);
}
else if (octave > defoct) {
for (octave -= defoct; octave > 0; octave--) {
out("+");
}
}
else if (octave < defoct) {
for (octave = defoct - octave; octave > 0; octave--) {
out("-");
}
}
/* sometimes mark as cue size */
if (sometimes(SMALL)) {
out("?");
}
/* add tag sometimes */
if (sometimes(tag)) {
out("=");
out(create_tag());
out(" ");
}
/* sometimes add head shape override */
if (sometimes(noteheads) && sometimes(10)) {
outfmt("hs \"%s\"", picklist(Noteheadlist,
sizeof(Noteheadlist) / sizeof(struct LIST), -1));
}
}
if (css_index > 0) {
if (sometimes(50)) {
outfmt("above");
}
else {
outfmt("below");
}
}
}
/* generate things in [ ] before group */
void
genbrack()
{
static int brackgen = 0;
char *str;
int i;
out("[");
brackgen++;
for (i = myrandom(1, MAXBRACK); i > 0; i--) {
str = picklist(Bracklist,
sizeof(Bracklist) / sizeof (struct LIST), brackgen);
if (str != (char *) 0) {
out(str);
if (i > 1) {
/* it's legal to have more than one [ ] */
if (sometimes(multi_brack)) {
out("][");
}
else {
out(";");
}
}
}
}
if (sometimes(tag)) {
out(";=");
out(create_tag());
out(" ");
}
out("]");
if (sometimes(gtc)) {
out("...");
}
}
/* return a random item from given list. If generation is set to -1, return
* any item. If not, return only items that haven't been used yet this
* generation. */
char *
picklist(list_p, leng, generation)
struct LIST *list_p;
int leng;
int generation;
{
int choice;
int retries = 0;
/* choose random item on list. If everything chosen is already used,
* give up eventually */
do {
choice = myrandom(0, leng - 1);
if (generation == -1) {
return(list_p[choice].str);
}
if (list_p[choice].used != generation) {
list_p[choice].used = generation;
return(list_p[choice].str);
}
} while (++ retries < leng * 4);
return(char *) 0;
}
/* print a string up to leng characters long, any printable character */
void
genstring(leng)
int leng;
{
outfmt("%s", create_a_string(0, leng));
}
/* create a random string, returning it in static buffer */
char *
create_a_string(int minleng, int leng)
{
char ch;
int do_box;
static char buff[BUFSIZ];
int offset;
if (leng > sizeof(buff) - 1) {
leng = sizeof(buff) - 1;
}
leng = myrandom(minleng, leng);
offset = 0;
buff[offset++] = '"';
/* Yes, I mean single = here */
if ((do_box = sometimes(box)) != 0) {
buff[offset++] = '\\';
buff[offset++] = '[';
}
for ( ; leng > 0; leng--) {
if (sometimes(string_escapes)) {
switch (myrandom(1, 10)) {
case 1:
buff[offset++] = '\\';
buff[offset++] = 'b';
break;
case 2:
buff[offset++] = '\\';
buff[offset++] = 'n';
break;
case 3:
buff[offset++] = '\\';
buff[offset++] = '/';
break;
case 4:
buff[offset++] = '\\';
buff[offset++] = ':';
break;
case 5:
sprintf(buff+offset, "\\s(+%d)", myrandom(1,5));
while (buff[offset] != '\0') {
offset++;
}
break;
case 6:
sprintf(buff+offset, "\\v(%d)", myrandom(1,100));
while (buff[offset] != '\0') {
offset++;
}
break;
case 7:
buff[offset++] = '\\';
buff[offset++] = '%';
break;
case 8:
buff[offset++] = '\\';
buff[offset++] = '#';
break;
case 9:
if (Numkeymaps > 0) {
int m;
char *mapname;
buff[offset++] = '\\';
buff[offset++] = 'm';
buff[offset++] = '(';
mapname = Keymapnames[myrandom(0, Numkeymaps-1)];
for (m = 0; mapname[m] != 0; m++) {
buff[offset++] = mapname[m];
}
buff[offset++] = ')';
break;
}
/* Fall through to default if no keymaps */
default:
sprintf(buff+offset,
"\\f(%s %s)", picklist(Familylist,
sizeof(Familylist) / sizeof(struct LIST), - 1),
picklist(Fontlist,
sizeof(Fontlist) / sizeof(struct LIST), -1));
while (buff[offset] != '\0') {
offset++;
}
break;
}
continue;
}
if (sometimes(15)) {
ch = ' '; /* real text has a lot of spaces */
}
else {
ch = myrandom((int)' ', (int)'~');
/* backslash things that need that */
if (ch == '\\' || ch == '"') {
buff[offset++] = '\\';
}
}
buff[offset++] = ch;
}
if (do_box) {
buff[offset++] = '\\';
buff[offset++] = ']';
}
buff[offset++] = '"';
buff[offset] = '\0';
return(buff);
}
/* Like create_a_string, except no string escapes and such */
char *
create_a_name(int minleng, int leng)
{
char ch;
static char buff[BUFSIZ];
int offset;
if (leng > sizeof(buff) - 1) {
leng = sizeof(buff) - 1;
}
leng = myrandom(minleng, leng);
offset = 0;
for ( ; leng > 0; leng--) {
ch = myrandom((int)' ', (int)'~');
if (ch == '\\' || ch == '"') {
buff[offset++] = '\\';
}
buff[offset++] = ch;
}
buff[offset] = '\0';
return(buff);
}
/* print a time value */
void
prtime(g_p)
struct GRP *g_p;
{
int d;
if (EQ(Two, g_p->basictime)) {
out("1/2");
}
else if (EQ(Four, g_p->basictime)) {
out("1/4");
}
else if (EQ(Eight, g_p->basictime)) {
out("1/8");
}
else {
outfmt("%d", g_p->basictime.d);
}
/* print dots if any */
for (d = g_p->dots; d > 0; d--) {
out(".");
}
}
/* print usage message and exit */
void
usage(char *pname)
{
#ifdef GENONLY
fprintf(stderr, "usage: %s [-i iterations] [-p prefix]\n", pname);
#else
fprintf(stderr, "usage: %s [-d] [-i iterations] [-n] [-p prefix] [-t timeout] [-v]\n", pname);
#endif
exit(1);
}
/* run a test. Generate a test file, run the command on it. If it core dumps
* or exhibits other nasty behavior, save the file, otherwise throw it away */
void
run_test(int index, char *command, char *suffix, char *prefix, int timeout, int verbose)
{
char filename[100]; /* name of generated input file */
char cmd[BUFSIZ]; /* the command to execute */
int ret; /* return code */
int exitval; /* exit value of execution */
sprintf(filename, "%s%d", prefix, index);
if ((outf = fopen(filename, "w+")) == (FILE *) 0) {
fprintf(stderr, "can't open %s\n", filename);
return;
}
initvals();
gen();
fclose(outf);
#ifndef GENONLY
if (sometimes(xoption)) {
int start, end;
start = myrandom(-2, 2);
end = myrandom(-2, 2);
sprintf(cmd, "%s -x%d,%d %s %s", command, start, end,
filename, suffix);
}
else {
sprintf(cmd, "%s %s %s", command, filename, suffix);
}
ret = exectest(cmd, timeout, verbose, 0, &exitval);
num_non_midi_tests++;
if (WIFEXITED(exitval) && strcmp(command, "mup") == 0) {
int ret2;
/* run mup with MIDI option */
if (sometimes(xoption)) {
int start, end;
start = myrandom(-2, 2);
end = myrandom(-2, 2);
sprintf(cmd, "mup -x%d,%d -m /dev/null %s", start, end, filename);
}
else {
sprintf(cmd, "mup -m /dev/null %s", filename);
}
ret2 = exectest(cmd, timeout, verbose, 1, &exitval);
num_midi_tests++;
if (ret == YES && ret2 == YES) {
unlink(filename);
}
}
#endif
}
#ifndef GENONLY
/* execute test. Return YES if should remove file, NO if not */
int
exectest(char *cmd, int timeout, int verbose, int doing_midi, int *ret_p)
{
int ret; /* wait() exit code of child */
int code; /* exit code of child */
long now;
char *timestamp;
struct stat statinfo;
int wpid; /* PID returned by wait() */
if (verbose) {
time(&now);
timestamp = ctime(&now);
timestamp[19] = '\0';
fprintf(stderr, "\n========= %s: %s ===========\n",
timestamp + 4, cmd);
}
unlink("core");
signal(SIGALRM, alarmhandler);
alarm(timeout);
switch(child = fork()) {
case 0:
execlp("sh", "sh", "-c", cmd, (char *) 0);
/*FALLTHRU*/
case -1:
fprintf(stderr, "failed to execute command\n");
exit(1);
default:
/* wait for child to die */
do {
wpid = wait(&ret);
} while (wpid != child);
alarm(0);
*ret_p = ret;
/* we don't remove the file if
* 1) if produced a core dump
* 2) was killed
* 3) exited non-zero or output contained things that
* look suspiciously like floating float overflows,
* and user asked to save failures.
*/
if (WCOREDUMP(ret) || stat("core", &statinfo) == 0) {
if (verbose) {
fprintf(stderr, "\tcore dumped!\n");
}
num_core_dumped++;
return(NO);
}
if (WIFEXITED(ret)) {
code = WEXITSTATUS(ret);
if (verbose) {
fprintf(stderr, "\texit code was %d\n", code);
}
if (code != 0) {
num_exited_nonzero++;
if (doing_midi) {
num_midi_nonzero++;
}
}
else {
/* Check for floating point errors in output */
if ( ! doing_midi) {
int f;
struct stat info;
char * addr;
int n;
if ((f = open("RegGen2.out", O_RDONLY)) >= 0) {
fstat(f, &info);
addr = (char *) mmap(0, info.st_size, PROT_READ,
MAP_SHARED, f, 0);
close(f);
n = info.st_size;
if (addr != 0) {
for (n = 0; n < info.st_size - 3; n++) {
if (addr[n] == 'n' &&
strncmp(addr+n, "nan ", 4) == 0) {
num_nans++;
code = 1;
break;
}
else if (isdigit(addr[n])) {
if (strspn(addr+n, "0123456789") > 15) {
num_huge_nums++;
code = 1;
break;
}
}
}
munmap(addr, info.st_size);
}
else {
fprintf(stderr, "mmap failed: %s\n", strerror(errno));
}
if (n < info.st_size - 3) {
/* treat as fail */
*ret_p = 1;
return(NO);
}
}
}
}
if (savenonzero == YES && code != 0) {
return(NO);
}
}
else {
if (verbose) {
fprintf(stderr, "\twas killed\n");
}
num_killed++;
return(NO);
}
return(YES);
break;
}
}
/* if alarm goes off, assume child is in an infinite loop, and put it
* out of its misery */
void
alarmhandler(int sig)
{
kill(child, SIGTERM);
}
#endif
/* generate lyrics */
void
genlyrics(grplist_p, staff, staffs)
struct GRP *grplist_p;
int staff;
int staffs; /* how many total staffs */
{
struct GRP *g_p;
int syls;
/* do stuff before colon */
out("lyrics ");
if (sometimes(LYRABOVE)) {
out("above ");
outfmt("%d", staff);
}
else if (sometimes(LYRBETWEEN) && staff < staffs) {
out("between");
outfmt("%d", staff);
out("&");
outfmt("%d", staff + 1);
}
else if (sometimes(LYRBELOW)) {
out("below");
outfmt("%d", staff);
}
else {
outfmt("%d", staff);
}
out(":");
/* print time values, some with space */
for (syls = 0, g_p = grplist_p; g_p != (struct GRP *) 0; g_p = g_p->next) {
prtime(g_p);
if (sometimes(LYRSPACE)) {
out("s");
}
else {
syls++;
}
out(";");
}
/* print verse number */
if (sometimes(use1)) {
out("[1]");
}
/* generate lyric syllables */
outfmt("\"");
for ( ; syls > 0; syls--) {
gensyl(syls > 1 ? YES : NO);
}
outfmt("\"");
out(";");
newline();
}
/* generate lyric syllables, some with dashes or underscores */
void
gensyl(mid)
int mid; /* YES if in middle of string (not end) */
{
int leng;
if (sometimes(sylposition)) {
if (sometimes(50)) {
outfmt("%d", myrandom(0,16)-8);
}
outfmt("|");
}
for (leng = myrandom(1, 6); leng > 0; leng--) {
putc(myrandom((int)'a', (int) 'z'), outf);
}
if (sometimes(LYRDASH)) {
outfmt("-");
}
else if (sometimes(UNDERSCORE)) {
outfmt("_");
}
else if (mid) {
outfmt(" ");
}
}
/* take all the lines starting from foffset and rearrange them. To rearrange
* whole lines, repchar will be a newline. Otherwise, you can scramble part of
* a line by putting each piece on a separate line, then using ' ' as the
* repchar to put everything onto one line */
void
scramble_lines(long foffset, char repchar)
{
long end;
long leng, c;
char *p;
char *buff; /* copy of text to be scrambled */
char **lines_p; /* malloc-ed array of pointers to lines in buff */
int lines = 0; /* how many lines in buff */
int n; /* index into lines_p */
int index; /* index into lines_p */
int i;
int lastwasnl; /* YES if prev char was a newline */
/* get a buffer and read in the part of the file to be scrambled */
end = ftell(outf);
fseek(outf, foffset, SEEK_SET);
leng = end - foffset;
if (leng <= 0) {
fseek(outf, end, SEEK_SET);
return;
}
if ((buff = (char *)malloc(leng)) == (char *) 0) {
fprintf(stderr, "malloc failed\n");
exit(1);
}
/* read into buffer, counting the number of lines */
for (p = buff; p < buff + leng; p++) {
*p = getc(outf);
if (*p == '\n') {
lines++;
}
}
/* sometimes the last newline may have white space after it, which
* effectively makes an additional line (albeit an unterminated one) */
if ( *(p-1) != '\n') {
lines++;
}
if (lines < 1) {
/* nothing to scramble */
free(buff);
return;
}
/* now malloc array of pointers, one for each line */
if ((lines_p = (char **) malloc(lines * sizeof(char *))) == (char **) 0) {
fprintf(stderr, " malloc failed\n");
exit(1);
}
/* go through buff again, saving a pointer to the beginning of each line */
lastwasnl = YES;
for (n = c = 0; c < leng; c++) {
if (lastwasnl == YES) {
lines_p[n++] = buff + c;
}
lastwasnl = (buff[c] == '\n' ? YES : NO);
}
if (n != lines) {
fprintf(stderr, "bug: n != lines %d %d\n", n, lines);
exit(2);
}
/* now go into loop. pick a random line and output it. collapse
* the array to not include that line. repeat till done */
fseek(outf, foffset, SEEK_SET);
for (c = lines; c > 0; c--) {
index = myrandom(0, c - 1);
/* output the line chosen */
for (p = lines_p[index]; p < buff + leng; p++) {
if (*p == '\n') {
putc(repchar, outf);
break;
}
else {
putc(*p, outf);
}
}
/* move others down */
for (i = index; i < c - 1; i++) {
lines_p[i] = lines_p[i+1];
}
}
if (ftell(outf) != end) {
fprintf(stderr, "bug: rewritten length doesn't match original\n");
exit(2);
}
free(buff);
free(lines_p);
}
/* do < or > statements */
void
cresc(staff, staffs, meas, measures, num)
int staff;
int staffs; /* how many staffs */
int meas; /* current measure number */
int measures; /* total number of measures */
int num; /* numerator of time signature */
{
if (sometimes(50)) {
out("<");
}
else {
out(">");
}
place(staff, staffs, YES, NO);
stuff(num, NO, YES, measures - meas);
newline();
}
/* choose a place: above, below, between */
void
place(staff, staffs, between_ok, req)
int staff;
int staffs;
int between_ok; /* YES if between is legal */
int req; /* YES if required */
{
if (sometimes(STUFFABOVE)) {
out("above ");
outfmt("%d", staff);
}
else if (between_ok == YES && sometimes(STUFFBETWEEN)
&& staff < staffs) {
out("between");
outfmt("%d", staff);
out("&");
outfmt("%d", staff + 1);
}
else if (sometimes(STUFFBELOW) || req == YES) {
out("below");
outfmt("%d", staff);
}
else {
outfmt("%d", staff);
}
if (sometimes(dist)) {
outfmt(" dist %d.%d ", myrandom(-2, 2), myrandom(0, 999) );
}
if (sometimes(aligntag)) {
outfmt(" align %d", myrandom(0,10000));
}
out(":");
}
/* generate a "til" clause */
void
gen_til(count100, num, measrem)
int count100; /* where the STUFF started times 100 */
int num; /* numerator of time sig */
int measrem; /* measures left in the song */
{
out("til");
/* do some with only one part or the other, some with both */
if (sometimes(TILSAMEMEAS) || measrem == 0) {
count100 = myrandom(count100, (num + 1) * 100);
outfmt("%d.%02d", count100 / 100, count100 % 100);
}
else if (sometimes(TILMEASONLY)) {
outfmt("%d", myrandom(1, measrem));
out("m");
}
else {
outfmt("%d", myrandom(1, measrem));
out("m");
out("+");
count100 = myrandom(0, (num + 1) * 100);
outfmt("%d.%02d", count100 / 100, count100 % 100);
}
}
/* generate a generic stuff item */
void
stuff(num, str, til, measrem)
int num; /* numerator of time signature */
int str; /* if YES, generate a string */
int til; /* if YES generate a til clause */
int measrem; /* measures remaining */
{
int count;
/* generate starting place. Get a random number 100 times too big,
* and make a float number with 2 decimal digits from that */
count = myrandom(0, (num + 1) * 100);
outfmt("%d.%d", count / 100, count % 100);
if (str == YES) {
genstring(myrandom(0, MAXSTR));
}
else if (str == OCTSTR) {
out("\"8va\"");
}
else if (str == GRIDCHORD) {
out(picklist(Gridlist, Numgrids, -1));
}
if (til == YES) {
gen_til(count, num, measrem);
}
out(";");
}
/* generate rom, bold, etc stuffs */
void
textstuff(staff, staffs, meas, measures, num)
int staff;
int staffs; /* how many staffs */
int meas; /* current measure number */
int measures; /* total number of measures */
int num; /* numerator of time signature */
{
int use_chord_grid = NO;
if (sometimes(FAMILY)) {
out(picklist(Familylist,
sizeof(Familylist) / sizeof(struct LIST), - 1));
}
out(" ");
out(picklist(Fontlist, sizeof(Fontlist) / sizeof(struct LIST), -1));
if (sometimes(FNTSIZE)) {
out("(");
outfmt("%d", myrandom(MINSIZE, maxsize));
out(")");
}
else {
out(" ");
}
if (sometimes(modifier)) {
switch(myrandom(1, 5)) {
case 1:
case 4:
case 5:
out("chord ");
if (Numgrids > 0) {
use_chord_grid = YES;
}
break;
case 2:
out("analysis ");
break;
case 3:
out("figbass ");
break;
}
}
place(staff, staffs, YES, NO);
if (use_chord_grid) {
stuff(num, GRIDCHORD, NO, measures - meas);
}
else {
stuff(num, YES, sometimes(TILTEXT), measures - meas);
}
newline();
}
/* generate phrase marks */
void
phrasestuff(staff, staffs, meas, measures, num)
int staff;
int staffs; /* how many staffs */
int meas; /* current measure number */
int measures; /* total number of measures */
int num; /* numerator of time signature */
{
if (sometimes(phrasemod)) {
if (sometimes(50)) {
out("dotted ");
}
else {
out("dashed ");
}
}
out("phrase ");
place(staff, staffs, NO, NO);
stuff(num, NO, YES, measures - meas);
newline();
}
/* generate octave marks */
void
octstuff(staff, staffs, meas, measures, num)
int staff;
int staffs; /* how many staffs */
int meas; /* current measure number */
int measures; /* total number of measures */
int num; /* numerator of time signature */
{
out("octave ");
place(staff, staffs, NO, YES);
stuff(num, OCTSTR, sometimes(50), measures - meas);
newline();
}
/* generate pedal commands */
void
pedalstuff(staff, num)
int staff;
int num;
{
int n;
int when;
out("pedal ");
if (sometimes(50)) {
out("below");
}
outfmt("%d:", staff);
when = 0;
for (n = 0; n < pedpermeas; n++) {
/* generate number 100 times bigger, then format
* as number with 2 decimal digits. */
when += myrandom(10, num * 100);
if (when > (num + 1) * 100) {
break;
}
outfmt("%d.%02d", when / 100, when % 100);
/* sometimes end pedal if appropriate */
if (sometimes(endped) && Pedstate[staff] == 1) {
out("*");
Pedstate[staff] = 0;
}
else {
Pedstate[staff] = 1;
}
out(";");
}
newline();
}
/* sometimes put things between bars */
void
betweenbars()
{
int did_something = NO;
if (sometimes(HDFT)) {
headfoot();
did_something = YES;
}
if (sometimes(block)) {
int i;
out("block ");
newline();
for (i = 0; i < myrandom(0, 4); i++) {
genprint();
}
did_something = YES;
}
/* TODO: could sometimes do score/staff/voice things here */
/* make sure we get back to music context */
if (did_something == YES) {
out("music");
newline();
}
}
/* generate header/footer */
void
headfoot()
{
char *hdfttype;
int i;
/* generate a header/footer if we can find one that hasn't been
* generated before */
if ((hdfttype = picklist(Headfootlist,
sizeof(Headfootlist) / sizeof(struct LIST),
1)) != (char *) 0) {
/* output header, footer, header2, or footer2 */
out(hdfttype);
outfmt(" %s", picklist(Pagesidelist,
sizeof(Pagesidelist) / sizeof(struct LIST), -1));
newline();
/* generate items for header/footer */
for (i = MINHDFTITEMS; i < MAXHDFTITEMS; i++) {
if (sometimes(HDFTFONT)) {
out("font=");
out(picklist(Fontlist, sizeof(Fontlist)
/ sizeof(struct LIST), -1));
newline();
}
else if (sometimes(HDFTSIZE)) {
out("size=");
outfmt("%d", myrandom(MINSIZE, maxsize));
}
/*TODO: could also sometimesdo print/left/right/center here */
else {
out("title ");
if (sometimes(FAMILY)) {
out(picklist(Familylist,
sizeof(Familylist)
/ sizeof(struct LIST), - 1));
out(" ");
}
if (sometimes(FNT)) {
out(picklist(Fontlist, sizeof(Fontlist)
/ sizeof(struct LIST), -1));
out(" ");
}
if (sometimes(FNTSIZE)) {
out("(");
outfmt("%d", myrandom(MINSIZE, maxsize));
out(")");
}
/* generate one to three strings */
genstring(MAXTITLE);
if (sometimes(TITLE2)) {
genstring(MAXTITLE);
}
else if (sometimes(TITLE3)) {
genstring(MAXTITLE);
genstring(MAXTITLE);
}
}
newline();
}
}
}
/* for a given test, pick random values for the parameters that govern what
* is generated */
void
initvals()
{
int n;
use1 = myrandom(0,100);
measrest = myrandom(0, 75);
measspace = myrandom(0, 45);
measrpt = myrandom(0, 5);
mingridheight = myrandom(0, 10);
minalignscale = myrandom(0, 10);
brack = myrandom(0, 10);
whitebefore = myrandom(0, 100);
whiteafter = myrandom(0, 100);
extranl = myrandom(0, 25);
swingunit = myrandom(0, 20);
stemlen = myrandom(0, 15);
stemshorten = myrandom(0, 45);
staffmult = myrandom(0, 15);
crnl = myrandom(0, 40);
cr_only = myrandom(0, 10);
midmeas = myrandom(0, 10);
noteheads = myrandom(0, 10);
typo = myrandom(0, 20);
scorefeed = myrandom(0, 30);
pagefeed = myrandom(0, 20);
marginoverride = myrandom(0, 20);
sylposition = myrandom(0, 30);
staffpad = myrandom(0, 30);
scorepad = myrandom(0, 30);
rehstyle = myrandom(0, 50);
restart = myrandom(0, 10);
dotted = myrandom(5,25);
dbldotted = myrandom(0, 20);
timedflt = myrandom(0, 100);
wrongtime = myrandom(0, 3);
rest = myrandom(0, 65);
space = myrandom(0, 35);
uncompressible = myrandom(5, 50);
subdivide = myrandom(2, 50);
accidental = myrandom(0, 60);
rehlet = myrandom(0, 20);
rehnum = myrandom(0, 20);
rehmnum = myrandom(0, 20);
rehstr = myrandom(0, 20);
multirest = myrandom(0, 15);
restsymmult = myrandom(0, 15);
printedtime = myrandom(0, 10);
additive_time = myrandom(0, 8);
cross_staff_stems = myrandom(0, 2);
maxnotes = myrandom(1, 11);
phrase = myrandom(0, 10);
octavesbeyond = myrandom(0, 2);
alt = myrandom(0,5);
numalt = myrandom(1, 3);
custombeam = myrandom(0, 25);
esbm = myrandom(0, 15);
autobeaming = myrandom(0, 2);
ph_eph = myrandom(2, 15);
slope = myrandom(0, 8);
compoundts = myrandom(0, 5);
comments = myrandom(0, 10);
vcombine = myrandom(0, 10);
pagesize = myrandom(0, 10);
pedal = myrandom(0, 15);
pedpermeas = myrandom(1, 5);
endped = myrandom(0, 30);
margins = myrandom(0, 25);
dist = myrandom(0, 15);
aligntag = myrandom(0,10);
division = myrandom(0, 10);
endingstyle = myrandom(0, 20);
label = myrandom(0, 25);
measnum = myrandom(0,40);
maxmeasures = myrandom(0, 15);
maxscores = myrandom(0, 15);
slashesbetween = myrandom(0, 25);
bracketrepeats = myrandom(0, 20);
repeatdots = myrandom(0, 15);
withfont = myrandom(0, 35);
emptymeas = myrandom(0, 20);
pack = myrandom(0, 40);
transpose = myrandom(0, 20);
chordtranslation = myrandom(0, 10);
useaccs = myrandom(0, 8);
carryaccs = myrandom(0, 7);
alignped = myrandom(0, 20);
alignlabels = myrandom(0, 10);
extendlyrics = myrandom(0, 60);
tag = 0; /*** tags don't really work yet **/
abstag = myrandom(0,20);
prints = myrandom(0, 5);
dd_bar = myrandom(0, 5);
string_escapes = myrandom(0, 3);
modifier = myrandom(0,35);
box = myrandom(0,10);
staffscale = myrandom(0, 7);
multi_brack = myrandom(0, 10);
gtc = myrandom(0, 7);
unsetparam = myrandom(0, 35);
viswhereused = myrandom(0, 30);
paragraph = myrandom(0, 30);
block = myrandom(0, 15);
restcombine = myrandom(0, 50);
firstpage = myrandom(0, 10);
fretx = myrandom(0, 20);
freto = myrandom(0, 20);
fretdash = myrandom(0, 20);
gridfret = myrandom(0, 50);
gridscale = myrandom(0, 40);
gridparen = myrandom(0, 50);
grids = myrandom(15, 60);
orderlist = myrandom(10, 50);
phrasemod = myrandom(0, 25);
xoption = myrandom(5, 35);
maxsize = myrandom(15, MAXSIZE);
print = myrandom(1, 8);
line = myrandom(1, 8);
curve = myrandom(1, 4);
bulgecurve = myrandom(1, 4);
keymaps = myrandom(1, 6);
tuning = myrandom(2, 8);
midi = myrandom(2, 25);
midi_to = myrandom(2, 10);
control = myrandom(5, 20);
/* The next two only get used if control is used */
saveparms = myrandom(50, 70);
restoreparms = myrandom(40, 60);
barstyle = myrandom(10, 25);
subbarstyle = myrandom(5, 15);
midlinestemfloat = myrandom(2, 10);
beamslope = myrandom(3, 12);
tupletslope = myrandom(3, 12);
numbermultrpt = myrandom(3, 12);
defaultphraseside = myrandom(5, 15);
samescore = myrandom(2, 7);
samepage = myrandom(2, 7);
Samescore_inprog = NO;
Samepage_inprog = NO;
for (n = 1; n <= MAXSTAFFS; n++) {
Pedstate[n] = 0;
}
}
/* create a tag. */
char *
create_tag()
{
int i;
int tag; /* index into Tagtable */
int len; /* strlen of tag */
/* if tag table is full, reuse an existing tag */
if (Numtags >= MAXTAGS) {
tag = myrandom(0, MAXTAGS - 1);
}
else if (sometimes(ONELETTAG)) {
Tagtable[Numtags][0] = myrandom('a', 'z');
Tagtable[Numtags][1] = '\0';
tag = Numtags++;
}
else {
Tagtable[Numtags][0] = '_';
len = myrandom(2, MAXTAGLEN);
for (i = 1; i < len; i++) {
Tagtable[Numtags][i] = myrandom('a' - 1, 'z');
if (Tagtable[Numtags][i] == 'a' - 1) {
Tagtable[Numtags][i] = '_';
}
}
Tagtable[Numtags][i] = '\0';
tag = Numtags++;
}
return(Tagtable[tag]);
}
/* generate print/left/right/center statements */
void
genprint()
{
char *xtag, *ytag;
if (sometimes(paragraph)) {
if (sometimes(30)) {
out("ragged ");
}
else if (sometimes(50)) {
out("justified ");
}
out ("paragraph ");
if (sometimes(30)) {
out(picklist(Familylist, sizeof(Familylist)
/ sizeof(struct LIST), -1));
out(" ");
}
if (sometimes(30)) {
out(picklist(Fontlist, sizeof(Fontlist)
/ sizeof(struct LIST), -1));
}
if (sometimes(30)) {
outfmt("(%d)", myrandom(3,20));
}
genstring(MAXPARASTR);
newline();
return;
}
out(picklist(Printcmdslist,
sizeof(Printcmdslist) / sizeof(struct LIST), -1));
xtag = gettag();
ytag = gettag();
out ("(");
if (xtag == (char *) 0 || sometimes(abstag)) {
outfmt("%d", myrandom(0, 200));
}
else {
out(xtag);
out(".");
switch(myrandom(0,2)) {
case 0:
out("e");
break;
case 1:
out("w");
break;
default:
out("x");
break;
}
}
out(",");
if (ytag == (char *) 0 || sometimes(abstag)) {
outfmt("%d", myrandom(0, 250));
}
else {
out(ytag);
out(".");
switch(myrandom(0,2)) {
case 0:
out("n");
break;
case 1:
out("s");
break;
default:
out("y");
break;
}
}
out(")");
genstring(MAXSTR);
newline();
}
/* Return a random entry from the list of tags */
char *
gettag()
{
return(Tagtable[myrandom(0, Numtags - 1)]);
}
#if ! defined(unix) && ! defined(__APPLE__)
#define NEED_GETOPT
#endif
#ifdef NEED_GETOPT
/* for non-unix or other systems that don't have a getopt() function,
* define one here. This is NOT a general purpose implementation of getopt(),
* but something good enough to work with Mup */
int Optch = '-';
int optind = 1;
char *optarg;
static int argoffset;
#define NOARG 1
#define WITHARG 2
#define BADOPT 3
int
getopt(argc, argv, optstring)
int argc;
char **argv;
char *optstring;
{
int option;
if (optind >= argc) {
return(EOF);
}
if (argoffset == 0) {
#ifdef __DOS__
if (argv[optind][argoffset] == '-'
|| argv[optind][argoffset] == '/') {
#else
if (argv[optind][argoffset] == '-') {
#endif
argoffset = 1;
}
else {
return(EOF);
}
}
/* determine if option is valid and if should have an argument */
option = argv[optind][argoffset] & 0x7f;
switch (opttype(option, optstring)) {
case NOARG:
/* valid option without argument. Keep track of where
* to look for next option */
if (argv[optind][++argoffset] == '\0') {
optind++;
argoffset = 0;
}
break;
case WITHARG:
/* valid option with argument. */
if (argv[optind][++argoffset] != '\0') {
/* argument immediately follows in same argv */
optarg = &(argv[optind][argoffset]);
optind++;
}
else {
/* white space. argument must be in next argv */
optind++;
if (optind >= argc) {
fprintf(stderr, "missing argument to %c%c option\n", Optch, option);
return('?');
}
optarg = &(argv[optind][0]);
optind++;
}
argoffset = 0;
break;
default:
fprintf(stderr, "invalid option %c%c\n", Optch, option);
option = '?';
}
return(option);
}
/* look up option in optstring and return type of option */
int
opttype(option, optstring)
int option;
char *optstring;
{
char *p;
for (p = optstring; *p != '\0'; ) {
if (*p++ == option) {
return(*p == ':' ? WITHARG : NOARG);
}
if (*p == ':') {
p++;
}
}
return(BADOPT);
}
#endif
/* return a list of tab strings to use and output a corresponding stafflines,
* and return the number of strings via the passed-in pointer */
struct STRINGDATA *
tabstafflines(int *nstrings_p)
{
struct STRINGDATA *stringdata_p;
int n;
int t;
/* decide how many strings to use */
*nstrings_p = rand() % MAXSTRINGS + 1;
if ((stringdata_p = (struct STRINGDATA *) malloc (sizeof(struct STRINGDATA) * *nstrings_p)) == (struct STRINGDATA *) 0) {
fprintf(stderr, "malloc failed\n");
exit(1);
}
out("stafflines=tab(");
for (n = 0; n < *nstrings_p; n++) {
stringdata_p[n].pitch = myrandom((int) 'a', (int) 'g');
outfmt("%c", stringdata_p[n].pitch);
switch (myrandom(0, 2)) {
case 0:
stringdata_p[n].accidental = ' ';
break;
case 1:
stringdata_p[n].accidental = '#';
break;
case 2:
stringdata_p[n].accidental = '&';
break;
}
if (stringdata_p[n].accidental != ' ') {
outfmt("%c", stringdata_p[n].accidental);
}
stringdata_p[n].nticks = myrandom(0, 3);
for (t = stringdata_p[n].nticks; t > 0; t--) {
out("'");
}
if ((stringdata_p[n].octave = myrandom(0, 15)) < 9) {
outfmt("%d", stringdata_p[n].octave);
}
/* note: sometimes may get duplicate strings. That's okay--
* it tests error conditions. */
}
out(")");
newline();
return(stringdata_p);
}
/* pick notes for tablature staff */
void
picktabnotes(int nstrings, struct STRINGDATA *stringdata_p)
{
int n;
int u; /* how many strings actually used */
for (u = n = 0; n < nstrings; n++) {
if ( ! sometimes(TABSTRING)) {
continue;
}
do_a_tab_note(stringdata_p, n);
u++;
}
if (u == 0) {
/* need to have at least one string used,
* so pick a random one */
do_a_tab_note(stringdata_p, myrandom(0, nstrings - 1));
}
}
/* do a single tab note, using string n */
void
do_a_tab_note(struct STRINGDATA *stringdata_p, int n)
{
int t;
outfmt("%c", stringdata_p[n].pitch);
if (stringdata_p[n].accidental != ' ') {
outfmt("%c", stringdata_p[n].accidental);
}
for (t = 0; t < stringdata_p[n].nticks; t++) {
out("'");
}
/* pick a random fret */
outfmt("%d", myrandom(0, 99));
/* TODO: should test bends and slides */
}
/* generate a grid */
void
gen_grid(int gridlist_index)
{
int s, i;
int paren1, paren2; /* strings on which to put parentheses */
char *chordname;
/* generate a random name for the grid */
chordname = create_a_string(1, 12);
outfmt("%s", chordname);
/* save a copy of the name for later use */
if ((Gridlist[gridlist_index].str
= (char *) malloc(strlen(chordname)+1)) == 0) {
fprintf(stderr, "failed to malloc for grid name\n");
exit(1);
}
strcpy(Gridlist[gridlist_index].str, chordname);
Gridlist[gridlist_index].used = 0;
out("\"");
/* generate for a random number of strings */
s = myrandom(1, 9);
if (sometimes(gridparen) && s > 1) {
paren1 = myrandom(0, s-2);
paren2 = myrandom(paren1+1, s-1);
}
else {
paren1 = paren2 = -1;
}
for (i = 0; i < s; i++) {
if (i == paren1) {
out("(");
}
if (sometimes(fretx)) {
out("x ");
}
else if (sometimes(freto)) {
out("o ");
}
else if (sometimes(fretdash)) {
out("- ");
}
else {
outfmt("%d ", myrandom(1, 99));
}
if (i == paren2) {
out(")");
}
}
out("\"");
newline();
}
/* Set the default octave based on the clef, to match what Mup does */
void
adjust_defoct(char * clefname, int staff)
{
if( !strcmp(clefname, "bass")
|| !strcmp(clefname, "treble8")
|| !strcmp(clefname, "tenor")
|| !strcmp(clefname, "baritone")) {
Staffinfo[staff].defoct = 3;
}
if ( !strcmp(clefname, "frenchviolin")
|| !strcmp(clefname, "8treble")) {
Staffinfo[staff].defoct = 5;
}
if ( !strcmp(clefname, "bass8")
|| !strcmp(clefname, "subbass")) {
Staffinfo[staff].defoct = 2;
}
}
/* The following bunch of stuff is to support generating random
* coordinate expressions */
const char *Func1list[] = {
"sqrt",
"sin",
"cos",
"tan",
"asin",
"acos",
"atan"
};
const int Numfunc1 = sizeof(Func1list) / sizeof(Func1list[0]);
const char *Func2list[] = {
"atan2",
"hypot"
};
const int Numfunc2 = sizeof(Func2list) / sizeof(Func2list[0]);
typedef enum {
E_LITERAL,
E_TIME,
E_TAGREF,
E_FUNC1,
E_FUNC2,
MAXETYPES
} ETYPE;
const char Operators[] = "+-*/%";
const char Directions[] = "nsewxy";
/* Output a random number, often a floating point one */
void
outrandfloat()
{
if (sometimes(50)) {
/* a floating point number */
outfmt("%d.%05d", myrandom(0, myrandom(1,100)),
myrandom(0,10000000));
}
else {
/* a whole number */
outfmt("%d", myrandom(0, myrandom(1,100)));
}
}
/* Choose and return a random expression type */
ETYPE
pick_etype()
{
int e;
e = myrandom(0, 100);
if (e < 40) {
return(E_LITERAL);
}
else if (e < 70) {
return(E_TAGREF);
}
else if (e < 85) {
return(E_TIME);
}
else if (e < 93) {
return(E_FUNC1);
}
else {
return(E_FUNC2);
}
}
/* Generate a random expression */
void
gen_expr(int max_elem)
{
int elements;
/* generate a random number of elements for the expression */
for (elements = myrandom(1, max_elem); elements > 0; elements--) {
switch (pick_etype()) {
case E_LITERAL:
outrandfloat();
break;
case E_TIME:
out("time ");
outrandfloat();
break;
case E_TAGREF:
out(Tagtable[myrandom(0, Numtags - 1)]);
outfmt(".%c", Directions[myrandom(0, strlen(Directions) - 1)]);
break;
case E_FUNC1:
outfmt("%s(", Func1list[myrandom(0, Numfunc1 - 1)]);
gen_expr(2);
out(")");
break;
case E_FUNC2:
outfmt("%s(", Func2list[myrandom(0, Numfunc2 - 1)]);
gen_expr(2);
out(",");
gen_expr(2);
out(")");
break;
default:
fprintf(stderr, "bad expression type\n");
exit(1);
}
if (elements > 1) {
outfmt("%c", Operators[myrandom(0, strlen(Operators) - 1)]);
}
}
}
/* Generate a (x, y), where x and y are expressions */
void
coord()
{
out("(");
gen_expr(5);
out(",");
gen_expr(5);
out(")");
}
/* Generate things that include coordinates */
void
gen_coord_things()
{
if (sometimes(print)) {
out("print");
coord();
genstring(10);
newline();
}
if (sometimes(line)) {
out("line");
coord();
out("to");
coord();
newline();
}
if (sometimes(curve)) {
int points;
out("curve");
for (points = myrandom(3, 5); points > 0; points--) {
coord();
if (points > 1) {
out("to");
}
}
newline();
}
if (sometimes(bulgecurve)) {
out("curve");
coord();
out("to");
coord();
outfmt("bulge %d", myrandom(-4, 4));
newline();
}
}
/* Generate a keymap context */
void
gen_keymaps()
{
int entries;
char *name;
int e;
int n;
Numkeymaps = myrandom(0, MAX_KEYMAPS);
for (n = 0; n < Numkeymaps; n++) {
strcpy(Keymapnames[n], create_a_name(1, MAX_KEYMAP_NAME_LEN));
outfmt("keymap %s", Keymapnames[n]);
newline();
entries = myrandom(0, 20);
for (e = 0; e < entries; e++) {
out(create_a_string(1, 3));
out(create_a_string(0, 4));
newline();
}
}
}
/* Generate a "to" clause for a stuff */
void
gen_to(minval, maxval, start, ts_num, measrem, multi)
int minval;
int maxval;
int start;
int ts_num; /* time sig numerator */
int measrem;
int multi; /* YES for velocity */
{
int items;
int extra;
if (sometimes(midi_to)) {
for (items = myrandom(1, 4); items > 0; items--) {
outfmt("%d", myrandom(minval, maxval));
if (multi == YES) {
for (extra = myrandom(0,3); extra > 0; extra--) {
outfmt(",%d", myrandom(minval, maxval));
}
}
out(items > 1 ? "to" : "\"");
}
gen_til(start * 100, ts_num, measrem);
out(";");
}
else {
outfmt("%d\";", myrandom(minval, maxval));
}
}
/* Generate MIDI stuff */
void
gen_midi(staffs, ts_num, measrem)
int staffs;
int ts_num;
int measrem;
{
int start;
int n;
char * mtype;
for (n = myrandom(1, 3); n > 0; n--) {
if (sometimes(20)) {
out ("midi all:");
}
else {
outfmt("midi %d:", myrandom(1, staffs));
}
start = myrandom(0, ts_num);
mtype = picklist(Midi_list, sizeof(Midi_list)
/ sizeof(struct LIST), -1);
outfmt("%d \"%s=", start, mtype);
if (strcmp(mtype, "channel") == 0 ||
strcmp(mtype, "chanpressure") == 0 ||
strcmp(mtype, "port") == 0 ||
strcmp(mtype, "program") == 0) {
gen_to(0, 127, start, ts_num, measrem, NO);
}
else if (strcmp(mtype, "tempo") == 0) {
gen_to(10, 1000, start, ts_num, measrem, NO);
}
else if (strcmp(mtype, "parameter") == 0) {
outfmt("%d,", myrandom(0,127));
gen_to(0, 127, start, ts_num, measrem, NO);
}
else if (strcmp(mtype, "onvelocity") == 0
|| strcmp(mtype, "offvelocity") == 0) {
gen_to(0, 127, start, ts_num, measrem, YES);
}
else if (strcmp(mtype, "seqnum") == 0) {
outfmt("%d\";", myrandom(0,65535));
}
else if (strcmp(mtype, "hex") == 0) {
/*** TODO ***/
}
else {
outfmt("%s", create_a_name(1,10));
out("\";");
}
newline();
}
}
void
gen_barstyle()
{
out("barstyle=");
out(picklist(Barstylelist, sizeof(Barstylelist) / sizeof(struct LIST), -1));
newline();
}
void
gen_subbarstyle()
{
out("subbarstyle=");
switch(myrandom(0,2)) {
case 0: out("dashed "); break;
case 1: out("dotted "); break;
case 2: break;
}
switch(myrandom(0, 1)) {
case 0: out("bar "); break;
case 1: out("dblbar "); break;
}
switch(myrandom(0, 2)) {
case 0: out("between "); break;
case 1: out("(top to bottom)"); break;
case 2: out("(middle-1 to middle+1)"); break;
}
switch(myrandom(0, 2)) {
case 0: out(" all "); break;
case 1: out(" 1-2 " ); break;
case 2: out(" 1 "); break;
}
out("time");
switch(myrandom(0, 1)) {
case 0: out("1.5"); break;
case 1: out("2"); break;
}
newline();
}
|
tcmike/condo | apps/condo/domains/meter/schema/MeterResource.test.js | <filename>apps/condo/domains/meter/schema/MeterResource.test.js
/**
* Generated by `createschema meter.MeterResource 'name:Text;'`
*/
const { COLD_WATER_METER_RESOURCE_ID } = require('@condo/domains/meter/constants/constants')
const { MeterResource } = require('../utils/testSchema')
const { expectToThrowAccessDeniedErrorToObj } = require('@condo/domains/common/utils/testSchema')
const { makeClientWithNewRegisteredAndLoggedInUser } = require('@condo/domains/user/utils/testSchema')
const { makeLoggedInAdminClient, makeClient } = require('@core/keystone/test.utils')
const { createTestMeterResource, updateTestMeterResource } = require('@condo/domains/meter/utils/testSchema')
describe('MeterResource', () => {
describe('Create', () => {
test('user: cannot create MeterReadingSource', async () => {
const client = await makeClientWithNewRegisteredAndLoggedInUser()
await expectToThrowAccessDeniedErrorToObj(async () => {
await createTestMeterResource(client)
})
})
test('anonymous: cannot create Meter', async () => {
const client = await makeClient()
await expectToThrowAccessDeniedErrorToObj(async () => {
await createTestMeterResource(client)
})
})
test('admin: cannot create Meter', async () => {
const admin = await makeLoggedInAdminClient()
await expectToThrowAccessDeniedErrorToObj(async () => {
await createTestMeterResource(admin)
})
})
})
describe('Update', () => {
test('user: cannot create MeterReadingSource', async () => {
const client = await makeClientWithNewRegisteredAndLoggedInUser()
const [resource] = await MeterResource.getAll(client, { id: COLD_WATER_METER_RESOURCE_ID })
await expectToThrowAccessDeniedErrorToObj(async () => {
await updateTestMeterResource(client, resource.id, {})
})
})
test('anonymous: cannot update Meter', async () => {
const client = await makeClient()
const [resource] = await MeterResource.getAll(client, { id: COLD_WATER_METER_RESOURCE_ID })
await expectToThrowAccessDeniedErrorToObj(async () => {
await updateTestMeterResource(client, resource.id, {})
})
})
test('admin: cannot update Meter', async () => {
const admin = await makeLoggedInAdminClient()
const [resource] = await MeterResource.getAll(admin, { id: COLD_WATER_METER_RESOURCE_ID })
await expectToThrowAccessDeniedErrorToObj(async () => {
await updateTestMeterResource(admin, resource.id, {})
})
})
})
describe('Soft delete', () => {
test('user: cannot soft delete MeterReadingSource', async () => {
const client = await makeClientWithNewRegisteredAndLoggedInUser()
const [resource] = await MeterResource.getAll(client, { id: COLD_WATER_METER_RESOURCE_ID })
await expectToThrowAccessDeniedErrorToObj(async () => {
await updateTestMeterResource(client, resource.id, {})
})
})
test('anonymous: cannot soft delete Meter', async () => {
const client = await makeClient()
const [resource] = await MeterResource.getAll(client, { id: COLD_WATER_METER_RESOURCE_ID })
await expectToThrowAccessDeniedErrorToObj(async () => {
await updateTestMeterResource(client, resource.id, {})
})
})
test('admin: cannot soft delete Meter', async () => {
const admin = await makeLoggedInAdminClient()
const [resource] = await MeterResource.getAll(admin, { id: COLD_WATER_METER_RESOURCE_ID })
await expectToThrowAccessDeniedErrorToObj(async () => {
await updateTestMeterResource(admin, resource.id, {})
})
})
})
describe('Read', () => {
test('user: can read MeterReadingSources', async () => {
const client = await makeClientWithNewRegisteredAndLoggedInUser()
const sources = await MeterResource.getAll(client, {})
expect(sources.length).toBeGreaterThan(0)
})
test('anonymous: cannot read MeterReadingSources', async () => {
const client = await makeClient()
const sources = await MeterResource.getAll(client, {})
expect(sources.length).toBeGreaterThan(0)
})
test('admin: can read MeterReadingSources', async () => {
const admin = await makeLoggedInAdminClient()
const sources = await MeterResource.getAll(admin, {})
expect(sources.length).toBeGreaterThan(0)
})
})
})
|
ScalablyTyped/SlinkyTyped | j/jstree/src/main/scala/typingsSlinky/jstree/JSTreeStaticDefaultsCore.scala | <reponame>ScalablyTyped/SlinkyTyped
package typingsSlinky.jstree
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait JSTreeStaticDefaultsCore extends StObject {
/**
* the open / close animation duration in milliseconds - set this to `false` to disable the animation (default is `200`)
* @name $.jstree.defaults.core.animation
*/
var animation: js.UndefOr[js.Any] = js.native
/**
* determines what happens when a user tries to modify the structure of the tree
* If left as `false` all operations like create, rename, delete, move or copy are prevented.
* You can set this to `true` to allow all interactions or use a function to have better control.
*
* __Examples__
*
* $('#tree').jstree({
* 'core' : {
* 'check_callback' : function (operation, node, node_parent, node_position, more) {
* // operation can be 'create_node', 'rename_node', 'delete_node', 'move_node', 'copy_node' or 'edit'
* // in case of 'rename_node' node_position is filled with the new node name
* return operation === 'rename_node' ? true : false;
* }
* }
* });
*
* @name $.jstree.defaults.core.check_callback
*/
var check_callback: js.UndefOr[js.Any] = js.native
/**
* data configuration
*
* If left as `false` the HTML inside the jstree container element is used to populate the tree
* (that should be an unordered list with list items).
*
* You can also pass in a HTML string or a JSON array here.
*
* It is possible to pass in a standard jQuery-like AJAX config and jstree will automatically determine
* if the response is JSON or HTML and use that to populate the tree.
* In addition to the standard jQuery ajax options here you can suppy functions for `data` and `url`,
* the functions will be run in the current instance's scope and a param will be passed indicating which node is being loaded,
* the return value of those functions will be used.
*
* The last option is to specify a function, that function will receive the node being loaded as argument
* and a second param which is a function which should be called with the result.
*
* __Examples__
*
* // AJAX
* $('#tree').jstree({
* 'core' : {
* 'data' : {
* 'url' : '/get/children/',
* 'data' : function (node) {
* return { 'id' : node.id };
* }
* }
* });
*
* // direct data
* $('#tree').jstree({
* 'core' : {
* 'data' : [
* 'Simple root node',
* {
* 'id' : 'node_2',
* 'text' : 'Root node with options',
* 'state' : { 'opened' : true, 'selected' : true },
* 'children' : [ { 'text' : 'Child 1' }, 'Child 2']
* }
* ]
* });
*
* // function
* $('#tree').jstree({
* 'core' : {
* 'data' : function (obj, callback) {
* callback.call(this, ['Root 1', 'Root 2']);
* }
* });
*
* @name $.jstree.defaults.core.data
*/
var data: js.UndefOr[js.Any] = js.native
/**
* Should the node be toggled if the text is double clicked. Defaults to `true`
* @name $.jstree.defaults.core.dblclick_toggle
*/
var dblclick_toggle: js.UndefOr[Boolean] = js.native
/**
* a callback called with a single object parameter in the instance's scope when something goes wrong
* (operation prevented, ajax failed, etc)
* @name $.jstree.defaults.core.error
*/
def error(): js.Any = js.native
/**
* if left as `true` all parents of all selected nodes will be opened once the tree loads
* (so that all selected nodes are visible to the user)
* @name $.jstree.defaults.core.expand_selected_onload
*/
var expand_selected_onload: js.UndefOr[Boolean] = js.native
/**
* Force node text to plain text (and escape HTML). Defaults to `false`
* @name $.jstree.defaults.core.force_text
*/
var force_text: js.UndefOr[Boolean] = js.native
/**
* Default keyboard shortcuts (an object where each key is the button name or combo - like 'enter', 'ctrl-space', 'p', etc
* and the value is the function to execute in the instance's scope)
* @name $.jstree.defaults.core.keyboard
*/
var keyboard: js.UndefOr[JSTreeStaticDefaultsCoreKeyboard] = js.native
/**
* Should the loaded nodes be part of the state. Defaults to `false`
* @name $.jstree.defaults.core.dblclick_toggle
*/
var loaded_state: js.UndefOr[Boolean] = js.native
/**
* a boolean indicating if multiple nodes can be selected
* @name $.jstree.defaults.core.multiple
*/
var multiple: js.UndefOr[Boolean] = js.native
/**
* Should the last active node be focused when the tree container is blurred and the focused again.
* This helps working with screen readers. Defaults to `true`
* @name $.jstree.defaults.core.restore_focus
*/
var restore_focus: js.UndefOr[Boolean] = js.native
/**
* configure the various strings used throughout the tree
*
* You can use an object where the key is the string you need to replace and the value is your replacement.
* Another option is to specify a function which will be called with an argument of the needed string and should return the replacement.
* If left as `false` no replacement is made.
*
* __Examples__
*
* $('#tree').jstree({
* 'core' : {
* 'strings' : {
* 'Loading ...' : 'Please wait ...'
* }
* }
* });
*
* @name $.jstree.defaults.core.strings
*/
var strings: js.UndefOr[js.Any] = js.native
/**
* theme configuration object
* @name $.jstree.defaults.core.themes
*/
var themes: js.UndefOr[JSTreeStaticDefaultsCoreThemes] = js.native
/**
* if left as `true` web workers will be used to parse incoming JSON data where possible,
* so that the UI will not be blocked by large requests.
* Workers are however about 30% slower. Defaults to `true`
* @name $.jstree.defaults.core.worker
*/
var worker: js.UndefOr[Boolean] = js.native
}
object JSTreeStaticDefaultsCore {
@scala.inline
def apply(error: () => js.Any): JSTreeStaticDefaultsCore = {
val __obj = js.Dynamic.literal(error = js.Any.fromFunction0(error))
__obj.asInstanceOf[JSTreeStaticDefaultsCore]
}
@scala.inline
implicit class JSTreeStaticDefaultsCoreMutableBuilder[Self <: JSTreeStaticDefaultsCore] (val x: Self) extends AnyVal {
@scala.inline
def setAnimation(value: js.Any): Self = StObject.set(x, "animation", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationUndefined: Self = StObject.set(x, "animation", js.undefined)
@scala.inline
def setCheck_callback(value: js.Any): Self = StObject.set(x, "check_callback", value.asInstanceOf[js.Any])
@scala.inline
def setCheck_callbackUndefined: Self = StObject.set(x, "check_callback", js.undefined)
@scala.inline
def setData(value: js.Any): Self = StObject.set(x, "data", value.asInstanceOf[js.Any])
@scala.inline
def setDataUndefined: Self = StObject.set(x, "data", js.undefined)
@scala.inline
def setDblclick_toggle(value: Boolean): Self = StObject.set(x, "dblclick_toggle", value.asInstanceOf[js.Any])
@scala.inline
def setDblclick_toggleUndefined: Self = StObject.set(x, "dblclick_toggle", js.undefined)
@scala.inline
def setError(value: () => js.Any): Self = StObject.set(x, "error", js.Any.fromFunction0(value))
@scala.inline
def setExpand_selected_onload(value: Boolean): Self = StObject.set(x, "expand_selected_onload", value.asInstanceOf[js.Any])
@scala.inline
def setExpand_selected_onloadUndefined: Self = StObject.set(x, "expand_selected_onload", js.undefined)
@scala.inline
def setForce_text(value: Boolean): Self = StObject.set(x, "force_text", value.asInstanceOf[js.Any])
@scala.inline
def setForce_textUndefined: Self = StObject.set(x, "force_text", js.undefined)
@scala.inline
def setKeyboard(value: JSTreeStaticDefaultsCoreKeyboard): Self = StObject.set(x, "keyboard", value.asInstanceOf[js.Any])
@scala.inline
def setKeyboardUndefined: Self = StObject.set(x, "keyboard", js.undefined)
@scala.inline
def setLoaded_state(value: Boolean): Self = StObject.set(x, "loaded_state", value.asInstanceOf[js.Any])
@scala.inline
def setLoaded_stateUndefined: Self = StObject.set(x, "loaded_state", js.undefined)
@scala.inline
def setMultiple(value: Boolean): Self = StObject.set(x, "multiple", value.asInstanceOf[js.Any])
@scala.inline
def setMultipleUndefined: Self = StObject.set(x, "multiple", js.undefined)
@scala.inline
def setRestore_focus(value: Boolean): Self = StObject.set(x, "restore_focus", value.asInstanceOf[js.Any])
@scala.inline
def setRestore_focusUndefined: Self = StObject.set(x, "restore_focus", js.undefined)
@scala.inline
def setStrings(value: js.Any): Self = StObject.set(x, "strings", value.asInstanceOf[js.Any])
@scala.inline
def setStringsUndefined: Self = StObject.set(x, "strings", js.undefined)
@scala.inline
def setThemes(value: JSTreeStaticDefaultsCoreThemes): Self = StObject.set(x, "themes", value.asInstanceOf[js.Any])
@scala.inline
def setThemesUndefined: Self = StObject.set(x, "themes", js.undefined)
@scala.inline
def setWorker(value: Boolean): Self = StObject.set(x, "worker", value.asInstanceOf[js.Any])
@scala.inline
def setWorkerUndefined: Self = StObject.set(x, "worker", js.undefined)
}
}
|
elvinsolano/astro-design-system | node_modules/tailwind-react-ui/site/addComponents.js | <filename>node_modules/tailwind-react-ui/site/addComponents.js
import * as library from '../src'
Object.keys(library).forEach(key => {
global[key] = library[key]
})
|
Wiladams/nd | testy/test_bitbang.cpp |
#include "bitbang.hpp"
#include <cstdio>
using namespace bitbang;
void test_BITMASK()
{
printf("==== test_BITMASK ====\n");
printf("BITMASK64(0,2): 0x%llx\n", BITMASK64(0,2));
printf("BITMASK32(0,31): 0x%lx\n", BITMASK32(0,31));
printf("BITMASK32(0,15): 0x%08lx\n", BITMASK32(0,15));
printf("BITMASK32(16,31): 0x%lx\n", BITMASK32(16,31));
printf("BITMASK16(0,15): 0x%04x\n", BITMASK16(0,15));
printf("BITMASK16(8,15): 0x%04x\n", BITMASK16(8,15));
printf("BITMASK16(0,7): 0x%04x\n", BITMASK16(0,7));
}
void test_BIT64()
{
for (unsigned int i = 0; i<64; i++) {
//printf("ABIT[%2zd]: 0x%016llx\n", i, BIT(i));
printf("BIT64[%2d]: o%llo\n", i, BIT64(i));
}
}
void test_bitshift()
{
printf("1<<31 : 0x%lx\n", ((uint32_t)1) << 31);
printf("(1<<31) << 1 : 0x%lx\n", (((uint32_t)1) << 31) << 1);
printf("((1<<31) << 1) -1 : 0x%lx\n", ((((uint32_t)1) << 31) << 1)-1);
}
void test_bitbytes()
{
uint8_t bytes[] = {0xE5,0x9d,0x03,0x04};
printf("0,3[%x]: %Ix\n", bytes[0], bitsValueFromBytes(bytes, 0, 3));
printf("3,13[%x]: %Ix\n", bytes[1], bitsValueFromBytes(bytes, 3, 13));
printf("16,8[%x]: %Ix\n", bytes[2], bitsValueFromBytes(bytes, 16, 8));
printf("24,8[%x]: %Ix\n", bytes[3], bitsValueFromBytes(bytes, 24, 8));
}
void main()
{
//test_bitshift();
//test_BIT64();
//test_BITMASK();
test_bitbytes();
} |
r7h2/testing_01 | demos/z-demo-01/src/com/hcl/Car.java | <reponame>r7h2/testing_01
package com.hcl;
public class Car { // a blueprint or recipe
// encapsulating your data by using the private keyword
private String model; // null by default
private int year; // 0 by default
private String licensePlate;
private boolean registered; // false by default
public void startUp() {
System.out.println("starting method");
System.out.println("model: " + model + "\nyear: " + year + "\nlicensePlate: " +
licensePlate + "\nregistered: " + registered);
} // end of the startUp method
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public boolean isRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
}
|
TEDxVienna/continuum | venv/Lib/site-packages/PySide2/examples/installer_test/hello.py | # This Python file uses the following encoding: utf-8
# It has been edited by fix-complaints.py .
#############################################################################
##
## Copyright (C) 2019 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of Qt for Python.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and The Qt Company. For licensing terms
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 3 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL3 included in the
## packaging of this file. Please review the following information to
## ensure the GNU Lesser General Public License version 3 requirements
## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 2.0 or (at your option) the GNU General
## Public license version 3 or any later version approved by the KDE Free
## Qt Foundation. The licenses are as published by the Free Software
## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-2.0.html and
## https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
#############################################################################
"""
hello.py
--------
This simple script shows a label with changing "Hello World" messages.
It can be used directly as a script, but we use it also to automatically
test PyInstaller. See testing/wheel_tester.py .
When used with PyInstaller, it automatically stops its execution after
2 seconds.
"""
from __future__ import print_function
import sys
import random
import platform
import time
from PySide2.QtWidgets import (QApplication, QLabel, QPushButton,
QVBoxLayout, QWidget)
from PySide2.QtCore import Slot, Qt, QTimer
class MyWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.hello = ["<NAME>", "你好,世界", "<NAME>",
"<NAME>", "Привет мир"]
self.button = QPushButton("Click me!")
self.text = QLabel("Hello World embedded={}".format(sys.pyside_uses_embedding))
self.text.setAlignment(Qt.AlignCenter)
self.layout = QVBoxLayout()
self.layout.addWidget(self.text)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
# Connecting the signal
self.button.clicked.connect(self.magic)
@Slot()
def magic(self):
self.text.setText(random.choice(self.hello))
if __name__ == "__main__":
print("Start of hello.py ", time.ctime())
print(" sys.version = {}".format(sys.version.splitlines()[0]))
print(" platform.platform() = {}".format(platform.platform()))
app = QApplication()
widget = MyWidget()
widget.resize(800, 600)
widget.show()
if sys.pyside_uses_embedding:
milliseconds = 2 * 1000 # run 2 second
QTimer.singleShot(milliseconds, app.quit)
retcode = app.exec_()
print("End of hello.py ", time.ctime())
sys.exit(retcode)
|
JNKielmann/cotect | app/mobile/client/cotect-backend/model/CaseContact.js | /**
* Cotect User Endpoints
* User endpoints REST API for cotect project.
*
* The version of the OpenAPI document: 0.1.2
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
/**
* The CaseContact model module.
* @module model/CaseContact
* @version 0.1.2
*/
class CaseContact {
/**
* Constructs a new <code>CaseContact</code>.
* @alias module:model/CaseContact
* @param phoneNumber {String}
*/
constructor(phoneNumber) {
CaseContact.initialize(this, phoneNumber);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, phoneNumber) {
obj['phone_number'] = phoneNumber;
}
/**
* Constructs a <code>CaseContact</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/CaseContact} obj Optional instance to populate.
* @return {module:model/CaseContact} The populated <code>CaseContact</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new CaseContact();
if (data.hasOwnProperty('phone_number')) {
obj['phone_number'] = ApiClient.convertToType(data['phone_number'], 'String');
}
if (data.hasOwnProperty('contact_dates')) {
obj['contact_dates'] = ApiClient.convertToType(data['contact_dates'], ['Date']);
}
}
return obj;
}
}
/**
* @member {String} phone_number
*/
CaseContact.prototype['phone_number'] = undefined;
/**
* @member {Array.<Date>} contact_dates
*/
CaseContact.prototype['contact_dates'] = undefined;
export default CaseContact;
|
J-VOL/mage | Mage/src/main/java/mage/watchers/common/AttackedOrBlockedThisCombatWatcher.java | package mage.watchers.common;
import mage.MageObjectReference;
import mage.constants.WatcherScope;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.watchers.Watcher;
import java.util.HashSet;
import java.util.Set;
/**
* @author LevelX2
*/
public class AttackedOrBlockedThisCombatWatcher extends Watcher {
private final Set<MageObjectReference> attackedThisTurnCreatures = new HashSet<>();
private final Set<MageObjectReference> blockedThisTurnCreatures = new HashSet<>();
public AttackedOrBlockedThisCombatWatcher() {
super(WatcherScope.GAME);
}
@Override
public void watch(GameEvent event, Game game) {
switch (event.getType()) {
case BEGIN_COMBAT_STEP_PRE:
this.attackedThisTurnCreatures.clear();
this.blockedThisTurnCreatures.clear();
return;
case ATTACKER_DECLARED:
this.attackedThisTurnCreatures.add(new MageObjectReference(event.getSourceId(), game));
return;
case BLOCKER_DECLARED:
this.blockedThisTurnCreatures.add(new MageObjectReference(event.getSourceId(), game));
}
}
public Set<MageObjectReference> getAttackedThisTurnCreatures() {
return this.attackedThisTurnCreatures;
}
public Set<MageObjectReference> getBlockedThisTurnCreatures() {
return this.blockedThisTurnCreatures;
}
}
|
giseleblair/manager-ui | public/vendors/tinymce/plugins/powerpaste/langs/nb_NO.js | <filename>public/vendors/tinymce/plugins/powerpaste/langs/nb_NO.js
tinymce.addI18n("nb_NO", {
"Paste Formatting Options": "Lim formateringsvalg",
"Choose to keep or remove formatting in the pasted content.":
"Velges for \u00E5 beholde formateringsvalgene i det limte innholdet.",
"Keep Formatting": "Behold formatering",
"Remove Formatting": "Fjern formatering",
"Local Image Import": "Lokal bildeimport",
"Trigger paste again from the keyboard to paste content with images.":
"Utl\u00F8s liming igjen fra tastaturet for \u00E5 lime inn innhold med bilder.",
'Press <span class="ephox-polish-help-kbd">ESC</span> to ignore local images and continue editing.':
'Trykk <span class="ephox-polish-help-kbd">ESC</span> for \u00E5 ignorere lokale bilder og fortsette redigering.',
"Please wait...": "Vent litt ...",
'Safari does not support direct paste of images. <a href="https://support.ephox.com/entries/88543243-Safari-Direct-paste-of-images-does-not-work" style="text-decoration: underline">More information on image pasting for Safari</a>':
'Safari st\u00F8tter ikke direkte liming av bilder. <a href="https://support.ephox.com/entries/88543243-Safari-Direct-paste-of-images-does-not-work" style="text-decoration: underline">Mer informasjon om bildeliming for Safari</a>',
"The images service was not found: (": "Bildetjenesten ble ikke funnet: (",
"Image failed to upload: (": "Bildet ble ikke opplastet: (",
").": ").",
"Local image paste has been disabled. Local images have been removed from pasted content.":
"Liming av lokal bilder er deaktivert. Lokale bilder er fjernet fra limt innhold."
});
|
gaoqingloon/javase | src/main/java/com/lolo/javase/day05/ReviewTest.java | package com.lolo.javase.day05;
class ReviewTest {
public static void main(String[] args) {
int sum;
//for(int i = 1;i <= 100;i++){
if (4 % 2 != 0) {
//System.out.println(i);
sum = 1;
} else {
sum = 2;
}
//}
System.out.println(sum);
}
} |
Qwudi/wudi | wudi-study/src/main/java/com/hwq/thread/volatilestudyt/Atomic.java | <reponame>Qwudi/wudi
package com.hwq.thread.volatilestudyt;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Auther: haowenqiang
* @Description: 验证volatile不保证原子性
*/
class Data{
//加不加volatile 多线程调用add是一个效果,num本身就不是原子操作,
//说明volatile对于本身不是原子性的操作不保证其原子性
volatile int num = 0;
AtomicInteger atomicInteger = new AtomicInteger(0);
public void add(){
/*
++操作是 【非原子操作】
其字节码一目了然:
public void add();
Code:
0: aload_0
1: dup
2: getfield #2 // Field num:I
5: iconst_1
6: iadd
7: putfield #2 // Field num:I
10: return
*/
num++;
}
//解决非原子性问题:多线程对一个共享数的加操作使用juc中的 AtomicInteger getAndIncrement方法
public void atomicIncrement(){
atomicInteger.getAndIncrement();
}
}
public class Atomic {
public static void main(String[] args) throws InterruptedException {
Data data = new Data();
CountDownLatch countDownLatch = new CountDownLatch(10);
//新建10个线程每个线程执行1000次++操作 预期结果10000
for(int i = 1; i<=10 ; i++){
new Thread(()->{
for(int j = 1 ; j <= 1000; j++){
//非原子性++
data.add();
//原子性++
data.atomicIncrement();
}
//countDownLatch -1
countDownLatch.countDown();
}).start();
}
//countDownLatch为0时主线程执行
countDownLatch.await();
//结果每次都不一样,都不到10000,说明不保证原子性
System.out.println("非原子结果值: " + data.num);
System.out.println("原子结果值: " + data.atomicInteger);
}
}
|
artwallace/jsm | jsm/screens/bunkerdefense/scenery/cloud.js | <filename>jsm/screens/bunkerdefense/scenery/cloud.js
import { actor2dbase } from '../../../engine/actor2dbase.js';
import { getRandomIntFromRange } from '../../../engine/utilities.js';
//TODO: Vary the color
export class cloud extends actor2dbase {
#pieces = [];
#minNumOfPieces = 1;
#maxNumOfPieces = 7;
#minPieceWidth = 40;
#maxPieceWidth = 85;
#minPieceHeight = 15;
#maxPieceHeight = 25;
#startAngle = 0;
#endAngle = Math.PI * 2;
color = 'rgba(255, 255, 255, 0.75)';
constructor(game) {
super(game, 0, 0, 0);
this.layer = this.game.level.defaultLayer + 2;
}
initialize() {
let count = getRandomIntFromRange(this.#minNumOfPieces, this.#maxNumOfPieces);
for (let index = 0; index < count; index++) {
let pieceOffsetX = getRandomIntFromRange(-this.#minPieceWidth, this.#minPieceWidth);
let pieceOffsetY = getRandomIntFromRange(-this.#minPieceHeight, this.#minPieceHeight);
let radiusX = getRandomIntFromRange(this.#minPieceWidth, this.#maxPieceWidth);
let radiusY = getRandomIntFromRange(this.#minPieceHeight, this.#maxPieceHeight);
this.#pieces[index] = { pieceOffsetX, pieceOffsetY, radiusX, radiusY };
}
}
update(delta) {
super.update(delta);
this.actionFlyAcross(delta, 40);
if (this.x > this.game.level.levelWidth + (this.#maxPieceWidth * 2)) {
this.readyForDeletion = true;
}
}
draw() {
super.draw();
this.game.view.ctx.fillStyle = this.color;
this.#pieces.forEach(piece => {
this.game.view.ctx.beginPath();
this.game.view.ctx.ellipse(this.x + piece.pieceOffsetX, this.y + piece.pieceOffsetY, piece.radiusX, piece.radiusY, 0, this.#startAngle, this.#endAngle);
this.game.view.ctx.closePath();
this.game.view.ctx.fill();
});
}
} |
jnvshubham7/CPP_Programming | HackerEarth/DAA_Contest_3/1.cpp | <filename>HackerEarth/DAA_Contest_3/1.cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
/*
Time complexity : O(4 ^ (N ^ 2))
Space complexity : O(N ^ 2)
Where 'N' is the dimension of the matrix.
*/
void insertCurrentState(vector<vector<int>> &solution, vector<vector<int>> &ans, int n){
// Insert the solution matrix element by element in ans.
vector<int> currentState;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
currentState.push_back(solution[i][j]);
}
}
ans.push_back(currentState);
}
void solveMaze(vector<vector<int>> &maze, vector<vector<int>> &solution, vector<vector<int>> &ans, int x, int y, int n){
// Base case that we reach our destination.
if (x == n - 1 && y == n - 1){
solution[x][y] = 1;
// Call to add the updated solution matrix in 'ANS'.
insertCurrentState(solution, ans, n);
return;
}
// Condition of out of boundary of the maze.
if (x > n - 1 || x < 0 || y > n - 1 || y < 0){
return;
}
/*
Condition for 'MAZE[x][y]==0' - if that particular cell is block.
'SOLUTION[x][y]'' == 1 - if it is already visited or already we go through it.
*/
if (maze[x][y] == 0 || solution[x][y] == 1){
return;
}
// No problem comes in visiting this cell so visit it.
solution[x][y] = 1;
// Recursive calls to all directions(call to function having same name with diff value of params).
// Up move.
solveMaze(maze, solution, ans, x - 1, y, n);
// Down move.
solveMaze(maze, solution, ans, x + 1, y, n);
// Left move.
solveMaze(maze, solution, ans, x, y - 1, n);
// Right move.
solveMaze(maze, solution, ans, x, y + 1, n);
// Backtracking if there is no further path exists.
solution[x][y] = 0;
}
vector<vector<int>> ratInAMaze(vector<vector<int>> maze, int n){
// Initialize the 'SOLUTION' matrix by all 0s.
vector<vector<int>> solution(n, vector<int>(n, 0));
// Vector used to store all the paths.
vector<vector<int>> ans;
// Final call to function to print the solutions.
solveMaze(maze, solution, ans, 0, 0, n);
// Return the updated ans.
return ans;
}
// vector<vector<int>> ratInAMaze(vector<vector<int>> maze, int n){
// // Initialize the 'SOLUTION' matrix by all 0s.
// vector<vector<int>> solution(n, vector<int>(n, 0));
// // Vector used to store all the paths.
// vector<vector<int>> ans;
// // Final call to function to print the solutions.
// solveMaze(maze, solution, ans, 0, 0, n);
// // Return the updated ans.
// return ans;
// }
// void insertCurrentState(vector<vector<int>> &solution, vector<vector<int>> &ans, int n){
// // Insert the solution matrix element by element in ans.
// vector<int> currentState;
// for (int i = 0; i < n; i++){
// for (int j = 0; j < n; j++){
// currentState.push_back(solution[i][j]);
// }
// }
// ans.push_back(currentState);
// }
// void solveMaze(vector<vector<int>> &maze, vector<vector<int>> &solution, vector<vector<int>> &ans, int x, int y, int n){
// // Base case that we reach our destination.
// if (x == n - 1 && y == n - 1){
// solution[x][y] = 1;
// // Call to add the updated solution matrix in 'ANS'.
// insertCurrentState(solution, ans, n);
// return;
// }
// // Condition of out of boundary of the maze.
// if (x > n - 1 || x < 0 || y > n - 1 || y < 0){
// return;
// }
// /*
// Condition for 'MAZE[x][y]==0' - if that particular cell is block.
// 'SOLUTION[x][y]'' == 1 - if it is already visited or already we go through it.
// */
// if (maze[x][y] == 0 || solution[x][y] == 1){
// return;
// }
// // No problem comes in visiting this cell so visit it.
// solution[x][y] = 1;
// // Recursive calls to all directions(call to function having same name with diff value of params).
// // Up move.
// solveMaze(maze, solution, ans, x - 1, y, n);
// // Down move.
// solveMaze(maze, solution, ans, x + 1, y, n);
// // Left move.
// solveMaze(maze, solution, ans, x, y - 1, n);
// // Right move.
// solveMaze(maze, solution, ans, x, y + 1, n);
// // Backtracking if there is no further path exists.
// solution[x][y] = 0;
// }
int main(){
int n;
cin >> n;
vector<vector<int>> maze(n, vector<int>(n));
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
cin >> maze[i][j];
}
}
vector<vector<int>> ans = ratInAMaze(maze, n);
for (int i = 0; i < ans.size(); i++){
for (int j = 0; j < ans[i].size(); j++){
cout << ans[i][j] << " ";
}
cout << endl;
}
// You are given a 'N' * 'N' maze with a rat placed at 'MAZE[0][0]'.
// Find and print all paths that rat can follow to reach its destination i.e.
// 'MAZE['N' - 1]['N' - 1]'. Rat can move in any direction ( left, right, up and down).
// ll N;
// cin>>N;
// ll maze[N][N];
// for(ll i = 0; i < N; i++)
// {
// for(ll j = 0; j < N; j++)
// {
// cin>>maze[i][j];
// }
// }
//solve this by backtracking and recursion
//
// You are given a 'N' * 'N' maze with a rat placed at 'MAZE[0][0]'.
// Find and print all paths that rat can follow to reach its destination i.e.
// 'MAZE['N' - 1]['N' - 1]'. Rat can move in any direction ( left, right, up and down).
//
// vector<vector<int>> ans = ratInAMaze(maze, N);
// // Print the paths.
// for(ll i = 0; i < ans.size(); i++)
// {
// for(ll j = 0; j < ans[i].size(); j++)
// {
// cout<<ans[i][j]<<" ";
// }
// cout<<endl;
// }
//ll dp[N][N];
// dp[i][j] = 1 if there is a path from maze[0][0] to maze[i][j]
// dp[i][j] = 0 if there is no path from maze[0][0] to maze[i][j]
// dp[i][j] = -1 if we have already visited maze[i][j]
// dp[i][j] = -2 if we have already visited maze[i][j] and there is no path from maze[0][0] to maze[i][j]
//use dp to store the path
// dp[i][j] = 1 if there is a path from maze[0][0] to maze[i][j]
// dp[i][j] = 0 if there is no path from maze[0][0] to maze[i][j]
// dp[i][j] = -1 if we have already visited maze[i][j]
// dp[i][j] = -2 if we have already visited maze[i][j] and there is no path from maze[0][0] to maze[i][j]
//find path
//1. start from (0,0)
//2. if (i,j) is not visited
//3. mark it as visited
//4. if (i,j) is destination
//5. print path
//6. unmark it
return 0;
}
/*
Time complexity : O(4 ^ (N ^ 2))
Space complexity : O(N ^ 2)
Where 'N' is the dimension of the matrix.
*/
// void insertCurrentState(vector<vector<int>> &solution, vector<vector<int>> &ans, int n){
// // Insert the solution matrix element by element in ans.
// vector<int> currentState;
// for (int i = 0; i < n; i++){
// for (int j = 0; j < n; j++){
// currentState.push_back(solution[i][j]);
// }
// }
// ans.push_back(currentState);
// }
// void solveMaze(vector<vector<int>> &maze, vector<vector<int>> &solution, vector<vector<int>> &ans, int x, int y, int n){
// // Base case that we reach our destination.
// if (x == n - 1 && y == n - 1){
// solution[x][y] = 1;
// // Call to add the updated solution matrix in 'ANS'.
// insertCurrentState(solution, ans, n);
// return;
// }
// // Condition of out of boundary of the maze.
// if (x > n - 1 || x < 0 || y > n - 1 || y < 0){
// return;
// }
// /*
// Condition for 'MAZE[x][y]==0' - if that particular cell is block.
// 'SOLUTION[x][y]'' == 1 - if it is already visited or already we go through it.
// */
// if (maze[x][y] == 0 || solution[x][y] == 1){
// return;
// }
// // No problem comes in visiting this cell so visit it.
// solution[x][y] = 1;
// // Recursive calls to all directions(call to function having same name with diff value of params).
// // Up move.
// solveMaze(maze, solution, ans, x - 1, y, n);
// // Down move.
// solveMaze(maze, solution, ans, x + 1, y, n);
// // Left move.
// solveMaze(maze, solution, ans, x, y - 1, n);
// // Right move.
// solveMaze(maze, solution, ans, x, y + 1, n);
// // Backtracking if there is no further path exists.
// solution[x][y] = 0;
// }
// vector<vector<int>> ratInAMaze(vector<vector<int>> maze, int n){
// // Initialize the 'SOLUTION' matrix by all 0s.
// vector<vector<int>> solution(n, vector<int>(n, 0));
// // Vector used to store all the paths.
// vector<vector<int>> ans;
// // Final call to function to print the solutions.
// solveMaze(maze, solution, ans, 0, 0, n);
// // Return the updated ans.
// return ans;
// }
// #include<bits/stdc++.h>
// using namespace std;
// int board[20][20] = {0};
// void ratMaze(int maze[][20], int n, int row, int col){
// if(row == n-1 && col == n-1){
// for(int i = 0; i< n; i++){
// for(int j = 0; j<n; j++){
// cout<<board[i][j]<<" ";
// }
// }
// cout<<endl;
// return;
// }
// if(row < n-1 && col < n){
// if(board[row + 1][col] == 0 && maze[row+1][col] == 1 ){
// board[row+1][col] = 1;
// ratMaze(maze, n, row+1, col);
// board[row+1][col] = 0;
// }
// }
// if(row < n && col < n+1){
// if(board[row][col+1] == 0 && maze[row][col+1] == 1 ){
// board[row][col+1] = 1;
// ratMaze(maze, n, row, col+1);
// board[row][col+1] = 0;
// }
// }
// if(row >= 0 && col >= 1 && row<n && col<n){
// if(board[row][col-1] == 0 && maze[row][col-1] == 1 ){
// board[row][col-1] = 1;
// ratMaze(maze, n, row, col-1);
// board[row][col-1] = 0;
// }
// }
// if(row >=1 && col >=0 && row<n && col<n){
// if(board[row - 1][col] == 0 && maze[row-1][col] == 1 ){
// board[row-1][col] = 1;
// ratMaze(maze, n, row-1, col);
// board[row-1][col] = 0;
// }
// }
// }
// void ratInAMaze(int maze[][20], int n){
// memset(board,0,15*15*sizeof(int));
// board[0][0] = 1;
// ratMaze(maze,n,0,0);
// return;
// } |
yanweixin/Batis | application/web/src/main/java/com/batis/application/web/security/LoginFilter.java | package com.batis.application.web.security;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return super.getAuthenticationManager().authenticate(authRequest);
}
}
|
basxsoftwareassociation/bread | bread/views/edit.py | <gh_stars>10-100
import re
import urllib
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils.translation import gettext as _
from django.utils.translation import pgettext_lazy
from django.views.decorators.cache import never_cache
from django.views.generic import UpdateView
from guardian.mixins import PermissionRequiredMixin
from ..utils import filter_fieldlist, model_urlname, reverse_model
from .util import BreadView, CustomFormMixin
class EditView(
CustomFormMixin,
BreadView,
messages.views.SuccessMessageMixin,
PermissionRequiredMixin,
UpdateView,
):
"""TODO: documentation"""
accept_global_perms = True
fields = None
urlparams = (("pk", int),)
def __init__(self, *args, **kwargs):
all = filter_fieldlist(
kwargs.get("model", getattr(self, "model")), ["__all__"], for_form=True
)
self.fields = kwargs.get("fields", getattr(self, "fields", None))
self.fields = all if self.fields is None else self.fields
super().__init__(*args, **kwargs)
def get_required_permissions(self, request):
return [f"{self.model._meta.app_label}.change_{self.model.__name__.lower()}"]
def get_context_data(self, *args, **kwargs):
return {
**super().get_context_data(*args, **kwargs),
"layout": self._get_layout_cached(),
"pagetitle": str(self.object),
}
def get_success_message(self, cleaned_data):
return _("Saved %s" % self.object)
# prevent browser caching edit views
@never_cache
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def generate_copyview(model, attrs=None, labelfield=None, copy_related_fields=()):
"""creates a copy of a model instance and redirects to the edit view of the newly created instance
attrs: custom field values for the new instance
labelfield: name of a model field which will be used to create copy-labels (Example, Example (Copy 2), Example (Copy 3), etc)
"""
attrs = attrs or {}
def copy(request, pk: int):
instance = get_object_or_404(model, pk=pk)
if labelfield:
attrs[labelfield] = copylabel(getattr(instance, labelfield))
try:
clone = deepcopy_object(instance, attrs, copy_related_fields)
except Exception as e:
messages.error(request, e)
if request.GET.get("next"):
return redirect(urllib.parse.unquote(request.GET["next"]))
return redirect(reverse_model(model, "browse"))
if request.GET.get("next"):
return redirect(urllib.parse.unquote(request.GET["next"]))
messages.success(request, _("Created copy %s" % instance))
return redirect(reverse(model_urlname(model, "read"), args=[clone.pk]))
return copy
def bulkcopy(request, queryset, attrs=None, labelfield=None, copy_related_fields=()):
"""creates a copy all instances of a queryset
attrs: custom field values for the new instance
labelfield: name of a model field which will be used to create copy-labels (Example, Example (Copy 2), Example (Copy 3), etc)
copy_related_fields: related fields which should also be (deep) copied
"""
attrs = attrs or {}
created = 0
errors = 0
for instance in queryset:
if labelfield:
attrs[labelfield] = copylabel(getattr(instance, labelfield))
try:
deepcopy_object(instance, attrs, copy_related_fields)
created += 1
except Exception as e:
messages.error(request, e)
errors += 1
messages.success(request, _("Created %s copies" % created))
return redirect(request.path)
def deepcopy_object(instance, attrs=None, copy_related_fields=()):
"""
Creates a 'deep' coyp of the model instance
Related fields are only copied if they are listed in copy_related_fields
ManyToMany relationships are copied automatically if they have no key in 'attrs'
attrs defineds default values for fields
"""
oldpk = instance.pk
# see https://docs.djangoproject.com/en/3.2/topics/db/queries/#copying-model-instances
many2manyfields = {
f.name: getattr(instance, f.name).all()
for f in instance._meta.get_fields()
if f.many_to_many
}
instance.pk = None
instance.id = None
instance._state.adding = True
for k, v in (attrs or {}).items():
setattr(instance, k, v() if callable(v) else v)
instance.save()
for field, queryset in many2manyfields.items():
getattr(instance, field).set(queryset)
oldinstance = type(instance).objects.get(pk=oldpk)
for field in copy_related_fields:
related_name = oldinstance._meta.get_field(field).field.name
for obj in getattr(oldinstance, field).all():
obj.pk = None
obj.id = None
obj._state.adding = True
setattr(obj, related_name, instance)
obj.save()
instance.save()
return instance
def copylabel(original_name):
"""create names/labels with the sequence (Copy), (Copy 2), (Copy 3), etc."""
copylabel = pgettext_lazy("this is a copy", "Copy")
copy_re = f"\\({copylabel}( [0-9]*)?\\)"
match = re.search(copy_re, original_name)
if match is None:
label = f"{original_name} ({copylabel})"
elif match.groups()[0] is None:
label = re.sub(copy_re, f"({copylabel} 2)", original_name)
else:
n = int(match.groups()[0].strip()) + 1
label = re.sub(copy_re, f"({copylabel} {n})", original_name)
return label
|
jensgelbek/Fog | src/main/java/web/pages/Ordre.java | package web.pages;
import api.Utils;
import domain.items.*;
import domain.materials.Material;
import domain.materials.StykListeLinje;
import domain.materials.Stykliste;
import infrastructure.Lists;
import web.BaseServlet;
import web.svg.SvgCarport;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/ordre")
public class Ordre extends BaseServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var s = req.getSession();
int ordreId = Integer.parseInt(req.getParameter("ordre"));
s.setAttribute("ordreId",ordreId);
try {
Lists list = new Lists();
req.setAttribute("carportMeasure", list.carportMeasure());
req.setAttribute("tag", list.tag());
req.setAttribute("shedW", list.shedwidth());
req.setAttribute("shedL", list.shedlength());
Order order = api.findOrder(ordreId);
Carport carport = api.findCarport(order.getCarportId());
Stykliste stykliste = api.findStykliste(ordreId);
Customer customer= api.findCustomer(order.getKundeEmail());
req.setAttribute("order", order);
req.setAttribute("carport", carport);
req.setAttribute("volumenliste", stykliste.volumenListe);
req.setAttribute("unitliste",stykliste.unitListe);
req.setAttribute("customer",customer);
req.setAttribute("svg", SvgCarport.carport(carport.getWidth(), carport.getLenght(), carport.getShedWidth(), carport.getShedLength()).toString());
} catch (DBException e) {
e.printStackTrace();
}
try {
render("Ordre", "/WEB-INF/webpages/ordre.jsp", req, resp);
} catch (ServletException | IOException e) {
log(e.getMessage());
resp.sendError(400, e.getMessage());
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var s = req.getSession();
int ordreId= (int) s.getAttribute("ordreId");
if (req.getParameter("edit") != null) {
int orderId= Integer.parseInt(req.getParameter("edit"));
Carport carport= null;
try {
carport = api.findCarport(api.findOrder(orderId).getCarportId());
} catch (DBException e) {
e.printStackTrace();
}
carport.setLenght(Integer.parseInt(req.getParameter("length")));
carport.setWidth(Integer.parseInt(req.getParameter("width")));
carport.setShedLength(Integer.parseInt(req.getParameter("shedlength")));
carport.setShedWidth(Integer.parseInt(req.getParameter("shedwidth")));
api.updateCarport(carport);
try {
api.deletStykliste(orderId);
Stykliste stykliste= api.calculateStykliste(carport);
int newPrice= Utils.calculatePrice(stykliste);
api.updateOrderPrice(orderId,newPrice);
api.commitStykliste(stykliste,orderId);
} catch (DBException e) {
e.printStackTrace();
}
resp.sendRedirect(req.getContextPath() + "/ordre?ordre="+orderId);
}
if (req.getParameter("editunit") != null) {
int styklistelinjeid= Integer.parseInt(req.getParameter("editunit"));
int antal= Integer.parseInt(req.getParameter("antalunit"));
api.updateStykListeLinjeAntal(styklistelinjeid, antal);
resp.sendRedirect(req.getContextPath() + "/ordre?ordre="+ordreId);
}
if (req.getParameter("editvolumen") != null) {
int styklistelinjeid= Integer.parseInt(req.getParameter("editvolumen"));
//opdater antal
int antal= Integer.parseInt(req.getParameter("antal"));
api.updateStykListeLinjeAntal(styklistelinjeid, antal);
resp.sendRedirect(req.getContextPath() + "/ordre?ordre="+ordreId);
}
if (req.getParameter("editprice") != null) {
int newPrice= Integer.parseInt(req.getParameter("pris"));
api.updateOrderPrice(ordreId,newPrice);
resp.sendRedirect(req.getContextPath() + "/ordre?ordre="+ordreId);
}
}
}
|
sandeel31/o3de | Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h | <filename>Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h<gh_stars>1-10
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
// include the required headers
#include "EMotionFXConfig.h"
#include "MemoryCategories.h"
#include "MotionInstance.h"
#include "Actor.h"
#include "ActorInstance.h"
#include "EventManager.h"
#include "BaseObject.h"
#include "DebugDraw.h"
#include "EventManager.h"
#include "Importer/Importer.h"
namespace EMotionFX
{
enum EventTypes
{
EVENT_TYPE_ON_PLAY_MOTION,
EVENT_TYPE_ON_DELETE_MOTION,
// Keep this block together since MotionInstance only cares about these. Also keep EVENT_TYPE_MOTION_INSTANCE_FIRST_EVENT
// at the beginning and EVENT_TYPE_MOTION_INSTANCE_LAST_EVENT at the end (and updated)
EVENT_TYPE_MOTION_INSTANCE_FIRST_EVENT,
EVENT_TYPE_ON_EVENT = EVENT_TYPE_MOTION_INSTANCE_FIRST_EVENT,
EVENT_TYPE_ON_START_MOTION_INSTANCE,
EVENT_TYPE_ON_DELETE_MOTION_INSTANCE,
EVENT_TYPE_ON_STOP,
EVENT_TYPE_ON_HAS_LOOPED,
EVENT_TYPE_ON_HAS_REACHED_MAX_NUM_LOOPS,
EVENT_TYPE_ON_HAS_REACHED_MAX_PLAY_TIME,
EVENT_TYPE_ON_IS_FROZEN_AT_LAST_FRAME,
EVENT_TYPE_ON_CHANGED_PAUSE_STATE,
EVENT_TYPE_ON_CHANGED_ACTIVE_STATE,
EVENT_TYPE_ON_START_BLENDING,
EVENT_TYPE_ON_STOP_BLENDING,
EVENT_TYPE_ON_QUEUE_MOTION_INSTANCE,
EVENT_TYPE_MOTION_INSTANCE_LAST_EVENT = EVENT_TYPE_ON_QUEUE_MOTION_INSTANCE,
EVENT_TYPE_ON_DELETE_ACTOR,
EVENT_TYPE_ON_SIMULATE_PHYSICS,
EVENT_TYPE_ON_CUSTOM_EVENT,
EVENT_TYPE_ON_DRAW_LINE,
EVENT_TYPE_ON_DRAW_TRIANGLE,
EVENT_TYPE_ON_DRAW_TRIANGLES,
EVENT_TYPE_ON_CREATE_ANIM_GRAPH,
EVENT_TYPE_ON_CREATE_ANIM_GRAPH_INSTANCE,
EVENT_TYPE_ON_CREATE_MOTION,
EVENT_TYPE_ON_CREATE_MOTION_SET,
EVENT_TYPE_ON_CREATE_MOTION_INSTANCE,
EVENT_TYPE_ON_CREATE_MOTION_SYSTEM,
EVENT_TYPE_ON_CREATE_ACTOR,
EVENT_TYPE_ON_POST_CREATE_ACTOR,
EVENT_TYPE_ON_DELETE_ANIM_GRAPH,
EVENT_TYPE_ON_DELETE_ANIM_GRAPH_INSTANCE,
EVENT_TYPE_ON_DELETE_MOTION_SET,
EVENT_TYPE_ON_DELETE_MOTION_SYSTEM,
EVENT_TYPE_ON_RAY_INTERSECTION_TEST,
// Keep this block together since AnimGraphInstance only cares about these. Also keep EVENT_TYPE_ANIM_GRAPH_INSTANCE_FIRST_EVENT
// at the beginning and EVENT_TYPE_ANIM_GRAPH_INSTANCE_LAST_EVENT at the end (and updated)
EVENT_TYPE_ANIM_GRAPH_INSTANCE_FIRST_EVENT,
EVENT_TYPE_ON_STATE_ENTER = EVENT_TYPE_ANIM_GRAPH_INSTANCE_FIRST_EVENT,
EVENT_TYPE_ON_STATE_ENTERING,
EVENT_TYPE_ON_STATE_EXIT,
EVENT_TYPE_ON_STATE_END,
EVENT_TYPE_ON_START_TRANSITION,
EVENT_TYPE_ON_END_TRANSITION,
EVENT_TYPE_ANIM_GRAPH_INSTANCE_LAST_EVENT = EVENT_TYPE_ON_END_TRANSITION,
EVENT_TYPE_ON_SET_VISUAL_MANIPULATOR_OFFSET,
EVENT_TYPE_ON_INPUT_PORTS_CHANGED,
EVENT_TYPE_ON_OUTPUT_PORTS_CHANGED,
EVENT_TYPE_ON_RENAMED_NODE,
EVENT_TYPE_ON_CREATED_NODE,
EVENT_TYPE_ON_REMOVE_NODE,
EVENT_TYPE_ON_REMOVED_CHILD_NODE,
EVENT_TYPE_ON_PROGRESS_START,
EVENT_TYPE_ON_PROGRESS_END,
EVENT_TYPE_ON_PROGRESS_TEXT,
EVENT_TYPE_ON_PROGRESS_VALUE,
EVENT_TYPE_ON_SUB_PROGRESS_TEXT,
EVENT_TYPE_ON_SUB_PROGRESS_VALUE,
EVENT_TYPE_ON_SCALE_ACTOR_DATA,
EVENT_TYPE_ON_SCALE_MOTION_DATA,
EVENT_TYPE_ON_SCALE_ANIM_GRAPH_DATA,
EVENT_TYPE_COUNT
};
/**
* The event handler, which is responsible for processing the events.
* This class contains several methods which you can overload to perform custom things event comes up.
* You can inherit your own event handler from this base class and add it to the event manager using EMFX_EVENTMGR.AddEventHandler(...) method
* to make it use your custom event handler.
* Every event your derived class handles has to be returned by the GetHandledEventTypes method. This helps filtering
* the event dispatching to only the handlers that are interested about such event.
*/
class EMFX_API EventHandler
{
public:
AZ_CLASS_ALLOCATOR_DECL
EventHandler() = default;
virtual ~EventHandler() = default;
/**
* The main method that processes a event.
* @param eventInfo The struct holding the information about the triggered event.
*/
virtual void OnEvent(const EventInfo& eventInfo)
{
MCORE_UNUSED(eventInfo);
// find the event index in the array
// const uint32 eventIndex = GetEventManager().FindEventTypeIndex( eventInfo.mEventTypeID );
// get the name of the event
// const char* eventName = (eventIndex != MCORE_INVALIDINDEX32) ? GetEventManager().GetEventTypeString( eventIndex ) : "<unknown>";
// log it
// MCore::LogDetailedInfo("EMotionFX: *** Motion event %s at time %f of type ID %d ('%s') with parameters '%s' for actor '%s' on motion '%s' has been triggered", isEventStart ? "START" : "END", timeValue, eventTypeID, eventName, parameters, actorInstance->GetActor()->GetName(), motionInstance->GetMotion()->GetName());
/*
// when you implement your own event handler, of course you can just do something like a switch statement.
// then the FindEventTypeIndex and GetEventTypeString aren't needed at all
switch (eventTypeID)
{
case EVENT_SOUND:
//....
break;
case EVENT_SCRIPT:
//....
break;
//....
};
*/
}
/**
* Event handlers need to overload this function and return the list of events they are interested about
*/
virtual const AZStd::vector<EventTypes> GetHandledEventTypes() const = 0;
/**
* The event that gets triggered when a MotionSystem::PlayMotion(...) is being executed.
* The difference between OnStartMotionInstance() and this OnPlayMotion() is that the OnPlayMotion doesn't
* guarantee that the motion is being played yet, as it can also be added to the motion queue.
* The OnStartMotionInstance() method will be called once the motion is really being played.
* @param motion The motion that is being played.
* @param info The playback info used to play the motion.
*/
virtual void OnPlayMotion(Motion* motion, PlayBackInfo* info) { MCORE_UNUSED(motion); MCORE_UNUSED(info); }
/**
* The event that gets triggered when a motion instance is really being played.
* This can be a manual call through MotionInstance::PlayMotion or when the MotionQueue class
* will start playing a motion that was on the queue.
* The difference between OnStartMotionInstance() and this OnPlayMotion() is that the OnPlayMotion doesn't
* guarantee that the motion is being played yet, as it can also be added to the motion queue.
* The OnStartMotionInstance() method will be called once the motion is really being played.
* @param motionInstance The motion instance that is being played.
* @param info The playback info used to play the motion.
*/
virtual void OnStartMotionInstance(MotionInstance* motionInstance, PlayBackInfo* info) { MCORE_UNUSED(motionInstance); MCORE_UNUSED(info); }
/**
* The event that gets triggered once a MotionInstance object is being deleted.
* This can happen when calling the MotionSystem::RemoveMotionInstance() method manually, or when
* EMotion FX internally removes the motion instance because it has no visual influence anymore.
* The destructor of the MotionInstance class automatically triggers this event.
* @param motionInstance The motion instance that is being deleted.
*/
virtual void OnDeleteMotionInstance(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* The event that gets triggered once a Motion object is being deleted.
* You could for example use this event to delete any allocations you have done inside the
* custom user data object linked with the Motion object.
* You can get and set this data object with the Motion::GetCustomData() and Motion::SetCustomData(...) methods.
* @param motion The motion that is being deleted.
*/
virtual void OnDeleteMotion(Motion* motion) { MCORE_UNUSED(motion); }
/**
* The event that gets triggered when a motion instance is being stopped using one of the MotionInstance::Stop() methods.
* EMotion FX will internally stop the motion automatically when the motion instance reached its maximum playback time
* or its maximum number of loops.
* @param motionInstance The motion instance that is being stopped.
*/
virtual void OnStop(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once a given motion instance has looped.
* @param motionInstance The motion instance that got looped.
*/
virtual void OnHasLooped(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once a given motion instance has reached its maximum number of allowed loops.
* In this case the motion instance will also be stopped automatically afterwards.
* @param motionInstance The motion instance that reached its maximum number of allowed loops.
*/
virtual void OnHasReachedMaxNumLoops(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once a given motion instance has reached its maximum playback time.
* For example if this motion instance is only allowed to play for 2 seconds, and the total playback time reaches
* two seconds, then this event will be triggered.
* @param motionInstance The motion instance that reached its maximum playback time.
*/
virtual void OnHasReachedMaxPlayTime(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once the motion instance is set to freeze at the last frame once the
* motion reached its end (when it reached its maximum number of loops or playtime).
* In this case this event will be triggered once.
* @param motionInstance The motion instance that got into a frozen state.
*/
virtual void OnIsFrozenAtLastFrame(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once the motion pause state changes.
* For example when the motion is unpaused but gets paused, then this even twill be triggered.
* Paused motions don't get their playback times updated. They do however still perform blending, so it is
* still possible to fade them in or out.
* @param motionInstance The motion instance that changed its paused state.
*/
virtual void OnChangedPauseState(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once the motion active state changes.
* For example when the motion is active but gets set to inactive using the MotionInstance::SetActive(...) method,
* then this even twill be triggered.
* Inactive motions don't get processed at all. They will not update their playback times, blending, nor will they take
* part in any blending calculations of the final node transforms. In other words, it will just be like the motion instance
* does not exist at all.
* @param motionInstance The motion instance that changed its active state.
*/
virtual void OnChangedActiveState(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once a motion instance is automatically changing its weight value over time.
* For example when a motion is automatically being faded in from weight 0 to a given target weight in half
* a second, then once this blending starts, this event is being triggered.
* Once the the MotionInstance::SetWeight(...) method is being called with a blend time bigger than zero, and
* if the motion instance isn't currently already blending, then this event will be triggered.
* This event most likely will get triggered when using the MotionSystem::PlayMotion() and MotionInstance::Stop() methods.
* @param motionInstance The motion instance which is changing its weight value over time.
*/
virtual void OnStartBlending(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once a motion instance stops it automatic changing of its weight value over time.
* For example when a motion is automatically being faded in from weight 0 to a given target weight in half
* a second, and once the target weight is reached after half a second, will cause this event to be triggered.
* Once the the MotionInstance::SetWeight(...) method is being called with a blend time equal to zero and the
* motion instance is currently blending its weight value, then this event will be triggered.
* This event most likely will get triggered when using the MotionSystem::PlayMotion() and MotionInstance::Stop() methods.
* @param motionInstance The motion instance for which the automatic weight blending just stopped.
*/
virtual void OnStopBlending(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
/**
* This event gets triggered once the given motion instance gets added to the motion queue.
* This happens when you set the PlayBackInfo::mPlayNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion)
* will not directly start playing the motion (OnStartMotionInstance), but will add it to the motion queue instead.
* The motion queue will then start playing the motion instance once it should.
* @param motionInstance The motion instance that gets added to the motion queue.
* @param info The playback information used to play this motion instance.
*/
virtual void OnQueueMotionInstance(MotionInstance* motionInstance, PlayBackInfo* info) { MCORE_UNUSED(motionInstance); MCORE_UNUSED(info); }
//---------------------------------------------------------------------
/**
* The event that gets triggered once an Actor object is being deleted.
* You could for example use this event to delete any allocations you have done inside the
* custom user data object linked with the Actor object.
* You can get and set this data object with the Actor::GetCustomData() and Actor::SetCustomData(...) methods.
* @param actor The actor that is being deleted.
*/
virtual void OnDeleteActor(Actor* actor) { MCORE_UNUSED(actor); }
virtual void OnSimulatePhysics(float timeDelta) { MCORE_UNUSED(timeDelta); }
virtual void OnCustomEvent(uint32 eventType, void* data) { MCORE_UNUSED(eventType); MCORE_UNUSED(data); }
virtual void OnDrawTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) { MCORE_UNUSED(posA); MCORE_UNUSED(posB); MCORE_UNUSED(posC); MCORE_UNUSED(normalA); MCORE_UNUSED(normalB); MCORE_UNUSED(normalC); MCORE_UNUSED(color); }
virtual void OnDrawTriangles() {}
// creation callbacks
virtual void OnCreateAnimGraph(AnimGraph* animGraph) { MCORE_UNUSED(animGraph); }
virtual void OnCreateAnimGraphInstance(AnimGraphInstance* animGraphInstance) { MCORE_UNUSED(animGraphInstance); }
virtual void OnCreateMotion(Motion* motion) { MCORE_UNUSED(motion); }
virtual void OnCreateMotionSet(MotionSet* motionSet) { MCORE_UNUSED(motionSet); }
virtual void OnCreateMotionInstance(MotionInstance* motionInstance) { MCORE_UNUSED(motionInstance); }
virtual void OnCreateMotionSystem(MotionSystem* motionSystem) { MCORE_UNUSED(motionSystem); }
virtual void OnCreateActor(Actor* actor) { MCORE_UNUSED(actor); }
virtual void OnPostCreateActor(Actor* actor) { MCORE_UNUSED(actor); }
// delete callbacks
virtual void OnDeleteAnimGraph(AnimGraph* animGraph) { MCORE_UNUSED(animGraph); }
virtual void OnDeleteAnimGraphInstance(AnimGraphInstance* animGraphInstance) { MCORE_UNUSED(animGraphInstance); }
virtual void OnDeleteMotionSet(MotionSet* motionSet) { MCORE_UNUSED(motionSet); }
virtual void OnDeleteMotionSystem(MotionSystem* motionSystem) { MCORE_UNUSED(motionSystem); }
/**
* Perform a ray intersection test and return the intersection info.
* The first event handler registered that sets the IntersectionInfo::mIsValid to true will be outputting to the outIntersectInfo parameter.
* @param start The start point, in world space.
* @param end The end point, in world space.
* @param outIntersectInfo The resulting intersection info.
* @result Returns true when an intersection occurred and false when no intersection occurred.
*/
virtual bool OnRayIntersectionTest(const AZ::Vector3& start, const AZ::Vector3& end, IntersectionInfo* outIntersectInfo) { MCORE_UNUSED(start); MCORE_UNUSED(end); MCORE_UNUSED(outIntersectInfo); return false; }
virtual void OnStateEnter(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStateEntering(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStateExit(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStateEnd(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStartTransition(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(transition); }
virtual void OnEndTransition(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(transition); }
virtual void OnSetVisualManipulatorOffset(AnimGraphInstance* animGraphInstance, uint32 paramIndex, const AZ::Vector3& offset) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(paramIndex); MCORE_UNUSED(offset); }
virtual void OnInputPortsChanged(AnimGraphNode* node, const AZStd::vector<AZStd::string>& newInputPorts, const AZStd::string& memberName, const AZStd::vector<AZStd::string>& memberValue) { AZ_UNUSED(node); AZ_UNUSED(newInputPorts); AZ_UNUSED(memberName); AZ_UNUSED(memberValue); }
virtual void OnOutputPortsChanged(AnimGraphNode* node, const AZStd::vector<AZStd::string>& newOutputPorts, const AZStd::string& memberName, const AZStd::vector<AZStd::string>& memberValue) { AZ_UNUSED(node); AZ_UNUSED(newOutputPorts); AZ_UNUSED(memberName); AZ_UNUSED(memberValue); }
virtual void OnRenamedNode(AnimGraph* animGraph, AnimGraphNode* node, const AZStd::string& oldName) { MCORE_UNUSED(animGraph); MCORE_UNUSED(node); MCORE_UNUSED(oldName); }
virtual void OnCreatedNode(AnimGraph* animGraph, AnimGraphNode* node) { MCORE_UNUSED(animGraph); MCORE_UNUSED(node); }
virtual void OnRemoveNode(AnimGraph* animGraph, AnimGraphNode* nodeToRemove) { MCORE_UNUSED(animGraph); MCORE_UNUSED(nodeToRemove); }
virtual void OnRemovedChildNode(AnimGraph* animGraph, AnimGraphNode* parentNode) { MCORE_UNUSED(animGraph); MCORE_UNUSED(parentNode); }
virtual void OnProgressStart() {}
virtual void OnProgressEnd() {}
virtual void OnProgressText(const char* text) { MCORE_UNUSED(text); }
virtual void OnProgressValue(float percentage) { MCORE_UNUSED(percentage); }
virtual void OnSubProgressText(const char* text) { MCORE_UNUSED(text); }
virtual void OnSubProgressValue(float percentage) { MCORE_UNUSED(percentage); }
virtual void OnScaleActorData(Actor* actor, float scaleFactor) { MCORE_UNUSED(actor); MCORE_UNUSED(scaleFactor); }
virtual void OnScaleMotionData(Motion* motion, float scaleFactor) { MCORE_UNUSED(motion); MCORE_UNUSED(scaleFactor); }
};
/**
* The per anim graph instance event handlers.
* This allows you to capture events triggered on a specific anim graph instance, rather than globally.
*/
class EMFX_API AnimGraphInstanceEventHandler
{
public:
AZ_CLASS_ALLOCATOR_DECL
AnimGraphInstanceEventHandler() = default;
virtual ~AnimGraphInstanceEventHandler() = default;
/**
* Event handlers need to overload this function and return the list of events they are interested about
*/
virtual const AZStd::vector<EventTypes> GetHandledEventTypes() const = 0;
virtual void OnStateEnter(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStateEntering(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStateExit(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStateEnd(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); }
virtual void OnStartTransition(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(transition); }
virtual void OnEndTransition(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(transition); }
};
/**
* The per motion instance event handlers.
* This allows you to capture events triggered on a specific motion instance, rather than globally.
*/
class EMFX_API MotionInstanceEventHandler
{
public:
AZ_CLASS_ALLOCATOR_DECL
MotionInstanceEventHandler() = default;
virtual ~MotionInstanceEventHandler() = default;
/**
* Event handlers need to overload this function and return the list of events they are interested about
*/
virtual const AZStd::vector<EventTypes> GetHandledEventTypes() const = 0;
void SetMotionInstance(MotionInstance* motionInstance) { mMotionInstance = motionInstance; }
MCORE_INLINE MotionInstance* GetMotionInstance() { return mMotionInstance; }
/**
* The method that processes an event.
* @param eventInfo The struct holding the information about the triggered event.
*/
virtual void OnEvent(const EventInfo& eventInfo) { MCORE_UNUSED(eventInfo); }
/**
* The event that gets triggered when a motion instance is really being played.
* This can be a manual call through MotionInstance::PlayMotion or when the MotionQueue class
* will start playing a motion that was on the queue.
* The difference between OnStartMotionInstance() and this OnPlayMotion() is that the OnPlayMotion doesn't
* guarantee that the motion is being played yet, as it can also be added to the motion queue.
* The OnStartMotionInstance() method will be called once the motion is really being played.
* @param info The playback info used to play the motion.
*/
virtual void OnStartMotionInstance(PlayBackInfo* info) { MCORE_UNUSED(info); }
/**
* The event that gets triggered once a MotionInstance object is being deleted.
* This can happen when calling the MotionSystem::RemoveMotionInstance() method manually, or when
* EMotion FX internally removes the motion instance because it has no visual influence anymore.
* The destructor of the MotionInstance class automatically triggers this event.
*/
virtual void OnDeleteMotionInstance() {}
/**
* The event that gets triggered when a motion instance is being stopped using one of the MotionInstance::Stop() methods.
* EMotion FX will internally stop the motion automatically when the motion instance reached its maximum playback time
* or its maximum number of loops.
*/
virtual void OnStop() {}
/**
* This event gets triggered once a given motion instance has looped.
*/
virtual void OnHasLooped() {}
/**
* This event gets triggered once a given motion instance has reached its maximum number of allowed loops.
* In this case the motion instance will also be stopped automatically afterwards.
*/
virtual void OnHasReachedMaxNumLoops() {}
/**
* This event gets triggered once a given motion instance has reached its maximum playback time.
* For example if this motion instance is only allowed to play for 2 seconds, and the total playback time reaches
* two seconds, then this event will be triggered.
*/
virtual void OnHasReachedMaxPlayTime() {}
/**
* This event gets triggered once the motion instance is set to freeze at the last frame once the
* motion reached its end (when it reached its maximum number of loops or playtime).
* In this case this event will be triggered once.
*/
virtual void OnIsFrozenAtLastFrame() {}
/**
* This event gets triggered once the motion pause state changes.
* For example when the motion is unpaused but gets paused, then this even twill be triggered.
* Paused motions don't get their playback times updated. They do however still perform blending, so it is
* still possible to fade them in or out.
*/
virtual void OnChangedPauseState() {}
/**
* This event gets triggered once the motion active state changes.
* For example when the motion is active but gets set to inactive using the MotionInstance::SetActive(...) method,
* then this even twill be triggered.
* Inactive motions don't get processed at all. They will not update their playback times, blending, nor will they take
* part in any blending calculations of the final node transforms. In other words, it will just be like the motion instance
* does not exist at all.
*/
virtual void OnChangedActiveState() {}
/**
* This event gets triggered once a motion instance is automatically changing its weight value over time.
* For example when a motion is automatically being faded in from weight 0 to a given target weight in half
* a second, then once this blending starts, this event is being triggered.
* Once the the MotionInstance::SetWeight(...) method is being called with a blend time bigger than zero, and
* if the motion instance isn't currently already blending, then this event will be triggered.
* This event most likely will get triggered when using the MotionSystem::PlayMotion() and MotionInstance::Stop() methods.
*/
virtual void OnStartBlending() {}
/**
* This event gets triggered once a motion instance stops it automatic changing of its weight value over time.
* For example when a motion is automatically being faded in from weight 0 to a given target weight in half
* a second, and once the target weight is reached after half a second, will cause this event to be triggered.
* Once the the MotionInstance::SetWeight(...) method is being called with a blend time equal to zero and the
* motion instance is currently blending its weight value, then this event will be triggered.
* This event most likely will get triggered when using the MotionSystem::PlayMotion() and MotionInstance::Stop() methods.
*/
virtual void OnStopBlending() {}
/**
* This event gets triggered once the given motion instance gets added to the motion queue.
* This happens when you set the PlayBackInfo::mPlayNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion)
* will not directly start playing the motion (OnStartMotionInstance), but will add it to the motion queue instead.
* The motion queue will then start playing the motion instance once it should.
* @param info The playback information used to play this motion instance.
*/
virtual void OnQueueMotionInstance(PlayBackInfo* info) { MCORE_UNUSED(info); }
protected:
MotionInstance* mMotionInstance = nullptr;
};
} // namespace EMotionFX
|
opticdev/marvin | training/src/main/scala-2.12/com/opticdev/marvin/training/rulesengine/codegen/CodeGenImplicits.scala | <gh_stars>10-100
package com.opticdev.marvin.training.rulesengine.codegen
import com.stripe.brushfire.{AnnotatedTree, LeafNode, SplitNode}
import treehugger.forest._
import definitions._
import treehuggerDSL._
import treehugger.forest._
import definitions._
import com.opticdev.marvin.runtime.pattern._
import org.apache.commons.io.FileUtils
import trainingr.rulesengine.{BFTree, TreeBuildingResults, _}
import treehuggerDSL._
object CodeGenImplicits {
implicit class TreeResultMapToObject(resultMap: Map[String, TreeBuildingResults]) {
def toAst(langName: String = "REPLACE_WITH_LANGUAGE_NAME"): treehugger.forest.PackageDef = {
BLOCK(
IMPORT("com.opticdev.marvin.runtime.ast._"),
IMPORT("com.opticdev.marvin.runtime.mutators.{BaseAstMutator, LanguageMutators}"),
IMPORT("com.opticdev.marvin.runtime.pattern._"),
IMPORT("com.opticdev.marvin.runtime.predicates.{_}"),
OBJECTDEF(langName+"Mutators") withParents("NodeMutatorMap") := BLOCK(
resultMap.map(_.toAst) :+
(VAL("patternMatcher").withFlags(Flags.IMPLICIT) := NEW("PatternMatcher")) :+
(VAL("mapping", "Map[String, BaseAstMutator]") := MAKE_MAP(
resultMap.map(i=> TUPLE(LIT(i._1), NEW(i._1)))
))
)
) withoutPackage
}
}
implicit class TreeResultToClassAst(record: (String, TreeBuildingResults)) {
def toAst = {
val name = record._1
val treeResult = record._2
CLASSDEF(name) withParents("BaseAstMutator") := BLOCK(
DEF("expectedPattern", "CodePattern") withParams(PARAM("node", "BaseAstNode")) := treeResult.tree.toAst.withComment("Accuracy = "+treeResult.accuracy),
VAL("nodeType", StringClass) withFlags(Flags.OVERRIDE) := LIT(name)
)
}
}
implicit class AstNodeModelTreeToAst(astNodeModel: BFTree) {
private case class PredicateAndCode(key: String, nameInCode: String, valDef: treehugger.forest.ValDef)
def toAst: treehugger.forest.Block = {
val predicateBlock = {
val predicateBuffer = collection.mutable.ListBuffer[PredicateAndCode]()
astNodeModel.mapKeys(i => {
val split = i.split("\\.")
val key = split(0)
val predicate = split(1)
val name = split.mkString
val test: treehugger.forest.ValDef = VAL(name, BooleanClass) := (REF(predicate) DOT "evaluate") ((REF("node") DOT "properties" DOT "getOrElse") (LIT(key), REF("AstNull")))
predicateBuffer += PredicateAndCode(i, name, test)
null
})
predicateBuffer.toList
}
def logicFromTree(bfNode: BFNode) : TermTree = {
bfNode match {
case split: BFSplitNode => {
val predicate = predicateBlock.find(_.key == split.key).get.nameInCode
val binaryExpression = if (split.predicate.value) REF(predicate) else NOT(REF(predicate))
IF (binaryExpression) THEN BLOCK(logicFromTree(split.leftChild)) ELSE BLOCK(logicFromTree(split.rightChild))
}
case leaf: BFLeafNode => {
val pattern = leaf.target.head._1
import ComponentCodeGenImplicits._
REF("CodePattern") APPLY pattern.components.map(_.toAst)
}
}
}
BLOCK( predicateBlock.map(_.valDef) :+ logicFromTree(astNodeModel.root) :_*)
}
}
implicit class TreeObject(tree: Tree) {
def saveToFile(path: String): Unit = FileUtils.writeStringToFile(new java.io.File(path), asString)
def asString = treeToString(tree)
}
}
object ComponentCodeGenImplicits {
implicit class PatternComponentToAst(patternComponent: PatternComponent) {
def toAst: treehugger.forest.Tree with Serializable = patternComponent match {
case Space => REF("Space")
case Line => REF("Line")
case SymbolComponent(raw) => REF("SymbolComponent") APPLY LIT(raw)
case ChildNode(key) => REF("ChildNode") APPLY LIT(key)
case ChildNodeList(key, topDelineator) => REF("ChildNodeList") APPLY (LIT(key), LIT(topDelineator))
case PropertyBinding(key) => REF("PropertyBinding") APPLY LIT(key)
}
}
}
|
woq-blended/blended | blended.updater.config/shared/src/main/scala/blended/updater/config/ProfileInfo.scala | <reponame>woq-blended/blended
package blended.updater.config
case class ProfileInfo(
timeStamp: Long,
profiles: List[ProfileRef]
)
|
manggoguy/parsec-modified | pkgs/apps/facesim/src/Benchmarks/facesim/Storytelling/STORYTELLING_EXAMPLE.h | //#####################################################################
// Copyright 2005, <NAME>.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class STORYTELLING_EXAMPLE
//#####################################################################
#ifndef __STORYTELLING_EXAMPLE__
#define __STORYTELLING_EXAMPLE__
#include "../FACE_EXAMPLE.h"
#include "../../../Public_Library/Constitutive_Models/DIAGONALIZED_FACE_3D.h"
#include "../../../Public_Library/Collisions_And_Interactions/COLLISION_PENALTY_FORCES.h"
namespace PhysBAM
{
template <class T, class RW>
class STORYTELLING_EXAMPLE: public FACE_EXAMPLE<T, RW>
{
public:
using SOLIDS_FLUIDS_EXAMPLE<T>::output_directory;
using SOLIDS_FLUIDS_EXAMPLE<T>::data_directory;
using FACE_EXAMPLE<T, RW>::model_directory;
using FACE_EXAMPLE<T, RW>::input_directory;
using SOLIDS_FLUIDS_EXAMPLE<T>::frame_rate;
using SOLIDS_FLUIDS_EXAMPLE<T>::restart;
using SOLIDS_FLUIDS_EXAMPLE<T>::restart_frame;
using SOLIDS_FLUIDS_EXAMPLE<T>::last_frame;
using SOLIDS_FLUIDS_EXAMPLE_3D<T, RW>::solids_parameters;
using FACE_EXAMPLE<T, RW>::newton_tolerance;
using FACE_EXAMPLE<T, RW>::newton_iterations;
using FACE_EXAMPLE<T, RW>::use_rigid_body_collision;
using FACE_EXAMPLE<T, RW>::use_self_collision;
using FACE_EXAMPLE<T, RW>::use_partially_converged_result;
using FACE_EXAMPLE<T, RW>::number_of_muscles;
using FACE_EXAMPLE<T, RW>::attached_nodes;
using FACE_EXAMPLE<T, RW>::jaw_attachment_index;
using FACE_EXAMPLE<T, RW>::control_parameters;
using SOLIDS_FLUIDS_EXAMPLE<T>::verbose;
std::string control_directory;
T control_frame_rate;
FACE_CONTROL_PARAMETERS<T> input_control_parameters;
ACTIVATION_CONTROL_SET<T> *input_activation_controls;
ATTACHMENT_FRAME_CONTROL_SET<T> *input_attachment_frame_controls;
STORYTELLING_EXAMPLE()
{
output_directory = "Storytelling/output";
control_directory = data_directory + "/Face_Data/Motion_Data/Storytelling_Controls";
// Simulation source
model_directory = data_directory + "/Face_Data/Eftychis_840k";
input_directory = model_directory + "/Front_370k";
// Control settings
control_frame_rate = frame_rate;
// Restart and initialization settings
restart = false;
restart_frame = 0;
last_frame = 1;
// Simulation settings
solids_parameters.cg_tolerance = (T) 2e-3;
solids_parameters.cg_iterations = 200;
//newton_tolerance=(T)5e-2;
//newton_iterations=10;
newton_tolerance = (T) 500;
newton_iterations = 1;
// Collision settings
use_rigid_body_collision = true;
use_self_collision = false;
solids_parameters.perform_collision_body_collisions = use_rigid_body_collision || use_self_collision;
// Solver settings
use_partially_converged_result = true;
// Debugging settings
solids_parameters.deformable_body_parameters.print_residuals = true;
verbose = true;
}
~STORYTELLING_EXAMPLE()
{}
//#####################################################################
// Function Initialize_Bodies
//#####################################################################
void Initialize_Bodies()
{
FACE_EXAMPLE<T, RW>::Initialize_Bodies();
DEFORMABLE_OBJECT_3D<T>& deformable_object = solids_parameters.deformable_body_parameters.list (1);
input_activation_controls = new ACTIVATION_CONTROL_SET<T>;
for (int i = 1; i <= number_of_muscles; i++) input_activation_controls->Add_Activation();
input_control_parameters.list.Append_Element (input_activation_controls);
input_attachment_frame_controls = new ATTACHMENT_FRAME_CONTROL_SET<T> (deformable_object.particles.X.array, attached_nodes, jaw_attachment_index);
input_attachment_frame_controls->template Initialize_Jaw_Joint_From_File<RW> (input_directory + "/jaw_joint_parameters");
input_control_parameters.list.Append_Element (input_attachment_frame_controls);
}
//#####################################################################
// Function Set_External_Controls
//#####################################################################
void Set_External_Controls (const T time)
{
T fractional_control_frame = time * control_frame_rate;
int integer_control_frame = (int) fractional_control_frame;
T interpolation_fraction = fractional_control_frame - (T) integer_control_frame;
std::string last_control_filename = control_directory + "/storytelling_controls." + STRING_UTILITIES::string_sprintf ("%d", integer_control_frame);
std::string next_control_filename = control_directory + "/storytelling_controls." + STRING_UTILITIES::string_sprintf ("%d", integer_control_frame + 1);
FILE_UTILITIES::Read_From_File<RW> (last_control_filename, input_control_parameters);
input_control_parameters.Save_Controls();
FILE_UTILITIES::Read_From_File<RW> (next_control_filename, input_control_parameters);
input_control_parameters.Interpolate (interpolation_fraction);
VECTOR_ND<T> input_controls;
input_control_parameters.Get (input_controls);
control_parameters.Set (input_controls);
}
//#####################################################################
};
}
#endif
|
ryanb93/newrelic-java-agent | instrumentation/spring-webflux-5.0.0/src/main/java/org/springframework/web/reactive/ServerResponse_Instrumentation.java | <filename>instrumentation/spring-webflux-5.0.0/src/main/java/org/springframework/web/reactive/ServerResponse_Instrumentation.java
/*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package org.springframework.web.reactive;
import com.newrelic.agent.bridge.Token;
import com.newrelic.api.agent.TransactionNamePriority;
import com.newrelic.api.agent.weaver.MatchType;
import com.newrelic.api.agent.weaver.Weave;
import com.newrelic.api.agent.weaver.Weaver;
import com.nr.agent.instrumentation.spring.reactive.Util;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPattern;
import reactor.core.publisher.Mono;
@Weave(type = MatchType.Interface, originalName = "org.springframework.web.reactive.function.server.ServerResponse")
public abstract class ServerResponse_Instrumentation {
public Mono<Void> writeTo(ServerWebExchange exchange, ServerResponse.Context context) {
final Token token = (Token) exchange.getAttribute(Util.NR_TOKEN);
if (token != null) {
final PathPattern pathPattern = exchange.getAttribute("org.springframework.web.reactive.function.server.RouterFunctions.matchingPattern");
String txnName = exchange.getAttribute(Util.NR_TXN_NAME);
if (pathPattern != null) {
// If the pattern string provided by Spring is available we should use it
txnName = pathPattern.getPatternString();
}
final String methodName = " (" + exchange.getRequest().getMethod() + ")";
if (txnName != null && statusCode().value() != 404) {
final String txnNameWithMethod = removeTrailingSlash(txnName) + methodName;
token.getTransaction()
.setTransactionName(TransactionNamePriority.FRAMEWORK_HIGH, true, "Spring", txnNameWithMethod);
} else {
token.getTransaction()
.setTransactionName(TransactionNamePriority.FRAMEWORK_LOW, true, "Spring", "Unknown Route" + methodName);
}
}
return Weaver.callOriginal();
}
private String removeTrailingSlash(String txnName) {
if (txnName.endsWith("/")) {
return txnName.substring(0, txnName.length() - 1);
}
return txnName;
}
public abstract HttpStatus statusCode();
}
|
saikrishna169/pipedream | components/eventbrite/sources/common/base.js | const eventbrite = require("../../eventbrite.app.js");
module.exports = {
props: {
eventbrite,
db: "$.service.db",
organization: { propDefinition: [eventbrite, "organization"] },
},
methods: {
generateMeta() {
throw new Error("generateMeta is not implemented");
},
emitEvent(data) {
const meta = this.generateMeta(data);
this.$emit(data, meta);
},
async *resourceStream(resourceFn, resource, params = null) {
let hasMoreItems;
do {
const { [resource]: items, pagination = {} } = await resourceFn(params);
for (const item of items) {
yield item;
}
hasMoreItems = !!pagination.has_more_items;
params.continuation = pagination.continuation;
} while (hasMoreItems);
},
},
}; |
Zhengfating/F2FDemo | app/src/main/java/com/alipay/api/response/AlipayEcoMycarParkingConfigSetResponse.java | package com.alipay.api.response;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.eco.mycar.parking.config.set response.
*
* @author auto create
* @since 1.0, 2018-06-25 14:52:49
*/
public class AlipayEcoMycarParkingConfigSetResponse extends AlipayResponse {
private static final long serialVersionUID = 3339327388549265788L;
}
|
luiz158/Hibernate-SpringBoot | HibernateSpringBootOffsetPagination/src/main/java/com/bookstore/controller/BookstoreController.java | package com.bookstore.controller;
import com.bookstore.entity.Author;
import com.bookstore.service.BookstoreService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookstoreController {
private final BookstoreService bookstoreService;
public BookstoreController(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
@GetMapping("/authors/{page}/{size}")
public Page<Author> fetchAuthors(@PathVariable int page, @PathVariable int size) {
return bookstoreService.fetchNextPage(page, size);
}
@GetMapping("/authorsByGenre/{page}/{size}")
public Page<Author> fetchAuthorsByGenre(@PathVariable int page, @PathVariable int size) {
return bookstoreService.fetchNextPageByGenre(page, size);
}
@GetMapping("/authorsByGenreExplicitCount/{page}/{size}")
public Page<Author> fetchAuthorsByGenreExplicitCount(@PathVariable int page, @PathVariable int size) {
return bookstoreService.fetchNextPageByGenreExplicitCount(page, size);
}
@GetMapping("/authorsByGenreNative/{page}/{size}")
public Page<Author> fetchAuthorsByGenreNative(@PathVariable int page, @PathVariable int size) {
return bookstoreService.fetchNextPageByGenreNative(page, size);
}
@GetMapping("/authorsByGenreNativeExplicitCount/{page}/{size}")
public Page<Author> fetchAuthorsByGenreNativeExplicitCount(@PathVariable int page, @PathVariable int size) {
return bookstoreService.fetchNextPageByGenreNativeExplicitCount(page, size);
}
@GetMapping("/authors")
// Request example: http://localhost:8080/authors?page=1&size=3&sort=name,desc
public Page<Author> fetchAuthors(Pageable pageable) {
return bookstoreService.fetchNextPagePageable(pageable);
}
}
|
softcontext/spring1107 | spring-mvc-2/src/main/java/com/example/demo/dto/ServerResponse.java | <filename>spring-mvc-2/src/main/java/com/example/demo/dto/ServerResponse.java
package com.example.demo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ServerResponse {
private String status = "Success";
private String message;
private Object data;
private String errorCode;
private String errorMessage;
public ServerResponse(Object data) {
this.data = data;
}
public ServerResponse(String status, String message, Object data) {
this.status = status;
this.message = message;
this.data = data;
}
public ServerResponse(String status, String message, String errorCode, String errorMessage) {
this.status = status;
this.message = message;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
} |
ScalablyTyped/SlinkyTyped | e/electron/src/main/scala/typingsSlinky/electron/global/Electron/TouchBar.scala | <filename>e/electron/src/main/scala/typingsSlinky/electron/global/Electron/TouchBar.scala
package typingsSlinky.electron.global.Electron
import org.scalablytyped.runtime.Instantiable0
import org.scalablytyped.runtime.Instantiable1
import typingsSlinky.electron.Electron.TouchBarButtonConstructorOptions
import typingsSlinky.electron.Electron.TouchBarColorPickerConstructorOptions
import typingsSlinky.electron.Electron.TouchBarConstructorOptions
import typingsSlinky.electron.Electron.TouchBarGroupConstructorOptions
import typingsSlinky.electron.Electron.TouchBarLabelConstructorOptions
import typingsSlinky.electron.Electron.TouchBarPopoverConstructorOptions
import typingsSlinky.electron.Electron.TouchBarScrubberConstructorOptions
import typingsSlinky.electron.Electron.TouchBarSegmentedControlConstructorOptions
import typingsSlinky.electron.Electron.TouchBarSliderConstructorOptions
import typingsSlinky.electron.Electron.TouchBarSpacerConstructorOptions
import typingsSlinky.node.eventsMod.EventEmitter
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@JSGlobal("Electron.TouchBar")
@js.native
class TouchBar protected ()
extends typingsSlinky.electron.Electron.TouchBar {
// Docs: https://electronjs.org/docs/api/touch-bar
/**
* TouchBar
*/
def this(options: TouchBarConstructorOptions) = this()
}
object TouchBar {
@JSGlobal("Electron.TouchBar")
@js.native
val ^ : js.Any = js.native
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarButton")
@js.native
class TouchBarButton protected ()
extends typingsSlinky.electron.Electron.TouchBarButton {
// Docs: https://electronjs.org/docs/api/touch-bar-button
/**
* TouchBarButton
*/
def this(options: TouchBarButtonConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarButton` */
@JSGlobal("Electron.TouchBar.TouchBarButton")
@js.native
def TouchBarButton: Instantiable1[
/* options */ TouchBarButtonConstructorOptions,
typingsSlinky.electron.Electron.TouchBarButton
] = js.native
@scala.inline
def TouchBarButton_=(
x: Instantiable1[
/* options */ TouchBarButtonConstructorOptions,
typingsSlinky.electron.Electron.TouchBarButton
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarButton")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarColorPicker")
@js.native
class TouchBarColorPicker protected ()
extends typingsSlinky.electron.Electron.TouchBarColorPicker {
// Docs: https://electronjs.org/docs/api/touch-bar-color-picker
/**
* TouchBarColorPicker
*/
def this(options: TouchBarColorPickerConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarColorPicker` */
@JSGlobal("Electron.TouchBar.TouchBarColorPicker")
@js.native
def TouchBarColorPicker: Instantiable1[
/* options */ TouchBarColorPickerConstructorOptions,
typingsSlinky.electron.Electron.TouchBarColorPicker
] = js.native
@scala.inline
def TouchBarColorPicker_=(
x: Instantiable1[
/* options */ TouchBarColorPickerConstructorOptions,
typingsSlinky.electron.Electron.TouchBarColorPicker
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarColorPicker")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarGroup")
@js.native
class TouchBarGroup protected () extends EventEmitter {
// Docs: https://electronjs.org/docs/api/touch-bar-group
/**
* TouchBarGroup
*/
def this(options: TouchBarGroupConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarGroup` */
@JSGlobal("Electron.TouchBar.TouchBarGroup")
@js.native
def TouchBarGroup: Instantiable1[
/* options */ TouchBarGroupConstructorOptions,
typingsSlinky.electron.Electron.TouchBarGroup
] = js.native
@scala.inline
def TouchBarGroup_=(
x: Instantiable1[
/* options */ TouchBarGroupConstructorOptions,
typingsSlinky.electron.Electron.TouchBarGroup
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarGroup")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarLabel")
@js.native
class TouchBarLabel protected ()
extends typingsSlinky.electron.Electron.TouchBarLabel {
// Docs: https://electronjs.org/docs/api/touch-bar-label
/**
* TouchBarLabel
*/
def this(options: TouchBarLabelConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarLabel` */
@JSGlobal("Electron.TouchBar.TouchBarLabel")
@js.native
def TouchBarLabel: Instantiable1[
/* options */ TouchBarLabelConstructorOptions,
typingsSlinky.electron.Electron.TouchBarLabel
] = js.native
@scala.inline
def TouchBarLabel_=(
x: Instantiable1[
/* options */ TouchBarLabelConstructorOptions,
typingsSlinky.electron.Electron.TouchBarLabel
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarLabel")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarOtherItemsProxy")
@js.native
// Docs: https://electronjs.org/docs/api/touch-bar-other-items-proxy
/**
* TouchBarOtherItemsProxy
*/
class TouchBarOtherItemsProxy () extends EventEmitter
/* static member */
/* was `typeof TouchBarOtherItemsProxy` */
@JSGlobal("Electron.TouchBar.TouchBarOtherItemsProxy")
@js.native
def TouchBarOtherItemsProxy: Instantiable0[typingsSlinky.electron.Electron.TouchBarOtherItemsProxy] = js.native
@scala.inline
def TouchBarOtherItemsProxy_=(x: Instantiable0[typingsSlinky.electron.Electron.TouchBarOtherItemsProxy]): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarOtherItemsProxy")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarPopover")
@js.native
class TouchBarPopover protected ()
extends typingsSlinky.electron.Electron.TouchBarPopover {
// Docs: https://electronjs.org/docs/api/touch-bar-popover
/**
* TouchBarPopover
*/
def this(options: TouchBarPopoverConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarPopover` */
@JSGlobal("Electron.TouchBar.TouchBarPopover")
@js.native
def TouchBarPopover: Instantiable1[
/* options */ TouchBarPopoverConstructorOptions,
typingsSlinky.electron.Electron.TouchBarPopover
] = js.native
@scala.inline
def TouchBarPopover_=(
x: Instantiable1[
/* options */ TouchBarPopoverConstructorOptions,
typingsSlinky.electron.Electron.TouchBarPopover
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarPopover")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarScrubber")
@js.native
class TouchBarScrubber protected ()
extends typingsSlinky.electron.Electron.TouchBarScrubber {
// Docs: https://electronjs.org/docs/api/touch-bar-scrubber
/**
* TouchBarScrubber
*/
def this(options: TouchBarScrubberConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarScrubber` */
@JSGlobal("Electron.TouchBar.TouchBarScrubber")
@js.native
def TouchBarScrubber: Instantiable1[
/* options */ TouchBarScrubberConstructorOptions,
typingsSlinky.electron.Electron.TouchBarScrubber
] = js.native
@scala.inline
def TouchBarScrubber_=(
x: Instantiable1[
/* options */ TouchBarScrubberConstructorOptions,
typingsSlinky.electron.Electron.TouchBarScrubber
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarScrubber")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarSegmentedControl")
@js.native
class TouchBarSegmentedControl protected ()
extends typingsSlinky.electron.Electron.TouchBarSegmentedControl {
// Docs: https://electronjs.org/docs/api/touch-bar-segmented-control
/**
* TouchBarSegmentedControl
*/
def this(options: TouchBarSegmentedControlConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarSegmentedControl` */
@JSGlobal("Electron.TouchBar.TouchBarSegmentedControl")
@js.native
def TouchBarSegmentedControl: Instantiable1[
/* options */ TouchBarSegmentedControlConstructorOptions,
typingsSlinky.electron.Electron.TouchBarSegmentedControl
] = js.native
@scala.inline
def TouchBarSegmentedControl_=(
x: Instantiable1[
/* options */ TouchBarSegmentedControlConstructorOptions,
typingsSlinky.electron.Electron.TouchBarSegmentedControl
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarSegmentedControl")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarSlider")
@js.native
class TouchBarSlider protected ()
extends typingsSlinky.electron.Electron.TouchBarSlider {
// Docs: https://electronjs.org/docs/api/touch-bar-slider
/**
* TouchBarSlider
*/
def this(options: TouchBarSliderConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarSlider` */
@JSGlobal("Electron.TouchBar.TouchBarSlider")
@js.native
def TouchBarSlider: Instantiable1[
/* options */ TouchBarSliderConstructorOptions,
typingsSlinky.electron.Electron.TouchBarSlider
] = js.native
@scala.inline
def TouchBarSlider_=(
x: Instantiable1[
/* options */ TouchBarSliderConstructorOptions,
typingsSlinky.electron.Electron.TouchBarSlider
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarSlider")(x.asInstanceOf[js.Any])
/* This class was inferred from a value with a constructor. In rare cases (like HTMLElement in the DOM) it might not work as you expect. */
@JSGlobal("Electron.TouchBar.TouchBarSpacer")
@js.native
class TouchBarSpacer protected ()
extends typingsSlinky.electron.Electron.TouchBarSpacer {
// Docs: https://electronjs.org/docs/api/touch-bar-spacer
/**
* TouchBarSpacer
*/
def this(options: TouchBarSpacerConstructorOptions) = this()
}
/* static member */
/* was `typeof TouchBarSpacer` */
@JSGlobal("Electron.TouchBar.TouchBarSpacer")
@js.native
def TouchBarSpacer: Instantiable1[
/* options */ TouchBarSpacerConstructorOptions,
typingsSlinky.electron.Electron.TouchBarSpacer
] = js.native
@scala.inline
def TouchBarSpacer_=(
x: Instantiable1[
/* options */ TouchBarSpacerConstructorOptions,
typingsSlinky.electron.Electron.TouchBarSpacer
]
): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("TouchBarSpacer")(x.asInstanceOf[js.Any])
}
|
askmohanty/metasfresh | misc/services/mobile-webui/mobile-webui-frontend/src/utils/picking.js | export const getPickFrom = ({ stepProps, altStepId }) => {
return altStepId ? stepProps.pickFromAlternatives[altStepId] : stepProps.mainPickFrom;
};
export const getQtyToPick = ({ stepProps, altStepId }) => {
return altStepId ? getPickFrom({ stepProps, altStepId }).qtyToPick : stepProps.qtyToPick;
};
|
dbsteward/dbsteward-go | lib/xml_parser.go | <filename>lib/xml_parser.go<gh_stars>1-10
package lib
import (
"encoding/xml"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/dbsteward/dbsteward/lib/model"
"github.com/dbsteward/dbsteward/lib/util"
)
// TODO(go,3) no globals
var GlobalXmlParser *XmlParser = NewXmlParser()
type XmlParser struct{}
func NewXmlParser() *XmlParser {
return &XmlParser{}
}
func (self *XmlParser) LoadDefintion(file string) (*model.Definition, error) {
f, err := os.Open(file)
if err != nil {
return nil, errors.Wrapf(err, "could not read dbxml file %s", file)
}
defer f.Close()
doc := &model.Definition{}
err = xml.NewDecoder(f).Decode(doc)
if err != nil {
return nil, errors.Wrapf(err, "could not parse dbxml file %s", file)
}
return doc, nil
}
func (self *XmlParser) SaveDoc(filename string, doc *model.Definition) {
f, err := os.Create(filename)
GlobalDBSteward.FatalIfError(err, "Could not open file %s for writing", filename)
defer f.Close()
// TODO(go,nth) get rid of empty closing tags like <grant ...></grant> => <grant .../>
// Go doesn't natively support this (yet?), and google is being google about it
// https://github.com/golang/go/issues/21399
enc := xml.NewEncoder(f)
enc.Indent("", " ")
err = enc.Encode(doc)
GlobalDBSteward.FatalIfError(err, "Could not marshal document")
}
func (self *XmlParser) FormatXml(doc *model.Definition) string {
d, err := xml.MarshalIndent(doc, "", " ")
GlobalDBSteward.FatalIfError(err, "could not marshal definition")
return string(d)
}
func (self *XmlParser) GetSqlFormat(files []string) model.SqlFormat {
// TODO(go,core)
return model.SqlFormatPgsql8
}
func (self *XmlParser) XmlComposite(files []string) *model.Definition {
doc, _ := self.XmlCompositeAddendums(files, 0)
return doc
}
func (self *XmlParser) XmlCompositeAddendums(files []string, addendums uint) (*model.Definition, *model.Definition) {
var composite, addendumsDoc *model.Definition
startAddendumsIdx := -1
if addendums > 0 {
addendumsDoc = &model.Definition{}
startAddendumsIdx = len(files) - int(addendums)
}
for _, file := range files {
GlobalDBSteward.Notice("Loading XML %s...", file)
doc, err := self.LoadDefintion(file)
GlobalDBSteward.FatalIfError(err, "Failed to load and parse xml file %s", file)
GlobalDBSteward.Notice("Compositing XML %s", file)
composite, err = self.CompositeDoc(composite, doc, file, startAddendumsIdx, addendumsDoc)
GlobalDBSteward.FatalIfError(err, "Failed to composite xml file %s", file)
}
self.ValidateXml(self.FormatXml(composite))
return composite, addendumsDoc
}
func (self *XmlParser) CompositeDoc(base, overlay *model.Definition, file string, startAddendumsIdx int, addendumsDoc *model.Definition) (*model.Definition, error) {
util.Assert(overlay != nil, "CompositeDoc overlay must not be nil, you probably want CompositeDoc(nil, doc, ...) instead")
if base == nil {
base = &model.Definition{}
}
overlay, err := self.expandIncludes(overlay, file)
if err != nil {
return base, err
}
overlay = self.expandTabrowData(overlay)
overlay, err = self.SqlFormatConvert(overlay)
if err != nil {
return base, err
}
// TODO(go,core) data addendums
// TODO(go,slony) slony composite aspects
base.Merge(overlay)
self.VendorParse(base)
// NOTE: v1 had schema validation occur _during_ the merge, which arguably is more efficient,
// but also is a very different operation. We're going to try a separate validation step in v2+
errs := base.Validate()
if len(errs) > 0 {
// TODO(go,nth) can we find a better way to represent validation errors? should we actually validate _outside_ this function?
return base, &multierror.Error{
Errors: errs,
}
}
return base, nil
}
func (self *XmlParser) expandTabrowData(doc *model.Definition) *model.Definition {
for _, schema := range doc.Schemas {
for _, table := range schema.Tables {
if table.Rows != nil {
table.Rows.ConvertTabRows()
}
}
}
return doc
}
func (self *XmlParser) expandIncludes(doc *model.Definition, file string) (*model.Definition, error) {
for _, includeFile := range doc.IncludeFiles {
include := includeFile.Name
// if the include is relative, make it relative to the parent file
if !filepath.IsAbs(include) {
inc, err := filepath.Abs(filepath.Join(filepath.Dir(file), include))
if err != nil {
return doc, fmt.Errorf("could not establish absolute path to file %s included from %s", include, file)
}
include = inc
}
includeDoc, err := self.LoadDefintion(include)
if err != nil {
return doc, fmt.Errorf("Failed to load and parse xml file %s included from %s", include, file)
}
doc, err = self.CompositeDoc(doc, includeDoc, include, -1, nil)
if err != nil {
return doc, errors.Wrapf(err, "while compositing included file %s from %s", include, file)
}
}
doc.IncludeFiles = nil
return doc, nil
}
func (self *XmlParser) XmlCompositePgData(doc *model.Definition, dataFiles []string) *model.Definition {
// TODO(go,pgsql) pgdata compositing
return nil
}
func (self *XmlParser) SqlFormatConvert(doc *model.Definition) (*model.Definition, error) {
// legacy 1.0 column add directive attribute conversion
for _, schema := range doc.Schemas {
for _, table := range schema.Tables {
for _, column := range table.Columns {
column.ConvertStageDirectives()
}
}
}
// mssql10 sql format conversions
// TODO(feat) apply mssql10_type_convert to function parameters/returns as well. see below mysql5 impl
if GlobalDBSteward.SqlFormat == model.SqlFormatMssql10 {
for _, schema := range doc.Schemas {
// if objects are being placed in the public schema, move the schema definition to dbo
// TODO(go,4) can we use a "SCHEMA_PUBLIC" macro or something to simplify this?
if strings.EqualFold(schema.Name, "public") {
if dbo := doc.TryGetSchemaNamed("dbo"); dbo != nil {
return doc, fmt.Errorf("Attempting to rename schema 'public' to 'dbo' but schema 'dbo' already exists")
}
schema.Name = "dbo"
}
for _, table := range schema.Tables {
for _, column := range table.Columns {
if strings.EqualFold(column.ForeignSchema, "public") {
column.ForeignSchema = "dbo"
}
if column.Type != "" {
self.mssql10TypeConvert(column)
}
}
}
// TODO(go,mssql) do we need to check function types like we do for mysql?
}
}
// mysql5 format conversions
if GlobalDBSteward.SqlFormat == model.SqlFormatMysql5 {
for _, schema := range doc.Schemas {
for _, table := range schema.Tables {
for _, column := range table.Columns {
if column.Type != "" {
typ, def := self.mysql5TypeConvert(column.Type, column.Default)
column.Type = typ
column.Default = def
}
}
}
for _, function := range schema.Functions {
typ, _ := self.mysql5TypeConvert(function.Returns, "")
function.Returns = typ
for _, param := range function.Parameters {
typ, _ := self.mysql5TypeConvert(param.Type, "")
param.Type = typ
}
}
}
}
return doc, nil
}
// TODO(go,3) push this to mssql package
// TODO(go,3) should we defer this to sql generation time instead?
func (self *XmlParser) mssql10TypeConvert(column *model.Column) {
// all arrays to varchar(896) - our accepted varchar key max for mssql databases
// the reason this is done to varchar(896) instead of varchar(MAX)
// is that mssql will not allow binary blobs or long string types to be keys of indexes and foreign keys
// attempting to do so results in errors like
// Column 'app_mode' in table 'dbo.registration_step_list' is of a type that is invalid for use as a key column in an index.
if strings.HasSuffix(column.Type, "[]") {
column.Type = "varchar(896)"
}
switch strings.ToLower(column.Type) {
case "boolean", "bool":
column.Type = "char(1)"
if column.Default != "" {
switch strings.ToLower(column.Default) {
case "t", "'t'", "true":
column.Default = "'t'"
case "f", "'f'", "false":
column.Default = "'f'"
default:
GlobalDBSteward.Fatal("unknown column type bool default %s", column.Default)
}
}
case "inet":
column.Type = "varchar(16)"
case "interval", "character varying", "varchar", "text":
column.Type = "varchar(MAX)"
case "timestamp", "timestamp without time zone":
column.Type = "datetime2"
case "timestamp with time zone":
column.Type = "datetimeoffset(7)"
case "time with time zone":
column.Type = "time"
case "serial":
// pg serial = ms int identity
// see http://msdn.microsoft.com/en-us/library/ms186775.aspx
column.Type = "int identity(1, 1)"
if column.SerialStart != nil {
column.Type = fmt.Sprintf("int identity(%d, 1)", *column.SerialStart)
}
case "bigserial":
column.Type = "bigint identity(1, 1)"
if column.SerialStart != nil {
column.Type = fmt.Sprintf("bigint identity(%d, 1)", *column.SerialStart)
}
case "uuid":
// PostgreSQL's type uuid adhering to RFC 4122 -- see http://www.postgresql.org/docs/8.4/static/datatype-uuid.html
// MSSQL almost equivalent known as uniqueidentifier -- see http://msdn.microsoft.com/en-us/library/ms187942.aspx
// the column type is "a 16-byte GUID", 36 characters in length -- it does not claim to be, but appears to be their RFC 4122 implementation
column.Type = "uniqueidentifier"
default:
// no match to postgresql built-in types
// check for custom types in the public schema
// these should be changed to dbo
column.Type = util.IReplaceAll(column.Type, "public.", "dbo.")
}
// mssql doesn't understand epoch
if strings.EqualFold(column.Default, "'epoch'") {
column.Default = "'1970-01-01'"
}
}
func (self *XmlParser) mysql5TypeConvert(typ, def string) (string, string) {
// TODO(go,mysql)
return typ, def
}
func (self *XmlParser) VendorParse(doc *model.Definition) {
if parser := GlobalDBSteward.Lookup().XmlParser; parser != nil {
parser.Process(doc)
}
}
func (self *XmlParser) SlonyIdNumber(doc *model.Definition) *model.Definition {
// TODO(go,slony)
return nil
}
func (self *XmlParser) FileSort(file, sortedFile string) {
// TODO(go,xmlutil)
}
func (self *XmlParser) ValidateXml(xmlstr string) {
// TODO(go,core) validate the given xml against DTD. and/or, do we even need this now that we're serializing straight from structs?
}
func (self *XmlParser) RoleEnum(doc *model.Definition, role string) string {
if role == model.RolePublic && GlobalDBSteward.SqlFormat == model.SqlFormatMysql5 {
role = model.RoleApplication
GlobalDBSteward.Warning("MySQL doesn't support the PUBLIC role, using ROLE_APPLICATION (%s) instead", role)
}
if doc.Database == nil {
// TODO(go,nth) somehow was incompletely constructed
doc.Database = &model.Database{
Roles: &model.RoleAssignment{},
}
}
roles := doc.Database.Roles
switch role {
case model.RolePublic, model.RolePgsql:
// RolePublic, RolePgsql are their own constants
return role
case model.RoleApplication:
return roles.Application
case model.RoleOwner:
return roles.Owner
case model.RoleReadOnly:
return roles.ReadOnly
case model.RoleReplication:
return roles.Replication
}
// NEW: if role matches any of the specific role assignments, don't consider it to be an error
// this is basically the case where the user has manually resolved the role
if strings.EqualFold(roles.Application, role) ||
strings.EqualFold(roles.Owner, role) ||
strings.EqualFold(roles.ReadOnly, role) ||
strings.EqualFold(roles.Replication, role) ||
util.IIndexOfStr(role, roles.CustomRoles) >= 0 {
return role
}
if !GlobalDBSteward.IgnoreCustomRoles {
GlobalDBSteward.Fatal("Failed to confirm custom role: %s", role)
}
GlobalDBSteward.Warning("Ignoring custom roles, Role '%s' is being overridden by ROLE_OWNER (%s)", role, roles.Owner)
return roles.Owner
}
|
indrgun/functional-utils | src/main/java/fi/solita/utils/functional/Tuple1.java | package fi.solita.utils.functional;
public class Tuple1<T1> extends Tuple implements Tuple._1<T1> {
public final T1 _1;
public Tuple1(T1 t1) {
this._1 = t1;
}
public <T> Tuple2<T, T1> prepend(T t) {
return Tuple.of(t, _1);
}
public <T> Tuple2<T1, T> append(T t) {
return Tuple.of(_1, t);
}
public T1 get_1() {
return _1;
}
@Override
public Object[] toArray() {
return new Object[]{_1};
}
}
|
mikelange49/pedalevite | src/lal/Mat.h | <reponame>mikelange49/pedalevite
/*****************************************************************************
Mat.h
Author: <NAME>, 2020
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
*Tab=3***********************************************************************/
#pragma once
#if ! defined (lal_Mat_HEADER_INCLUDED)
#define lal_Mat_HEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "lal/MatResizableInterface.h"
#include <vector>
namespace lal
{
template <typename T> class MatView;
template <typename T> class MatViewConst;
template <typename T>
class Mat
: public MatResizableInterface <T>
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
MatView <T> make_sub (int r, int c, int h, int w);
MatViewConst <T>
make_sub (int r, int c, int h, int w) const;
void set_zero ();
void set_id ();
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
// lal::MatConstInterface
int do_get_rows () const override;
int do_get_cols () const override;
const T & do_at (int r, int c) const override;
const T * do_get_data () const override;
int do_get_stride () const override;
// lal::MatInterface
T & do_at (int r, int c) override;
T * do_get_data () override;
// lal::MatResizableInterface
void do_reserve (int r, int c) override;
void do_resize (int r, int c) override;
void do_resize (int n, Dir dir) override;
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
int conv_coord_to_pos (int r, int c) const;
int _rows = 0; // >= 0
int _cols = 0; // >= 0
std::vector <T>
_data;
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
bool operator == (const Mat &other) const = delete;
bool operator != (const Mat &other) const = delete;
}; // class Mat
} // namespace lal
#include "lal/Mat.hpp"
#endif // lal_Mat_HEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
|
bluebird88/HIS | his-cloud/his-cloud-api-pc/src/main/java/com/neu/his/cloud/api/pc/service/dms/DmsNonDrugItemRecordService.java | <reponame>bluebird88/HIS<filename>his-cloud/his-cloud-api-pc/src/main/java/com/neu/his/cloud/api/pc/service/dms/DmsNonDrugItemRecordService.java
package com.neu.his.cloud.api.pc.service.dms;
import com.neu.his.cloud.api.pc.common.CommonResult;
import com.neu.his.cloud.api.pc.dto.dms.DmsNonDrugItemRecordListParam;
import com.neu.his.cloud.api.pc.dto.dms.DmsNonDrugItemRecordResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@FeignClient(value = "his-cloud-service-dms")
public interface DmsNonDrugItemRecordService {
@RequestMapping(value = "/nonDrugItemRecord/apply", method = RequestMethod.POST)
CommonResult apply(@RequestBody DmsNonDrugItemRecordListParam dmsNonDrugItemRecordListParam);
@RequestMapping(value = "/nonDrugItemRecord/invalid", method = RequestMethod.POST)
CommonResult invalid(@RequestParam("ids") List<Long> ids);
@RequestMapping(value = "/nonDrugItemRecord/listByRegAndType", method = RequestMethod.POST)
CommonResult<List<DmsNonDrugItemRecordResult>> listByRegAndType(@RequestParam("registrationId") Long registrationId, @RequestParam("type") Integer type);
}
|
Alpana07/phosphor-logging | extensions/openpower-pels/section_factory.hpp | #pragma once
#include "section.hpp"
#include "stream.hpp"
namespace openpower
{
namespace pels
{
namespace section_factory
{
/**
* @brief Create a PEL section based on its data
*
* This creates the appropriate PEL section object based on the section ID in
* the first 2 bytes of the stream, but returns the base class Section pointer.
*
* If there isn't a class specifically for that section, it defaults to
* creating an instance of the 'Generic' class.
*
* @param[in] pelData - The PEL data stream
*
* @return std::unique_ptr<Section> - class of the appropriate type
*/
std::unique_ptr<Section> create(Stream& pelData);
} // namespace section_factory
} // namespace pels
} // namespace openpower
|
suhanime/installer | pkg/diagnostics/error.go | <filename>pkg/diagnostics/error.go
package diagnostics
import (
"bytes"
"fmt"
"io"
"regexp"
"strings"
"github.com/pkg/errors"
)
// Err wraps diagnostics information for an error.
// Err allows providing information like source, reason and message
// that provides a much better user error reporting capability.
type Err struct {
Orig error
// Source defines with entity is generating the error.
// It allows passing along information about where the error is being
// generated from. for example, the Asset.
Source string
// Reason is a CamelCase string that summarizes the error in one word.
// It allows easy catgeorizations of known errors.
Reason string
// Message is free-form strings which provides important details or
// diagnostics for the error. When writing messages, make sure to keep in mind
// that the audience for message is end-users who might not be experts.
Message string
}
// Unwrap allows the error to be unwrapped.
func (e *Err) Unwrap() error { return e.Orig }
// Error returns a string representation of the Err. The returned value
// is expected to be a single value.
// The format of the error string returned is,
// `error(<Reason>) from <Source>: <Message>: <Cause of Orig>`
func (e *Err) Error() string {
buf := &bytes.Buffer{}
if len(e.Source) > 0 {
fmt.Fprintf(buf, "error(%s) from %s", e.Reason, e.Source)
} else {
fmt.Fprintf(buf, "error(%s)", e.Reason)
}
if msg := strings.TrimSpace(e.Message); len(msg) > 0 {
msg = breakre.ReplaceAllString(msg, " ")
fmt.Fprintf(buf, ": %s", msg)
}
if c := errors.Cause(e.Orig); c != nil {
fmt.Fprintf(buf, ": %s", errors.Cause(e.Orig))
}
return buf.String()
}
// Print prints the Err to Writer in a way that is more verbose and
// sectionalized.
// The output looks like:
// Error from <Source>:
// Reason: <reason>
//
// Message:
// <Message>
//
// Original:
// <Orig>
func (e *Err) Print(w io.Writer) {
fmt.Fprintf(w, "Error from %q\n", e.Source)
fmt.Fprintf(w, "Reason: %s\n", e.Reason)
if len(e.Message) > 0 {
fmt.Fprintf(w, "\nMessage:\n")
fmt.Fprintln(w, e.Message)
}
fmt.Fprintf(w, "\nOriginal error:\n")
fmt.Fprintln(w, e.Orig)
}
var breakre = regexp.MustCompile(`\r?\n`)
|
ger-benjamin/ngeo | contribs/gmf/src/services/wmstime.js | <gh_stars>0
goog.provide('gmf.WMSTime');
goog.require('gmf');
goog.require('ngeo.Time');
goog.require('goog.asserts');
/**
* gmf - WMS time service
* @extends {ngeo.Time}
* @param {angular.$filter} $filter angular filter service.
* @constructor
* @struct
* @ngInject
* @ngdoc service
* @ngname gmfWMSTime
*/
gmf.WMSTime = function($filter) {
/**
* @private
* @type {angular.$filter}
*/
this.$filter_ = $filter;
ngeo.Time.call(this);
};
ol.inherits(gmf.WMSTime, ngeo.Time);
/**
* gmfWMSTime.prototype.formatWMSTimeValue_ - Format time regarding a
* resolution
*
* @param {number} time (in ms format) timestamp to format
* @param {ngeox.TimePropertyResolutionEnum} resolution resolution to use
* @param {boolean=} opt_toUTC to get the UTC date
* @return {string} ISO-8601 date string regarding the resolution
* @private
*/
gmf.WMSTime.prototype.formatWMSTimeValue_ = function(time, resolution, opt_toUTC) {
var date = new Date(time);
var utc = opt_toUTC ? 'UTC' : undefined;
switch (resolution) {
case 'year':
return this.$filter_('date')(date, 'yyyy', utc);
case 'month':
return this.$filter_('date')(date, 'yyyy-MM', utc);
case 'day':
return this.$filter_('date')(date, 'yyyy-MM-dd', utc);
default:
//case "second":
return date.toISOString().replace(/\.\d{3}/, '');
}
};
/**
* gmfWMSTime.prototype.formatWMSTimeParam - Format time to be used as a
* WMS Time query parameter
*
* @param {ngeox.TimeProperty} wmsTimeProperty a wmstime property from a node
* @param {{start : number, end : (number|undefined)}} times start & end time selected (in ms format)
* @param {boolean=} opt_toUTC to get the UTC date
* @return {string} ISO-8601 date string ready to be used as a query parameter for a
* WMS request
* @export
*/
gmf.WMSTime.prototype.formatWMSTimeParam = function(wmsTimeProperty, times, opt_toUTC) {
goog.asserts.assert(wmsTimeProperty.resolution !== undefined);
if (wmsTimeProperty.mode === 'range') {
goog.asserts.assert(times.end !== undefined);
return (
this.formatWMSTimeValue_(times.start, wmsTimeProperty.resolution, opt_toUTC) + '/' +
this.formatWMSTimeValue_(times.end, wmsTimeProperty.resolution, opt_toUTC)
);
} else {
return this.formatWMSTimeValue_(times.start, wmsTimeProperty.resolution, opt_toUTC);
}
};
gmf.module.service('gmfWMSTime', gmf.WMSTime);
|
eclipse-basyx/basyx-sdk-python | basyx/aas/compliance_tool/cli.py | # Copyright (c) 2020 the Eclipse BaSyx Authors
#
# This program and the accompanying materials are made available under the terms of the MIT License, available in
# the LICENSE file of this project.
#
# SPDX-License-Identifier: MIT
"""
Command line script which is a compliance tool for creating and checking json and xml files in compliance with
"Details of the Asset Administration Shell" specification of Plattform Industrie 4.0. It uses the create_example() from
examples.data.__init__.py
"""
import argparse
import datetime
import logging
import pyecma376_2
from basyx.aas import model
from basyx.aas.adapter import aasx
from basyx.aas.adapter.xml import write_aas_xml_file
from basyx.aas.compliance_tool import compliance_check_xml as compliance_tool_xml, \
compliance_check_json as compliance_tool_json, compliance_check_aasx as compliance_tool_aasx
from basyx.aas.adapter.json import write_aas_json_file
from basyx.aas.examples.data import create_example, create_example_aas_binding, TEST_PDF_FILE
from basyx.aas.compliance_tool.state_manager import ComplianceToolStateManager, Status
def parse_cli_arguments() -> argparse.ArgumentParser:
"""
This function returns the argument-parser for the cli
"""
parser = argparse.ArgumentParser(
prog='compliance_tool',
description='Compliance tool for creating and checking json and xml files in compliance with "Details of the '
'Asset Administration Shell" specification of Plattform Industrie 4.0. \n\n'
'This tool has five features: \n'
'1. create a xml or json file or an AASX file using xml or json files with example aas elements\n'
'2. check if a given xml or json file is compliant with the official json or xml aas schema and '
'is deserializable\n'
'3. check if the data in a given xml, json or aasx file is the same as the example data\n'
'4. check if two given xml, json or aasx files contain the same aas elements in any order\n\n'
'As a first argument, the feature must be specified (create, schema, deserialization, example, '
'files) or in short (c, s, d, e or f).\n'
'Depending the chosen feature, different additional arguments must be specified:\n'
'create or c: path to the file which shall be created (file_1)\n'
'deseriable or d: file to be checked (file_1)\n'
'example or e: file to be checked (file_1)\n'
'file_compare or f: files to compare (file_1, file_2)\n,'
'In any case, it must be specified whether the (given or created) files are json (--json) or '
'xml (--xml).\n'
'All features except "schema" support reading/writing AASX packages instead of plain XML or JSON '
'files via the --aasx option.\n\n'
'Additionally, the tool offers some extra features for more convenient usage:\n\n'
'a. Different levels of verbosity:\n'
' Default output is just the status for each step performed. With -v or --verbose, additional '
'information in case of status = FAILED will be provided. With one more -v or --verbose, additional'
' information even in case of status = SUCCESS or WARNINGS will be provided.\n'
'b. Suppressing output on success:\n'
' With -q or --quite no output will be generated if the status = SUCCESS.\n'
'c. Save log additionally in a logfile:\n'
' With -l or --logfile, a path to the file where the logfiles shall be created can be specified.',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('action', choices=['create', 'c', 'schema', 's', 'deserialization', 'd', 'example', 'e',
'files', 'f'],
help='c or create: creates a file with example data\n'
'd or deserialization: checks if a given file is compliance with the official schema and '
'is deserializable\n'
'e or example: checks if a given file contains the example aas elements\n'
'f or file_compare: checks if two given files contain the same aas elements in any order')
parser.add_argument('file_1', help="path to file 1")
parser.add_argument('file_2', nargs='?', default=None, help="path to file 2: is required if action f or files is "
"choosen")
parser.add_argument('-v', '--verbose', help="Print detailed information for each check. Multiple -v options "
"increase the verbosity. 1: Detailed error information, 2: Additional "
"detailed success information", action='count', default=0)
parser.add_argument('-q', '--quite', help="no information output if successful", action='store_true')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--json', help="Use AAS json format when checking or creating files", action='store_true')
group.add_argument('--xml', help="Use AAS xml format when checking or creating files", action='store_true')
parser.add_argument('-l', '--logfile', help="Log file to be created in addition to output to stdout", default=None)
parser.add_argument('--aasx', help="Create or read AASX files", action='store_true')
return parser
def main():
parser = parse_cli_arguments()
args = parser.parse_args()
# Todo try to find out in which format the file is if not --json or --xml
manager = ComplianceToolStateManager()
logger = logging.getLogger(__name__)
logger.propagate = False
logger.addHandler(manager)
if args.action == 'create' or args.action == 'c':
manager.add_step('Create example data')
if args.aasx:
data = create_example_aas_binding()
else:
data = create_example()
manager.set_step_status(Status.SUCCESS)
try:
manager.add_step('Open file')
if args.aasx:
with aasx.AASXWriter(args.file_1) as writer:
manager.set_step_status(Status.SUCCESS)
manager.add_step('Write data to file')
files = aasx.DictSupplementaryFileContainer()
with open(TEST_PDF_FILE, 'rb') as f:
files.add_file("/TestFile.pdf", f, "application/pdf")
# Create OPC/AASX core properties
cp = pyecma376_2.OPCCoreProperties()
cp.created = datetime.datetime(2020, 1, 1, 0, 0, 0)
cp.creator = "Eclipse BaSyx Python Testing Framework"
cp.description = "Test_Description"
cp.lastModifiedBy = "Eclipse BaSyx Python Testing Framework Compliance Tool"
cp.modified = datetime.datetime(2020, 1, 1, 0, 0, 1)
cp.revision = "1.0"
cp.version = "2.0.1"
cp.title = "Test Title"
writer.write_aas_objects("/aasx/data.json" if args.json else "/aasx/data.xml",
[obj.identification for obj in data], data, files,
write_json=args.json)
writer.write_core_properties(cp)
manager.set_step_status(Status.SUCCESS)
elif args.json:
with open(args.file_1, 'w', encoding='utf-8-sig') as file:
manager.set_step_status(Status.SUCCESS)
manager.add_step('Write data to file')
write_aas_json_file(file=file, data=data, indent=4)
manager.set_step_status(Status.SUCCESS)
elif args.xml:
with open(args.file_1, 'wb') as file:
manager.set_step_status(Status.SUCCESS)
manager.add_step('Write data to file')
write_aas_xml_file(file=file, data=data, pretty_print=True)
manager.set_step_status(Status.SUCCESS)
except IOError as error:
logger.error(error)
manager.set_step_status(Status.FAILED)
elif args.action == 'deserialization' or args.action == 'd':
if args.aasx:
compliance_tool_aasx.check_deserialization(args.file_1, manager)
elif args.json:
compliance_tool_json.check_deserialization(args.file_1, manager)
elif args.xml:
compliance_tool_xml.check_deserialization(args.file_1, manager)
elif args.action == 'example' or args.action == 'e':
if args.aasx:
compliance_tool_aasx.check_aas_example(args.file_1, manager)
elif args.json:
compliance_tool_json.check_aas_example(args.file_1, manager)
elif args.xml:
compliance_tool_xml.check_aas_example(args.file_1, manager)
elif args.action == 'files' or args.action == 'f':
if args.file_2:
if args.aasx:
compliance_tool_aasx.check_aasx_files_equivalence(args.file_1, args.file_2, manager)
elif args.json:
compliance_tool_json.check_json_files_equivalence(args.file_1, args.file_2, manager)
elif args.xml:
compliance_tool_xml.check_xml_files_equivalence(args.file_1, args.file_2, manager)
else:
parser.error("f or files requires two file path.")
exit()
if manager.status is Status.SUCCESS and args.quite:
exit()
print(manager.format_state_manager(args.verbose))
if args.logfile:
try:
with open(args.logfile, 'w', encoding='utf-8-sig') as file:
file.write(manager.format_state_manager(args.verbose))
except IOError as error:
print('Could not open logfile: \n{}'.format(error))
if __name__ == "__main__":
main()
|
JBerny/astroplant_explorer | explorer/basic_demos/relay_demo.py | """
Demo/test program for the AE_Relay driver.
See https://github.com/sensemakersamsterdam/astroplant_explorer
"""
#
# (c) Sensemakersams.org and others. See https://github.com/sensemakersamsterdam/astroplant_explorer
# Author: <NAME>
#
# Warning: if import of ae_* modules fails, then you need to set up PYTHONPATH.
# To test start python, import sys and type sys.path. The ae module directory
# should be included.
from time import sleep
import sys
from ae_drivers import AE_Pin, OFF
from ae_drivers.relay import AE_Relay
rly1 = AE_Relay('rly1', 'Fan1 Relay', AE_Pin.D16)
rly1.setup(initial_state=OFF)
print('Relay demo. rly1 prints as:', rly1)
print('and its description is:', rly1.description)
print('\nRelay going on now for 2 seconds...')
rly1.on()
sleep(2)
rly1.off()
print('Done!\n')
print('Relay going on and off rapidly 6 times...')
for _ in range(6):
rly1.toggle()
sleep(1)
print('.', end='', sep='')
sys.stdout.flush()
print('\nDone!\n')
rly1.off() # make sure we start off...
print('And now we read status for the relay when off...')
print('Relay is_on() gives:', rly1.is_on())
print('Relay is_off() gives:', rly1.is_off())
print('Relay value() gives:', rly1.value())
sleep(2)
print('\nAnd now we toggle the relay with toggle() and read its status again.')
rly1.toggle()
print('Relay is_on() now gives:', rly1.is_on())
print('Relay is_off() now gives:', rly1.is_off())
print('Relay value() now gives:', rly1.value())
sleep(2)
rly1.off()
print('\nDemo ended. Relay should be off.')
|
vaavud/androidvaavudsdk | VaavudSDK/src/main/java/com/vaavud/vaavudSDK/core/listener/LocationEventListener.java | package com.vaavud.vaavudSDK.core.listener;
import com.vaavud.vaavudSDK.core.model.event.LocationEvent;
import com.vaavud.vaavudSDK.model.event.VelocityEvent;
import com.vaavud.vaavudSDK.model.event.BearingEvent;
/**
* Created by juan on 19/01/16.
*/
public interface LocationEventListener {
void newLocation(LocationEvent event);
void newVelocity(VelocityEvent event);
void newBearing(BearingEvent event);
void permisionError(String permission);
}
|
rveerama1/istio | security/pkg/k8s/tokenreview/k8sauthn_test.go | // Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tokenreview
import (
"fmt"
"reflect"
"testing"
authenticationv1 "k8s.io/api/authentication/v1"
)
// TestGetTokenReviewResult verifies that getTokenReviewResult returns expected {<namespace>, <serviceaccountname>}.
func TestGetTokenReviewResult(t *testing.T) {
testCases := []struct {
name string
tokenReview authenticationv1.TokenReview
expectedError error
expectedResult []string
}{
{
name: "the service account authentication error",
tokenReview: authenticationv1.TokenReview{
Status: authenticationv1.TokenReviewStatus{
Error: "authentication error",
},
},
expectedError: fmt.Errorf("the service account authentication returns an error: authentication error"),
expectedResult: nil,
},
{
name: "not authenticated",
tokenReview: authenticationv1.TokenReview{
Status: authenticationv1.TokenReviewStatus{
Authenticated: false,
},
},
expectedError: fmt.Errorf("the token is not authenticated"),
expectedResult: nil,
},
{
name: "token is not a service account",
tokenReview: authenticationv1.TokenReview{
Status: authenticationv1.TokenReviewStatus{
Authenticated: true,
User: authenticationv1.UserInfo{
Groups: []string{
"system:serviceaccounts:default",
},
},
},
},
expectedError: fmt.Errorf("the token is not a service account"),
expectedResult: nil,
},
{
name: "invalid username",
tokenReview: authenticationv1.TokenReview{
Status: authenticationv1.TokenReviewStatus{
Authenticated: true,
User: authenticationv1.UserInfo{
Username: "system:serviceaccount:example-pod-sa",
Groups: []string{
"system:serviceaccounts",
"system:serviceaccounts:default",
"system:authenticated",
},
},
},
},
expectedError: fmt.Errorf("invalid username field in the token review result"),
expectedResult: nil,
},
{
name: "success",
tokenReview: authenticationv1.TokenReview{
Status: authenticationv1.TokenReviewStatus{
Authenticated: true,
User: authenticationv1.UserInfo{
Username: "system:serviceaccount:default:example-pod-sa",
UID: "ff578a9e-65d3-11e8-aad2-42010a8a001d",
Groups: []string{
"system:serviceaccounts",
"system:serviceaccounts:default",
"system:authenticated",
},
},
},
},
expectedError: nil,
expectedResult: []string{"default", "example-pod-sa"},
},
}
for _, tc := range testCases {
result, err := getTokenReviewResult(&tc.tokenReview)
if !reflect.DeepEqual(result, tc.expectedResult) {
t.Errorf("TestGetTokenReviewResult failed: case: %q, actual result is %v, expected is %v", tc.name, result, tc.expectedResult)
}
if !reflect.DeepEqual(err, tc.expectedError) {
t.Errorf("TestGetTokenReviewResult failed: case: %q, actual error is %v, expected is %v", tc.name, err, tc.expectedError)
}
}
}
|
harperse/CloverBootloader | FileSystems/GrubFS/grub/grub-core/io/offset.c | <reponame>harperse/CloverBootloader
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2013 Free Software Foundation, Inc.
*
* GRUB 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 3 of the License, or
* (at your option) any later version.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/file.h>
#include <grub/dl.h>
GRUB_MOD_LICENSE ("GPLv3+");
struct grub_offset_file
{
grub_file_t parent;
grub_off_t off;
};
static grub_ssize_t
grub_offset_read (grub_file_t file, char *buf, grub_size_t len)
{
struct grub_offset_file *data = file->data;
if (grub_file_seek (data->parent, data->off + file->offset) == (grub_off_t) -1)
return -1;
return grub_file_read (data->parent, buf, len);
}
static grub_err_t
grub_offset_close (grub_file_t file)
{
struct grub_offset_file *data = file->data;
if (data->parent)
grub_file_close (data->parent);
/* No need to close the same device twice. */
file->device = 0;
return 0;
}
static struct grub_fs grub_offset_fs = {
.name = "offset",
.dir = 0,
.open = 0,
.read = grub_offset_read,
.close = grub_offset_close,
.label = 0,
.next = 0
};
void
grub_file_offset_close (grub_file_t file)
{
struct grub_offset_file *off_data = file->data;
off_data->parent = NULL;
grub_file_close (file);
}
grub_file_t
grub_file_offset_open (grub_file_t parent, grub_off_t start, grub_off_t size)
{
struct grub_offset_file *off_data;
grub_file_t off_file, last_off_file;
grub_file_filter_id_t filter;
off_file = grub_zalloc (sizeof (*off_file));
off_data = grub_zalloc (sizeof (*off_data));
if (!off_file || !off_data)
{
grub_free (off_file);
grub_free (off_data);
return 0;
}
off_data->off = start;
off_data->parent = parent;
off_file->device = parent->device;
off_file->data = off_data;
off_file->fs = &grub_offset_fs;
off_file->size = size;
last_off_file = NULL;
for (filter = GRUB_FILE_FILTER_COMPRESSION_FIRST;
off_file && filter <= GRUB_FILE_FILTER_COMPRESSION_LAST; filter++)
if (grub_file_filters_enabled[filter])
{
last_off_file = off_file;
off_file = grub_file_filters_enabled[filter] (off_file, parent->name);
}
if (!off_file)
{
off_data->parent = NULL;
grub_file_close (last_off_file);
return 0;
}
return off_file;
}
|
goranstack/bluebrim | LayoutShared/src/main/java/com/bluebrim/layout/shared/CoLayoutableIF.java | <gh_stars>0
package com.bluebrim.layout.shared;
/**
* Any object that is to be laid out by the layout engine in CoLayoutSpec must implement this interface.
*/
public interface CoLayoutableIF
{
double getArea(); // the area of the layoutable
public CoImmutableColumnGridIF getColumnGrid();
double getContentHeight(); // height of layoutables content
double getContentWidth(); // height of layoutables content
boolean getDoRunAround();
public double getInteriorHeight(); // interior height (span between top and bottom margins) of layoutable
public double getInteriorWidth(); // interior width (span between left and right margins) of layoutable
public double getLayoutHeight(); // layoutables height if valid, 0 otherwise
CoLayoutableContainerIF getLayoutParent();
public double getLayoutWidth(); // layoutables width if valid, 0 otherwise
public double getLeftEdge(); // left edge position of the layoutable (in parents coordinate space)
public double getRightEdge(); // right edge position of the layoutable (in parents coordinate space)
public double getTopEdge(); // top edge position of the layoutable (in parents coordinate space)
double getBottomEdge(); // bottom edge position of the layoutable (in parents coordinate space)
public double getX();
public double getY();
boolean hasValidLayout(); // is layout valid
public void invalidateHeight(); // POSTCONDITION: layout height is invalid
public void invalidateWidth(); // POSTCONDITION: layout height is invalid
public void reshapeToContentHeight();
public void reshapeToContentWidth ();
void setLayoutHeight( double height ); // POSTCONDITION: layout height is valid
public void setLayoutLocation( double x, double y ); // POSTCONDITION: layout is valid
public void setLayoutSuccess( boolean b ); // declare the layot a success or failure
public void setLayoutWidth( double width ); // POSTCONDITION: layout width is valid
public void setLayoutX( double x ); // POSTCONDITION: layout is valid
public void setLayoutY( double y ); // POSTCONDITION: layout is valid
CoLayoutSpecIF getLayoutSpec();
} |
mptrepanier/hail | src/test/scala/is/hail/methods/ExportSuite.scala | package is.hail.methods
import is.hail.{SparkSuite, TestUtils}
import is.hail.expr.types._
import is.hail.utils._
import is.hail.testUtils._
import org.testng.annotations.Test
import scala.io.Source
class ExportSuite extends SparkSuite {
@Test def test() {
var vds = hc.importVCF("src/test/resources/sample.vcf")
vds = TestUtils.splitMultiHTS(vds)
vds = SampleQC(vds)
val out = tmpDir.createTempFile("out", ".tsv")
vds.colsTable().select(Array("Sample = row.s",
"row.qc.call_rate",
"row.qc.n_called",
"row.qc.n_not_called",
"row.qc.n_hom_ref",
"row.qc.n_het",
"row.qc.n_hom_var",
"row.qc.n_snp",
"row.qc.n_insertion",
"row.qc.n_deletion",
"row.qc.n_singleton",
"row.qc.n_transition",
"row.qc.n_transversion",
"row.qc.n_star",
"row.qc.dp_mean",
"row.qc.dp_stdev",
"row.qc.gq_mean",
"row.qc.gq_stdev",
"row.qc.n_non_ref",
"row.qc.r_ti_tv",
"row.qc.r_het_hom_var",
"row.qc.r_insertion_deletion")).export(out)
val sb = new StringBuilder()
sb.tsvAppend(Array(1, 2, 3, 4, 5))
assert(sb.result() == "1,2,3,4,5")
sb.clear()
sb.tsvAppend(5.124)
assert(sb.result() == "5.12400e+00")
val readBackAnnotated = vds.annotateColsTable(hc.importTable(out, types = Map(
"call_rate" -> TFloat64(),
"n_called" -> TInt64(),
"n_not_called" -> TInt64(),
"n_hom_ref" -> TInt64(),
"n_het" -> TInt64(),
"n_hom_var" -> TInt64(),
"n_snp" -> TInt64(),
"n_insertion" -> TInt64(),
"n_deletion" -> TInt64(),
"n_singleton" -> TInt64(),
"n_transition" -> TInt64(),
"n_transversion" -> TInt64(),
"n_star" -> TInt64(),
"dp_mean" -> TFloat64(),
"dp_stdev" -> TFloat64(),
"gq_mean" -> TFloat64(),
"gq_stdev" -> TFloat64(),
"n_non_ref" -> TInt64(),
"r_ti_tv" -> TFloat64(),
"r_het_hom_var" -> TFloat64(),
"r_insertion_deletion" -> TFloat64())).keyBy("Sample"),
root = "readBackQC")
val (t, qcQuerier) = readBackAnnotated.querySA("sa.qc")
val (t2, rbQuerier) = readBackAnnotated.querySA("sa.readBackQC")
assert(t == t2)
readBackAnnotated.colValues.value.foreach { annotation =>
t.valuesSimilar(qcQuerier(annotation), rbQuerier(annotation))
}
}
@Test def testExportSamples() {
val vds = TestUtils.splitMultiHTS(hc.importVCF("src/test/resources/sample.vcf")
.filterColsExpr("""sa.s == "C469::HG02026""""))
assert(vds.numCols == 1)
// verify exports localSamples
val f = tmpDir.createTempFile("samples", ".tsv")
vds.colsTable().select(Array("row.s")).export(f, header = false)
assert(sc.textFile(f).count() == 1)
}
@Test def testAllowedNames() {
val f = tmpDir.createTempFile("samples", ".tsv")
val f2 = tmpDir.createTempFile("samples", ".tsv")
val f3 = tmpDir.createTempFile("samples", ".tsv")
val vds = TestUtils.splitMultiHTS(hc.importVCF("src/test/resources/sample.vcf"))
vds.colsTable().select(Array("`S.A.M.P.L.E.ID` = row.s")).export(f)
vds.colsTable().select(Array("`$$$I_HEARD_YOU_LIKE!_WEIRD~^_CHARS****` = row.s", "ANOTHERTHING = row.s")).export(f2)
vds.colsTable().select(Array("`I have some spaces and tabs\\there` = row.s", "`more weird stuff here` = row.s")).export(f3)
hadoopConf.readFile(f) { reader =>
val lines = Source.fromInputStream(reader)
.getLines()
assert(lines.next == "S.A.M.P.L.E.ID")
}
hadoopConf.readFile(f2) { reader =>
val lines = Source.fromInputStream(reader)
.getLines()
assert(lines.next == "$$$I_HEARD_YOU_LIKE!_WEIRD~^_CHARS****\tANOTHERTHING")
}
hadoopConf.readFile(f3) { reader =>
val lines = Source.fromInputStream(reader)
.getLines()
assert(lines.next == "I have some spaces and tabs\there\tmore weird stuff here")
}
}
@Test def testIf() {
// this should run without errors
val f = tmpDir.createTempFile("samples", ".tsv")
var vds = hc.importVCF("src/test/resources/sample.vcf")
vds = TestUtils.splitMultiHTS(vds)
vds = SampleQC(vds)
vds
.colsTable()
.select(Array("computation = 5 * (if (row.qc.call_rate < .95) 0 else 1)"))
.export(f)
}
}
|
gkgoat1/lexy | docs/assets/playground/char_class_macro.cpp | <reponame>gkgoat1/lexy
// INPUT:atom
struct production
{
static constexpr auto atext
= LEXY_CHAR_CLASS("atext",
dsl::ascii::alpha / dsl::ascii::digit / LEXY_LIT("!") / LEXY_LIT("#")
/ LEXY_LIT("$") / LEXY_LIT("%") / LEXY_LIT("&") / LEXY_LIT("'")
/ LEXY_LIT("*") / LEXY_LIT("+") / LEXY_LIT("-") / LEXY_LIT("/")
/ LEXY_LIT("=") / LEXY_LIT("?") / LEXY_LIT("^") / LEXY_LIT("_")
/ LEXY_LIT("`") / LEXY_LIT("{") / LEXY_LIT("|") / LEXY_LIT("}"));
static constexpr auto rule = dsl::identifier(atext);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.