code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
<div class="modal-header">
<button type="button" class="close" ng-click="$dismiss()" aria-hidden="true">×</button>
<h4 class="modal-title" id="new-file-label">New file...</h4>
</div>
<form name="newFileForm" novalidate ng-submit="newFile()">
<div class="modal-body" style="font-size: 16px; padding-bottom: 0">
<div ng-class="{'has-error': inputError}" class="form-group">
<div class="row">
<div class="col-xs-4 text-right" style="padding-right: 10px">
<select ng-model="new_file_folder" style="outline: none" class="form-control">
<option>common</option>
<option>{{question}}</option>
<option>tests</option>
</select>
</div>
<div class="col-xs-8" style="padding-left: 0">
<input type="text"
ng-model="new_file_name"
name="new_file_name"
class="form-control"
placeholder="(file name)"
focus-me="true"
style="outline: none; width: 200px; padding-left: 5px">
<span class="help-block" ng-show="inputError">{{inputError}}</span>
</div>
</div>
<div class="row" id="upload-file-row">
<div class="col-xs-8 col-xs-offset-4 form-group" style="padding-left: 0">
<label for="file-to-upload">
<span class="text-muted">or</span>
upload files:
</label>
<input type="file" name="file-to-upload" multiple id="file-to-upload"
class="form-control"
filelist-bind="new_file_upload">
<label style="font-size:14px">
<input type="checkbox" name="normalize-newlines" ng-model="normalize" />
Normalize newlines on upload
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="$dismiss()">Cancel</button>
<input type="submit" class="btn btn-primary" value="OK"></input>
</div>
</form>
| Java |
/*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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/>.
*
* When signing a commercial license with Infinite Automation Software,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*
* See www.infiniteautomation.com for commercial license options.
*
* @author Matthew Lohbihler
*/
package com.serotonin.bacnet4j.type.notificationParameters;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.type.AmbiguousValue;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.StatusFlags;
import com.serotonin.bacnet4j.util.sero.ByteQueue;
public class CommandFailure extends NotificationParameters {
private static final long serialVersionUID = 5727410398456093753L;
public static final byte TYPE_ID = 3;
private final Encodable commandValue;
private final StatusFlags statusFlags;
private final Encodable feedbackValue;
public CommandFailure(Encodable commandValue, StatusFlags statusFlags, Encodable feedbackValue) {
this.commandValue = commandValue;
this.statusFlags = statusFlags;
this.feedbackValue = feedbackValue;
}
@Override
protected void writeImpl(ByteQueue queue) {
writeEncodable(queue, commandValue, 0);
write(queue, statusFlags, 1);
writeEncodable(queue, feedbackValue, 2);
}
public CommandFailure(ByteQueue queue) throws BACnetException {
commandValue = new AmbiguousValue(queue, 0);
statusFlags = read(queue, StatusFlags.class, 1);
feedbackValue = new AmbiguousValue(queue, 2);
}
@Override
protected int getTypeId() {
return TYPE_ID;
}
public Encodable getCommandValue() {
return commandValue;
}
public StatusFlags getStatusFlags() {
return statusFlags;
}
public Encodable getFeedbackValue() {
return feedbackValue;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((commandValue == null) ? 0 : commandValue.hashCode());
result = PRIME * result + ((feedbackValue == null) ? 0 : feedbackValue.hashCode());
result = PRIME * result + ((statusFlags == null) ? 0 : statusFlags.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final CommandFailure other = (CommandFailure) obj;
if (commandValue == null) {
if (other.commandValue != null)
return false;
}
else if (!commandValue.equals(other.commandValue))
return false;
if (feedbackValue == null) {
if (other.feedbackValue != null)
return false;
}
else if (!feedbackValue.equals(other.feedbackValue))
return false;
if (statusFlags == null) {
if (other.statusFlags != null)
return false;
}
else if (!statusFlags.equals(other.statusFlags))
return false;
return true;
}
}
| Java |
/* event-config.h
*
* This file was generated by cmake when the makefiles were generated.
*
* DO NOT EDIT THIS FILE.
*
* Do not rely on macros in this file existing in later versions.
*/
#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
#define EVENT2_EVENT_CONFIG_H_INCLUDED_
/* Numeric representation of the version */
#define EVENT__NUMERIC_VERSION @EVENT_NUMERIC_VERSION@
#define EVENT__PACKAGE_VERSION "@EVENT_PACKAGE_VERSION@"
#define EVENT__VERSION_MAJOR @EVENT_VERSION_MAJOR@
#define EVENT__VERSION_MINOR @EVENT_VERSION_MINOR@
#define EVENT__VERSION_PATCH @EVENT_VERSION_PATCH@
/* Version number of package */
#define EVENT__VERSION "@EVENT_VERSION@"
/* Name of package */
#define EVENT__PACKAGE "libevent"
/* Define to the address where bug reports for this package should be sent. */
#define EVENT__PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define EVENT__PACKAGE_NAME ""
/* Define to the full name and version of this package. */
#define EVENT__PACKAGE_STRING ""
/* Define to the one symbol short name of this package. */
#define EVENT__PACKAGE_TARNAME ""
/* Define if libevent should build without support for a debug mode */
#cmakedefine EVENT__DISABLE_DEBUG_MODE 1
/* Define if libevent should not allow replacing the mm functions */
#cmakedefine EVENT__DISABLE_MM_REPLACEMENT 1
/* Define if libevent should not be compiled with thread support */
#cmakedefine EVENT__DISABLE_THREAD_SUPPORT 1
/* Define to 1 if you have the `accept4' function. */
#cmakedefine EVENT__HAVE_ACCEPT4 1
/* Define to 1 if you have the `arc4random' function. */
#cmakedefine EVENT__HAVE_ARC4RANDOM 1
/* Define to 1 if you have the `arc4random_buf' function. */
#cmakedefine EVENT__HAVE_ARC4RANDOM_BUF 1
/* Define to 1 if you have the `arc4random_addrandom' function. */
#cmakedefine EVENT__HAVE_ARC4RANDOM_ADDRANDOM 1
/* Define if clock_gettime is available in libc */
#cmakedefine EVENT__DNS_USE_CPU_CLOCK_FOR_ID 1
/* Define is no secure id variant is available */
#cmakedefine EVENT__DNS_USE_GETTIMEOFDAY_FOR_ID 1
#cmakedefine EVENT__DNS_USE_FTIME_FOR_ID 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine EVENT__HAVE_ARPA_INET_H 1
/* Define to 1 if you have the `clock_gettime' function. */
#cmakedefine EVENT__HAVE_CLOCK_GETTIME 1
/* Define to 1 if you have the declaration of `CTL_KERN'. */
#define EVENT__HAVE_DECL_CTL_KERN @EVENT__HAVE_DECL_CTL_KERN@
/* Define to 1 if you have the declaration of `KERN_ARND'. */
#define EVENT__HAVE_DECL_KERN_ARND @EVENT__HAVE_DECL_KERN_ARND@
/* Define to 1 if you have the declaration of `KERN_RANDOM'. */
#define EVENT__HAVE_DECL_KERN_RANDOM @EVENT__HAVE_DECL_KERN_RANDOM@
/* Define to 1 if you have the declaration of `RANDOM_UUID'. */
#define EVENT__HAVE_DECL_RANDOM_UUID @EVENT__HAVE_DECL_RANDOM_UUID@
/* Define if /dev/poll is available */
#cmakedefine EVENT__HAVE_DEVPOLL 1
/* Define to 1 if you have the <netdb.h> header file. */
#cmakedefine EVENT__HAVE_NETDB_H 1
/* Define to 1 if fd_mask type is defined */
#cmakedefine EVENT__HAVE_FD_MASK 1
/* Define to 1 if the <sys/queue.h> header file defines TAILQ_FOREACH. */
#cmakedefine EVENT__HAVE_TAILQFOREACH 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine EVENT__HAVE_DLFCN_H 1
/* Define if your system supports the epoll system calls */
#cmakedefine EVENT__HAVE_EPOLL 1
/* Define to 1 if you have the `epoll_create1' function. */
#cmakedefine EVENT__HAVE_EPOLL_CREATE1 1
/* Define to 1 if you have the `epoll_ctl' function. */
#cmakedefine EVENT__HAVE_EPOLL_CTL 1
/* Define to 1 if you have the `eventfd' function. */
#cmakedefine EVENT__HAVE_EVENTFD 1
/* Define if your system supports event ports */
#cmakedefine EVENT__HAVE_EVENT_PORTS 1
/* Define to 1 if you have the `fcntl' function. */
#cmakedefine EVENT__HAVE_FCNTL 1
/* Define to 1 if you have the <fcntl.h> header file. */
#cmakedefine EVENT__HAVE_FCNTL_H 1
/* Define to 1 if you have the `getaddrinfo' function. */
#cmakedefine EVENT__HAVE_GETADDRINFO 1
/* Define to 1 if you have the `getegid' function. */
#cmakedefine EVENT__HAVE_GETEGID 1
/* Define to 1 if you have the `geteuid' function. */
#cmakedefine EVENT__HAVE_GETEUID 1
/* TODO: Check for different gethostname argument counts. CheckPrototypeDefinition.cmake can be used. */
/* Define this if you have any gethostbyname_r() */
#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R 1
/* Define this if gethostbyname_r takes 3 arguments */
#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R_3_ARG 1
/* Define this if gethostbyname_r takes 5 arguments */
#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R_5_ARG 1
/* Define this if gethostbyname_r takes 6 arguments */
#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R_6_ARG 1
/* Define to 1 if you have the `getifaddrs' function. */
#cmakedefine EVENT__HAVE_GETIFADDRS 1
/* Define to 1 if you have the `getnameinfo' function. */
#cmakedefine EVENT__HAVE_GETNAMEINFO 1
/* Define to 1 if you have the `getprotobynumber' function. */
#cmakedefine EVENT__HAVE_GETPROTOBYNUMBER 1
/* Define to 1 if you have the `getservbyname' function. */
#cmakedefine EVENT__HAVE_GETSERVBYNAME 1
/* Define to 1 if you have the `gettimeofday' function. */
#cmakedefine EVENT__HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have the <ifaddrs.h> header file. */
#cmakedefine EVENT__HAVE_IFADDRS_H 1
/* Define to 1 if you have the `inet_ntop' function. */
#cmakedefine EVENT__HAVE_INET_NTOP 1
/* Define to 1 if you have the `inet_pton' function. */
#cmakedefine EVENT__HAVE_INET_PTON 1
/* Define to 1 if you have the <inttypes.h> header file. */
#cmakedefine EVENT__HAVE_INTTYPES_H 1
/* Define to 1 if you have the `issetugid' function. */
#cmakedefine EVENT__HAVE_ISSETUGID 1
/* Define to 1 if you have the `kqueue' function. */
#cmakedefine EVENT__HAVE_KQUEUE 1
/* Define if the system has zlib */
#cmakedefine EVENT__HAVE_LIBZ 1
/* Define to 1 if you have the `mach_absolute_time' function. */
#cmakedefine EVENT__HAVE_MACH_ABSOLUTE_TIME 1
/* Define to 1 if you have the <mach/mach_time.h> header file. */
#cmakedefine EVENT__HAVE_MACH_MACH_TIME_H 1
/* Define to 1 if you have the <memory.h> header file. */
#cmakedefine EVENT__HAVE_MEMORY_H 1
/* Define to 1 if you have the `mmap' function. */
#cmakedefine EVENT__HAVE_MMAP 1
/* Define to 1 if you have the `nanosleep' function. */
#cmakedefine EVENT__HAVE_NANOSLEEP 1
/* Define to 1 if you have the `usleep' function. */
#cmakedefine EVENT__HAVE_USLEEP 1
/* Define to 1 if you have the <netinet/in6.h> header file. */
#cmakedefine EVENT__HAVE_NETINET_IN6_H 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#cmakedefine EVENT__HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#cmakedefine EVENT__HAVE_NETINET_TCP_H 1
/* Define if the system has openssl */
#cmakedefine EVENT__HAVE_OPENSSL 1
/* Define to 1 if you have the `pipe' function. */
#cmakedefine EVENT__HAVE_PIPE 1
/* Define to 1 if you have the `pipe2' function. */
#cmakedefine EVENT__HAVE_PIPE2 1
/* Define to 1 if you have the `poll' function. */
#cmakedefine EVENT__HAVE_POLL 1
/* Define to 1 if you have the <poll.h> header file. */
#cmakedefine EVENT__HAVE_POLL_H 1
/* Define to 1 if you have the `port_create' function. */
#cmakedefine EVENT__HAVE_PORT_CREATE 1
/* Define to 1 if you have the <port.h> header file. */
#cmakedefine EVENT__HAVE_PORT_H 1
/* Define if we have pthreads on this system */
#cmakedefine EVENT__HAVE_PTHREADS 1
/* Define to 1 if you have the `putenv' function. */
#cmakedefine EVENT__HAVE_PUTENV 1
/* Define to 1 if the system has the type `sa_family_t'. */
#cmakedefine EVENT__HAVE_SA_FAMILY_T 1
/* Define to 1 if you have the `select' function. */
#cmakedefine EVENT__HAVE_SELECT 1
/* Define to 1 if you have the `setenv' function. */
#cmakedefine EVENT__HAVE_SETENV 1
/* Define if F_SETFD is defined in <fcntl.h> */
#cmakedefine EVENT__HAVE_SETFD 1
/* Define to 1 if you have the `setrlimit' function. */
#cmakedefine EVENT__HAVE_SETRLIMIT 1
/* Define to 1 if you have the `sendfile' function. */
#cmakedefine EVENT__HAVE_SENDFILE 1
/* Define to 1 if you have the `sigaction' function. */
#cmakedefine EVENT__HAVE_SIGACTION 1
/* Define to 1 if you have the `signal' function. */
#cmakedefine EVENT__HAVE_SIGNAL 1
/* Define to 1 if you have the `splice' function. */
#cmakedefine EVENT__HAVE_SPLICE 1
/* Define to 1 if you have the <stdarg.h> header file. */
#cmakedefine EVENT__HAVE_STDARG_H 1
/* Define to 1 if you have the <stddef.h> header file. */
#cmakedefine EVENT__HAVE_STDDEF_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine EVENT__HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#cmakedefine EVENT__HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine EVENT__HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#cmakedefine EVENT__HAVE_STRING_H 1
/* Define to 1 if you have the `strlcpy' function. */
#cmakedefine EVENT__HAVE_STRLCPY 1
/* Define to 1 if you have the `strsep' function. */
#cmakedefine EVENT__HAVE_STRSEP 1
/* Define to 1 if you have the `strtok_r' function. */
#cmakedefine EVENT__HAVE_STRTOK_R 1
/* Define to 1 if you have the `strtoll' function. */
#cmakedefine EVENT__HAVE_STRTOLL 1
/* Define to 1 if the system has the type `struct addrinfo'. */
#cmakedefine EVENT__HAVE_STRUCT_ADDRINFO 1
/* Define to 1 if the system has the type `struct in6_addr'. */
#cmakedefine EVENT__HAVE_STRUCT_IN6_ADDR 1
/* Define to 1 if `s6_addr16' is member of `struct in6_addr'. */
#cmakedefine EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
/* Define to 1 if `s6_addr32' is member of `struct in6_addr'. */
#cmakedefine EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
/* Define to 1 if the system has the type `struct sockaddr_in6'. */
#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
/* Define to 1 if `sin6_len' is member of `struct sockaddr_in6'. */
#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 1
/* Define to 1 if `sin_len' is member of `struct sockaddr_in'. */
#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1
/* Define to 1 if the system has the type `struct sockaddr_storage'. */
#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY 1
/* Define to 1 if the system has the type `struct linger'. */
#cmakedefine EVENT__HAVE_STRUCT_LINGER 1
/* Define to 1 if you have the `sysctl' function. */
#cmakedefine EVENT__HAVE_SYSCTL 1
/* Define to 1 if you have the <sys/devpoll.h> header file. */
#cmakedefine EVENT__HAVE_SYS_DEVPOLL_H 1
/* Define to 1 if you have the <sys/epoll.h> header file. */
#cmakedefine EVENT__HAVE_SYS_EPOLL_H 1
/* Define to 1 if you have the <sys/eventfd.h> header file. */
#cmakedefine EVENT__HAVE_SYS_EVENTFD_H 1
/* Define to 1 if you have the <sys/event.h> header file. */
#cmakedefine EVENT__HAVE_SYS_EVENT_H 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine EVENT__HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#cmakedefine EVENT__HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine EVENT__HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/queue.h> header file. */
#cmakedefine EVENT__HAVE_SYS_QUEUE_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine EVENT__HAVE_SYS_RESOURCE_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#cmakedefine EVENT__HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <sys/sendfile.h> header file. */
#cmakedefine EVENT__HAVE_SYS_SENDFILE_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#cmakedefine EVENT__HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine EVENT__HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/sysctl.h> header file. */
#cmakedefine EVENT__HAVE_SYS_SYSCTL_H 1
/* Define to 1 if you have the <sys/timerfd.h> header file. */
#cmakedefine EVENT__HAVE_SYS_TIMERFD_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#cmakedefine EVENT__HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine EVENT__HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/uio.h> header file. */
#cmakedefine EVENT__HAVE_SYS_UIO_H 1
/* Define to 1 if you have the <sys/wait.h> header file. */
#cmakedefine EVENT__HAVE_SYS_WAIT_H 1
/* Define to 1 if you have the <errno.h> header file. */
#cmakedefine EVENT__HAVE_ERRNO_H 1
/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
#cmakedefine EVENT__HAVE_TAILQFOREACH 1
/* Define if timeradd is defined in <sys/time.h> */
#cmakedefine EVENT__HAVE_TIMERADD 1
/* Define if timerclear is defined in <sys/time.h> */
#cmakedefine EVENT__HAVE_TIMERCLEAR 1
/* Define if timercmp is defined in <sys/time.h> */
#cmakedefine EVENT__HAVE_TIMERCMP 1
/* Define to 1 if you have the `timerfd_create' function. */
#cmakedefine EVENT__HAVE_TIMERFD_CREATE 1
/* Define if timerisset is defined in <sys/time.h> */
#cmakedefine EVENT__HAVE_TIMERISSET 1
/* Define to 1 if the system has the type `uint8_t'. */
#cmakedefine EVENT__HAVE_UINT8_T 1
/* Define to 1 if the system has the type `uint16_t'. */
#cmakedefine EVENT__HAVE_UINT16_T 1
/* Define to 1 if the system has the type `uint32_t'. */
#cmakedefine EVENT__HAVE_UINT32_T 1
/* Define to 1 if the system has the type `uint64_t'. */
#cmakedefine EVENT__HAVE_UINT64_T 1
/* Define to 1 if the system has the type `uintptr_t'. */
#cmakedefine EVENT__HAVE_UINTPTR_T 1
/* Define to 1 if you have the `umask' function. */
#cmakedefine EVENT__HAVE_UMASK 1
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine EVENT__HAVE_UNISTD_H 1
/* Define to 1 if you have the `unsetenv' function. */
#cmakedefine EVENT__HAVE_UNSETENV 1
/* Define to 1 if you have the `vasprintf' function. */
#cmakedefine EVENT__HAVE_VASPRINTF 1
/* Define if kqueue works correctly with pipes */
#cmakedefine EVENT__HAVE_WORKING_KQUEUE 1
#ifdef __USE_UNUSED_DEFINITIONS__
/* Define to necessary symbol if this constant uses a non-standard name on your system. */
/* XXX: Hello, this isn't even used, nor is it defined anywhere... - Ellzey */
#define EVENT__PTHREAD_CREATE_JOINABLE ${EVENT__PTHREAD_CREATE_JOINABLE}
#endif
/* The size of `pthread_t', as computed by sizeof. */
#define EVENT__SIZEOF_PTHREAD_T @EVENT__SIZEOF_PTHREAD_T@
/* The size of a `int', as computed by sizeof. */
#define EVENT__SIZEOF_INT @EVENT__SIZEOF_INT@
/* The size of a `long', as computed by sizeof. */
#define EVENT__SIZEOF_LONG @EVENT__SIZEOF_LONG@
/* The size of a `long long', as computed by sizeof. */
#define EVENT__SIZEOF_LONG_LONG @EVENT__SIZEOF_LONG_LONG@
/* The size of `off_t', as computed by sizeof. */
#define EVENT__SIZEOF_OFF_T @EVENT__SIZEOF_OFF_T@
#define EVENT__SIZEOF_SSIZE_T @EVENT__SIZEOF_SSIZE_T@
/* The size of a `short', as computed by sizeof. */
#define EVENT__SIZEOF_SHORT @EVENT__SIZEOF_SHORT@
/* The size of `size_t', as computed by sizeof. */
#define EVENT__SIZEOF_SIZE_T @EVENT__SIZEOF_SIZE_T@
/* Define to 1 if you have the ANSI C header files. */
#cmakedefine EVENT__STDC_HEADERS 1
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#cmakedefine EVENT__TIME_WITH_SYS_TIME 1
/* The size of `socklen_t', as computed by sizeof. */
#define EVENT__SIZEOF_SOCKLEN_T @EVENT__SIZEOF_SOCKLEN_T@
/* The size of 'void *', as computer by sizeof */
#define EVENT__SIZEOF_VOID_P @EVENT__SIZEOF_VOID_P@
/* set an alias for whatever __func__ __FUNCTION__ is, what sillyness */
#if defined (__func__)
#define EVENT____func__ __func__
#elif defined(__FUNCTION__)
#define EVENT____func__ __FUNCTION__
#else
#define EVENT____func__ __FILE__
#endif
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
/* why not c++?
*
* and are we really expected to use EVENT__inline everywhere,
* shouldn't we just do:
* ifdef EVENT__inline
* define inline EVENT__inline
*
* - Ellzey
*/
#define EVENT__inline @EVENT__inline@
#endif
/* Define to `int' if <sys/tyes.h> does not define. */
#define EVENT__pid_t @EVENT__pid_t@
/* Define to `unsigned' if <sys/types.h> does not define. */
#define EVENT__size_t @EVENT__size_t@
/* Define to unsigned int if you dont have it */
#define EVENT__socklen_t @EVENT__socklen_t@
/* Define to `int' if <sys/types.h> does not define. */
#define EVENT__ssize_t @EVENT__ssize_t@
#endif /* \EVENT2_EVENT_CONFIG_H_INCLUDED_ */
| Java |
<?php
/**
* Kodekit - http://timble.net/kodekit
*
* @copyright Copyright (C) 2007 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit for the canonical source repository
*/
namespace Kodekit\Library;
/**
* Controller Permission Interface
*
* @author Johan Janssens <https://github.com/johanjanssens>
* @package Kodekit\Library\Controller\Permission
*/
interface ControllerPermissionInterface
{
/**
* Permission handler for render actions
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canRender();
/**
* Permission handler for read actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canRead();
/**
* Permission handler for browse actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canBrowse();
/**
* Permission handler for add actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canAdd();
/**
* Permission handler for edit actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canEdit();
/**
* Permission handler for delete actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Returns TRUE if action is permitted. FALSE otherwise.
*/
public function canDelete();
} | Java |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CO4.Example.Fib
where
import Language.Haskell.TH (runIO)
import qualified Satchmo.Core.SAT.Minisat
import qualified Satchmo.Core.Decode
import CO4
import CO4.Prelude hiding (nat,uNat,Nat)
$( [d|
data Nat = Z | S Nat deriving Show
constraint p n = eq p (fib n)
fib x =
case x of
Z -> Z
S x' -> case x' of
Z -> S Z
S x'' -> let f1 = fib x'
f2 = fib x''
in
add f1 f2
eq x y = case x of
Z -> case y of Z -> True
_ -> False
S x' -> case y of Z -> False
S y' -> eq x' y'
add x y = case x of
Z -> y
S x' -> S (add x' y)
|] >>= compile [ImportPrelude,Cache]
)
uNat 0 = knownZ
uNat i = union knownZ $ knownS $ uNat $ i - 1
allocator = uNat 4
nat 0 = Z
nat i = S $ nat $ i - 1
result p = solveAndTestP (nat p) allocator encConstraint constraint
| Java |
// Font.cpp: ActionScript Font handling, for Gnash.
//
// Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software
// Foundation, Inc
//
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Based on the public domain work of Thatcher Ulrich <[email protected]> 2003
#include "smart_ptr.h" // GNASH_USE_GC
#include "Font.h"
#include "log.h"
#include "ShapeRecord.h"
#include "DefineFontTag.h"
#include "FreetypeGlyphsProvider.h"
#include <utility> // for std::make_pair
#include <memory>
namespace gnash {
namespace {
/// Reverse lookup of Glyph in CodeTable.
//
/// Inefficient, which is probably why TextSnapshot was designed like it
/// is.
class CodeLookup
{
public:
CodeLookup(const int glyph) : _glyph(glyph) {}
bool operator()(const std::pair<const boost::uint16_t, int>& p) {
return p.second == _glyph;
}
private:
int _glyph;
};
}
Font::GlyphInfo::GlyphInfo()
:
advance(0)
{}
Font::GlyphInfo::GlyphInfo(std::auto_ptr<SWF::ShapeRecord> glyph,
float advance)
:
glyph(glyph.release()),
advance(advance)
{}
Font::GlyphInfo::GlyphInfo(const GlyphInfo& o)
:
glyph(o.glyph),
advance(o.advance)
{}
Font::Font(std::auto_ptr<SWF::DefineFontTag> ft)
:
_fontTag(ft.release()),
_name(_fontTag->name()),
_unicodeChars(_fontTag->unicodeChars()),
_shiftJISChars(_fontTag->shiftJISChars()),
_ansiChars(_fontTag->ansiChars()),
_italic(_fontTag->italic()),
_bold(_fontTag->bold())
{
if (_fontTag->hasCodeTable()) _embeddedCodeTable = _fontTag->getCodeTable();
}
Font::Font(const std::string& name, bool bold, bool italic)
:
_fontTag(0),
_name(name),
_unicodeChars(false),
_shiftJISChars(false),
_ansiChars(true),
_italic(italic),
_bold(bold)
{
assert(!_name.empty());
}
Font::~Font()
{
}
SWF::ShapeRecord*
Font::get_glyph(int index, bool embedded) const
{
// What to do if embedded is true and this is a
// device-only font?
const GlyphInfoRecords& lookup = (embedded && _fontTag) ?
_fontTag->glyphTable() : _deviceGlyphTable;
if (index >= 0 && (size_t)index < lookup.size()) {
return lookup[index].glyph.get();
}
// TODO: should we log an error here ?
return 0;
}
void
Font::addFontNameInfo(const FontNameInfo& fontName)
{
if (!_displayName.empty() || !_copyrightName.empty())
{
IF_VERBOSE_MALFORMED_SWF(
log_swferror(_("Attempt to set font display or copyright name "
"again. This should mean there is more than one "
"DefineFontName tag referring to the same Font. Don't "
"know what to do in this case, so ignoring."));
);
return;
}
_displayName = fontName.displayName;
_copyrightName = fontName.copyrightName;
}
Font::GlyphInfoRecords::size_type
Font::glyphCount() const
{
assert(_fontTag);
return _fontTag->glyphTable().size();
}
void
Font::setFlags(boost::uint8_t flags)
{
_shiftJISChars = flags & (1 << 6);
_unicodeChars = flags & (1 << 5);
_ansiChars = flags & (1 << 4);
_italic = flags & (1 << 1);
_bold = flags & (1 << 0);
}
void
Font::setCodeTable(std::auto_ptr<CodeTable> table)
{
if (_embeddedCodeTable)
{
IF_VERBOSE_MALFORMED_SWF(
log_swferror(_("Attempt to add an embedded glyph CodeTable to "
"a font that already has one. This should mean there "
"are several DefineFontInfo tags, or a DefineFontInfo "
"tag refers to a font created by DefineFone2 or "
"DefineFont3. Don't know what should happen in this "
"case, so ignoring."));
);
return;
}
_embeddedCodeTable.reset(table.release());
}
void
Font::setName(const std::string& name)
{
_name = name;
}
boost::uint16_t
Font::codeTableLookup(int glyph, bool embedded) const
{
const CodeTable& ctable = (embedded && _embeddedCodeTable) ?
*_embeddedCodeTable : _deviceCodeTable;
CodeTable::const_iterator it = std::find_if(ctable.begin(), ctable.end(),
CodeLookup(glyph));
assert (it != ctable.end());
return it->first;
}
int
Font::get_glyph_index(boost::uint16_t code, bool embedded) const
{
const CodeTable& ctable = (embedded && _embeddedCodeTable) ?
*_embeddedCodeTable : _deviceCodeTable;
int glyph_index = -1;
CodeTable::const_iterator it = ctable.find(code);
if (it != ctable.end()) {
glyph_index = it->second;
return glyph_index;
}
// Try adding an os font, if possible
if (!embedded) {
glyph_index = const_cast<Font*>(this)->add_os_glyph(code);
}
return glyph_index;
}
float
Font::get_advance(int glyph_index, bool embedded) const
{
// What to do if embedded is true and this is a
// device-only font?
const GlyphInfoRecords& lookup = (embedded && _fontTag) ?
_fontTag->glyphTable() : _deviceGlyphTable;
if (glyph_index < 0) {
// Default advance.
return 512.0f;
}
assert(static_cast<size_t>(glyph_index) < lookup.size());
assert(glyph_index >= 0);
return lookup[glyph_index].advance;
}
// Return the adjustment in advance between the given two
// DisplayObjects. Normally this will be 0; i.e. the
float
Font::get_kerning_adjustment(int last_code, int code) const
{
kerning_pair k;
k.m_char0 = last_code;
k.m_char1 = code;
kernings_table::const_iterator it = m_kerning_pairs.find(k);
if (it != m_kerning_pairs.end()) {
float adjustment = it->second;
return adjustment;
}
return 0;
}
size_t
Font::unitsPerEM(bool embed) const
{
// the EM square is 1024 x 1024 for DefineFont up to 2
// and 20 as much for DefineFont3 up
if (embed) {
if ( _fontTag && _fontTag->subpixelFont() ) return 1024 * 20.0;
else return 1024;
}
FreetypeGlyphsProvider* ft = ftProvider();
if (!ft) {
log_error("Device font provider was not initialized, "
"can't get unitsPerEM");
return 0;
}
return ft->unitsPerEM();
}
int
Font::add_os_glyph(boost::uint16_t code)
{
FreetypeGlyphsProvider* ft = ftProvider();
if (!ft) return -1;
assert(_deviceCodeTable.find(code) == _deviceCodeTable.end());
float advance;
// Get the vectorial glyph
std::auto_ptr<SWF::ShapeRecord> sh = ft->getGlyph(code, advance);
if (!sh.get()) {
log_error("Could not create shape "
"glyph for DisplayObject code %u (%c) with "
"device font %s (%p)", code, code, _name, ft);
return -1;
}
// Find new glyph offset
int newOffset = _deviceGlyphTable.size();
// Add the new glyph id
_deviceCodeTable[code] = newOffset;
_deviceGlyphTable.push_back(GlyphInfo(sh, advance));
return newOffset;
}
bool
Font::matches(const std::string& name, bool bold, bool italic) const
{
return (_bold == bold && _italic == italic && name ==_name);
}
float
Font::leading() const {
return _fontTag ? _fontTag->leading() : 0.0f;
}
FreetypeGlyphsProvider*
Font::ftProvider() const
{
if (_ftProvider.get()) return _ftProvider.get();
if (_name.empty()) {
log_error("No name associated with this font, can't use device "
"fonts (should I use a default one?)");
return 0;
}
_ftProvider = FreetypeGlyphsProvider::createFace(_name, _bold, _italic);
if (!_ftProvider.get()) {
log_error("Could not create a freetype face %s", _name);
return 0;
}
return _ftProvider.get();
}
float
Font::ascent(bool embedded) const
{
if (embedded && _fontTag) return _fontTag->ascent();
FreetypeGlyphsProvider* ft = ftProvider();
if (ft) return ft->ascent();
return 0;
}
float
Font::descent(bool embedded) const
{
if (embedded && _fontTag) return _fontTag->descent();
FreetypeGlyphsProvider* ft = ftProvider();
if (ft) return ft->descent();
return 0;
}
bool
Font::is_subpixel_font() const {
return _fontTag ? _fontTag->subpixelFont() : false;
}
} // namespace gnash
// Local Variables:
// mode: C++
// indent-tabs-mode: t
// End:
| Java |
.container {
margin:10px;
} | Java |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2015 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Приступ одбијен',
'activated'=>'активиран',
'additional_options'=>'Додатне опције',
'admin_email'=>'Администратор Е-маил',
'admin_name'=>'Админ име',
'allow_usergalleries'=>'дозволи кориснику галерије',
'archive'=>'Архива',
'articles'=>'Чланци',
'autoresize'=>'Функција за промену величине слике',
'autoresize_js'=>'на основу Јавасцрипт',
'autoresize_off'=>'деактивиран',
'autoresize_php'=>'по ПХП',
'awards'=>'Награде',
'captcha'=>'Цаптцха',
'captcha_autodetect'=>'Аутоматско',
'captcha_bgcol'=>'Боја позадине',
'captcha_both'=>'оба',
'captcha_fontcol'=>'Боја фонта',
'captcha_image'=>'слика',
'captcha_linenoise'=>'сметње на линији',
'captcha_noise'=>'бука',
'captcha_only_math'=>'само математика',
'captcha_only_text'=>'само текст',
'captcha_text'=>'текст',
'captcha_type'=>'Тип Цаптцха',
'captcha_style'=>'Цаптцха стил',
'clan_name'=>'Име клана',
'clan_tag'=>'Клан ознака',
'clanwars'=>'РатКланова',
'comments'=>'Коментари',
'content_size'=>'Величина садржаја',
'deactivated'=>'деактивиран',
'default_language'=>'подразумевани језик',
'demos'=>'Демои',
'demos_top'=>'Топ 5 Демоа',
'demos_latest'=>'Последњих 5 Демоа',
'detect_visitor_language'=>'Одредити језик посетиоца',
'forum'=>'Форум',
'forum_posts'=>'Форум постови',
'forum_topics'=>'Форум Теме',
'format_date'=>'Формат датума',
'format_time'=>'Формат времена',
'files'=>'Фајлови',
'files_top'=>'Топ 5 Преузимања',
'files_latest'=>'Последњих 5 Преузимања',
'gallery'=>'Галерија',
'guestbook'=>'Књига гостију',
'headlines'=>'Наслови',
'insert_links'=>'убаците линкове чланова',
'latest_articles'=>'Најновији чланци',
'latest_results'=>'Последњи резултати',
'latest_topics'=>'најновије теме',
'login_duration'=>'Трајање пријаве',
'max_length_headlines'=>'макс. дужина наслова',
'max_length_latest_articles'=>'Макс. дужина последњих чланака',
'max_length_latest_topics'=>'Макс. дужина најновије теме',
'max_length_topnews'=>'Макс. дужина topnews',
'max_wrong_pw'=>'Макс. погрешних лозинки',
'messenger'=>'Гласник',
'msg_on_gb_entry'=>'Msg на GB унос',
'news'=>'Новости',
'other'=>'Други',
'page_title'=>'Почетна страница име',
'page_url'=>'УРЛ почетне странице',
'pagelock'=>'Закључај страницу',
'pictures'=>'Слике',
'profile_last_posts'=>'Профил последње поруке',
'public_admin'=>'Админ јавне зоне',
'registered_users'=>'Регистровани корисници',
'search_min_length'=>'Претрага мин. дужина',
'settings'=>'Подешавања',
'shoutbox'=>'Shoutbox',
'shoutbox_all_messages'=>'Shoutbox све поруке',
'shoutbox_refresh'=>'Shoutbox освежи',
'space_user'=>'Простор по кориснику (МБајт)',
'spam_check'=>'Потврди постове?',
'spamapiblockerror'=>'Блокирај Поруке?',
'spamapihost'=>'АПИ УРЛ адреса',
'spamapikey'=>'АПИ кључ',
'spamfilter'=>'Спам филтер',
'spammaxposts'=>'макс. Порука',
'sc_modules'=>'СЦ Модули',
'thumb_width'=>'Ширина палца',
'tooltip_1'=>'Ово је УРЛ ваше странице ЕГ (иоурдомаин.цом/патх/вебспелл). <br> Без хттп: // на почетку и не завршава са косом цртом! <br> Требало би да буде као',
'tooltip_2'=>'Ово је наслов ваше странице, приказан као прозор наслов',
'tooltip_3'=>'Назив ваше организације',
'tooltip_4'=>'Скраћени назив / ознака ваше организације',
'tooltip_5'=>'Име вебмастера = Ваше име',
'tooltip_6'=>'Е-маил адреса вебмастера',
'tooltip_7'=>'Максималне вести које су у потпуности приказане',
'tooltip_8'=>'Форум тема по страници',
'tooltip_9'=>'Слике по страници',
'tooltip_10'=>'Наведене Вести у архиви за страницу',
'tooltip_11'=>'Форум порука по страници',
'tooltip_12'=>'Величина (ширина) за Галерију тхумбс',
'tooltip_13'=>'Наслови наведени у sc_headlines',
'tooltip_14'=>'Теме наведене у latesttopics',
'tooltip_15'=>'Веб-простор за корисничке галерије по кориснику у Мбите',
'tooltip_16'=>'Максимална дужина заглавља у sc_headlines',
'tooltip_17'=>'Минимална дужина термина за претрагу',
'tooltip_18'=>'Да ли желите да дозволите корисничке галерије за сваког корисника?',
'tooltip_19'=>'Да ли желите да управљате галеријом слика директно на Вашој страници? (Боље бити изабран)',
'tooltip_20'=>'Чланака по страници',
'tooltip_21'=>'Награда по страници',
'tooltip_22'=>'Чланци наведени од sc_articles',
'tooltip_23'=>'Демоа по страници',
'tooltip_24'=>'Максимална дужина наслова чланака у sc_articles',
'tooltip_25'=>'Уноси у књигу гостију по страници',
'tooltip_26'=>'Коментара по страници',
'tooltip_27'=>'Порука по страници',
'tooltip_28'=>'РатКланова по страници',
'tooltip_29'=>'Регистрованих корисника по страници',
'tooltip_30'=>'Резултати наведени у sc_results',
'tooltip_31'=>'Најновије поруке које су наведене у профилу',
'tooltip_32'=>'Уноси наведени у sc_upcoming',
'tooltip_33'=>'Трајање да остану пријављени [у сатима] (0 = 20 минута)',
'tooltip_34'=>'Максимална величина (ширина) садржаја (слике, текст ,итд.) (0 = искључи)',
'tooltip_35'=>'Максимална величина (висина) садржаја (слика) (0 = искључи)',
'tooltip_36'=>'Треба ли Админима повратних информација порука о новим уносима у књигу гостију?',
'tooltip_37'=>'Shoutbox коментари који су приказани у shoutbox',
'tooltip_38'=>'Максимално сачуваних коментара у shoutbox',
'tooltip_39'=>'Период (у секундама) за shoutbox освежење',
'tooltip_40'=>'Подразумевани језик за сајт',
'tooltip_41'=>'Убаците линкове ка профилу члана аутоматски?',
'tooltip_42'=>'Максимална дужина теме у latesttopics',
'tooltip_43'=>'Максималан број погрешних уноса лозинке пре ИП бан-а',
'tooltip_44'=>'Приказ типа captcha',
'tooltip_45'=>'Боја позадине од captcha',
'tooltip_46'=>'Боја фонта од captcha',
'tooltip_47'=>'Садржај тип / стил captcha',
'tooltip_48'=>'Број буке-пиксела',
'tooltip_49'=>'Број буке-линија',
'tooltip_50'=>'Избор аутоматске функције за промену величине слике',
'tooltip_51'=>'Максимална дужина topnews у sc_topnews',
'tooltip_52'=>'Одредити језик посетиоца аутоматски',
'tooltip_53'=>'Потврдите поруке са екстерном базом података',
'tooltip_54'=>'Унесите свој Spam API кључ овде ако је доступан',
'tooltip_55'=>'Унесите УРЛ у АПИ хост сервера. <br> Уобичајено: хттпс://апи.вебспелл.орг',
'tooltip_56'=>'Број порука од када више неће бити потврђени од спољашње базе података',
'tooltip_57'=>'Блокирај постове, када дође до грешке',
'tooltip_58'=>'Излазни Формат датума',
'tooltip_59'=>'Излазни Формат времена',
'tooltip_60'=>'Омогући корисника књиге гостију на сајту?',
'tooltip_61'=>'Шта би требало да СБ Демо модул показује?',
'tooltip_62'=>'Шта би требало да СБ датотеке модула показују?',
'transaction_invalid'=>'ИД трансакције неважећи',
'upcoming_actions'=>'предстојеће акције',
'update'=>'ажурирање',
'user_guestbook'=>'Корисник Књиге гостију'
);
| Java |
using System.Linq;
using kino.Core.Framework;
using kino.Messaging;
namespace kino.Cluster
{
public partial class ScaleOutListener
{
private void ReceivedFromOtherNode(Message message)
{
if ((message.TraceOptions & MessageTraceOptions.Routing) == MessageTraceOptions.Routing)
{
var hops = string.Join("|",
message.GetMessageRouting()
.Select(h => $"{nameof(h.Uri)}:{h.Uri}/{h.Identity.GetAnyString()}"));
logger.Trace($"Message: {message} received from other node via hops {hops}");
}
}
}
} | Java |
Bitrix 17.0.9 Business Demo = f37a7cf627b2ec3aa4045ed4678789ad
| Java |
<?php
/**
* MyBB 1.8 Merge System
* Copyright 2014 MyBB Group, All Rights Reserved
*
* Website: http://www.mybb.com
* License: http://www.mybb.com/download/merge-system/license/
*/
// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}
class PHPBB3_Converter_Module_Pollvotes extends Converter_Module_Pollvotes {
var $settings = array(
'friendly_name' => 'poll votes',
'progress_column' => 'topic_id',
'default_per_screen' => 1000,
);
var $cache_poll_details = array();
function import()
{
global $import_session;
$query = $this->old_db->simple_select("poll_votes", "*", "", array('limit_start' => $this->trackers['start_pollvotes'], 'limit' => $import_session['pollvotes_per_screen']));
while($pollvote = $this->old_db->fetch_array($query))
{
$this->insert($pollvote);
}
}
function convert_data($data)
{
$insert_data = array();
// phpBB 3 values
$poll = $this->get_poll_details($data['topic_id']);
$insert_data['uid'] = $this->get_import->uid($data['vote_user_id']);
$insert_data['dateline'] = $poll['dateline'];
$insert_data['voteoption'] = $data['poll_option_id'];
$insert_data['pid'] = $poll['poll'];
return $insert_data;
}
function get_poll_details($tid)
{
global $db;
if(array_key_exists($tid, $this->cache_poll_details))
{
return $this->cache_poll_details[$tid];
}
$query = $db->simple_select("threads", "dateline,poll", "tid = '".$this->get_import->tid($tid)."'");
$poll = $db->fetch_array($query);
$db->free_result($query);
$this->cache_poll_details[$tid] = $poll;
return $poll;
}
function fetch_total()
{
global $import_session;
// Get number of poll votes
if(!isset($import_session['total_pollvotes']))
{
$query = $this->old_db->simple_select("poll_votes", "COUNT(*) as count");
$import_session['total_pollvotes'] = $this->old_db->fetch_field($query, 'count');
$this->old_db->free_result($query);
}
return $import_session['total_pollvotes'];
}
}
| Java |
#include <SDL_events.h>
class Engine
{
public:
static bool StaticInit();
virtual ~Engine();
static std::unique_ptr< Engine > sInstance;
virtual int Run();
void SetShouldKeepRunning( bool inShouldKeepRunning ) { mShouldKeepRunning = inShouldKeepRunning; }
virtual void HandleEvent( SDL_Event* inEvent );
protected:
Engine();
virtual void DoFrame();
private:
int DoRunLoop();
bool mShouldKeepRunning;
}; | Java |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
$installer->getConnection()->addColumn(
$installer->getTable('catalog_eav_attribute'),
'search_weight',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_FLOAT,
'unsigned' => true,
'nullable' => false,
'default' => '1',
'comment' => 'Search Weight'
]
);
$installer->endSetup();
}
}
| Java |
/*
* Copyright (C) 2012 Krawler Information Systems Pvt Ltd
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.krawler.portal.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* <a href="ListUtil.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
*
*/
public class ListUtil {
public static List copy(List master) {
if (master == null) {
return null;
}
return new ArrayList(master);
}
public static void copy(List master, List copy) {
if ((master == null) || (copy == null)) {
return;
}
copy.clear();
Iterator itr = master.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
copy.add(obj);
}
}
public static void distinct(List list) {
distinct(list, null);
}
public static void distinct(List list, Comparator comparator) {
if ((list == null) || (list.size() == 0)) {
return;
}
Set<Object> set = null;
if (comparator == null) {
set = new TreeSet<Object>();
}
else {
set = new TreeSet<Object>(comparator);
}
Iterator<Object> itr = list.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
if (set.contains(obj)) {
itr.remove();
}
else {
set.add(obj);
}
}
}
public static List fromArray(Object[] array) {
if ((array == null) || (array.length == 0)) {
return new ArrayList();
}
List list = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return list;
}
public static List fromCollection(Collection c) {
if ((c != null) && (c instanceof List)) {
return (List)c;
}
if ((c == null) || (c.size() == 0)) {
return new ArrayList();
}
List list = new ArrayList(c.size());
Iterator itr = c.iterator();
while (itr.hasNext()) {
list.add(itr.next());
}
return list;
}
public static List fromEnumeration(Enumeration enu) {
List list = new ArrayList();
while (enu.hasMoreElements()) {
Object obj = enu.nextElement();
list.add(obj);
}
return list;
}
public static List fromFile(String fileName) throws IOException {
return fromFile(new File(fileName));
}
public static List fromFile(File file) throws IOException {
List list = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
String s = StringPool.BLANK;
while ((s = br.readLine()) != null) {
list.add(s);
}
br.close();
return list;
}
public static List fromString(String s) {
return fromArray(StringUtil.split(s, StringPool.NEW_LINE));
}
public static List sort(List list) {
return sort(list, null);
}
public static List sort(List list, Comparator comparator) {
// if (list instanceof UnmodifiableList) {
// list = copy(list);
// }
//
// Collections.sort(list, comparator);
return list;
}
public static List subList(List list, int start, int end) {
List newList = new ArrayList();
int normalizedSize = list.size() - 1;
if ((start < 0) || (start > normalizedSize) || (end < 0) ||
(start > end)) {
return newList;
}
for (int i = start; i < end && i <= normalizedSize; i++) {
newList.add(list.get(i));
}
return newList;
}
public static List<Boolean> toList(boolean[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Boolean> list = new ArrayList<Boolean>(array.length);
for (boolean value : array) {
list.add(value);
}
return list;
}
public static List<Double> toList(double[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Double> list = new ArrayList<Double>(array.length);
for (double value : array) {
list.add(value);
}
return list;
}
public static List<Float> toList(float[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Float> list = new ArrayList<Float>(array.length);
for (float value : array) {
list.add(value);
}
return list;
}
public static List<Integer> toList(int[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Integer> list = new ArrayList<Integer>(array.length);
for (int value : array) {
list.add(value);
}
return list;
}
public static List<Long> toList(long[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Long> list = new ArrayList<Long>(array.length);
for (long value : array) {
list.add(value);
}
return list;
}
public static List<Short> toList(short[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Short> list = new ArrayList<Short>(array.length);
for (short value : array) {
list.add(value);
}
return list;
}
public static List<Boolean> toList(Boolean[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Boolean> list = new ArrayList<Boolean>(array.length);
for (Boolean value : array) {
list.add(value);
}
return list;
}
public static List<Double> toList(Double[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Double> list = new ArrayList<Double>(array.length);
for (Double value : array) {
list.add(value);
}
return list;
}
public static List<Float> toList(Float[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Float> list = new ArrayList<Float>(array.length);
for (Float value : array) {
list.add(value);
}
return list;
}
public static List<Integer> toList(Integer[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Integer> list = new ArrayList<Integer>(array.length);
for (Integer value : array) {
list.add(value);
}
return list;
}
public static List<Long> toList(Long[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Long> list = new ArrayList<Long>(array.length);
for (Long value : array) {
list.add(value);
}
return list;
}
public static List<Short> toList(Short[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Short> list = new ArrayList<Short>(array.length);
for (Short value : array) {
list.add(value);
}
return list;
}
public static List<String> toList(String[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<String> list = new ArrayList<String>(array.length);
for (String value : array) {
list.add(value);
}
return list;
}
public static String toString(List list, String param) {
return toString(list, param, StringPool.COMMA);
}
public static String toString(List list, String param, String delimiter) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
Object bean = list.get(i);
// Object value = BeanPropertiesUtil.getObject(bean, param);
//
// if (value == null) {
// value = StringPool.BLANK;
// }
//
// sb.append(value.toString());
if ((i + 1) != list.size()) {
sb.append(delimiter);
}
}
return sb.toString();
}
}
| Java |
/*
File: Carbon.h
Contains: Master include for all of Carbon
Version: QuickTime 7.3
Copyright: (c) 2007 (c) 2000-2001 by Apple Computer, Inc., all rights reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://developer.apple.com/bugreporter/
*/
#ifndef __CARBON__
#define __CARBON__
#ifndef __CORESERVICES__
#include "CoreServices.h"
#endif
#ifndef __APPLICATIONSERVICES__
#include "ApplicationServices.h"
#endif
#ifndef __APPLICATIONSERVICES__
#include "ApplicationServices.h"
#endif
#ifndef __HIOBJECT__
#include "HIObject.h"
#endif
#ifndef __HITOOLBAR__
#include "HIToolbar.h"
#endif
#ifndef __HIVIEW__
#include "HIView.h"
#endif
#ifndef __HITEXTUTILS__
#include "HITextUtils.h"
#endif
#ifndef __HISHAPE__
#include "HIShape.h"
#endif
#ifndef __BALLOONS__
#include "Balloons.h"
#endif
#ifndef __EVENTS__
#include "Events.h"
#endif
#ifndef __NOTIFICATION__
#include "Notification.h"
#endif
#ifndef __DRAG__
#include "Drag.h"
#endif
#ifndef __CONTROLS__
#include "Controls.h"
#endif
#ifndef __APPEARANCE__
#include "Appearance.h"
#endif
#ifndef __MACWINDOWS__
#include "MacWindows.h"
#endif
#ifndef __TEXTEDIT__
#include "TextEdit.h"
#endif
#ifndef __MENUS__
#include "Menus.h"
#endif
#ifndef __DIALOGS__
#include "Dialogs.h"
#endif
#ifndef __LISTS__
#include "Lists.h"
#endif
#ifndef __CARBONEVENTSCORE__
#include "CarbonEventsCore.h"
#endif
#ifndef __CARBONEVENTS__
#include "CarbonEvents.h"
#endif
#ifndef __TEXTSERVICES__
#include "TextServices.h"
#endif
#ifndef __SCRAP__
#include "Scrap.h"
#endif
#ifndef __MACTEXTEDITOR__
#include "MacTextEditor.h"
#endif
#ifndef __MACHELP__
#include "MacHelp.h"
#endif
#ifndef __CONTROLDEFINITIONS__
#include "ControlDefinitions.h"
#endif
#ifndef __TSMTE__
#include "TSMTE.h"
#endif
#ifndef __TRANSLATIONEXTENSIONS__
#include "TranslationExtensions.h"
#endif
#ifndef __TRANSLATION__
#include "Translation.h"
#endif
#ifndef __AEINTERACTION__
#include "AEInteraction.h"
#endif
#ifndef __TYPESELECT__
#include "TypeSelect.h"
#endif
#ifndef __MACAPPLICATION__
#include "MacApplication.h"
#endif
#ifndef __KEYBOARDS__
#include "Keyboards.h"
#endif
#ifndef __IBCARBONRUNTIME__
#include "IBCarbonRuntime.h"
#endif
#ifndef __CORESERVICES__
#include "CoreServices.h"
#endif
#ifndef __SOUND__
#include "Sound.h"
#endif
#ifndef __CORESERVICES__
#include "CoreServices.h"
#endif
#ifndef __OSA__
#include "OSA.h"
#endif
#ifndef __OSACOMP__
#include "OSAComp.h"
#endif
#ifndef __OSAGENERIC__
#include "OSAGeneric.h"
#endif
#ifndef __APPLESCRIPT__
#include "AppleScript.h"
#endif
#ifndef __ASDEBUGGING__
#include "ASDebugging.h"
#endif
#ifndef __ASREGISTRY__
#include "ASRegistry.h"
#endif
#ifndef __FINDERREGISTRY__
#include "FinderRegistry.h"
#endif
#ifndef __DIGITALHUBREGISTRY__
#include "DigitalHubRegistry.h"
#endif
#ifndef __APPLICATIONSERVICES__
#include "ApplicationServices.h"
#endif
#ifndef __PMAPPLICATION__
#include "PMApplication.h"
#endif
#ifndef __NAVIGATION__
#include "Navigation.h"
#endif
#ifndef __APPLICATIONSERVICES__
#include "ApplicationServices.h"
#endif
#ifndef __COLORPICKER__
#include "ColorPicker.h"
#endif
#ifndef __CMCALIBRATOR__
#include "CMCalibrator.h"
#endif
#ifndef __NSL__
#include "NSL.h"
#endif
#ifndef __FONTPANEL__
#include "FontPanel.h"
#endif
#ifndef __HTMLRENDERING__
#include "HTMLRendering.h"
#endif
#ifndef __SPEECHRECOGNITION__
#include "SpeechRecognition.h"
#endif
#ifndef __CORESERVICES__
#include "CoreServices.h"
#endif
#ifndef __KEYCHAINHI__
#include "KeychainHI.h"
#endif
#ifndef __URLACCESS__
#include "URLAccess.h"
#endif
#ifndef __CORESERVICES__
#include "CoreServices.h"
#endif
#ifndef __APPLEHELP__
#include "AppleHelp.h"
#endif
#ifndef __CORESERVICES__
#include "CoreServices.h"
#endif
#ifndef __ICAAPPLICATION__
#include "ICAApplication.h"
#endif
#ifndef __ICADEVICE__
#include "ICADevice.h"
#endif
#ifndef __ICACAMERA__
#include "ICACamera.h"
#endif
#endif /* __CARBON__ */
| Java |
<?php
/**
* Created by PhpStorm.
* User: mkt
* Date: 2015-10-28
* Time: 14:49
*/
namespace view;
require_once("view/ListView.php");
/**
* View that shows a list of unique sessions
* for a specific ip-number
*/
class SessionListView extends ListView
{
private $logSessions = array();
private static $loggedDate = "loggedDate";
private static $pageTitle = "Ip-address: ";
private static $sessionURL = "session";
//get list of unique session for that specific ip-number
public function getSessionList($selectedIP)
{
$logItems = $this->getLogItemsList();
foreach ($logItems as $logItem) {
$latest = $this->getLatestSession($logItem[$this->sessionId], $logItems);
if ($logItem[$this->ip] === $selectedIP) {
if($this->checkIfUnique($logItem[$this->sessionId], $this->sessionId, $this->logSessions)){
array_push($this->logSessions, [$this->sessionId => $logItem[$this->sessionId], Self::$loggedDate => $latest]);
}
}
}
$this->sortBy(Self::$loggedDate, $this->logSessions);
$this->renderHTML(Self::$pageTitle . $selectedIP, $this->renderSessionList());
}
/**
* @param $sessionId
* @param $logItems, array of ip-numbers, sessions, and dates
* @return mixed
* uses temporary array to sort session dates and get the latest logged
*/
private function getLatestSession($sessionId, $logItems)
{
$sessionDateArray = array();
foreach ($logItems as $logItem) {
$dateTime = $this->convertMicroTime($logItem[$this->microTime]);
if ($sessionId == $logItem[$this->sessionId]) {
if (!in_array($dateTime, $sessionDateArray)) {
array_push($sessionDateArray, $dateTime);
}
}
}
return end($sessionDateArray);
}
/**
* @return bool
* checks if user clicked sessionlink
* to view specific logged items in that session
*/
public function sessionLinkIsClicked() {
if (isset($_GET[self::$sessionURL]) ) {
return true;
}
return false;
}
private function getSessionUrl($session) {
return "?".self::$sessionURL."=$session";
}
public function getSession() {
assert($this->sessionLinkIsClicked());
return $_GET[self::$sessionURL];
}
/**
* @return string that represents HTML for that list of sessions
*/
private function renderSessionList()
{
$ret = "<ul>";
foreach ($this->logSessions as $sessions) {
$sessionId = $sessions[$this->sessionId];
$lastLogged = $sessions[Self::$loggedDate];
$sessionUrl = $this->getSessionUrl($sessions[$this->sessionId]);
$ret .= "<li>Session: <a href='$sessionUrl'>$sessionId</a></li>";
$ret .= "<li>Last logged: $lastLogged</li>";
$ret .= "<br>";
}
$ret .= "</ul>";
return $ret;
}
} | Java |
/**
* Copyright (c) 2012, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mail.compose;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import com.android.mail.providers.Account;
import com.android.mail.providers.Message;
import com.android.mail.providers.ReplyFromAccount;
import com.android.mail.utils.AccountUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.List;
public class FromAddressSpinner extends Spinner implements OnItemSelectedListener {
private List<Account> mAccounts;
private ReplyFromAccount mAccount;
private final List<ReplyFromAccount> mReplyFromAccounts = Lists.newArrayList();
private OnAccountChangedListener mAccountChangedListener;
public FromAddressSpinner(Context context) {
this(context, null);
}
public FromAddressSpinner(Context context, AttributeSet set) {
super(context, set);
}
public void setCurrentAccount(ReplyFromAccount account) {
mAccount = account;
selectCurrentAccount();
}
private void selectCurrentAccount() {
if (mAccount == null) {
return;
}
int currentIndex = 0;
for (ReplyFromAccount acct : mReplyFromAccounts) {
if (TextUtils.equals(mAccount.name, acct.name)
&& TextUtils.equals(mAccount.address, acct.address)) {
setSelection(currentIndex, true);
break;
}
currentIndex++;
}
}
public ReplyFromAccount getMatchingReplyFromAccount(String accountString) {
if (!TextUtils.isEmpty(accountString)) {
for (ReplyFromAccount acct : mReplyFromAccounts) {
if (accountString.equals(acct.address)) {
return acct;
}
}
}
return null;
}
public ReplyFromAccount getCurrentAccount() {
return mAccount;
}
/**
* @param action Action being performed; if this is COMPOSE, show all
* accounts. Otherwise, show just the account this was launched
* with.
* @param currentAccount Account used to launch activity.
* @param syncingAccounts
*/
public void initialize(int action, Account currentAccount, Account[] syncingAccounts,
Message refMessage) {
final List<Account> accounts = AccountUtils.mergeAccountLists(mAccounts,
syncingAccounts, true /* prioritizeAccountList */);
if (action == ComposeActivity.COMPOSE) {
mAccounts = accounts;
} else {
// First assume that we are going to use the current account as the reply account
Account replyAccount = currentAccount;
if (refMessage != null && refMessage.accountUri != null) {
// This is a reply or forward of a message access through the "combined" account.
// We want to make sure that the real account is in the spinner
for (Account account : accounts) {
if (account.uri.equals(refMessage.accountUri)) {
replyAccount = account;
break;
}
}
}
mAccounts = ImmutableList.of(replyAccount);
}
initFromSpinner();
}
@VisibleForTesting
protected void initFromSpinner() {
// If there are not yet any accounts in the cached synced accounts
// because this is the first time mail was opened, and it was opened
// directly to the compose activity, don't bother populating the reply
// from spinner yet.
if (mAccounts == null || mAccounts.size() == 0) {
return;
}
FromAddressSpinnerAdapter adapter =
new FromAddressSpinnerAdapter(getContext());
mReplyFromAccounts.clear();
for (Account account : mAccounts) {
mReplyFromAccounts.addAll(account.getReplyFroms());
}
adapter.addAccounts(mReplyFromAccounts);
setAdapter(adapter);
selectCurrentAccount();
setOnItemSelectedListener(this);
}
public List<ReplyFromAccount> getReplyFromAccounts() {
return mReplyFromAccounts;
}
public void setOnAccountChangedListener(OnAccountChangedListener listener) {
mAccountChangedListener = listener;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ReplyFromAccount selection = (ReplyFromAccount) getItemAtPosition(position);
if (!selection.address.equals(mAccount.address)) {
mAccount = selection;
mAccountChangedListener.onAccountChanged();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
/**
* Classes that want to know when a different account in the
* FromAddressSpinner has been selected should implement this interface.
* Note: if the user chooses the same account as the one that has already
* been selected, this method will not be called.
*/
public static interface OnAccountChangedListener {
public void onAccountChanged();
}
}
| Java |
-- 442
-- PKCColumnA
-- ListElementAdder with ChainedSupplier with PrimaryKeyConstraintSupplier and PrimaryKeyColumnsWithAlternativesSupplier - Added HCPID
CREATE TABLE "Users" (
"MID" INT PRIMARY KEY,
"Password" VARCHAR(20),
"Role" VARCHAR(20) NOT NULL,
"sQuestion" VARCHAR(100),
"sAnswer" VARCHAR(30),
CHECK ("Role" IN ('patient', 'admin', 'hcp', 'uap', 'er', 'tester', 'pha', 'lt'))
)
CREATE TABLE "Hospitals" (
"HospitalID" VARCHAR(10) PRIMARY KEY,
"HospitalName" VARCHAR(30) NOT NULL
)
CREATE TABLE "Personnel" (
"MID" INT PRIMARY KEY,
"AMID" INT,
"role" VARCHAR(20) NOT NULL,
"enabled" INT NOT NULL,
"lastName" VARCHAR(20) NOT NULL,
"firstName" VARCHAR(20) NOT NULL,
"address1" VARCHAR(20) NOT NULL,
"address2" VARCHAR(20) NOT NULL,
"city" VARCHAR(15) NOT NULL,
"state" VARCHAR(2) NOT NULL,
"zip" VARCHAR(10),
"zip1" VARCHAR(5),
"zip2" VARCHAR(4),
"phone" VARCHAR(12),
"phone1" VARCHAR(3),
"phone2" VARCHAR(3),
"phone3" VARCHAR(4),
"specialty" VARCHAR(40),
"email" VARCHAR(55),
"MessageFilter" VARCHAR(60),
CHECK ("role" IN ('admin', 'hcp', 'uap', 'er', 'tester', 'pha', 'lt')),
CHECK ("state" IN ('', 'AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY'))
)
CREATE TABLE "Patients" (
"MID" INT PRIMARY KEY,
"lastName" VARCHAR(20),
"firstName" VARCHAR(20),
"email" VARCHAR(55),
"address1" VARCHAR(20),
"address2" VARCHAR(20),
"city" VARCHAR(15),
"state" VARCHAR(2),
"zip1" VARCHAR(5),
"zip2" VARCHAR(4),
"phone1" VARCHAR(3),
"phone2" VARCHAR(3),
"phone3" VARCHAR(4),
"eName" VARCHAR(40),
"ePhone1" VARCHAR(3),
"ePhone2" VARCHAR(3),
"ePhone3" VARCHAR(4),
"iCName" VARCHAR(20),
"iCAddress1" VARCHAR(20),
"iCAddress2" VARCHAR(20),
"iCCity" VARCHAR(15),
"ICState" VARCHAR(2),
"iCZip1" VARCHAR(5),
"iCZip2" VARCHAR(4),
"iCPhone1" VARCHAR(3),
"iCPhone2" VARCHAR(3),
"iCPhone3" VARCHAR(4),
"iCID" VARCHAR(20),
"DateOfBirth" DATE,
"DateOfDeath" DATE,
"CauseOfDeath" VARCHAR(10),
"MotherMID" INT,
"FatherMID" INT,
"BloodType" VARCHAR(3),
"Ethnicity" VARCHAR(20),
"Gender" VARCHAR(13),
"TopicalNotes" VARCHAR(200),
"CreditCardType" VARCHAR(20),
"CreditCardNumber" VARCHAR(19),
"MessageFilter" VARCHAR(60),
"DirectionsToHome" VARCHAR(512),
"Religion" VARCHAR(64),
"Language" VARCHAR(32),
"SpiritualPractices" VARCHAR(100),
"AlternateName" VARCHAR(32),
CHECK ("state" IN ('AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY')),
CHECK ("ICState" IN ('AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY'))
)
CREATE TABLE "HistoryPatients" (
"ID" INT PRIMARY KEY,
"changeDate" DATE NOT NULL,
"changeMID" INT NOT NULL,
"MID" INT NOT NULL,
"lastName" VARCHAR(20),
"firstName" VARCHAR(20),
"email" VARCHAR(55),
"address1" VARCHAR(20),
"address2" VARCHAR(20),
"city" VARCHAR(15),
"state" CHAR(2),
"zip1" VARCHAR(5),
"zip2" VARCHAR(4),
"phone1" VARCHAR(3),
"phone2" VARCHAR(3),
"phone3" VARCHAR(4),
"eName" VARCHAR(40),
"ePhone1" VARCHAR(3),
"ePhone2" VARCHAR(3),
"ePhone3" VARCHAR(4),
"iCName" VARCHAR(20),
"iCAddress1" VARCHAR(20),
"iCAddress2" VARCHAR(20),
"iCCity" VARCHAR(15),
"ICState" VARCHAR(2),
"iCZip1" VARCHAR(5),
"iCZip2" VARCHAR(4),
"iCPhone1" VARCHAR(3),
"iCPhone2" VARCHAR(3),
"iCPhone3" VARCHAR(4),
"iCID" VARCHAR(20),
"DateOfBirth" DATE,
"DateOfDeath" DATE,
"CauseOfDeath" VARCHAR(10),
"MotherMID" INT,
"FatherMID" INT,
"BloodType" VARCHAR(3),
"Ethnicity" VARCHAR(20),
"Gender" VARCHAR(13),
"TopicalNotes" VARCHAR(200),
"CreditCardType" VARCHAR(20),
"CreditCardNumber" VARCHAR(19),
"MessageFilter" VARCHAR(60),
"DirectionsToHome" VARCHAR(100),
"Religion" VARCHAR(64),
"Language" VARCHAR(32),
"SpiritualPractices" VARCHAR(100),
"AlternateName" VARCHAR(32),
CHECK ("state" IN ('AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY')),
CHECK ("ICState" IN ('AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY'))
)
CREATE TABLE "LoginFailures" (
"ipaddress" VARCHAR(100) PRIMARY KEY NOT NULL,
"failureCount" INT NOT NULL,
"lastFailure" TIMESTAMP NOT NULL
)
CREATE TABLE "ResetPasswordFailures" (
"ipaddress" VARCHAR(128) PRIMARY KEY NOT NULL,
"failureCount" INT NOT NULL,
"lastFailure" TIMESTAMP NOT NULL
)
CREATE TABLE "icdcodes" (
"Code" NUMERIC(5, 2) PRIMARY KEY NOT NULL,
"Description" VARCHAR(50) NOT NULL,
"Chronic" VARCHAR(3) NOT NULL,
CHECK ("Chronic" IN ('no', 'yes'))
)
CREATE TABLE "CPTCodes" (
"Code" VARCHAR(5) PRIMARY KEY NOT NULL,
"Description" VARCHAR(30) NOT NULL,
"Attribute" VARCHAR(30)
)
CREATE TABLE "DrugReactionOverrideCodes" (
"Code" VARCHAR(5) PRIMARY KEY NOT NULL,
"Description" VARCHAR(80) NOT NULL
)
CREATE TABLE "NDCodes" (
"Code" VARCHAR(10) PRIMARY KEY NOT NULL,
"Description" VARCHAR(100) NOT NULL
)
CREATE TABLE "DrugInteractions" (
"FirstDrug" VARCHAR(9) NOT NULL,
"SecondDrug" VARCHAR(9) NOT NULL,
"Description" VARCHAR(100) NOT NULL,
PRIMARY KEY ("FirstDrug", "SecondDrug")
)
CREATE TABLE "TransactionLog" (
"transactionID" INT PRIMARY KEY NOT NULL,
"loggedInMID" INT NOT NULL,
"secondaryMID" INT NOT NULL,
"transactionCode" INT NOT NULL,
"timeLogged" TIMESTAMP NOT NULL,
"addedInfo" VARCHAR(255)
)
CREATE TABLE "HCPRelations" (
"HCP" INT NOT NULL,
"UAP" INT NOT NULL,
PRIMARY KEY ("HCP", "UAP")
)
CREATE TABLE "PersonalRelations" (
"PatientID" INT NOT NULL,
"RelativeID" INT NOT NULL,
"RelativeType" VARCHAR(35) NOT NULL
)
CREATE TABLE "Representatives" (
"representerMID" INT,
"representeeMID" INT,
PRIMARY KEY ("representerMID", "representeeMID")
)
CREATE TABLE "HCPAssignedHos" (
"hosID" VARCHAR(10) NOT NULL,
"HCPID" INT NOT NULL,
PRIMARY KEY ("hosID", "HCPID")
)
CREATE TABLE "DeclaredHCP" (
"PatientID" INT NOT NULL,
"HCPID" INT NOT NULL,
PRIMARY KEY ("PatientID", "HCPID")
)
CREATE TABLE "OfficeVisits" (
"ID" INT PRIMARY KEY,
"visitDate" DATE,
"HCPID" INT,
"notes" VARCHAR(50),
"PatientID" INT,
"HospitalID" VARCHAR(10)
)
CREATE TABLE "PersonalHealthInformation" (
"PatientID" INT NOT NULL,
"Height" INT,
"Weight" INT,
"Smoker" INT NOT NULL,
"SmokingStatus" INT NOT NULL,
"BloodPressureN" INT,
"BloodPressureD" INT,
"CholesterolHDL" INT,
"CholesterolLDL" INT,
"CholesterolTri" INT,
"HCPID" INT,
"AsOfDate" TIMESTAMP NOT NULL
)
CREATE TABLE "PersonalAllergies" (
"PatientID" INT NOT NULL,
"Allergy" VARCHAR(50) NOT NULL
)
CREATE TABLE "Allergies" (
"ID" INT PRIMARY KEY,
"PatientID" INT NOT NULL,
"Description" VARCHAR(50) NOT NULL,
"FirstFound" TIMESTAMP NOT NULL
)
CREATE TABLE "OVProcedure" (
"ID" INT,
"VisitID" INT NOT NULL,
"CPTCode" VARCHAR(5) NOT NULL,
"HCPID" VARCHAR(10) NOT NULL,
PRIMARY KEY ("ID", "HCPID")
)
CREATE TABLE "OVMedication" (
"ID" INT PRIMARY KEY,
"VisitID" INT NOT NULL,
"NDCode" VARCHAR(9) NOT NULL,
"StartDate" DATE,
"EndDate" DATE,
"Dosage" INT,
"Instructions" VARCHAR(500)
)
CREATE TABLE "OVReactionOverride" (
"ID" INT PRIMARY KEY,
"OVMedicationID" INT REFERENCES "OVMedication" ("ID") NOT NULL,
"OverrideCode" VARCHAR(5),
"OverrideComment" VARCHAR(255)
)
CREATE TABLE "OVDiagnosis" (
"ID" INT PRIMARY KEY,
"VisitID" INT NOT NULL,
"ICDCode" DECIMAL(5, 2) NOT NULL
)
CREATE TABLE "GlobalVariables" (
"Name" VARCHAR(20) PRIMARY KEY,
"Value" VARCHAR(20)
)
CREATE TABLE "FakeEmail" (
"ID" INT PRIMARY KEY,
"ToAddr" VARCHAR(100),
"FromAddr" VARCHAR(100),
"Subject" VARCHAR(500),
"Body" VARCHAR(2000),
"AddedDate" TIMESTAMP NOT NULL
)
CREATE TABLE "ReportRequests" (
"ID" INT PRIMARY KEY,
"RequesterMID" INT,
"PatientMID" INT,
"ApproverMID" INT,
"RequestedDate" TIMESTAMP,
"ApprovedDate" TIMESTAMP,
"ViewedDate" TIMESTAMP,
"Status" VARCHAR(30),
"Comment" VARCHAR(50)
)
CREATE TABLE "OVSurvey" (
"VisitID" INT PRIMARY KEY,
"SurveyDate" TIMESTAMP NOT NULL,
"WaitingRoomMinutes" INT,
"ExamRoomMinutes" INT,
"VisitSatisfaction" INT,
"TreatmentSatisfaction" INT
)
CREATE TABLE "LOINC" (
"LaboratoryProcedureCode" VARCHAR(7),
"Component" VARCHAR(100),
"KindOfProperty" VARCHAR(100),
"TimeAspect" VARCHAR(100),
"System" VARCHAR(100),
"ScaleType" VARCHAR(100),
"MethodType" VARCHAR(100)
)
CREATE TABLE "LabProcedure" (
"LaboratoryProcedureID" INT PRIMARY KEY,
"PatientMID" INT,
"LaboratoryProcedureCode" VARCHAR(7),
"Rights" VARCHAR(10),
"Status" VARCHAR(20),
"Commentary" VARCHAR(50),
"Results" VARCHAR(50),
"NumericalResults" VARCHAR(20),
"NumericalResultsUnit" VARCHAR(20),
"UpperBound" VARCHAR(20),
"LowerBound" VARCHAR(20),
"OfficeVisitID" INT,
"LabTechID" INT,
"PriorityCode" INT,
"ViewedByPatient" BOOLEAN NOT NULL,
"UpdatedDate" TIMESTAMP NOT NULL
)
CREATE TABLE "message" (
"message_id" INT,
"parent_msg_id" INT,
"from_id" INT NOT NULL,
"to_id" INT NOT NULL,
"sent_date" TIMESTAMP NOT NULL,
"message" VARCHAR(50),
"subject" VARCHAR(50),
"been_read" INT
)
CREATE TABLE "Appointment" (
"appt_id" INT PRIMARY KEY,
"doctor_id" INT NOT NULL,
"patient_id" INT NOT NULL,
"sched_date" TIMESTAMP NOT NULL,
"appt_type" VARCHAR(30) NOT NULL,
"comment" VARCHAR(50)
)
CREATE TABLE "AppointmentType" (
"apptType_id" INT PRIMARY KEY,
"appt_type" VARCHAR(30) NOT NULL,
"duration" INT NOT NULL
)
CREATE TABLE "referrals" (
"id" INT PRIMARY KEY,
"PatientID" INT NOT NULL,
"SenderID" INT NOT NULL,
"ReceiverID" INT NOT NULL,
"ReferralDetails" VARCHAR(50),
"OVID" INT NOT NULL,
"viewed_by_patient" BOOLEAN NOT NULL,
"viewed_by_HCP" BOOLEAN NOT NULL,
"TimeStamp" TIMESTAMP NOT NULL,
"PriorityCode" INT
)
CREATE TABLE "RemoteMonitoringData" (
"id" INT PRIMARY KEY,
"PatientID" INT NOT NULL,
"systolicBloodPressure" INT,
"diastolicBloodPressure" INT,
"glucoseLevel" INT,
"height" INT,
"weight" INT,
"pedometerReading" INT,
"timeLogged" TIMESTAMP NOT NULL,
"ReporterRole" VARCHAR(50),
"ReporterID" INT
)
CREATE TABLE "RemoteMonitoringLists" (
"PatientMID" INT,
"HCPMID" INT,
"SystolicBloodPressure" BOOLEAN,
"DiastolicBloodPressure" BOOLEAN,
"GlucoseLevel" BOOLEAN,
"Height" BOOLEAN,
"Weight" BOOLEAN,
"PedometerReading" BOOLEAN,
PRIMARY KEY ("PatientMID", "HCPMID")
)
CREATE TABLE "AdverseEvents" (
"id" INT PRIMARY KEY,
"Status" VARCHAR(10),
"PatientMID" INT,
"PresImmu" VARCHAR(50),
"Code" VARCHAR(20),
"Comment" VARCHAR(2000),
"Prescriber" INT,
"TimeLogged" TIMESTAMP
)
CREATE TABLE "ProfilePhotos" (
"MID" INT PRIMARY KEY,
"Photo" VARCHAR(50),
"UpdatedDate" TIMESTAMP NOT NULL
)
CREATE TABLE "PatientSpecificInstructions" (
"id" INT PRIMARY KEY,
"VisitID" INT,
"Modified" TIMESTAMP NOT NULL,
"Name" VARCHAR(100),
"URL" VARCHAR(250),
"Comment" VARCHAR(500)
)
CREATE TABLE "ReferralMessage" (
"messageID" INT NOT NULL,
"referralID" INT NOT NULL,
PRIMARY KEY ("messageID", "referralID")
)
| Java |
/* Header File for abc controller for use in simulink */
#ifndef _ABC_CONTROLLER_
#define _ABC_CONTROLLER_
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#include <limits.h>
#include "abc_controller_type.h"
extern void ABC_Controller(double input[16], double output[4], double bona_in[5], double save_data[12]);
extern float Derivative(float Prev_value, float Current_value, float Delta_t);
extern float lag_filter(float X, float tau, float Y_last);
#endif /* _ABC_CONTROLLER_ */
| Java |
#!/bin/sh
. ./include.sh
${examples_dir}precision > /dev/null
| Java |
# coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'%Y-%m-%d': '%Y.%m.%d.',
'%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S',
'%s rows deleted': '%s sorok t\xc3\xb6rl\xc5\x91dtek',
'%s rows updated': '%s sorok friss\xc3\xadt\xc5\x91dtek',
'Available databases and tables': 'El\xc3\xa9rhet\xc5\x91 adatb\xc3\xa1zisok \xc3\xa9s t\xc3\xa1bl\xc3\xa1k',
'Cannot be empty': 'Nem lehet \xc3\xbcres',
'Check to delete': 'T\xc3\xb6rl\xc3\xa9shez v\xc3\xa1laszd ki',
'Client IP': 'Client IP',
'Controller': 'Controller',
'Copyright': 'Copyright',
'Current request': 'Jelenlegi lek\xc3\xa9rdez\xc3\xa9s',
'Current response': 'Jelenlegi v\xc3\xa1lasz',
'Current session': 'Jelenlegi folyamat',
'DB Model': 'DB Model',
'Database': 'Adatb\xc3\xa1zis',
'Delete:': 'T\xc3\xb6r\xc3\xb6l:',
'Description': 'Description',
'E-mail': 'E-mail',
'Edit': 'Szerkeszt',
'Edit This App': 'Alkalmaz\xc3\xa1st szerkeszt',
'Edit current record': 'Aktu\xc3\xa1lis bejegyz\xc3\xa9s szerkeszt\xc3\xa9se',
'First name': 'First name',
'Group ID': 'Group ID',
'Hello World': 'Hello Vil\xc3\xa1g',
'Import/Export': 'Import/Export',
'Index': 'Index',
'Internal State': 'Internal State',
'Invalid Query': 'Hib\xc3\xa1s lek\xc3\xa9rdez\xc3\xa9s',
'Invalid email': 'Invalid email',
'Last name': 'Last name',
'Layout': 'Szerkezet',
'Main Menu': 'F\xc5\x91men\xc3\xbc',
'Menu Model': 'Men\xc3\xbc model',
'Name': 'Name',
'New Record': '\xc3\x9aj bejegyz\xc3\xa9s',
'No databases in this application': 'Nincs adatb\xc3\xa1zis ebben az alkalmaz\xc3\xa1sban',
'Origin': 'Origin',
'Password': 'Password',
'Powered by': 'Powered by',
'Query:': 'Lek\xc3\xa9rdez\xc3\xa9s:',
'Record ID': 'Record ID',
'Registration key': 'Registration key',
'Reset Password key': 'Reset Password key',
'Role': 'Role',
'Rows in table': 'Sorok a t\xc3\xa1bl\xc3\xa1ban',
'Rows selected': 'Kiv\xc3\xa1lasztott sorok',
'Stylesheet': 'Stylesheet',
'Sure you want to delete this object?': 'Biztos t\xc3\xb6rli ezt az objektumot?',
'Table name': 'Table name',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.',
'Timestamp': 'Timestamp',
'Update:': 'Friss\xc3\xadt:',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.',
'User ID': 'User ID',
'View': 'N\xc3\xa9zet',
'Welcome to web2py': 'Isten hozott a web2py-ban',
'appadmin is disabled because insecure channel': 'az appadmin a biztons\xc3\xa1gtalan csatorna miatt letiltva',
'cache': 'gyors\xc3\xadt\xc3\xb3t\xc3\xa1r',
'change password': 'jelsz\xc3\xb3 megv\xc3\xa1ltoztat\xc3\xa1sa',
'click here for online examples': 'online p\xc3\xa9ld\xc3\xa1k\xc3\xa9rt kattints ide',
'click here for the administrative interface': 'az adminisztr\xc3\xa1ci\xc3\xb3s fel\xc3\xbclet\xc3\xa9rt kattints ide',
'customize me!': 'v\xc3\xa1ltoztass meg!',
'data uploaded': 'adat felt\xc3\xb6ltve',
'database': 'adatb\xc3\xa1zis',
'database %s select': 'adatb\xc3\xa1zis %s kiv\xc3\xa1laszt\xc3\xa1s',
'db': 'db',
'design': 'design',
'done!': 'k\xc3\xa9sz!',
'edit profile': 'profil szerkeszt\xc3\xa9se',
'export as csv file': 'export\xc3\xa1l csv f\xc3\xa1jlba',
'insert new': '\xc3\xbaj beilleszt\xc3\xa9se',
'insert new %s': '\xc3\xbaj beilleszt\xc3\xa9se %s',
'invalid request': 'hib\xc3\xa1s k\xc3\xa9r\xc3\xa9s',
'login': 'bel\xc3\xa9p',
'logout': 'kil\xc3\xa9p',
'lost password': 'elveszett jelsz\xc3\xb3',
'new record inserted': '\xc3\xbaj bejegyz\xc3\xa9s felv\xc3\xa9ve',
'next 100 rows': 'k\xc3\xb6vetkez\xc5\x91 100 sor',
'or import from csv file': 'vagy bet\xc3\xb6lt\xc3\xa9s csv f\xc3\xa1jlb\xc3\xb3l',
'previous 100 rows': 'el\xc5\x91z\xc5\x91 100 sor',
'record': 'bejegyz\xc3\xa9s',
'record does not exist': 'bejegyz\xc3\xa9s nem l\xc3\xa9tezik',
'record id': 'bejegyz\xc3\xa9s id',
'register': 'regisztr\xc3\xa1ci\xc3\xb3',
'selected': 'kiv\xc3\xa1lasztott',
'state': '\xc3\xa1llapot',
'table': 't\xc3\xa1bla',
'unable to parse csv file': 'nem lehet a csv f\xc3\xa1jlt beolvasni',
}
| Java |
/*
* Copyright (C) 2009-2011 Andy Spencer <[email protected]>
*
* 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 <math.h>
#include <glib.h>
#include <gdk/gdkgl.h>
#include <gdk/gdkkeysyms.h>
#include <objects/grits-volume.h>
#include <objects/grits-callback.h>
#include <objects/marching.h>
#include <GL/gl.h>
#include <rsl.h>
#include <tester.h>
/******************
* iso ball setup *
******************/
static double dist = 0.75;
static gdouble distp(VolPoint *a,
gdouble bx, gdouble by, gdouble bz)
{
return 1/((a->c.x-bx)*(a->c.x-bx) +
(a->c.y-by)*(a->c.y-by) +
(a->c.z-bz)*(a->c.z-bz)) * 0.10;
//return 1-MIN(1,sqrt((a->c.x-bx)*(a->c.x-bx) +
// (a->c.y-by)*(a->c.y-by) +
// (a->c.z-bz)*(a->c.z-bz)));
}
static VolGrid *load_balls(float dist, int xs, int ys, int zs)
{
VolGrid *grid = vol_grid_new(xs, ys, zs);
for (int x = 0; x < xs; x++)
for (int y = 0; y < ys; y++)
for (int z = 0; z < zs; z++) {
VolPoint *point = vol_grid_get(grid, x, y, z);
point->c.x = ((double)x/(xs-1)*2-1);
point->c.y = ((double)y/(ys-1)*2-1);
point->c.z = ((double)z/(zs-1)*2-1);
point->value =
distp(point, -dist, 0, 0) +
distp(point, dist, 0, 0);
point->value *= 100;
}
return grid;
}
/***************
* radar setup *
***************/
/* Load the radar into a Grits Volume */
static void _cart_to_sphere(VolCoord *out, VolCoord *in)
{
gdouble angle = in->x;
gdouble dist = in->y;
gdouble tilt = in->z;
gdouble lx = sin(angle);
gdouble ly = cos(angle);
gdouble lz = sin(tilt);
out->x = (ly*dist)/20000;
out->y = (lz*dist)/10000-0.5;
out->z = (lx*dist)/20000-1.5;
}
static VolGrid *load_radar(gchar *file, gchar *site)
{
/* Load radar file */
RSL_read_these_sweeps("all", NULL);
Radar *rad = RSL_wsr88d_to_radar(file, site);
Volume *vol = RSL_get_volume(rad, DZ_INDEX);
RSL_sort_rays_in_volume(vol);
/* Count dimensions */
Sweep *sweep = vol->sweep[0];
Ray *ray = sweep->ray[0];
gint nsweeps = vol->h.nsweeps;
gint nrays = sweep->h.nrays/(1/sweep->h.beam_width)+1;
gint nbins = ray->h.nbins /(1000/ray->h.gate_size);
nbins = MIN(nbins, 100);
/* Convert to VolGrid */
VolGrid *grid = vol_grid_new(nrays, nbins, nsweeps);
gint rs, bs, val;
gint si=0, ri=0, bi=0;
for (si = 0; si < nsweeps; si++) {
sweep = vol->sweep[si];
rs = 1.0/sweep->h.beam_width;
for (ri = 0; ri < nrays; ri++) {
/* TODO: missing rays, pick ri based on azimuth */
ray = sweep->ray[(ri*rs) % sweep->h.nrays];
bs = 1000/ray->h.gate_size;
for (bi = 0; bi < nbins; bi++) {
if (bi*bs >= ray->h.nbins)
break;
val = ray->h.f(ray->range[bi*bs]);
if (val == BADVAL || val == RFVAL ||
val == APFLAG || val == NOECHO ||
val == NOTFOUND_H || val == NOTFOUND_V ||
val > 80)
val = 0;
VolPoint *point = vol_grid_get(grid, ri, bi, si);
point->value = val;
point->c.x = deg2rad(ray->h.azimuth);
point->c.y = bi*bs*ray->h.gate_size + ray->h.range_bin1;
point->c.z = deg2rad(ray->h.elev);
} } }
/* Convert to spherical coords */
for (si = 0; si < nsweeps; si++)
for (ri = 0; ri < nrays; ri++)
for (bi = 0; bi < nbins; bi++) {
VolPoint *point = vol_grid_get(grid, ri, bi, si);
if (point->c.y == 0)
point->value = nan("");
else
_cart_to_sphere(&point->c, &point->c);
}
return grid;
}
/**********
* Common *
**********/
static gboolean key_press(GritsTester *tester, GdkEventKey *event, GritsVolume *volume)
{
if (event->keyval == GDK_KEY_v) grits_volume_set_level(volume, volume->level-0.5);
else if (event->keyval == GDK_KEY_V) grits_volume_set_level(volume, volume->level+0.5);
else if (event->keyval == GDK_KEY_d) dist += 0.5;
else if (event->keyval == GDK_KEY_D) dist -= 0.5;
return FALSE;
}
/********
* Main *
********/
int main(int argc, char **argv)
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GritsTester *tester = grits_tester_new();
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(tester));
gtk_widget_show_all(window);
/* Grits Volume */
VolGrid *balls_grid = load_balls(dist, 50, 50, 50);
GritsVolume *balls = grits_volume_new(balls_grid);
balls->proj = GRITS_VOLUME_CARTESIAN;
balls->disp = GRITS_VOLUME_SURFACE;
balls->color[0] = (0.8)*0xff;
balls->color[1] = (0.6)*0xff;
balls->color[2] = (0.2)*0xff;
balls->color[3] = (1.0)*0xff;
grits_volume_set_level(balls, 50);
grits_tester_add(tester, GRITS_OBJECT(balls));
g_signal_connect(tester, "key-press-event", G_CALLBACK(key_press), balls);
/* Grits Volume */
//char *file = "/home/andy/.cache/grits/nexrad/level2/KGWX/KGWX_20101130_0459.raw";
//char *file = "/home/andy/.cache/grits/nexrad/level2/KTLX/KTLX_19990503_2351.raw";
//VolGrid *radar_grid = load_radar(file, "KTLX");
//GritsVolume *radar = grits_volume_new(radar_grid);
//radar->proj = GRITS_VOLUME_SPHERICAL;
//radar->disp = GRITS_VOLUME_SURFACE;
//radar->color[0] = (0.8)*0xff;
//radar->color[1] = (0.6)*0xff;
//radar->color[2] = (0.2)*0xff;
//radar->color[3] = (1.0)*0xff;
//grits_volume_set_level(radar, 50);
//grits_tester_add(tester, GRITS_OBJECT(radar));
//g_signal_connect(tester, "key-press-event", G_CALLBACK(key_press), radar);
/* Go */
gtk_main();
return 0;
}
| Java |
#!/usr/bin/perl
#---------------------------------
# Copyright 2011 ByWater Solutions
#
#---------------------------------
#
# -D Ruth Bavousett
#
#---------------------------------
#
# EXPECTS:
# -nothing
#
# DOES:
# -corrects borrower zipcodes that start with zero, if --update is given
#
# CREATES:
# -nothing
#
# REPORTS:
# -what would be changed, if --debug is given
# -count of records examined
# -count of record modified
use autodie;
use strict;
use warnings;
use Carp;
use Data::Dumper;
use English qw( -no_match_vars );
use Getopt::Long;
use Readonly;
use Text::CSV_XS;
local $OUTPUT_AUTOFLUSH = 1;
Readonly my $NULL_STRING => q{};
my $debug = 0;
my $doo_eet = 0;
my $i = 0;
my $written = 0;
my $modified = 0;
my $problem = 0;
my $input_filename = "";
GetOptions(
'debug' => \$debug,
'update' => \$doo_eet,
);
#for my $var ($input_filename) {
# croak ("You're missing something") if $var eq $NULL_STRING;
#}
use C4::Context;
use C4::Members;
my $dbh = C4::Context->dbh();
my $query = "SELECT borrowernumber,zipcode FROM borrowers where zipcode is not null and zipcode != ''";
my $find = $dbh->prepare($query);
$find->execute();
LINE:
while (my $line=$find->fetchrow_hashref()) {
last LINE if ($debug && $doo_eet && $modified >0);
$i++;
print '.' unless ($i % 10);
print "\r$i" unless ($i % 100);
next LINE if ($line->{zipcode} !~ m/^\d+$/);
next LINE if (length($line->{zipcode}) >= 5);
my $newzip = sprintf "%05d",$line->{zipcode};
$debug and print "Borrower: $line->{borrowernumber} Changing $line->{zipcode} to $newzip.\n";
if ($doo_eet){
C4::Members::ModMember(borrowernumber => $line->{'borrowernumber'},
zipcode => $newzip,
);
}
$modified++;
}
print << "END_REPORT";
$i records found.
$modified records updated.
END_REPORT
exit;
| Java |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FEFTwiddler.GUI.UnitViewer
{
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public partial class DragonVein : UserControl
{
private Model.Unit _unit;
public DragonVein()
{
InitializeComponent();
InitializeControls();
}
public void LoadUnit(Model.Unit unit)
{
_unit = unit;
PopulateControls();
}
private void InitializeControls()
{
}
private void PopulateControls()
{
var characterData = Data.Database.Characters.GetByID(_unit.CharacterID);
if (characterData != null)
{
var isDefault = characterData.CanUseDragonVein;
chkDragonVein.Checked = _unit.Trait_CanUseDragonVein || isDefault;
chkDragonVein.Enabled = !isDefault;
}
else
{
chkDragonVein.Checked = _unit.Trait_CanUseDragonVein;
}
}
private void chkDragonVein_CheckedChanged(object sender, EventArgs e)
{
var characterData = Data.Database.Characters.GetByID(_unit.CharacterID);
// If a character can't use Dragon Vein by default
if (chkDragonVein.Checked && characterData != null && !characterData.CanUseDragonVein)
_unit.Trait_CanUseDragonVein = true;
else
_unit.Trait_CanUseDragonVein = false;
}
}
}
| Java |
using UnityEngine;
using System.Collections;
using System;
namespace Frontiers.World.WIScripts
{
public class Key : WIScript
{
public override void OnInitialized ()
{
if (!worlditem.Is <QuestItem> ()) {
worlditem.Props.Name.DisplayName = State.KeyName;
}
}
public KeyState State = new KeyState ();
}
[Serializable]
public class KeyState
{
public bool DisappearFromInventory = true;
public string KeyType = "SimpleKey";
public string KeyTag = "Master";
public string KeyName = "Key";
}
}
| Java |
define(
"dojo/cldr/nls/nb/gregorian", //begin v1.x content
{
"dateFormatItem-Ehm": "E h.mm a",
"days-standAlone-short": [
"sø.",
"ma.",
"ti.",
"on.",
"to.",
"fr.",
"lø."
],
"months-format-narrow": [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"field-second-relative+0": "nå",
"quarters-standAlone-narrow": [
"1",
"2",
"3",
"4"
],
"field-weekday": "Ukedag",
"dateFormatItem-yQQQ": "QQQ y",
"dateFormatItem-yMEd": "E d.MM.y",
"field-wed-relative+0": "onsdag denne uken",
"dateFormatItem-GyMMMEd": "E d. MMM y G",
"dateFormatItem-MMMEd": "E d. MMM",
"field-wed-relative+1": "onsdag neste uke",
"eraNarrow": [
"f.Kr.",
"fvt.",
"e.Kr.",
"vt"
],
"dateFormatItem-yMM": "MM.y",
"field-tue-relative+-1": "tirsdag sist uke",
"days-format-short": [
"sø.",
"ma.",
"ti.",
"on.",
"to.",
"fr.",
"lø."
],
"dateFormat-long": "d. MMMM y",
"field-fri-relative+-1": "fredag sist uke",
"field-wed-relative+-1": "onsdag sist uke",
"months-format-wide": [
"januar",
"februar",
"mars",
"april",
"mai",
"juni",
"juli",
"august",
"september",
"oktober",
"november",
"desember"
],
"dateTimeFormat-medium": "{1}, {0}",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-full": "EEEE d. MMMM y",
"field-thu-relative+-1": "torsdag sist uke",
"dateFormatItem-Md": "d.M.",
"dayPeriods-format-abbr-am": "a.m.",
"dateFormatItem-yMd": "d.M.y",
"dateFormatItem-yM": "M.y",
"field-era": "Tidsalder",
"months-standAlone-wide": [
"januar",
"februar",
"mars",
"april",
"mai",
"juni",
"juli",
"august",
"september",
"oktober",
"november",
"desember"
],
"timeFormat-short": "HH.mm",
"quarters-format-wide": [
"1. kvartal",
"2. kvartal",
"3. kvartal",
"4. kvartal"
],
"timeFormat-long": "HH.mm.ss z",
"dateFormatItem-yMMM": "MMM y",
"dateFormatItem-yQQQQ": "QQQQ y",
"field-year": "År",
"dateFormatItem-MMdd": "d.M.",
"field-hour": "Time",
"months-format-abbr": [
"jan.",
"feb.",
"mar.",
"apr.",
"mai",
"jun.",
"jul.",
"aug.",
"sep.",
"okt.",
"nov.",
"des."
],
"field-sat-relative+0": "lørdag denne uken",
"field-sat-relative+1": "lørdag neste uke",
"timeFormat-full": "HH.mm.ss zzzz",
"field-day-relative+0": "i dag",
"field-day-relative+1": "i morgen",
"field-thu-relative+0": "torsdag denne uken",
"dateFormatItem-GyMMMd": "d. MMM y G",
"field-day-relative+2": "i overmorgen",
"field-thu-relative+1": "torsdag neste uke",
"dateFormatItem-H": "HH",
"months-standAlone-abbr": [
"jan",
"feb",
"mar",
"apr",
"mai",
"jun",
"jul",
"aug",
"sep",
"okt",
"nov",
"des"
],
"quarters-format-abbr": [
"K1",
"K2",
"K3",
"K4"
],
"quarters-standAlone-wide": [
"1. kvartal",
"2. kvartal",
"3. kvartal",
"4. kvartal"
],
"dateFormatItem-Gy": "y G",
"dateFormatItem-M": "L.",
"days-standAlone-wide": [
"søndag",
"mandag",
"tirsdag",
"onsdag",
"torsdag",
"fredag",
"lørdag"
],
"timeFormat-medium": "HH.mm.ss",
"field-sun-relative+0": "søndag denne uken",
"dateFormatItem-Hm": "HH.mm",
"quarters-standAlone-abbr": [
"K1",
"K2",
"K3",
"K4"
],
"field-sun-relative+1": "søndag neste uke",
"eraAbbr": [
"f.Kr.",
"e.Kr."
],
"field-minute": "Minutt",
"field-dayperiod": "AM/PM",
"days-standAlone-abbr": [
"sø.",
"ma.",
"ti.",
"on.",
"to.",
"fr.",
"lø."
],
"dateFormatItem-d": "d.",
"dateFormatItem-ms": "mm.ss",
"quarters-format-narrow": [
"1",
"2",
"3",
"4"
],
"field-day-relative+-1": "i går",
"dateFormatItem-h": "h a",
"dateTimeFormat-long": "{1} 'kl.' {0}",
"dayPeriods-format-narrow-am": "a",
"field-day-relative+-2": "i forgårs",
"dateFormatItem-MMMd": "d. MMM",
"dateFormatItem-MEd": "E d.M",
"dateTimeFormat-full": "{1} {0}",
"field-fri-relative+0": "fredag denne uken",
"dateFormatItem-yMMMM": "MMMM y",
"field-fri-relative+1": "fredag neste uke",
"field-day": "Dag",
"days-format-wide": [
"søndag",
"mandag",
"tirsdag",
"onsdag",
"torsdag",
"fredag",
"lørdag"
],
"field-zone": "Tidssone",
"dateFormatItem-y": "y",
"months-standAlone-narrow": [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"field-year-relative+-1": "i fjor",
"field-month-relative+-1": "forrige måned",
"dateFormatItem-hm": "h.mm a",
"dayPeriods-format-abbr-pm": "p.m.",
"days-format-abbr": [
"søn.",
"man.",
"tir.",
"ons.",
"tor.",
"fre.",
"lør."
],
"eraNames": [
"f.Kr.",
"e.Kr."
],
"dateFormatItem-yMMMd": "d. MMM y",
"days-format-narrow": [
"S",
"M",
"T",
"O",
"T",
"F",
"L"
],
"days-standAlone-narrow": [
"S",
"M",
"T",
"O",
"T",
"F",
"L"
],
"dateFormatItem-MMM": "LLL",
"field-month": "Måned",
"field-tue-relative+0": "tirsdag denne uken",
"field-tue-relative+1": "tirsdag neste uke",
"dayPeriods-format-wide-am": "a.m.",
"dateFormatItem-EHm": "E HH.mm",
"field-mon-relative+0": "mandag denne uken",
"field-mon-relative+1": "mandag neste uke",
"dateFormat-short": "dd.MM.y",
"dateFormatItem-EHms": "E HH.mm.ss",
"dateFormatItem-Ehms": "E h.mm.ss a",
"field-second": "Sekund",
"field-sat-relative+-1": "lørdag sist uke",
"dateFormatItem-yMMMEd": "E d. MMM y",
"field-sun-relative+-1": "søndag sist uke",
"field-month-relative+0": "denne måneden",
"field-month-relative+1": "neste måned",
"dateFormatItem-Ed": "E d.",
"dateTimeFormats-appendItem-Timezone": "{0} {1}",
"field-week": "Uke",
"dateFormat-medium": "d. MMM y",
"field-year-relative+0": "i år",
"field-week-relative+-1": "forrige uke",
"field-year-relative+1": "neste år",
"dayPeriods-format-narrow-pm": "p",
"dateTimeFormat-short": "{1}, {0}",
"dateFormatItem-Hms": "HH.mm.ss",
"dateFormatItem-hms": "h.mm.ss a",
"dateFormatItem-GyMMM": "MMM y G",
"field-mon-relative+-1": "mandag sist uke",
"field-week-relative+0": "denne uken",
"field-week-relative+1": "neste uke"
}
//end v1.x content
); | Java |
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['button-content'],
audio: Ember.inject.service(),
soundName: null,
rate: 1,
preloadSounds: function() {
this.get('audio');
}.on('init'),
actions: {
play() {
this.get('audio').play(this.get('soundName'), this.get('rate'));
}
}
});
| Java |
/*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cfa.model;
import org.sosy_lab.cpachecker.cfa.ast.FileLocation;
import org.sosy_lab.cpachecker.cfa.ast.ADeclaration;
import com.google.common.base.Optional;
public class ADeclarationEdge extends AbstractCFAEdge {
protected final ADeclaration declaration;
protected ADeclarationEdge(final String pRawSignature, final FileLocation pFileLocation,
final CFANode pPredecessor, final CFANode pSuccessor, final ADeclaration pDeclaration) {
super(pRawSignature, pFileLocation, pPredecessor, pSuccessor);
declaration = pDeclaration;
}
@Override
public CFAEdgeType getEdgeType() {
return CFAEdgeType.DeclarationEdge;
}
public ADeclaration getDeclaration() {
return declaration;
}
@Override
public Optional<? extends ADeclaration> getRawAST() {
return Optional.of(declaration);
}
@Override
public String getCode() {
return declaration.toASTString();
}
}
| Java |
<?php
// Copyright (C) <2015> <it-novum GmbH>
//
// This file is dual licensed
//
// 1.
// 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, version 3 of the License.
//
// 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/>.
//
// 2.
// If you purchased an openITCOCKPIT Enterprise Edition you can use this file
// under the terms of the openITCOCKPIT Enterprise Edition license agreement.
// License agreement and license key will be shipped with the order
// confirmation.
?>
<div class="row">
<div class="col-xs-12 col-md-2 text-muted">
<center><span id="selectionCount"></span></center>
</div>
<div class="col-xs-12 col-md-2 "><span id="selectAllDowntimes" class="pointer"><i
class="fa fa-lg fa-check-square-o"></i> <?php echo __('Select all'); ?></span></div>
<div class="col-xs-12 col-md-2"><span id="untickAllDowntimes" class="pointer"><i
class="fa fa-lg fa-square-o"></i> <?php echo __('Undo selection'); ?></span></div>
<div class="col-xs-12 col-md-2">
<?php if ($this->Acl->hasPermission('delete', 'Services', '')): ?>
<a href="javascript:void(0);" id="deleteAllServiceDowntimes" class="txt-color-red"
style="text-decoration: none;"> <i
class="fa fa-lg fa-trash-o"></i> <?php echo __('Delete'); ?></a>
<?php endif; ?>
</div>
</div> | Java |
<?php
/* Copyright (C) 2012 Regis Houssin <[email protected]>
*
* 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/>.
*/
$languages = array(
'CHARSET' => 'UTF-8',
'Language_ar_AR' => 'Arabia',
'Language_ar_SA' => 'Arabic',
'Language_bg_BG' => 'Bulgarian',
'Language_ca_ES' => 'Katalaani',
'Language_da_DA' => 'Tanska',
'Language_da_DK' => 'Tanska',
'Language_de_DE' => 'Saksa',
'Language_de_AT' => 'Saksa (Itävalta)',
'Language_el_GR' => 'Kreikkalainen',
'Language_en_AU' => 'Englanti (Australia)',
'Language_en_GB' => 'Englanti (Yhdistynyt kuningaskunta)',
'Language_en_IN' => 'Englanti (Intia)',
'Language_en_NZ' => 'Englanti (Uusi-Seelanti)',
'Language_en_US' => 'Englanti (Yhdysvallat)',
'Language_es_ES' => 'Espanjalainen',
'Language_es_AR' => 'Espanja (Argentiina)',
'Language_es_HN' => 'Espanja (Honduras)',
'Language_es_MX' => 'Espanja (Meksiko)',
'Language_es_PR' => 'Espanja (Puerto Rico)',
'Language_et_EE' => 'Estonian',
'Language_fa_IR' => 'Persialainen',
'Language_fi_FI' => 'Fins',
'Language_fr_BE' => 'Ranska (Belgia)',
'Language_fr_CA' => 'Ranska (Kanada)',
'Language_fr_CH' => 'Ranska (Sveitsi)',
'Language_fr_FR' => 'Ranskalainen',
'Language_he_IL' => 'Hebrew',
'Language_hu_HU' => 'Unkari',
'Language_is_IS' => 'Islannin',
'Language_it_IT' => 'Italialainen',
'Language_ja_JP' => 'Japanin kieli',
'Language_nb_NO' => 'Norja (bokmål)',
'Language_nl_BE' => 'Hollanti (Belgia)',
'Language_nl_NL' => 'Hollanti (Alankomaat)',
'Language_pl_PL' => 'Puola',
'Language_pt_BR' => 'Portugali (Brasilia)',
'Language_pt_PT' => 'Portugali',
'Language_ro_RO' => 'Romanialainen',
'Language_ru_RU' => 'Venäläinen',
'Language_ru_UA' => 'Venäjä (Ukraina)',
'Language_tr_TR' => 'Turkki',
'Language_sl_SI' => 'Slovenian',
'Language_sv_SV' => 'Ruotsi',
'Language_sv_SE' => 'Ruotsi',
'Language_zh_CN' => 'Kiinalainen',
'Language_is_IS' => 'Islannin'
);
?> | Java |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExtentTest.cs" company="Allors bvba">
// Copyright 2002-2012 Allors bvba.
//
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
//
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Platform 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.
//
// For more information visit http://www.allors.com/legal
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Allors.Adapters.Object.SqlClient
{
using System.Linq;
using Allors;
using Allors.Domain;
using Allors.Meta;
using Xunit;
public abstract class ExtentTest : Adapters.ExtentTest
{
[Fact]
public override void SortOne()
{
foreach (var init in this.Inits)
{
foreach (var marker in this.Markers)
{
init();
this.Populate();
this.Session.Commit();
this.c1B.C1AllorsString = "3";
this.c1C.C1AllorsString = "1";
this.c1D.C1AllorsString = "2";
this.Session.Commit();
marker();
var extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
var sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1C, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1B, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1C, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1B, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1C, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1B, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1B, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1C, sortedObjects[2]);
Assert.Equal(this.c1A, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1B, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1C, sortedObjects[2]);
Assert.Equal(this.c1A, sortedObjects[3]);
foreach (var useOperator in this.UseOperator)
{
if (useOperator)
{
marker();
var firstExtent = this.Session.Extent(MetaC1.Instance.ObjectType);
firstExtent.Filter.AddLike(MetaC1.Instance.C1AllorsString, "1");
var secondExtent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent = this.Session.Union(firstExtent, secondExtent);
secondExtent.Filter.AddLike(MetaC1.Instance.C1AllorsString, "3");
extent.AddSort(MetaC1.Instance.C1AllorsString);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(2, sortedObjects.Length);
Assert.Equal(this.c1C, sortedObjects[0]);
Assert.Equal(this.c1B, sortedObjects[1]);
}
}
}
}
}
[Fact]
public override void SortTwo()
{
foreach (var init in this.Inits)
{
init();
this.Populate();
this.c1B.C1AllorsString = "a";
this.c1C.C1AllorsString = "b";
this.c1D.C1AllorsString = "a";
this.c1B.C1AllorsInteger = 2;
this.c1C.C1AllorsInteger = 1;
this.c1D.C1AllorsInteger = 0;
this.Session.Commit();
var extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
extent.AddSort(MetaC1.Instance.C1AllorsInteger);
var sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1B, sortedObjects[2]);
Assert.Equal(this.c1C, sortedObjects[3]);
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
extent.AddSort(MetaC1.Instance.C1AllorsInteger, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1B, sortedObjects[2]);
Assert.Equal(this.c1C, sortedObjects[3]);
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
extent.AddSort(MetaC1.Instance.C1AllorsInteger, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1B, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1C, sortedObjects[3]);
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Descending);
extent.AddSort(MetaC1.Instance.C1AllorsInteger, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1C, sortedObjects[0]);
Assert.Equal(this.c1B, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1A, sortedObjects[3]);
}
}
[Fact]
public override void SortDifferentSession()
{
foreach (var init in this.Inits)
{
init();
var c1A = C1.Create(this.Session);
var c1B = C1.Create(this.Session);
var c1C = C1.Create(this.Session);
var c1D = C1.Create(this.Session);
c1A.C1AllorsString = "2";
c1B.C1AllorsString = "1";
c1C.C1AllorsString = "3";
var extent = this.Session.Extent(M.C1.Class);
extent.AddSort(M.C1.C1AllorsString, SortDirection.Ascending);
var sortedObjects = (C1[])extent.ToArray(typeof(C1));
var names = sortedObjects.Select(v => v.C1AllorsString).ToArray();
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(c1D, sortedObjects[0]);
Assert.Equal(c1B, sortedObjects[1]);
Assert.Equal(c1A, sortedObjects[2]);
Assert.Equal(c1C, sortedObjects[3]);
var c1AId = c1A.Id;
this.Session.Commit();
using (var session2 = this.CreateSession())
{
c1A = (C1)session2.Instantiate(c1AId);
extent = session2.Extent(M.C1.Class);
extent.AddSort(M.C1.C1AllorsString, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
names = sortedObjects.Select(v => v.C1AllorsString).ToArray();
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(c1D, sortedObjects[0]);
Assert.Equal(c1B, sortedObjects[1]);
Assert.Equal(c1A, sortedObjects[2]);
Assert.Equal(c1C, sortedObjects[3]);
}
}
}
}
} | Java |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://trad.spip.net/tradlang_module/forum?lang_cible=eo
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// B
'bouton_radio_articles_futurs' => 'nur al estontaj artikoloj (neniu ago ĉe la datenbazo).',
'bouton_radio_articles_tous' => 'al ĉiuj artikoloj senescepte.',
'bouton_radio_articles_tous_sauf_forum_desactive' => 'al ĉiuj artikoloj, escepte tiuj, kies forumo estas fermita.',
'bouton_radio_enregistrement_obligatoire' => 'Deviga memregistriĝo (la uzantoj devas aboniĝi, entajpante sian retpoŝtadreson antaŭ ol sendi kontribuaĵojn).',
'bouton_radio_moderation_priori' => 'Apriora moderigado (kontribuaĵoj estas publikigataj nur post validigo far de mastrumantoj).', # MODIF
'bouton_radio_modere_abonnement' => 'per abono',
'bouton_radio_modere_posteriori' => 'aposteriore moderigata', # MODIF
'bouton_radio_modere_priori' => 'apriore moderigata', # MODIF
'bouton_radio_publication_immediate' => 'Tujpublikigo de mesaĝoj
(la kontribuaĵoj afiŝiĝas tuj post ties sendo, la mastrumantoj povas
forviŝi ilin poste).',
// D
'documents_interdits_forum' => 'Dokumentoj malpermesitaj en la forumo',
// F
'form_pet_message_commentaire' => 'Ĉu mesaĝon, ĉu komenton ?',
'forum' => 'Forumo',
'forum_acces_refuse' => 'Vi ne plu havas alir-rajton al tiuj ĉi forumoj.',
'forum_attention_dix_caracteres' => '<b>Atentu !</b> via mesaĝo devas enhavi almenaŭ dek signojn.',
'forum_attention_trois_caracteres' => '<b>Atentu !</b> via titolo devas enhavi almenaŭ tri signojn.',
'forum_attention_trop_caracteres' => '<b>Atentu !</b> via mesaĝo estas tro longa (@compte@ signoj) : por esti registrita, ĝi ne preteratingu @max@ signojn.', # MODIF
'forum_avez_selectionne' => 'Vi selektis :',
'forum_cliquer_retour' => 'Musklaku <a href=\'@retour_forum@\'>ĉi tie</a> por daŭrigi.',
'forum_forum' => 'forumo',
'forum_info_modere' => 'Tiu ĉi forumo estas apriore moderigata : via kontribuo aperos nur post validigo far de mastrumanto de la forumo.', # MODIF
'forum_lien_hyper' => '<b>Hiperligo</b> (nedeviga)', # MODIF
'forum_message_definitif' => 'Definitiva mesaĝo : sendu al la forumo',
'forum_message_trop_long' => 'Via mesaĝo estas tro longa. La maksimuma longeco estas 20.000 signojn.', # MODIF
'forum_ne_repondez_pas' => 'Ne respondu al tiu ĉi retletero, sed en la forumo ĉe la jena adreso :', # MODIF
'forum_page_url' => '(Se via mesaĝo rilatas al artikolo publikigita ĉe la reto, aŭ al paĝo donanta pli da informoj, bonvolu indiki ĉi-poste la titolon de la paĝo kaj ties ret-adreson.)',
'forum_poste_par' => 'Mesaĝo posté@parauteur@ reage al via artikolo « @titre@ ».', # MODIF
'forum_qui_etes_vous' => '<b>Kiu vi estas ?</b> (nedeviga)', # MODIF
'forum_texte' => 'Teksto de via mesaĝo :', # MODIF
'forum_titre' => 'Titolo :', # MODIF
'forum_url' => 'URL :', # MODIF
'forum_valider' => 'Validigi tiun elekton',
'forum_voir_avant' => 'Vidi tiun ĉi mesaĝon antaŭ ol sendi ĝin', # MODIF
'forum_votre_email' => 'Via retpoŝtadreso',
'forum_votre_nom' => 'Via nomo (aŭ salutnomo) :', # MODIF
'forum_vous_enregistrer' => 'Por partopreni en ;
tiu ĉi forumo, vi devas antaŭe registriĝi. Bonvolu
indiki ĉi-sube la personan ensalutilon kiu estis
sendita al vi. Se vi ne estas registrita, vi devas',
'forum_vous_inscrire' => 'registriĝi.',
// I
'icone_poster_message' => 'Sendi mesaĝon',
'icone_suivi_forum' => 'Superrigardo de la publika forumo : @nb_forums@ kontribuo(j)',
'icone_suivi_forums' => 'Superrigardi/mastrumi la forumojn',
'icone_supprimer_message' => 'Forigi tiun mesaĝon',
'icone_valider_message' => 'Validigi tiun mesaĝon',
'info_activer_forum_public' => '<i>Por aktivigi la publikajn forumojn, bonvolu elekti ilian
defaŭltan moderig-reĝimon :</i>', # MODIF
'info_appliquer_choix_moderation' => 'Apliki tiun moderig-elekton :',
'info_config_forums_prive' => 'En la privata spaco de la retejo, vi povas aktivigi plurajn tipojn de forumoj :', # MODIF
'info_config_forums_prive_admin' => 'Forumo rezervita al retejaj mastrumantoj :',
'info_config_forums_prive_global' => 'Ĝenerala forumo, malfermita al ĉiuj redaktantoj :',
'info_config_forums_prive_objets' => 'Forumo sub ĉiu artikolo, fulminformo, referencigita retejo, ktp :',
'info_desactiver_forum_public' => 'Malaktivigi la uzon de la publikaj forumoj.
La publikaj forumoj estos laŭkaze unu post la alia permesitaj
laŭ la artikoloj ; ili estos malpermesataj koncerne rubrikojn, fulm-informojn, ktp.',
'info_envoi_forum' => 'Sendo de la forumoj al aŭtoroj de la artikoloj',
'info_fonctionnement_forum' => 'Funkciado de la forumo :',
'info_gauche_suivi_forum_2' => 'La paĝo pri <i>superkontrolo de la forumoj</i> estas mastrumilo por via retejo (kaj ne diskutejo aŭ redaktejo). Ĝi afiŝas ĉiujn kontribuaĵojn de la forumoj (de la publika spaco same kiel de la privata), kaj ebligas al vi mastrumi tiujn kontribuaĵojn.', # MODIF
'info_liens_syndiques_3' => 'forumoj',
'info_liens_syndiques_4' => 'estas',
'info_liens_syndiques_5' => 'forumo',
'info_liens_syndiques_6' => 'estas',
'info_liens_syndiques_7' => 'validigotaj',
'info_mode_fonctionnement_defaut_forum_public' => 'Defaŭlta funkcimodo de la publikaj forumoj',
'info_option_email' => 'Kiam vizitanto de la retejo sendas novan mesaĝon en la forumon
ligitan kun artikolo, eblas retpoŝte sciigi pri tiu mesaĝo al la aŭtoroj de la artikolo. Indiku por ĉia forumo, ĉu tiun eblecon oni uzu.',
'info_pas_de_forum' => 'neniu forumo',
'info_question_visiteur_ajout_document_forum' => 'Ĉu vi permesas al vizitantoj kunsendi dokumentojn (bildojn, sonaĵojn...) al siaj forumaj mesaĝoj ?', # MODIF
'info_question_visiteur_ajout_document_forum_format' => 'Laŭkaze, bonvolu indiki ĉi-sube la liston de dosiernomaj sufiksoj permesitaj por la forumoj (ekz : gif, jpg, png, mp3).', # MODIF
'item_activer_forum_administrateur' => 'Aktivigi la forumon de la mastrumantoj',
'item_config_forums_prive_global' => 'Aktivigi la forumon de redaktantoj',
'item_config_forums_prive_objets' => 'Aktivigi tiujn ĉi forumojn',
'item_desactiver_forum_administrateur' => 'Malaktivigi la forumon de la mastrumantoj',
'item_non_config_forums_prive_global' => 'Malaktivigi la forumon de redaktantoj',
'item_non_config_forums_prive_objets' => 'Malaktivigi tiujn ĉi forumojn',
// L
'lien_reponse_article' => 'Respondo al la artikolo',
'lien_reponse_breve_2' => 'Respondo al la fulm-informo',
'lien_reponse_rubrique' => 'Respondo al la rubriko',
'lien_reponse_site_reference' => 'Respondo al la referencigita retejo :', # MODIF
// O
'onglet_messages_internes' => 'Internaj mesaĝoj',
'onglet_messages_publics' => 'Publikaj mesaĝoj',
'onglet_messages_vide' => 'Sentekstaj mesaĝoj',
// R
'repondre_message' => 'Respondi al tiu mesaĝo',
// S
'statut_original' => 'originala',
// T
'titre_cadre_forum_administrateur' => 'Privata forumo de la mastrumantoj',
'titre_cadre_forum_interne' => 'Interna forumo',
'titre_config_forums_prive' => 'Forumoj de la privata spaco',
'titre_forum' => 'Forumo',
'titre_forum_suivi' => 'Superrigardo de la forumoj',
'titre_page_forum_suivi' => 'Superrigardo de la forumoj'
);
?>
| Java |
import { TestData } from '../../test-data';
import { ViewController } from 'ionic-angular';
import {
NavParamsMock,
BrandsActionsMock,
CategoriesActionsMock,
ModelsActionsMock,
ItemsActionsMock,
BrandsServiceMock,
CategoriesServiceMock,
ModelsServiceMock,
ItemsServiceMock,
} from '../../mocks';
import { InventoryFilterPage } from './inventory-filter';
let instance: InventoryFilterPage = null;
describe('InventoryFilter Page', () => {
beforeEach(() => {
instance = new InventoryFilterPage(
<any> new ViewController,
<any> new NavParamsMock,
<any> new BrandsServiceMock,
<any> new BrandsActionsMock,
<any> new ModelsServiceMock,
<any> new ModelsActionsMock,
<any> new CategoriesServiceMock,
<any> new CategoriesActionsMock,
<any> new ItemsServiceMock,
<any> new ItemsActionsMock
);
});
it('is created', () => {
expect(instance).toBeTruthy();
});
it('gets ids from store', () => {
instance.ngOnInit();
expect(instance.selectedBrandID).toEqual(TestData.itemFilters.brandID);
expect(instance.selectedModelID).toEqual(TestData.itemFilters.modelID);
expect(instance.selectedCategoryID).toEqual(TestData.itemFilters.categoryID);
});
it('calls filterModels if selectedBrandID is not -1', () => {
instance.navParams.param = TestData.apiItem.brandID;
spyOn(instance, 'onFilterModels');
instance.ngOnInit();
expect(instance.onFilterModels).toHaveBeenCalled();
});
it('filters models on filterModels()', () => {
spyOn(instance.modelsActions, 'filterModels');
instance.onFilterModels();
expect(instance.modelsActions.filterModels).toHaveBeenCalled();
});
it('resets filters on resetFilters()', () => {
spyOn(instance, 'onApplyFilters');
instance.onResetFilters();
expect(instance.selectedBrandID).toEqual(-1);
expect(instance.selectedModelID).toEqual(-1);
expect(instance.selectedCategoryID).toEqual(-1);
expect(instance.onApplyFilters).toHaveBeenCalled();
});
it('dismisses modal on dismiss', () => {
spyOn(instance.viewCtrl, 'dismiss');
instance.onDismiss();
expect(instance.viewCtrl.dismiss).toHaveBeenCalled();
});
it('dismisses modal on applyFilters', () => {
instance.selectedBrandID = TestData.itemFilters.brandID;
instance.selectedModelID = TestData.itemFilters.modelID;
instance.selectedCategoryID = TestData.itemFilters.categoryID;
const ids = {
brandID: TestData.itemFilters.brandID,
modelID: TestData.itemFilters.modelID,
categoryID: TestData.itemFilters.categoryID
};
spyOn(instance.viewCtrl, 'dismiss');
spyOn(instance.itemsActions, 'updateFilters');
instance.onApplyFilters();
expect(instance.viewCtrl.dismiss).toHaveBeenCalled();
expect(instance.itemsActions.updateFilters).toHaveBeenCalledWith(ids);
});
});
| Java |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\App\Test\Unit\View\Asset\MaterializationStrategy;
use \Magento\Framework\App\View\Asset\MaterializationStrategy\Factory;
use Magento\Framework\ObjectManagerInterface;
class FactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject
*/
private $objectManager;
protected function setUp()
{
$this->objectManager = $this->getMockBuilder('Magento\Framework\ObjectManagerInterface')
->setMethods([])
->getMock();
}
public function testCreateEmptyStrategies()
{
$asset = $this->getAsset();
$copyStrategy = $this->getMockBuilder('Magento\Framework\App\View\Asset\MaterializationStrategy\Copy')
->setMethods([])
->getMock();
$copyStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(true);
$this->objectManager->expects($this->once())
->method('get')
->with(Factory::DEFAULT_STRATEGY)
->willReturn($copyStrategy);
$factory = new Factory($this->objectManager, []);
$this->assertSame($copyStrategy, $factory->create($asset));
}
public function testCreateSupported()
{
$asset = $this->getAsset();
$copyStrategy = $this->getMockBuilder('Magento\Framework\App\View\Asset\MaterializationStrategy\Copy')
->setMethods([])
->getMock();
$copyStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(false);
$supportedStrategy = $this->getMockBuilder(
'Magento\Framework\App\View\Asset\MaterializationStrategy\StrategyInterface'
)
->setMethods([])
->getMock();
$supportedStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(true);
$factory = new Factory($this->objectManager, [$copyStrategy, $supportedStrategy]);
$this->assertSame($supportedStrategy, $factory->create($asset));
}
public function testCreateException()
{
$asset = $this->getAsset();
$copyStrategy = $this->getMockBuilder('Magento\Framework\App\View\Asset\MaterializationStrategy\Copy')
->setMethods([])
->getMock();
$copyStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(false);
$this->objectManager->expects($this->once())
->method('get')
->with(Factory::DEFAULT_STRATEGY)
->willReturn($copyStrategy);
$factory = new Factory($this->objectManager, []);
$this->setExpectedException('LogicException', 'No materialization strategy is supported');
$factory->create($asset);
}
/**
* @return \Magento\Framework\View\Asset\LocalInterface | \PHPUnit_Framework_MockObject_MockObject
*/
private function getAsset()
{
return $this->getMockBuilder('Magento\Framework\View\Asset\LocalInterface')
->setMethods([])
->getMock();
}
}
| Java |
#coding=gbk
"""Convert HTML page to Word 97 document
This script is used during the build process of "Dive Into Python"
(http://diveintopython.org/) to create the downloadable Word 97 version
of the book (http://diveintopython.org/diveintopython.doc)
Looks for 2 arguments on the command line. The first argument is the input (HTML)
file; the second argument is the output (.doc) file.
Only runs on Windows. Requires Microsoft Word 2000.
Safe to run on the same file(s) more than once. The output file will be
silently overwritten if it already exists.
The script has been modified by xiaq ([email protected]) to fit Simplified Chinese version of Microsoft Word.
"""
__author__ = "Mark Pilgrim ([email protected])"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"
import sys, os
from win32com.client import gencache, constants
def makeRealWordDoc(infile, outfile):
word = gencache.EnsureDispatch("Word.Application")
try:
worddoc = word.Documents.Open(FileName=infile)
try:
worddoc.TablesOfContents.Add(Range=word.ActiveWindow.Selection.Range, \
RightAlignPageNumbers=1, \
UseHeadingStyles=1, \
UpperHeadingLevel=1, \
LowerHeadingLevel=2, \
IncludePageNumbers=1, \
AddedStyles='', \
UseHyperlinks=1, \
HidePageNumbersInWeb=1)
worddoc.TablesOfContents(1).TabLeader = constants.wdTabLeaderDots
worddoc.TablesOfContents.Format = constants.wdIndexIndent
word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageHeader
word.Selection.TypeText(Text="Dive Into Python\t\thttp://diveintopython.org/")
word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageFooter
word.NormalTemplate.AutoTextEntries("- Ò³Âë -").Insert(Where=word.ActiveWindow.Selection.Range)
word.ActiveWindow.View.Type = constants.wdPrintView
worddoc.TablesOfContents(1).Update()
worddoc.SaveAs(FileName=outfile, \
FileFormat=constants.wdFormatDocument)
finally:
worddoc.Close(0)
del worddoc
finally:
word.Quit()
del word
if __name__ == "__main__":
infile = os.path.normpath(os.path.join(os.getcwd(), sys.argv[1]))
outfile = os.path.normpath(os.path.join(os.getcwd(), sys.argv[2]))
makeRealWordDoc(infile, outfile)
| Java |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Test\Unit\Model;
class TaxRateManagementTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Tax\Model\TaxRateManagement
*/
protected $model;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $searchCriteriaBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $filterBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $taxRuleRepositoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $taxRateRepositoryMock;
protected function setUp()
{
$this->filterBuilderMock = $this->getMock('\Magento\Framework\Api\FilterBuilder', [], [], '', false);
$this->taxRuleRepositoryMock = $this->getMock('\Magento\Tax\Api\TaxRuleRepositoryInterface', [], [], '', false);
$this->taxRateRepositoryMock = $this->getMock('\Magento\Tax\Api\TaxRateRepositoryInterface', [], [], '', false);
$this->searchCriteriaBuilderMock = $this->getMock(
'\Magento\Framework\Api\SearchCriteriaBuilder',
[],
[],
'',
false
);
$this->model = new \Magento\Tax\Model\TaxRateManagement(
$this->taxRuleRepositoryMock,
$this->taxRateRepositoryMock,
$this->filterBuilderMock,
$this->searchCriteriaBuilderMock
);
}
public function testGetRatesByCustomerAndProductTaxClassId()
{
$customerTaxClassId = 4;
$productTaxClassId = 42;
$rateIds = [10];
$productFilterMock = $this->getMock('\Magento\Framework\Api\Filter', [], [], '', false);
$customerFilterMock = $this->getMock('\Magento\Framework\Api\Filter', [], [], '', false);
$searchCriteriaMock = $this->getMock('\Magento\Framework\Api\SearchCriteria', [], [], '', false);
$searchResultsMock = $this->getMock('\Magento\Tax\Api\Data\TaxRuleSearchResultsInterface', [], [], '', false);
$taxRuleMock = $this->getMock('\Magento\Tax\Api\Data\TaxRuleInterface', [], [], '', false);
$taxRateMock = $this->getMock('\Magento\Tax\Api\Data\TaxRateInterface', [], [], '', false);
$this->filterBuilderMock->expects($this->exactly(2))->method('setField')->withConsecutive(
['customer_tax_class_ids'],
['product_tax_class_ids']
)->willReturnSelf();
$this->filterBuilderMock->expects($this->exactly(2))->method('setValue')->withConsecutive(
[$this->equalTo([$customerTaxClassId])],
[$this->equalTo([$productTaxClassId])]
)->willReturnSelf();
$this->filterBuilderMock->expects($this->exactly(2))->method('create')->willReturnOnConsecutiveCalls(
$customerFilterMock,
$productFilterMock
);
$this->searchCriteriaBuilderMock->expects($this->exactly(2))->method('addFilters')->withConsecutive(
[[$customerFilterMock]],
[[$productFilterMock]]
);
$this->searchCriteriaBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock);
$this->taxRuleRepositoryMock->expects($this->once())->method('getList')->with($searchCriteriaMock)
->willReturn($searchResultsMock);
$searchResultsMock->expects($this->once())->method('getItems')->willReturn([$taxRuleMock]);
$taxRuleMock->expects($this->once())->method('getTaxRateIds')->willReturn($rateIds);
$this->taxRateRepositoryMock->expects($this->once())->method('get')->with($rateIds[0])
->willReturn($taxRateMock);
$this->assertEquals(
[$taxRateMock],
$this->model->getRatesByCustomerAndProductTaxClassId($customerTaxClassId, $productTaxClassId)
);
}
}
| Java |
-----------------------------------
-- Area: LaLoff Amphitheater
-- NPC: Ark Angel's Tiger
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- TODO: Implement shared spawning and victory system with Ark Angel's Mandragora.
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local mobid = mob:getID()
for member = mobid-2, mobid+5 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local mobid = mob:getID()
-- Party hate. Keep everybody in the fight.
for member = mobid-2, mobid+5 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer)
end;
| Java |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Config\Model\Config\Backend;
class Serialized extends \Magento\Framework\App\Config\Value
{
/**
* @return void
*/
protected function _afterLoad()
{
if (!is_array($this->getValue())) {
$value = $this->getValue();
$this->setValue(empty($value) ? false : unserialize($value));
}
}
/**
* @return $this
*/
public function beforeSave()
{
if (is_array($this->getValue())) {
$this->setValue(serialize($this->getValue()));
}
return parent::beforeSave();
}
}
| Java |
/*
* log_ft_data.cpp
*
* Created on: Jul 9, 2010
* Author: dc
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <syslog.h>
#include <signal.h>
#include <unistd.h>
#include <native/task.h>
#include <native/timer.h>
#include <boost/thread.hpp>
#include <boost/ref.hpp>
#include <boost/tuple/tuple.hpp>
#include <barrett/detail/stacktrace.h>
#include <barrett/detail/stl_utils.h>
#include <barrett/units.h>
#include <barrett/log.h>
#include <barrett/products/product_manager.h>
using namespace barrett;
using detail::waitForEnter;
BARRETT_UNITS_FIXED_SIZE_TYPEDEFS;
typedef boost::tuple<double, cf_type, ct_type> tuple_type;
bool g_Going = true; // Global
void stopThreads(int sig) {
g_Going = false;
}
void warnOnSwitchToSecondaryMode(int)
{
syslog(LOG_ERR, "WARNING: Switched out of RealTime. Stack-trace:");
detail::syslog_stacktrace();
std::cerr << "WARNING: Switched out of RealTime. Stack-trace in syslog.\n";
}
void ftThreadEntryPoint(bool* going, double T_s, ForceTorqueSensor& fts, log::RealTimeWriter<tuple_type>* lw, int windowSize, int* numSamples, tuple_type* sum) {
tuple_type t;
rt_task_shadow(new RT_TASK, NULL, 10, 0);
rt_task_set_mode(0, T_PRIMARY | T_WARNSW, NULL);
rt_task_set_periodic(NULL, TM_NOW, T_s * 1e9);
RTIME now = rt_timer_read();
RTIME lastUpdate = now;
while (*going) {
rt_task_wait_period(NULL);
now = rt_timer_read();
fts.update(true); // Do a realtime update (no sleeping while waiting for messages)
boost::get<0>(t) = ((double) now - lastUpdate) * 1e-9;
boost::get<1>(t) = fts.getForce();
boost::get<2>(t) = fts.getTorque();
if (lw != NULL) {
lw->putRecord(t);
} else {
if (*numSamples == 0) {
boost::get<1>(*sum).setZero();
boost::get<2>(*sum).setZero();
}
if (*numSamples < windowSize) {
boost::get<1>(*sum) += boost::get<1>(t);
boost::get<2>(*sum) += boost::get<2>(t);
++(*numSamples);
}
}
lastUpdate = now;
}
rt_task_set_mode(T_WARNSW, 0, NULL);
}
void showUsageAndExit(const char* programName) {
printf("Usage: %s {-f <fileName> | -a <windowSize>} [<samplePeriodInSeconds>]\n", programName);
printf(" -f <fileName> Log data to a file\n");
printf(" -a <windowSize> Print statistics on segments of data\n");
exit(0);
}
int main(int argc, char** argv) {
char* outFile = NULL;
double T_s = 0.002; // Default: 500Hz
bool fileMode = false;
int windowSize = 0;
if (argc == 4) {
T_s = std::atof(argv[3]);
} else if (argc != 3) {
showUsageAndExit(argv[0]);
}
printf("Sample period: %fs\n", T_s);
if (strcmp(argv[1], "-f") == 0) {
fileMode = true;
outFile = argv[2];
printf("Output file: %s\n", outFile);
} else if (strcmp(argv[1], "-a") == 0) {
fileMode = false;
windowSize = atoi(argv[2]);
printf("Window size: %d\n", windowSize);
} else {
showUsageAndExit(argv[0]);
}
printf("\n");
signal(SIGXCPU, &warnOnSwitchToSecondaryMode);
char tmpFile[] = "/tmp/btXXXXXX";
log::RealTimeWriter<tuple_type>* lw = NULL;
if (fileMode) {
signal(SIGINT, &stopThreads);
if (mkstemp(tmpFile) == -1) {
printf("ERROR: Couldn't create temporary file!\n");
return 1;
}
lw = new barrett::log::RealTimeWriter<tuple_type>(tmpFile, T_s);
}
int numSamples = windowSize, numSets = 0;
tuple_type sum;
ProductManager pm;
if ( !pm.foundForceTorqueSensor() ) {
printf("ERROR: No Force-Torque Sensor found!\n");
return 1;
}
boost::thread ftThread(ftThreadEntryPoint, &g_Going, T_s, boost::ref(*pm.getForceTorqueSensor()), lw, windowSize, &numSamples, &sum);
if (fileMode) {
printf(">>> Logging data. Press [Ctrl-C] to exit.\n");
} else {
printf(">>> Press [Enter] to start a new sample. Press [Ctrl-C] to exit.\n\n");
printf("ID,FX,FY,FZ,TX,TY,TZ");
while (g_Going) {
waitForEnter();
numSamples = 0;
while (numSamples != windowSize) {
usleep(100000);
}
boost::get<1>(sum) /= windowSize;
boost::get<2>(sum) /= windowSize;
printf("%d,%f,%f,%f,%f,%f,%f", ++numSets, boost::get<1>(sum)[0], boost::get<1>(sum)[1], boost::get<1>(sum)[2], boost::get<2>(sum)[0], boost::get<2>(sum)[1], boost::get<2>(sum)[2]);
}
}
ftThread.join();
printf("\n");
if (fileMode) {
delete lw;
log::Reader<tuple_type> lr(tmpFile);
lr.exportCSV(outFile);
printf("Output written to %s.\n", outFile);
std::remove(tmpFile);
}
return 0;
}
| Java |
/*
Lehrstuhl fuer Energietransport und -speicherung
UNIVERSITAET DUISBURG-ESSEN
ef.Ruhr E-DeMa AP-2
Wissenschaftlicher Mitarbeiter:
Dipl.-Ing. Holger Kellerbauer
Das Linklayer-Paket "powerline" umfasst eine Sammlung von Modulen, die zur Simulation von Powerline-
Uebertragungsstrecken in intelligenten Energieverteilsystemen programmiert worden sind.
Dieser Quellcode wurde erstellt von Dipl.-Ing. Holger Kellerbauer - er basiert auf dem INET Framework-Modul
"Linklayer/Ethernet" von Andras Varga (c) 2003. Er ist gesitiges Eigentum des Lehrstuhles fuer Energietransport
und -speicherung der Universitaet Duisburg-Essen, und darf ohne Genehmigung weder weitergegeben, noch verwendet
werden.
*/
#include <stdio.h>
#include <string.h>
#include <omnetpp.h>
#include "Adapter_PLC_Base.h"
#include "IPassiveQueue.h"
#include "IInterfaceTable.h"
#include "InterfaceTableAccess.h"
//static const double SPEED_OF_LIGHT = 200000000.0; // TODO: Changed by Ramon; already defined in INETDefs.h
Adapter_PLC_Base::Adapter_PLC_Base()
{
nb = NULL;
queueModule = NULL;
interfaceEntry = NULL;
endTxMsg = endIFGMsg = endPauseMsg = NULL;
}
Adapter_PLC_Base::~Adapter_PLC_Base()
{
cancelAndDelete(endTxMsg);
cancelAndDelete(endIFGMsg);
cancelAndDelete(endPauseMsg);
}
void Adapter_PLC_Base::initialize()
{
physOutGate = gate("phys$o");
initializeFlags();
initializeTxrate();
WATCH(txrate);
initializeMACAddress();
initializeQueueModule();
initializeNotificationBoard();
initializeStatistics();
/*
The adapter has no higher layer!
*/
// registerInterface(txrate); // needs MAC address
// initialize queue
txQueue.setName("txQueue");
// initialize self messages
endTxMsg = new cMessage("EndTransmission", ENDTRANSMISSION);
endIFGMsg = new cMessage("EndIFG", ENDIFG);
endPauseMsg = new cMessage("EndPause", ENDPAUSE);
// initialize states
transmitState = TX_IDLE_STATE;
receiveState = RX_IDLE_STATE;
WATCH(transmitState);
WATCH(receiveState);
// initalize pause
pauseUnitsRequested = 0;
WATCH(pauseUnitsRequested);
// initialize queue limit
txQueueLimit = par("txQueueLimit");
WATCH(txQueueLimit);
}
void Adapter_PLC_Base::initializeQueueModule()
{
if (par("queueModule").stringValue()[0])
{
cModule *module = getParentModule()->getSubmodule(par("queueModule").stringValue());
queueModule = check_and_cast<IPassiveQueue *>(module);
if (COMMENTS_ON) EV << "Requesting first frame from queue module\n";
queueModule->requestPacket();
}
}
void Adapter_PLC_Base::initializeMACAddress()
{
const char *addrstr = par("address");
if (!strcmp(addrstr,"auto"))
{
// assign automatic address
address = MACAddress::generateAutoAddress();
// change module parameter from "auto" to concrete address
par("address").setStringValue(address.str().c_str());
}
else
{
address.setAddress(addrstr);
}
}
void Adapter_PLC_Base::initializeNotificationBoard()
{
hasSubscribers = false;
if (interfaceEntry) {
nb = NotificationBoardAccess().getIfExists();
notifDetails.setInterfaceEntry(interfaceEntry);
nb->subscribe(this, NF_SUBSCRIBERLIST_CHANGED);
updateHasSubcribers();
}
}
void Adapter_PLC_Base::initializeFlags()
{
// initialize connected flag
connected = physOutGate->getPathEndGate()->isConnected();
if (!connected)
if (COMMENTS_ON) EV << "MAC not connected to a network.\n";
WATCH(connected);
// TODO: this should be settable from the gui
// initialize disabled flag
// Note: it is currently not supported to enable a disabled MAC at runtime.
// Difficulties: (1) autoconfig (2) how to pick up channel state (free, tx, collision etc)
disabled = false;
WATCH(disabled);
// initialize promiscuous flag
promiscuous = par("promiscuous");
WATCH(promiscuous);
}
void Adapter_PLC_Base::initializeStatistics()
{
framesSentInBurst = 0;
bytesSentInBurst = 0;
numFramesSent = numFramesReceivedOK = numBytesSent = numBytesReceivedOK = 0;
numFramesPassedToHL = numDroppedBitError = numDroppedNotForUs = 0;
numFramesFromHL = numDroppedIfaceDown = 0;
numPauseFramesRcvd = numPauseFramesSent = 0;
WATCH(framesSentInBurst);
WATCH(bytesSentInBurst);
WATCH(numFramesSent);
WATCH(numFramesReceivedOK);
WATCH(numBytesSent);
WATCH(numBytesReceivedOK);
WATCH(numFramesFromHL);
WATCH(numDroppedIfaceDown);
WATCH(numDroppedBitError);
WATCH(numDroppedNotForUs);
WATCH(numFramesPassedToHL);
WATCH(numPauseFramesRcvd);
WATCH(numPauseFramesSent);
/*
numFramesSentVector.setName("framesSent");
numFramesReceivedOKVector.setName("framesReceivedOK");
numBytesSentVector.setName("bytesSent");
numBytesReceivedOKVector.setName("bytesReceivedOK");
numDroppedIfaceDownVector.setName("framesDroppedIfaceDown");
numDroppedBitErrorVector.setName("framesDroppedBitError");
numDroppedNotForUsVector.setName("framesDroppedNotForUs");
numFramesPassedToHLVector.setName("framesPassedToHL");
numPauseFramesRcvdVector.setName("pauseFramesRcvd");
numPauseFramesSentVector.setName("pauseFramesSent");
*/
}
void Adapter_PLC_Base::registerInterface(double txrate)
{
IInterfaceTable *ift = InterfaceTableAccess().getIfExists();
if (!ift)
return;
// interfaceEntry = new InterfaceEntry();
interfaceEntry = new InterfaceEntry(NULL); // TODO: Changed by Ramon
// interface name: our module name without special characters ([])
char *interfaceName = new char[strlen(getParentModule()->getFullName())+1];
char *d=interfaceName;
for (const char *s=getParentModule()->getFullName(); *s; s++)
if (isalnum(*s))
*d++ = *s;
*d = '\0';
interfaceEntry->setName(interfaceName);
delete [] interfaceName;
// data rate
interfaceEntry->setDatarate(txrate);
// generate a link-layer address to be used as interface token for IPv6
interfaceEntry->setMACAddress(address);
interfaceEntry->setInterfaceToken(address.formInterfaceIdentifier());
//InterfaceToken token(0, simulation.getUniqueNumber(), 64);
//interfaceEntry->setInterfaceToken(token);
// MTU: typical values are 576 (Internet de facto), 1500 (PLC-friendly),
// 4000 (on some point-to-point links), 4470 (Cisco routers default, FDDI compatible)
interfaceEntry->setMtu(par("mtu"));
// capabilities
interfaceEntry->setMulticast(true);
interfaceEntry->setBroadcast(true);
// add
// ift->addInterface(interfaceEntry, this);
ift->addInterface(interfaceEntry); // TODO: Changed by Ramon
}
bool Adapter_PLC_Base::checkDestinationAddress(PlcFrame *frame)
{
/*
// If not set to promiscuous = on, then checks if received frame contains destination MAC address
// matching port's MAC address, also checks if broadcast bit is set
if (!promiscuous && !frame->getDest().isBroadcast() && !frame->getDest().equals(address))
{
if (COMMENTS_ON) EV << "Frame `" << frame->getName() <<"' not destined to us, discarding\n";
numDroppedNotForUs++;
numDroppedNotForUsVector.record(numDroppedNotForUs);
delete frame;
return false;
}
*/
if (COMMENTS_ON) EV << "Since I'm an adapter, I will pass through every frame!" << endl;
return true;
}
void Adapter_PLC_Base::calculateParameters()
{
if (disabled || !connected)
{
bitTime = slotTime = interFrameGap = jamDuration = shortestFrameDuration = 0;
carrierExtension = frameBursting = false;
return;
}
// CHANGE ---------------------------------------------------------------------------------------
/*
Diesen Abschnitt mus man ausblenden, da er die Uebertragungsraten auf wenige, zulaessige
reduziert, was fuer Powerline absolut nicht zutreffend ist.
if (txrate != PLC_TXRATE && txrate != FAST_PLC_TXRATE &&
txrate != GIGABIT_PLC_TXRATE && txrate != FAST_GIGABIT_PLC_TXRATE)
{
error("nonstandard transmission rate %g, must be %g, %g, %g or %g bit/sec",
txrate, PLC_TXRATE, FAST_PLC_TXRATE, GIGABIT_PLC_TXRATE, FAST_GIGABIT_PLC_TXRATE);
}
*/
double temp = ROBO_DATARATE * 1000000;
if (txrate <= temp)
{
if (COMMENTS_ON) EV << "Measured datarate is estimated below ROBO datarate." << endl;
if (COMMENTS_ON) EV << "ROBO datarate is the lowest datarate possible." << endl;
if (COMMENTS_ON) EV << "TX rate will be set to ROBO datarate." << endl;
txrate = ROBO_DATARATE * 1000000;
}
if (txrate <= ROBO_DATARATE || txrate >= 1000000000) txrate = ROBO_DATARATE;
bitTime = 1/(double)txrate;
if (COMMENTS_ON) EV << endl << "Bit time is calculated to " << bitTime << "s." << endl;
/*
Dieser Abschnitt muss ausgeblendet werden, da die Berechnung der Parameter fuer
Powerline-Uebertragungen etwas anders von Statten gehen muss.
// set slot time
if (txrate==PLC_TXRATE || txrate==FAST_PLC_TXRATE)
slotTime = SLOT_TIME;
else
slotTime = GIGABIT_SLOT_TIME;
// only if Gigabit PLC
frameBursting = (txrate==GIGABIT_PLC_TXRATE || txrate==FAST_GIGABIT_PLC_TXRATE);
carrierExtension = (slotTime == GIGABIT_SLOT_TIME && !duplexMode);
interFrameGap = INTERFRAME_GAP_BITS/(double)txrate;
jamDuration = 8*JAM_SIGNAL_BYTES*bitTime;
shortestFrameDuration = carrierExtension ? GIGABIT_MIN_FRAME_WITH_EXT : MIN_PLC_FRAME;
*/
// set slot time
slotTime = 512/txrate;
if (COMMENTS_ON) EV << "Slot time is set to " << slotTime << "s." << endl;
// only if fast PLC
// Ein Burst darf nicht laenger als 5000 usec sein. 4 x MaxFramedauer < 5000 usec => FrameBursting = true!
simtime_t k = 0.005; /* s */
simtime_t x = (simtime_t)(bitTime * (MAX_PLC_FRAME * 8 /* bytes */) * 4);
if (COMMENTS_ON) EV << "Calculation for frame bursting resulted in " << x << " sec." << endl;
if (COMMENTS_ON) EV << "Threshold for frame bursting is " << k << " sec." << endl;
if (x < k)
{
frameBursting = true;
}
else
{
frameBursting = false;
}
if (COMMENTS_ON) EV << "Frame bursting is at " << frameBursting << "." << endl;
carrierExtension = false; // not available for PLC
if (frameBursting)
{
interFrameGap = /* INTERFRAME_GAP_BITS/(double)txrate; */ CIFS / 1000000;
}
else
{
interFrameGap = /* INTERFRAME_GAP_BITS/(double)txrate; */ RIFS / 1000000;
}
if (COMMENTS_ON) EV << "Inter frame gap is at " << interFrameGap << "s." << endl;
jamDuration = 8*JAM_SIGNAL_BYTES*bitTime;
if (COMMENTS_ON) EV << "Jam duration is at " << jamDuration << "s." << endl;
shortestFrameDuration = MIN_PLC_FRAME;
// ----------------------------------------------------------------------------------------------
}
void Adapter_PLC_Base::printParameters()
{
// Dump parameters
if (COMMENTS_ON) EV << "MAC address: " << address << (promiscuous ? ", promiscuous mode" : "") << endl;
if (COMMENTS_ON) EV << "txrate: " << txrate << ", " << (duplexMode ? "duplex" : "half-duplex") << endl;
#if 0
EV << "bitTime: " << bitTime << endl;
EV << "carrierExtension: " << carrierExtension << endl;
EV << "frameBursting: " << frameBursting << endl;
EV << "slotTime: " << slotTime << endl;
EV << "interFrameGap: " << interFrameGap << endl;
EV << endl;
#endif
}
void Adapter_PLC_Base::processFrameFromUpperLayer(PlcFrame *frame)
{
if (COMMENTS_ON) EV << "Received frame from upper layer: " << frame << endl;
if (frame->getDest().equals(address))
{
error("logic error: frame %s from higher layer has local MAC address as dest (%s)",
frame->getFullName(), frame->getDest().str().c_str());
}
if (frame->getByteLength() > MAX_PLC_FRAME)
error("packet from higher layer (%d bytes) exceeds maximum PLC frame size (%d)", frame->getByteLength(), MAX_PLC_FRAME);
// must be PlcFrame (or PlcPauseFrame) from upper layer
bool isPauseFrame = (dynamic_cast<PlcPauseFrame*>(frame)!=NULL);
if (!isPauseFrame)
{
numFramesFromHL++;
if (txQueueLimit && txQueue.length()>txQueueLimit)
error("txQueue length exceeds %d -- this is probably due to "
"a bogus app model generating excessive traffic "
"(or if this is normal, increase txQueueLimit!)",
txQueueLimit);
// fill in src address if not set
if (frame->getSrc().isUnspecified())
frame->setSrc(address);
// store frame and possibly begin transmitting
if (COMMENTS_ON) EV << "Packet " << frame << " arrived from higher layers, enqueueing\n";
txQueue.insert(frame);
}
else
{
if (COMMENTS_ON) EV << "PAUSE received from higher layer\n";
// PAUSE frames enjoy priority -- they're transmitted before all other frames queued up
if (!txQueue.empty())
txQueue.insertBefore(txQueue.front(), frame); // front() frame is probably being transmitted
else
txQueue.insert(frame);
}
}
void Adapter_PLC_Base::processMsgFromNetwork(cPacket *frame)
{
if (COMMENTS_ON) EV << "Received frame from network: " << frame << endl;
// frame must be PlcFrame or PlcJam
if (dynamic_cast<PlcFrame*>(frame)==NULL && dynamic_cast<PlcJam*>(frame)==NULL)
error("message with unexpected message class '%s' arrived from network (name='%s')",
frame->getClassName(), frame->getFullName());
// detect cable length violation in half-duplex mode
if (!duplexMode && simTime()-frame->getSendingTime()>=shortestFrameDuration)
error("very long frame propagation time detected, maybe cable exceeds maximum allowed length? "
"(%lgs corresponds to an approx. %lgm cable)",
SIMTIME_STR(simTime() - frame->getSendingTime()),
SIMTIME_STR((simTime() - frame->getSendingTime())*SPEED_OF_LIGHT));
}
void Adapter_PLC_Base::frameReceptionComplete(PlcFrame *frame)
{
int pauseUnits;
PlcPauseFrame *pauseFrame;
if ((pauseFrame=dynamic_cast<PlcPauseFrame*>(frame))!=NULL)
{
pauseUnits = pauseFrame->getPauseTime();
delete frame;
numPauseFramesRcvd++;
// numPauseFramesRcvdVector.record(numPauseFramesRcvd);
processPauseCommand(pauseUnits);
}
else
{
processReceivedDataFrame((PlcFrame *)frame);
}
}
void Adapter_PLC_Base::processReceivedDataFrame(PlcFrame *frame)
{
// bit errors
if (frame->hasBitError())
{
numDroppedBitError++;
// numDroppedBitErrorVector.record(numDroppedBitError);
delete frame;
return;
}
// strip preamble and SFD
frame->addByteLength(-PREAMBLE_BYTES-SFD_BYTES);
// statistics
numFramesReceivedOK++;
numBytesReceivedOK += frame->getByteLength();
// numFramesReceivedOKVector.record(numFramesReceivedOK);
// numBytesReceivedOKVector.record(numBytesReceivedOK);
if (!checkDestinationAddress(frame))
return;
numFramesPassedToHL++;
// numFramesPassedToHLVector.record(numFramesPassedToHL);
// pass up to upper layer
send(frame, "upperLayerOut");
}
void Adapter_PLC_Base::processPauseCommand(int pauseUnits)
{
if (transmitState==TX_IDLE_STATE)
{
if (COMMENTS_ON) EV << "PAUSE frame received, pausing for " << pauseUnitsRequested << " time units\n";
if (pauseUnits>0)
scheduleEndPausePeriod(pauseUnits);
}
else if (transmitState==PAUSE_STATE)
{
if (COMMENTS_ON) EV << "PAUSE frame received, pausing for " << pauseUnitsRequested << " more time units from now\n";
cancelEvent(endPauseMsg);
if (pauseUnits>0)
scheduleEndPausePeriod(pauseUnits);
}
else
{
// transmitter busy -- wait until it finishes with current frame (endTx)
// and then it'll go to PAUSE state
if (COMMENTS_ON) EV << "PAUSE frame received, storing pause request\n";
pauseUnitsRequested = pauseUnits;
}
}
void Adapter_PLC_Base::handleEndIFGPeriod()
{
if (transmitState!=WAIT_IFG_STATE)
error("Not in WAIT_IFG_STATE at the end of IFG period");
if (txQueue.empty())
error("End of IFG and no frame to transmit");
// End of IFG period, okay to transmit, if Rx idle OR duplexMode
cPacket *frame = (cPacket *)txQueue.front();
if (COMMENTS_ON) EV << "IFG elapsed, now begin transmission of frame " << frame << endl;
// CHANGE ----------------------------------------------------------------------------
// We skip carrier extension, because there is no for plc communications
/*
// Perform carrier extension if in Gigabit PLC
if (carrierExtension && frame->getByteLength() < GIGABIT_MIN_FRAME_WITH_EXT)
{
EV << "Performing carrier extension of small frame\n";
frame->setByteLength(GIGABIT_MIN_FRAME_WITH_EXT);
}
*/
// -----------------------------------------------------------------------------------
// start frame burst, if enabled
if (frameBursting)
{
if (COMMENTS_ON) EV << "Starting frame burst\n";
framesSentInBurst = 0;
bytesSentInBurst = 0;
}
}
void Adapter_PLC_Base::handleEndTxPeriod()
{
// we only get here if transmission has finished successfully, without collision
if (transmitState!=TRANSMITTING_STATE || (!duplexMode && receiveState!=RX_IDLE_STATE))
error("End of transmission, and incorrect state detected");
if (txQueue.empty())
error("Frame under transmission cannot be found");
// get frame from buffer
cPacket *frame = (cPacket *)txQueue.pop();
numFramesSent++;
numBytesSent += frame->getByteLength();
// numFramesSentVector.record(numFramesSent);
// numBytesSentVector.record(numBytesSent);
if (dynamic_cast<PlcPauseFrame*>(frame)!=NULL)
{
numPauseFramesSent++;
// numPauseFramesSentVector.record(numPauseFramesSent);
}
if (COMMENTS_ON) EV << "Transmission of " << frame << " successfully completed\n";
delete frame;
}
void Adapter_PLC_Base::handleEndPausePeriod()
{
if (transmitState != PAUSE_STATE)
error("At end of PAUSE not in PAUSE_STATE!");
if (COMMENTS_ON) EV << "Pause finished, resuming transmissions\n";
beginSendFrames();
}
void Adapter_PLC_Base::processMessageWhenNotConnected(cMessage *msg)
{
if (COMMENTS_ON) EV << "Interface is not connected -- dropping packet " << msg << endl;
delete msg;
numDroppedIfaceDown++;
}
void Adapter_PLC_Base::processMessageWhenDisabled(cMessage *msg)
{
if (COMMENTS_ON) EV << "MAC is disabled -- dropping message " << msg << endl;
delete msg;
}
void Adapter_PLC_Base::scheduleEndIFGPeriod()
{
// CHANGE ------------------------------------------------------------------------------
/*
Anders als bei CSMA/CD (Ethernet) wird bei PLC CSMA/CA angewendet. Hierzu wird zu der
"normalen" Wartezeit nach der Feststellung, dass das Medium nicht belegt ist, eine
zufaellige zusaetzliche Wartezeit addiert, die ein Vielfaches von 1.28 us ist (dieser
Wert konnte beim Modemhersteller devolo erfragt werden).
Hierdurch werden Kollisionen noch unwahrscheinlicher, da nach Freigabe nicht alle
Modems mit Sendewunsch gleichzeitig versuchen, das Medium zu belegen.
*/
// For CSMA/CA, we have to add a random selected additional wait time
int gap = CSMA_CA_MAX_ADDITIONAL_WAIT_TIME;
int x = rand()%10;
x = x * gap;
simtime_t additional_wait_time = (simtime_t) x/1000;
if (COMMENTS_ON) EV << "End of IFG period is scheduled at t=" << simTime()+interFrameGap +additional_wait_time << "." << endl;
// -------------------------------------------------------------------------------------
scheduleAt(simTime()+interFrameGap +additional_wait_time, endIFGMsg);
transmitState = WAIT_IFG_STATE;
}
// CHANGE ------------------------------------------------------------------------------
void Adapter_PLC_Base::scheduleEndIFGPeriod(int priority)
/*
Um trotz des durch CSMA/CA etwas zufaelligerem Mediumzugriff noch zu gewaehrleisten, das
wichtige Informationen zur Aufrechterhaltung der Verbindungen gegenueber einfachem
Datenverkehr bevorzugt werden, gibt es nach jeder Mediumsfreigabe die "Priority resolution
period". In vier Stufen erhalten zunaechst die Modems mit wichtigen Frames den Vorzug.
Die Periode wird dazu in 4 Teilabschnitte geteilt, und die durch CSMA/CA erweiterte
Wartezeit wird innerhalb der Fenster aufgeloest.
[----------------------------- Priority resolution period ------------------------------------]
t-> [Window 1 - Priority 4] [Window 2 - Priority 3] [Window 3 - Priority 2] [Window 4 - Priority 1]
*/
{
if (COMMENTS_ON) EV << "Scheduling end of IFG period ..." << endl;
if (COMMENTS_ON) EV << "Priority based traffic detected. Priority is " << priority << "." << endl;
// the higher the priority, the faster the channel access
double whole_period = PRIORITY_RESOLUTION_PERIOD;
if (COMMENTS_ON) EV << "Whole priority resolution period: " << whole_period << " micro sec" << endl;
double quarter_period = whole_period/4;
if (COMMENTS_ON) EV << "Quarter of the priority resolution period: " << quarter_period << " micro sec" << endl;
double basic_priority_period = whole_period - (priority * quarter_period);
if (COMMENTS_ON) EV << "Basic priority period for a priority of " << priority << " is: " << basic_priority_period << " micro sec" << endl;
double fluctuation = quarter_period * 0.9; // 16,12 us
if (COMMENTS_ON) EV << "The fluctuations are at maximum: " << fluctuation << " micro sec" << endl;
// For CSMA/CA, we have to add a random selected additional wait time
int gap = CSMA_CA_MAX_ADDITIONAL_WAIT_TIME;
int int_k = rand()%11; // 0 us to 14,08 us
if (COMMENTS_ON) EV << "Diceroll resulted in " << int_k << "." << endl;
double m = fluctuation - (int_k * gap);
double x = (m+basic_priority_period)/1000000;
simtime_t priority_wait_time = (simtime_t) x; // us
if (COMMENTS_ON) EV << "This time, the priority based additional wait time is calculated to: " << priority_wait_time * 1000000 << " micro sec" << endl;
simtime_t complete_wait_time = interFrameGap+priority_wait_time;
if (COMMENTS_ON) EV << "End of IFG period is scheduled at t=" << simTime()+complete_wait_time << " micro sec." << endl << endl;
scheduleAt(simTime()+complete_wait_time, endIFGMsg);
transmitState = WAIT_IFG_STATE;
}
// -------------------------------------------------------------------------------------
void Adapter_PLC_Base::scheduleEndTxPeriod(cPacket *frame)
{
scheduleAt(simTime()+frame->getBitLength()*bitTime, endTxMsg);
transmitState = TRANSMITTING_STATE;
}
void Adapter_PLC_Base::scheduleEndPausePeriod(int pauseUnits)
{
// length is interpreted as 512-bit-time units
simtime_t pausePeriod = pauseUnits*PAUSE_BITTIME*bitTime;
scheduleAt(simTime()+pausePeriod, endPauseMsg);
transmitState = PAUSE_STATE;
}
bool Adapter_PLC_Base::checkAndScheduleEndPausePeriod()
{
if (pauseUnitsRequested>0)
{
// if we received a PAUSE frame recently, go into PAUSE state
if (COMMENTS_ON) EV << "Going to PAUSE mode for " << pauseUnitsRequested << " time units\n";
scheduleEndPausePeriod(pauseUnitsRequested);
pauseUnitsRequested = 0;
return true;
}
return false;
}
void Adapter_PLC_Base::beginSendFrames()
{
if (!txQueue.empty())
{
// Other frames are queued, therefore wait IFG period and transmit next frame
if (COMMENTS_ON) EV << "Transmit next frame in output queue, after IFG period\n";
scheduleEndIFGPeriod();
}
else
{
transmitState = TX_IDLE_STATE;
if (queueModule)
{
// tell queue module that we've become idle
if (COMMENTS_ON) EV << "Requesting another frame from queue module\n";
queueModule->requestPacket();
}
else
{
// No more frames set transmitter to idle
if (COMMENTS_ON) EV << "No more frames to send, transmitter set to idle\n";
}
}
}
void Adapter_PLC_Base::fireChangeNotification(int type, cPacket *msg)
{
if (nb) {
notifDetails.setPacket(msg);
nb->fireChangeNotification(type, ¬ifDetails);
}
}
void Adapter_PLC_Base::finish()
{
/*
if (!disabled)
{
simtime_t t = simTime();
recordScalar("simulated time", t);
recordScalar("txrate (Mb)", txrate/1000000);
recordScalar("full duplex", duplexMode);
recordScalar("frames sent", numFramesSent);
recordScalar("frames rcvd", numFramesReceivedOK);
recordScalar("bytes sent", numBytesSent);
recordScalar("bytes rcvd", numBytesReceivedOK);
recordScalar("frames from higher layer", numFramesFromHL);
recordScalar("frames from higher layer dropped (iface down)", numDroppedIfaceDown);
recordScalar("frames dropped (bit error)", numDroppedBitError);
recordScalar("frames dropped (not for us)", numDroppedNotForUs);
recordScalar("frames passed up to HL", numFramesPassedToHL);
recordScalar("PAUSE frames sent", numPauseFramesSent);
recordScalar("PAUSE frames rcvd", numPauseFramesRcvd);
if (t>0)
{
recordScalar("frames/sec sent", numFramesSent/t);
recordScalar("frames/sec rcvd", numFramesReceivedOK/t);
recordScalar("bits/sec sent", 8*numBytesSent/t);
recordScalar("bits/sec rcvd", 8*numBytesReceivedOK/t);
}
}
*/
}
void Adapter_PLC_Base::updateDisplayString()
{
// icon coloring
const char *color;
if (receiveState==RX_COLLISION_STATE)
color = "red";
else if (transmitState==TRANSMITTING_STATE)
color = "yellow";
else if (transmitState==JAMMING_STATE)
color = "red";
else if (receiveState==RECEIVING_STATE)
color = "#4040ff";
else if (transmitState==BACKOFF_STATE)
color = "white";
else if (transmitState==PAUSE_STATE)
color = "gray";
else
color = "";
getDisplayString().setTagArg("i",1,color);
if (!strcmp(getParentModule()->getClassName(),"PLCInterface"))
getParentModule()->getDisplayString().setTagArg("i",1,color);
// connection coloring
updateConnectionColor(transmitState);
#if 0
// this code works but didn't turn out to be very useful
const char *txStateName;
switch (transmitState) {
case TX_IDLE_STATE: txStateName="IDLE"; break;
case WAIT_IFG_STATE: txStateName="WAIT_IFG"; break;
case TRANSMITTING_STATE: txStateName="TX"; break;
case JAMMING_STATE: txStateName="JAM"; break;
case BACKOFF_STATE: txStateName="BACKOFF"; break;
case PAUSE_STATE: txStateName="PAUSE"; break;
default: error("wrong tx state");
}
const char *rxStateName;
switch (receiveState) {
case RX_IDLE_STATE: rxStateName="IDLE"; break;
case RECEIVING_STATE: rxStateName="RX"; break;
case RX_COLLISION_STATE: rxStateName="COLL"; break;
default: error("wrong rx state");
}
char buf[80];
sprintf(buf, "tx:%s rx: %s\n#boff:%d #cTx:%d",
txStateName, rxStateName, backoffs, numConcurrentTransmissions);
getDisplayString().setTagArg("t",0,buf);
#endif
}
void Adapter_PLC_Base::updateConnectionColor(int txState)
{
const char *color;
if (txState==TRANSMITTING_STATE)
color = "yellow";
else if (txState==JAMMING_STATE || txState==BACKOFF_STATE)
color = "red";
else
color = "";
cGate *g = physOutGate;
while (g && g->getType()==cGate::OUTPUT)
{
g->getDisplayString().setTagArg("o",0,color);
g->getDisplayString().setTagArg("o",1, color[0] ? "3" : "1");
g = g->getNextGate();
}
}
void Adapter_PLC_Base::receiveChangeNotification(int category, const cPolymorphic *)
{
if (category==NF_SUBSCRIBERLIST_CHANGED)
updateHasSubcribers();
}
| Java |
/*
* Copyright (C) 2008-2009 Martin Willi
* Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
#include "eap_aka_3gpp2_card.h"
#include <daemon.h>
typedef struct private_eap_aka_3gpp2_card_t private_eap_aka_3gpp2_card_t;
/**
* Private data of an eap_aka_3gpp2_card_t object.
*/
struct private_eap_aka_3gpp2_card_t {
/**
* Public eap_aka_3gpp2_card_t interface.
*/
eap_aka_3gpp2_card_t public;
/**
* AKA functions
*/
eap_aka_3gpp2_functions_t *f;
/**
* do sequence number checking?
*/
bool seq_check;
/**
* SQN stored in this pseudo-USIM
*/
char sqn[AKA_SQN_LEN];
};
/**
* Functions from eap_aka_3gpp2_provider.c
*/
bool eap_aka_3gpp2_get_k(identification_t *id, char k[AKA_K_LEN]);
void eap_aka_3gpp2_get_sqn(char sqn[AKA_SQN_LEN], int offset);
METHOD(simaka_card_t, get_quintuplet, status_t,
private_eap_aka_3gpp2_card_t *this, identification_t *id,
char rand[AKA_RAND_LEN], char autn[AKA_AUTN_LEN], char ck[AKA_CK_LEN],
char ik[AKA_IK_LEN], char res[AKA_RES_MAX], int *res_len)
{
char *amf, *mac;
char k[AKA_K_LEN], ak[AKA_AK_LEN], sqn[AKA_SQN_LEN], xmac[AKA_MAC_LEN];
if (!eap_aka_3gpp2_get_k(id, k))
{
DBG1(DBG_IKE, "no EAP key found for %Y to authenticate with AKA", id);
return FAILED;
}
/* AUTN = SQN xor AK | AMF | MAC */
DBG3(DBG_IKE, "received autn %b", autn, AKA_AUTN_LEN);
DBG3(DBG_IKE, "using K %b", k, AKA_K_LEN);
DBG3(DBG_IKE, "using rand %b", rand, AKA_RAND_LEN);
memcpy(sqn, autn, AKA_SQN_LEN);
amf = autn + AKA_SQN_LEN;
mac = autn + AKA_SQN_LEN + AKA_AMF_LEN;
/* XOR anonymity key AK into SQN to decrypt it */
if (!this->f->f5(this->f, k, rand, ak))
{
return FAILED;
}
DBG3(DBG_IKE, "using ak %b", ak, AKA_AK_LEN);
memxor(sqn, ak, AKA_SQN_LEN);
DBG3(DBG_IKE, "using sqn %b", sqn, AKA_SQN_LEN);
/* calculate expected MAC and compare against received one */
if (!this->f->f1(this->f, k, rand, sqn, amf, xmac))
{
return FAILED;
}
if (!memeq_const(mac, xmac, AKA_MAC_LEN))
{
DBG1(DBG_IKE, "received MAC does not match XMAC");
DBG3(DBG_IKE, "MAC %b\nXMAC %b", mac, AKA_MAC_LEN, xmac, AKA_MAC_LEN);
return FAILED;
}
if (this->seq_check && memcmp(this->sqn, sqn, AKA_SQN_LEN) >= 0)
{
DBG3(DBG_IKE, "received SQN %b\ncurrent SQN %b",
sqn, AKA_SQN_LEN, this->sqn, AKA_SQN_LEN);
return INVALID_STATE;
}
/* update stored SQN to the received one */
memcpy(this->sqn, sqn, AKA_SQN_LEN);
/* CK/IK, calculate RES */
if (!this->f->f3(this->f, k, rand, ck) ||
!this->f->f4(this->f, k, rand, ik) ||
!this->f->f2(this->f, k, rand, res))
{
return FAILED;
}
*res_len = AKA_RES_MAX;
return SUCCESS;
}
METHOD(simaka_card_t, resync, bool,
private_eap_aka_3gpp2_card_t *this, identification_t *id,
char rand[AKA_RAND_LEN], char auts[AKA_AUTS_LEN])
{
char amf[AKA_AMF_LEN], k[AKA_K_LEN], aks[AKA_AK_LEN], macs[AKA_MAC_LEN];
if (!eap_aka_3gpp2_get_k(id, k))
{
DBG1(DBG_IKE, "no EAP key found for %Y to resync AKA", id);
return FALSE;
}
/* AMF is set to zero in resync */
memset(amf, 0, AKA_AMF_LEN);
if (!this->f->f5star(this->f, k, rand, aks) ||
!this->f->f1star(this->f, k, rand, this->sqn, amf, macs))
{
return FALSE;
}
/* AUTS = SQN xor AKS | MACS */
memcpy(auts, this->sqn, AKA_SQN_LEN);
memxor(auts, aks, AKA_AK_LEN);
memcpy(auts + AKA_AK_LEN, macs, AKA_MAC_LEN);
return TRUE;
}
METHOD(eap_aka_3gpp2_card_t, destroy, void,
private_eap_aka_3gpp2_card_t *this)
{
free(this);
}
/**
* See header
*/
eap_aka_3gpp2_card_t *eap_aka_3gpp2_card_create(eap_aka_3gpp2_functions_t *f)
{
private_eap_aka_3gpp2_card_t *this;
INIT(this,
.public = {
.card = {
.get_triplet = (void*)return_false,
.get_quintuplet = _get_quintuplet,
.resync = _resync,
.get_pseudonym = (void*)return_null,
.set_pseudonym = (void*)nop,
.get_reauth = (void*)return_null,
.set_reauth = (void*)nop,
},
.destroy = _destroy,
},
.f = f,
.seq_check = lib->settings->get_bool(lib->settings,
"%s.plugins.eap-aka-3gpp2.seq_check",
#ifdef SEQ_CHECK /* handle legacy compile time configuration as default */
TRUE,
#else /* !SEQ_CHECK */
FALSE,
#endif /* SEQ_CHECK */
lib->ns),
);
eap_aka_3gpp2_get_sqn(this->sqn, 0);
return &this->public;
}
| Java |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2015 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Hyrja e Ndaluar',
'add_rank'=>'shtoni Renditjen',
'actions'=>'Veprimet',
'delete'=>'fshij',
'edit_rank'=>'edito Renditjen',
'information_incomplete'=>'Disa të dhëna mungojnë.',
'max_posts'=>'max. Postimet',
'min_posts'=>'min. Postimet',
'new_rank'=>'Renditja e re',
'rank_icon'=>'Renditja Ikon-ave',
'rank_name'=>'Renditja Emri',
'really_delete'=>'Vërtet e fshini këtë Lidhje?',
'transaction_invalid'=>'ID e tranzaksionit e pavlefshme',
'update'=>'përditësim',
'user_ranks'=>'Renditja Përdoruesve'
);
| Java |
/**
* Copyright (C) 2015 Envidatec GmbH <[email protected]>
*
* This file is part of JECommons.
*
* JECommons 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 in version 3.
*
* JECommons 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
* JECommons. If not, see <http://www.gnu.org/licenses/>.
*
* JECommons is part of the OpenJEVis project, further project information are
* published at <http://www.OpenJEVis.org/>.
*/
package org.jevis.commons.dataprocessing.v2;
import java.util.List;
/**
*
* @author Florian Simon
*/
public interface Task {
void setDataProcessor(Function dp);
Function getDataProcessor();
void setDependency(List<Task> dps);
List<Task> getDependency();
Result getResult();
}
| Java |
import leon._
import lazyeval._
import lang._
import annotation._
import collection._
import instrumentation._
import math._
/**
* A constant time deque based on Okasaki's implementation: Fig.8.4 Pg. 112.
* Here, both front and rear streams are scheduled.
* We require both the front and the rear streams to be of almost equal
* size. If not, we lazily rotate the streams.
* The invariants are a lot more complex than in `RealTimeQueue`.
* The program also fixes a bug in Okasaki's implementatin: see function `rotateDrop`
*/
object RealTimeDeque {
sealed abstract class Stream[T] {
@inline
def isEmpty: Boolean = {
this match {
case SNil() => true
case _ => false
}
}
@inline
def isCons: Boolean = {
this match {
case SCons(_, _) => true
case _ => false
}
}
def size: BigInt = {
this match {
case SNil() => BigInt(0)
case SCons(x, t) => 1 + (t*).size
}
} ensuring (_ >= 0)
}
case class SCons[T](x: T, tail: Lazy[Stream[T]]) extends Stream[T]
case class SNil[T]() extends Stream[T]
@inline
def ssize[T](l: Lazy[Stream[T]]): BigInt = (l*).size
def isConcrete[T](l: Lazy[Stream[T]]): Boolean = {
l.isEvaluated && (l* match {
case SCons(_, tail) =>
isConcrete(tail)
case _ => true
})
}
@invstate
def revAppend[T](l1: Lazy[Stream[T]], l2: Lazy[Stream[T]]): Lazy[Stream[T]] = {
require(isConcrete(l1) && isConcrete(l2))
l1.value match {
case SNil() => l2
case SCons(x, tail) =>
val nt: Lazy[Stream[T]] = SCons[T](x, l2)
revAppend(tail, nt)
}
} ensuring(res => ssize(res) == ssize(l1) + ssize(l2) &&
isConcrete(res) &&
(ssize(l1) >= 1 ==> (res*).isCons) &&
time <= 20*ssize(l1) + 20)
@invstate
def drop[T](n: BigInt, l: Lazy[Stream[T]]): Lazy[Stream[T]] = {
require(n >= 0 && isConcrete(l) && ssize(l) >= n)
if (n == 0) {
l
} else {
l.value match {
case SNil() => l
case SCons(x, tail) => drop(n - 1, tail)
}
}
} ensuring(res => isConcrete(res) &&
ssize(res) == ssize(l) - n &&
time <= 20*n + 20)
@invstate
def take[T](n: BigInt, l: Lazy[Stream[T]]): Lazy[Stream[T]] = {
require(n >= 0 && isConcrete(l) && ssize(l) >= n)
val r: Lazy[Stream[T]] =
if (n == 0) {
SNil[T]()
} else {
l.value match {
case SNil() => l
case SCons(x, tail) =>
SCons[T](x, take(n - 1, tail))
}
}
r
} ensuring(res => isConcrete(res) &&
ssize(res) == n &&
time <= 30*n + 30)
@invstate
def takeLazy[T](n: BigInt, l: Lazy[Stream[T]]): Stream[T] = {
require(isConcrete(l) && n >= 1 && ssize(l) >= n)
l.value match {
case SCons(x, tail) =>
if (n == 1)
SCons[T](x, SNil[T]())
else
SCons[T](x, $(takeLazy(n - 1, tail)))
}
} ensuring(res => res.size == n && res.isCons &&
time <= 20)
@invstate
def rotateRev[T](r: Lazy[Stream[T]], f: Lazy[Stream[T]], a: Lazy[Stream[T]]): Stream[T] = {
require(isConcrete(r) && isConcrete(f) && isConcrete(a) &&
{
val lenf = ssize(f)
val lenr = ssize(r)
(lenf <= 2 * lenr + 3 && lenf >= 2 * lenr + 1)
})
r.value match {
case SNil() => revAppend(f, a).value // |f| <= 3
case SCons(x, rt) =>
SCons(x, $(rotateRev(rt, drop(2, f), revAppend(take(2, f), a))))
} // here, it doesn't matter whether 'f' has i elements or not, what we want is |drop(2,f)| + |take(2,f)| == |f|
} ensuring (res => res.size == (r*).size + (f*).size + (a*).size &&
res.isCons &&
time <= 250)
@invstate
def rotateDrop[T](r: Lazy[Stream[T]], i: BigInt, f: Lazy[Stream[T]]): Stream[T] = {
require(isConcrete(r) && isConcrete(f) && i >= 0 && {
val lenf = ssize(f)
val lenr = ssize(r)
(lenf >= 2 * lenr + 2 && lenf <= 2 * lenr + 3) && // size invariant between 'f' and 'r'
lenf > i
})
val rval = r.value
if(i < 2 || rval == SNil[T]()) { // A bug in Okasaki implementation: we must check for: 'rval = SNil()'
val a: Lazy[Stream[T]] = SNil[T]()
rotateRev(r, drop(i, f), a)
} else {
rval match {
case SCons(x, rt) =>
SCons(x, $(rotateDrop(rt, i - 2, drop(2, f))))
}
}
} ensuring(res => res.size == (r*).size + (f*).size - i &&
res.isCons && time <= 300)
def firstUneval[T](l: Lazy[Stream[T]]): Lazy[Stream[T]] = {
if (l.isEvaluated) {
l* match {
case SCons(_, tail) =>
firstUneval(tail)
case _ => l
}
} else
l
} ensuring (res => (!(res*).isEmpty || isConcrete(l)) &&
((res*).isEmpty || !res.isEvaluated) && // if the return value is not a Nil closure then it would not have been evaluated
(res.value match {
case SCons(_, tail) =>
firstUneval(l) == firstUneval(tail) // after evaluating the firstUneval closure in 'l' we can access the next unevaluated closure
case _ => true
}))
case class Queue[T](f: Lazy[Stream[T]], lenf: BigInt, sf: Lazy[Stream[T]],
r: Lazy[Stream[T]], lenr: BigInt, sr: Lazy[Stream[T]]) {
def isEmpty = lenf + lenr == 0
def valid = {
(firstUneval(f) == firstUneval(sf)) &&
(firstUneval(r) == firstUneval(sr)) &&
(lenf == ssize(f) && lenr == ssize(r)) &&
(lenf <= 2*lenr + 1 && lenr <= 2*lenf + 1) &&
{
val mind = min(2*lenr-lenf+2, 2*lenf-lenr+2)
ssize(sf) <= mind && ssize(sr) <= mind
}
}
}
/**
* A function that takes streams where the size of front and rear streams violate
* the balance invariant, and restores the balance.
*/
def createQueue[T](f: Lazy[Stream[T]], lenf: BigInt, sf: Lazy[Stream[T]],
r: Lazy[Stream[T]], lenr: BigInt, sr: Lazy[Stream[T]]): Queue[T] = {
require(firstUneval(f) == firstUneval(sf) &&
firstUneval(r) == firstUneval(sr) &&
(lenf == ssize(f) && lenr == ssize(r)) &&
((lenf - 1 <= 2*lenr + 1 && lenr <= 2*lenf + 1) ||
(lenf <= 2*lenr + 1 && lenr - 2 <= 2*lenf + 1)) &&
{
val mind = max(min(2*lenr-lenf+2, 2*lenf-lenr+2), 0)
ssize(sf) <= mind && ssize(sr) <= mind
})
if(lenf > 2*lenr + 1) {
val i = (lenf + lenr) / 2
val j = lenf + lenr - i
val nr = rotateDrop(r, i, f)
val nf = takeLazy(i, f)
Queue(nf, i, nf, nr, j, nr)
} else if(lenr > 2*lenf + 1) {
val i = (lenf + lenr) / 2
val j = lenf + lenr - i
val nf = rotateDrop(f, j, r) // here, both 'r' and 'f' are concretized
val nr = takeLazy(j, r)
Queue(nf, i, nf, nr, j, nr)
} else
Queue(f, lenf, sf, r, lenr, sr)
} ensuring(res => res.valid &&
time <= 400)
/**
* Forces the schedules, and ensures that `firstUneval` equality is preserved
*/
def force[T](tar: Lazy[Stream[T]], htar: Lazy[Stream[T]], other: Lazy[Stream[T]], hother: Lazy[Stream[T]]): Lazy[Stream[T]] = {
require(firstUneval(tar) == firstUneval(htar) &&
firstUneval(other) == firstUneval(hother))
tar.value match {
case SCons(_, tail) => tail
case _ => tar
}
} ensuring (res => {
//lemma instantiations
val in = inState[Stream[T]]
val out = outState[Stream[T]]
funeMonotone(tar, htar, in, out) &&
funeMonotone(other, hother, in, out) && {
//properties
val rsize = ssize(res)
firstUneval(htar) == firstUneval(res) && // follows from post of fune
firstUneval(other) == firstUneval(hother) &&
(rsize == 0 || rsize == ssize(tar) - 1)
} && time <= 350
})
/**
* Forces the schedules in the queue twice and ensures the `firstUneval` property.
*/
def forceTwice[T](q: Queue[T]): (Lazy[Stream[T]], Lazy[Stream[T]]) = {
require(q.valid)
val nsf = force(force(q.sf, q.f, q.r, q.sr), q.f, q.r, q.sr) // forces q.sf twice
val nsr = force(force(q.sr, q.r, q.f, nsf), q.r, q.f, nsf) // forces q.sr twice
(nsf, nsr)
}
// the following properties are ensured, but need not be stated
/*ensuring (res => {
val nsf = res._1
val nsr = res._2
firstUneval(q.f) == firstUneval(nsf) &&
firstUneval(q.r) == firstUneval(nsr) &&
(ssize(nsf) == 0 || ssize(nsf) == ssize(q.sf) - 2) &&
(ssize(nsr) == 0 || ssize(nsr) == ssize(q.sr) - 2) &&
time <= 1500
})*/
def empty[T] = {
val nil: Lazy[Stream[T]] = SNil[T]()
Queue(nil, 0, nil, nil, 0, nil)
}
/**
* Adding an element to the front of the list
*/
def cons[T](x: T, q: Queue[T]): Queue[T] = {
require(q.valid)
val nf: Stream[T] = SCons[T](x, q.f)
// force the front and rear scheds once
val nsf = force(q.sf, q.f, q.r, q.sr)
val nsr = force(q.sr, q.r, q.f, nsf)
createQueue(nf, q.lenf + 1, nsf, q.r, q.lenr, nsr)
} ensuring (res => res.valid && time <= 1200)
/**
* Removing the element at the front, and returning the tail
*/
def tail[T](q: Queue[T]): Queue[T] = {
require(!q.isEmpty && q.valid)
force(q.f, q.sf, q.r, q.sr) match { // force 'f'
case _ =>
tailSub(q)
}
} ensuring(res => res.valid && time <= 3000)
def tailSub[T](q: Queue[T]): Queue[T] = {
require(!q.isEmpty && q.valid && q.f.isEvaluated)
q.f.value match {
case SCons(x, nf) =>
val (nsf, nsr) = forceTwice(q)
// here, sf and sr got smaller by 2 holds, the schedule invariant still holds
createQueue(nf, q.lenf - 1, nsf, q.r, q.lenr, nsr)
case SNil() =>
// in this case 'r' will have only one element by invariant
empty[T]
}
} ensuring(res => res.valid && time <= 2750)
/**
* Reversing a list. Takes constant time.
* This implies that data structure is a `deque`.
*/
def reverse[T](q: Queue[T]): Queue[T] = {
require(q.valid)
Queue(q.r, q.lenr, q.sr, q.f, q.lenf, q.sf)
} ensuring(q.valid && time <= 10)
// Properties of `firstUneval`. We use `fune` as a shorthand for `firstUneval`
/**
* st1.subsetOf(st2) ==> fune(l, st2) == fune(fune(l, st1), st2)
*/
@traceInduct
def funeCompose[T](l1: Lazy[Stream[T]], st1: Set[Lazy[Stream[T]]], st2: Set[Lazy[Stream[T]]]): Boolean = {
require(st1.subsetOf(st2))
// property
(firstUneval(l1) withState st2) == (firstUneval(firstUneval(l1) withState st1) withState st2)
} holds
/**
* st1.subsetOf(st2) && fune(la,st1) == fune(lb,st1) ==> fune(la,st2) == fune(lb,st2)
* The `fune` equality is preseved by evaluation of lazy closures.
* This is a kind of frame axiom for `fune` but is slightly different in that
* it doesn't require (st2 \ st1) to be disjoint from la and lb.
*/
def funeMonotone[T](l1: Lazy[Stream[T]], l2: Lazy[Stream[T]], st1: Set[Lazy[Stream[T]]], st2: Set[Lazy[Stream[T]]]): Boolean = {
require((firstUneval(l1) withState st1) == (firstUneval(l2) withState st1) &&
st1.subsetOf(st2))
funeCompose(l1, st1, st2) && // lemma instantiations
funeCompose(l2, st1, st2) &&
// induction scheme
(if (l1.isEvaluated withState st1) {
l1* match {
case SCons(_, tail) =>
funeMonotone(tail, l2, st1, st2)
case _ => true
}
} else true) &&
(firstUneval(l1) withState st2) == (firstUneval(l2) withState st2) // property
} holds
}
| Java |
## roster_nb.py
## based on roster.py
##
## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
## modified by Dimitur Kirov <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2, 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.
# $Id: roster.py,v 1.17 2005/05/02 08:38:49 snakeru Exp $
"""
Simple roster implementation. Can be used though for different tasks like
mass-renaming of contacts.
"""
from protocol import JID, Iq, Presence, Node, NodeProcessed, NS_MUC_USER, NS_ROSTER
from plugin import PlugIn
import logging
log = logging.getLogger('nbxmpp.roster_nb')
class NonBlockingRoster(PlugIn):
"""
Defines a plenty of methods that will allow you to manage roster. Also
automatically track presences from remote JIDs taking into account that
every JID can have multiple resources connected. Does not currently support
'error' presences. You can also use mapping interface for access to the
internal representation of contacts in roster
"""
def __init__(self, version=None):
"""
Init internal variables
"""
PlugIn.__init__(self)
self.version = version
self._data = {}
self._set=None
self._exported_methods=[self.getRoster]
self.received_from_server = False
def Request(self, force=0):
"""
Request roster from server if it were not yet requested (or if the
'force' argument is set)
"""
if self._set is None:
self._set = 0
elif not force:
return
iq = Iq('get', NS_ROSTER)
if self.version is not None:
iq.setTagAttr('query', 'ver', self.version)
id_ = self._owner.getAnID()
iq.setID(id_)
self._owner.send(iq)
log.info('Roster requested from server')
return id_
def RosterIqHandler(self, dis, stanza):
"""
Subscription tracker. Used internally for setting items state in internal
roster representation
"""
sender = stanza.getAttr('from')
if not sender is None and not sender.bareMatch(
self._owner.User + '@' + self._owner.Server):
return
query = stanza.getTag('query')
if query:
self.received_from_server = True
self.version = stanza.getTagAttr('query', 'ver')
if self.version is None:
self.version = ''
for item in query.getTags('item'):
jid=item.getAttr('jid')
if item.getAttr('subscription')=='remove':
if self._data.has_key(jid): del self._data[jid]
# Looks like we have a workaround
# raise NodeProcessed # a MUST
log.info('Setting roster item %s...' % jid)
if not self._data.has_key(jid): self._data[jid]={}
self._data[jid]['name']=item.getAttr('name')
self._data[jid]['ask']=item.getAttr('ask')
self._data[jid]['subscription']=item.getAttr('subscription')
self._data[jid]['groups']=[]
if not self._data[jid].has_key('resources'): self._data[jid]['resources']={}
for group in item.getTags('group'):
if group.getData() not in self._data[jid]['groups']:
self._data[jid]['groups'].append(group.getData())
self._data[self._owner.User+'@'+self._owner.Server]={'resources': {}, 'name': None, 'ask': None, 'subscription': None, 'groups': None,}
self._set=1
# Looks like we have a workaround
# raise NodeProcessed # a MUST. Otherwise you'll get back an <iq type='error'/>
def PresenceHandler(self, dis, pres):
"""
Presence tracker. Used internally for setting items' resources state in
internal roster representation
"""
if pres.getTag('x', namespace=NS_MUC_USER):
return
jid=pres.getFrom()
if not jid:
# If no from attribue, it's from server
jid=self._owner.Server
jid=JID(jid)
if not self._data.has_key(jid.getStripped()): self._data[jid.getStripped()]={'name':None,'ask':None,'subscription':'none','groups':['Not in roster'],'resources':{}}
if type(self._data[jid.getStripped()]['resources'])!=type(dict()):
self._data[jid.getStripped()]['resources']={}
item=self._data[jid.getStripped()]
typ=pres.getType()
if not typ:
log.info('Setting roster item %s for resource %s...'%(jid.getStripped(), jid.getResource()))
item['resources'][jid.getResource()]=res={'show':None,'status':None,'priority':'0','timestamp':None}
if pres.getTag('show'): res['show']=pres.getShow()
if pres.getTag('status'): res['status']=pres.getStatus()
if pres.getTag('priority'): res['priority']=pres.getPriority()
if not pres.getTimestamp(): pres.setTimestamp()
res['timestamp']=pres.getTimestamp()
elif typ=='unavailable' and item['resources'].has_key(jid.getResource()): del item['resources'][jid.getResource()]
# Need to handle type='error' also
def _getItemData(self, jid, dataname):
"""
Return specific jid's representation in internal format. Used internally
"""
jid = jid[:(jid+'/').find('/')]
return self._data[jid][dataname]
def _getResourceData(self, jid, dataname):
"""
Return specific jid's resource representation in internal format. Used
internally
"""
if jid.find('/') + 1:
jid, resource = jid.split('/', 1)
if self._data[jid]['resources'].has_key(resource):
return self._data[jid]['resources'][resource][dataname]
elif self._data[jid]['resources'].keys():
lastpri = -129
for r in self._data[jid]['resources'].keys():
if int(self._data[jid]['resources'][r]['priority']) > lastpri:
resource, lastpri=r, int(self._data[jid]['resources'][r]['priority'])
return self._data[jid]['resources'][resource][dataname]
def delItem(self, jid):
"""
Delete contact 'jid' from roster
"""
self._owner.send(Iq('set', NS_ROSTER, payload=[Node('item', {'jid': jid, 'subscription': 'remove'})]))
def getAsk(self, jid):
"""
Return 'ask' value of contact 'jid'
"""
return self._getItemData(jid, 'ask')
def getGroups(self, jid):
"""
Return groups list that contact 'jid' belongs to
"""
return self._getItemData(jid, 'groups')
def getName(self, jid):
"""
Return name of contact 'jid'
"""
return self._getItemData(jid, 'name')
def getPriority(self, jid):
"""
Return priority of contact 'jid'. 'jid' should be a full (not bare) JID
"""
return self._getResourceData(jid, 'priority')
def getRawRoster(self):
"""
Return roster representation in internal format
"""
return self._data
def getRawItem(self, jid):
"""
Return roster item 'jid' representation in internal format
"""
return self._data[jid[:(jid+'/').find('/')]]
def getShow(self, jid):
"""
Return 'show' value of contact 'jid'. 'jid' should be a full (not bare)
JID
"""
return self._getResourceData(jid, 'show')
def getStatus(self, jid):
"""
Return 'status' value of contact 'jid'. 'jid' should be a full (not bare)
JID
"""
return self._getResourceData(jid, 'status')
def getSubscription(self, jid):
"""
Return 'subscription' value of contact 'jid'
"""
return self._getItemData(jid, 'subscription')
def getResources(self, jid):
"""
Return list of connected resources of contact 'jid'
"""
return self._data[jid[:(jid+'/').find('/')]]['resources'].keys()
def setItem(self, jid, name=None, groups=[]):
"""
Rename contact 'jid' and sets the groups list that it now belongs to
"""
iq = Iq('set', NS_ROSTER)
query = iq.getTag('query')
attrs = {'jid': jid}
if name:
attrs['name'] = name
item = query.setTag('item', attrs)
for group in groups:
item.addChild(node=Node('group', payload=[group]))
self._owner.send(iq)
def setItemMulti(self, items):
"""
Rename multiple contacts and sets their group lists
"""
iq = Iq('set', NS_ROSTER)
query = iq.getTag('query')
for i in items:
attrs = {'jid': i['jid']}
if i['name']:
attrs['name'] = i['name']
item = query.setTag('item', attrs)
for group in i['groups']:
item.addChild(node=Node('group', payload=[group]))
self._owner.send(iq)
def getItems(self):
"""
Return list of all [bare] JIDs that the roster is currently tracks
"""
return self._data.keys()
def keys(self):
"""
Same as getItems. Provided for the sake of dictionary interface
"""
return self._data.keys()
def __getitem__(self, item):
"""
Get the contact in the internal format. Raises KeyError if JID 'item' is
not in roster
"""
return self._data[item]
def getItem(self, item):
"""
Get the contact in the internal format (or None if JID 'item' is not in
roster)
"""
if self._data.has_key(item):
return self._data[item]
def Subscribe(self, jid):
"""
Send subscription request to JID 'jid'
"""
self._owner.send(Presence(jid, 'subscribe'))
def Unsubscribe(self, jid):
"""
Ask for removing our subscription for JID 'jid'
"""
self._owner.send(Presence(jid, 'unsubscribe'))
def Authorize(self, jid):
"""
Authorize JID 'jid'. Works only if these JID requested auth previously
"""
self._owner.send(Presence(jid, 'subscribed'))
def Unauthorize(self, jid):
"""
Unauthorise JID 'jid'. Use for declining authorisation request or for
removing existing authorization
"""
self._owner.send(Presence(jid, 'unsubscribed'))
def getRaw(self):
"""
Return the internal data representation of the roster
"""
return self._data
def setRaw(self, data):
"""
Return the internal data representation of the roster
"""
self._data = data
self._data[self._owner.User + '@' + self._owner.Server] = {
'resources': {},
'name': None,
'ask': None,
'subscription': None,
'groups': None
}
self._set = 1
def plugin(self, owner, request=1):
"""
Register presence and subscription trackers in the owner's dispatcher.
Also request roster from server if the 'request' argument is set. Used
internally
"""
self._owner.RegisterHandler('iq', self.RosterIqHandler, 'result', NS_ROSTER, makefirst = 1)
self._owner.RegisterHandler('iq', self.RosterIqHandler, 'set', NS_ROSTER)
self._owner.RegisterHandler('presence', self.PresenceHandler)
if request:
return self.Request()
def _on_roster_set(self, data):
if data:
self._owner.Dispatcher.ProcessNonBlocking(data)
if not self._set:
return
if not hasattr(self, '_owner') or not self._owner:
# Connection has been closed by receiving a <stream:error> for ex,
return
self._owner.onreceive(None)
if self.on_ready:
self.on_ready(self)
self.on_ready = None
return True
def getRoster(self, on_ready=None, force=False):
"""
Request roster from server if neccessary and returns self
"""
return_self = True
if not self._set:
self.on_ready = on_ready
self._owner.onreceive(self._on_roster_set)
return_self = False
elif on_ready:
on_ready(self)
return_self = False
if return_self or force:
return self
return None
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LightStone4net.WinUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("LightStone4net.WinUI")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("66735717-0731-4c11-900a-2277ca8f3ea7")] | Java |
using System.IO;
using System.Text;
using Microsoft.WindowsAzure.Storage.Blob;
namespace ScrewTurn.Wiki.Plugins.AzureStorage
{
/// <summary>
///
/// </summary>
public static class CloudBlobExtensions
{
/// <summary>
/// Uploads a string of text to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The text to upload, encoded as a UTF-8 string.</param>
public static void UploadText(this ICloudBlob blob, string content)
{
UploadText(blob, content, Encoding.UTF8, null);
}
/// <summary>
/// Uploads a string of text to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The text to upload.</param>
/// <param name="encoding">An object that indicates the text encoding to use.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void UploadText(this ICloudBlob blob, string content, Encoding encoding, BlobRequestOptions options)
{
UploadByteArray(blob, encoding.GetBytes(content), options);
}
/// <summary>
/// Uploads a file from the file system to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the file to upload.</param>
public static void UploadFile(this ICloudBlob blob, string fileName)
{
UploadFile(blob, fileName, null);
}
/// <summary>
/// Uploads a file from the file system to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the file to upload.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void UploadFile(this ICloudBlob blob, string fileName, BlobRequestOptions options)
{
using (var data = File.OpenRead(fileName))
{
blob.UploadFromStream(data, null, options);
}
}
/// <summary>
/// Uploads an array of bytes to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The array of bytes to upload.</param>
public static void UploadByteArray(this ICloudBlob blob, byte[] content)
{
UploadByteArray(blob, content, null);
}
/// <summary>
/// Uploads an array of bytes to a blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The array of bytes to upload.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void UploadByteArray(this ICloudBlob blob, byte[] content, BlobRequestOptions options)
{
using (var data = new MemoryStream(content))
{
blob.UploadFromStream(data, null, options);
}
}
/// <summary>
/// Downloads the blob's contents.
/// </summary>
/// <returns>The contents of the blob, as a string.</returns>
public static string DownloadText(this ICloudBlob blob)
{
return DownloadText(blob, null);
}
/// <summary>
/// Downloads the blob's contents.
/// </summary>
/// <param name="blob"></param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>The contents of the blob, as a string.</returns>
public static string DownloadText(this ICloudBlob blob, BlobRequestOptions options)
{
Encoding encoding = GetDefaultEncoding();
byte[] array = DownloadByteArray(blob, options);
return encoding.GetString(array);
}
/// <summary>
/// Downloads the blob's contents to a file.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the target file.</param>
public static void DownloadToFile(this ICloudBlob blob, string fileName)
{
DownloadToFile(blob, fileName, null);
}
/// <summary>
/// Downloads the blob's contents to a file.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the target file.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void DownloadToFile(this ICloudBlob blob, string fileName, BlobRequestOptions options)
{
using (var fileStream = File.Create(fileName))
{
blob.DownloadToStream(fileStream, null, options);
}
}
/// <summary>
/// Downloads the blob's contents as an array of bytes.
/// </summary>
/// <returns>The contents of the blob, as an array of bytes.</returns>
public static byte[] DownloadByteArray(this ICloudBlob blob)
{
return DownloadByteArray(blob, null);
}
/// <summary>
/// Downloads the blob's contents as an array of bytes.
/// </summary>
/// <param name="blob"></param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>The contents of the blob, as an array of bytes.</returns>
public static byte[] DownloadByteArray(this ICloudBlob blob, BlobRequestOptions options)
{
using (var memoryStream = new MemoryStream())
{
blob.DownloadToStream(memoryStream, null, options);
return memoryStream.ToArray();
}
}
/// <summary>
/// Gets the default encoding for the blob, which is UTF-8.
/// </summary>
/// <returns>The default <see cref="Encoding"/> object.</returns>
private static Encoding GetDefaultEncoding()
{
Encoding encoding = Encoding.UTF8;
return encoding;
}
}
}
| Java |
<?php
/**
* The view model to store the state of an ajax request/response in JSON objects.
*
* @author Jeremie Litzler
* @copyright Copyright (c) 2015
* @licence http://opensource.org/licenses/gpl-license.php GNU Public License
* @link https://github.com/WebDevJL/EasyMvc
* @since Version 1.0.0
* @package BaseJsonVm
*/
namespace Library\ViewModels;
if (!FrameworkConstants_ExecutionAccessRestriction) {
exit('No direct script access allowed');
}
class BaseJsonVm extends BaseVm {
/**
*
* @var mixed The response to use by the JavaScript Client
*/
protected $Response;
/**
* Getter for $Response member.
*
* @return mixed
* @see $Response member
*/
public function Response() {
return $this->Response;
}
}
| Java |
/*
This file is part of Darling.
Copyright (C) 2017 Lubos Dolezel
Darling 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.
Darling 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 Darling. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Foundation/Foundation.h>
@interface NSVBTestedFault : NSObject
@end
| Java |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ACE.Web.Models.Account;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace ACE.Web.Controllers
{
public class AccountController : Controller
{
[HttpGet]
public ActionResult Login()
{
return View(new LoginModel());
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
return View(model);
RestClient authClient = new RestClient(ConfigurationManager.AppSettings["Ace.Api"]);
var authRequest = new RestRequest("/Account/Authenticate", Method.POST);
authRequest.AddJsonBody(new { model.Username, model.Password });
var authResponse = authClient.Execute(authRequest);
if (authResponse.StatusCode == HttpStatusCode.Unauthorized)
{
model.ErrorMessage = "Incorrect Username or Password";
return View(model);
}
else if (authResponse.StatusCode != HttpStatusCode.OK)
{
model.ErrorMessage = "Error connecting to API";
return View(model);
}
// else we got an OK response
JObject response = JObject.Parse(authResponse.Content);
var authToken = (string)response.SelectToken("authToken");
if (!string.IsNullOrWhiteSpace(authToken))
{
JwtCookieManager.SetCookie(authToken);
return RedirectToAction("Index", "Home", null);
}
return View(model);
}
[HttpGet]
public ActionResult LogOff()
{
JwtCookieManager.SignOut();
return RedirectToAction("Index", "Home", null);
}
[HttpGet]
public ActionResult Register()
{
return View(new RegisterModel());
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
// create the user
return View();
}
}
} | Java |
<html>
<head>
<title>BOOST_PP_ARRAY_TO_SEQ</title>
<link rel="stylesheet" type="text/css" href="../styles.css">
</head>
<body>
<div style="margin-left: 0px;"> The <b>BOOST_PP_ARRAY_TO_SEQ</b> macro
converts an <i>array</i> to a <i>seq</i>. </div>
<h4> Usage </h4>
<div class="code"> <b>BOOST_PP_ARRAY_TO_SEQ</b>(<i>array</i>)
</div>
<h4> Arguments </h4>
<dl><dt>array</dt>
<dd> The <i>array</i> to be converted. </dd>
</dl>
<h4> Requirements </h4>
<div> <b>Header:</b> <a href="../headers/array/to_seq.html"><boost/preprocessor/array/to_seq.hpp></a>
</div>
<h4> Sample Code </h4>
<div>
<pre>#include <<a href="../headers/array/to_seq.html">boost/preprocessor/array/to_seq.hpp</a>><br><br><a href="array_to_seq.html">BOOST_PP_ARRAY_TO_SEQ</a>((3, (a, b, c))) // expands to (a)(b)(c)<br></pre>
</div>
<hr size="1">
<div style="margin-left: 0px;"> <i></i><i>© Copyright Edward Diener 2011</i> </div>
<div style="margin-left: 0px;">
<p><small>Distributed under the Boost Software License, Version 1.0.
(See accompanying file <a href="../../../../LICENSE_1_0.txt">LICENSE_1_0.txt</a>
or copy at <a href="http://www.boost.org/LICENSE_1_0.txt">www.boost.org/LICENSE_1_0.txt</a>)</small></p>
</div>
</body>
</html>
| Java |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext as _
from .models import AbuseReport, SearchTermRecord
admin.site.register(AbuseReport)
class SearchTermAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'ip_address', 'get_user_full_name', )
search_fields = ('term', )
def get_user_full_name(self, obj):
if obj.user is None:
return "(%s)" % _(u"None")
return obj.user.get_full_name()
get_user_full_name.short_description = "user"
admin.site.register(SearchTermRecord, SearchTermAdmin)
| Java |
"""
================================================================================
Logscaled Histogram
================================================================================
| Calculates a logarithmically spaced histogram for a data map.
| Written By: Matthew Stadelman
| Date Written: 2016/03/07
| Last Modifed: 2016/10/20
"""
import scipy as sp
from .histogram import Histogram
class HistogramLogscale(Histogram):
r"""
Performs a histogram where the bin limits are logarithmically spaced
based on the supplied scale factor. If there are negative values then
the first bin contains everything below 0, the next bin will contain
everything between 0 and 1.
kwargs include:
scale_fact - numeric value to generate axis scale for bins. A
scale fact of 10 creates bins: 0-1, 1-10, 10-100, etc.
"""
def __init__(self, field, **kwargs):
super().__init__(field)
self.args.update(kwargs)
self.output_key = 'hist_logscale'
self.action = 'histogram_logscale'
@classmethod
def _add_subparser(cls, subparsers, parent):
r"""
Adds a specific action based sub-parser to the supplied arg_parser
instance.
"""
parser = subparsers.add_parser(cls.__name__,
aliases=['histlog'],
parents=[parent],
help=cls.__doc__)
#
parser.add_argument('scale_fact', type=float, nargs='?', default=10.0,
help='base to generate logscale from')
parser.set_defaults(func=cls)
def define_bins(self, **kwargs):
r"""
This defines the bins for a logscaled histogram
"""
self.data_vector.sort()
sf = self.args['scale_fact']
num_bins = int(sp.logn(sf, self.data_vector[-1]) + 1)
#
# generating initial bins from 1 - sf**num_bins
low = list(sp.logspace(0, num_bins, num_bins + 1, base=sf))[:-1]
high = list(sp.logspace(0, num_bins, num_bins + 1, base=sf))[1:]
#
# Adding "catch all" bins for anything between 0 - 1 and less than 0
if self.data_vector[0] < 1.0:
low.insert(0, 0.0)
high.insert(0, 1.0)
if self.data_vector[0] < 0.0:
low.insert(0, self.data_vector[0])
high.insert(0, 0.0)
#
self.bins = [bin_ for bin_ in zip(low, high)]
| Java |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
namespace Macro.Desktop.View.WinForms
{
/// <summary>
/// Enumeration for specifying the style of check boxes displayed on a <see cref="BindingTreeView"/> control.
/// </summary>
public enum CheckBoxStyle
{
/// <summary>
/// Indicates that no check boxes should be displayed at all.
/// </summary>
None,
/// <summary>
/// Indicates that standard true/false check boxes should be displayed.
/// </summary>
Standard,
/// <summary>
/// Indicates that tri-state (true/false/unknown) check boxes should be displayed.
/// </summary>
TriState
}
} | Java |
#! /bin/sh
for i in `ls ./ | sed s'|.po||'` ; do
msgmerge --update --no-fuzzy-matching --no-wrap --add-location=file --backup=none ./$i.po pamac.pot
done
| Java |
package org.ovirt.engine.core.bll.transport;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.interfaces.FutureVDSCall;
import org.ovirt.engine.core.common.vdscommands.FutureVDSCommandType;
import org.ovirt.engine.core.common.vdscommands.TimeBoundPollVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.ResourceManager;
/**
* We need to detect whether vdsm supports jsonrpc or only xmlrpc. It is confusing to users
* when they have cluster 3.5+ and connect to vdsm <3.5 which supports only xmlrpc.
* In order to present version information in such situation we need fallback to xmlrpc.
*
*/
public class ProtocolDetector {
private Integer connectionTimeout = null;
private Integer retryAttempts = null;
private VDS vds;
public ProtocolDetector(VDS vds) {
this.vds = vds;
this.retryAttempts = Config.<Integer> getValue(ConfigValues.ProtocolFallbackRetries);
this.connectionTimeout = Config.<Integer> getValue(ConfigValues.ProtocolFallbackTimeoutInMilliSeconds);
}
/**
* Attempts to connect to vdsm using a proxy from {@code VdsManager} for a host.
* There are 3 attempts to connect.
*
* @return <code>true</code> if connected or <code>false</code> if connection failed.
*/
public boolean attemptConnection() {
boolean connected = false;
try {
for (int i = 0; i < this.retryAttempts; i++) {
long timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout);
FutureVDSCall<VDSReturnValue> task =
Backend.getInstance().getResourceManager().runFutureVdsCommand(FutureVDSCommandType.TimeBoundPoll,
new TimeBoundPollVDSCommandParameters(vds.getId(), timeout, TimeUnit.SECONDS));
VDSReturnValue returnValue =
task.get(timeout, TimeUnit.SECONDS);
connected = returnValue.getSucceeded();
if (connected) {
break;
}
Thread.sleep(this.connectionTimeout);
}
} catch (TimeoutException | InterruptedException ignored) {
}
return connected;
}
/**
* Stops {@code VdsManager} for a host.
*/
public void stopConnection() {
ResourceManager.getInstance().RemoveVds(this.vds.getId());
}
/**
* Fall back the protocol and attempts the connection {@link ProtocolDetector#attemptConnection()}.
*
* @return <code>true</code> if connected or <code>false</code> if connection failed.
*/
public boolean attemptFallbackProtocol() {
vds.setProtocol(VdsProtocol.XML);
ResourceManager.getInstance().AddVds(vds, false);
return attemptConnection();
}
/**
* Updates DB with fall back protocol (xmlrpc).
*/
public void setFallbackProtocol() {
final VdsStatic vdsStatic = this.vds.getStaticData();
vdsStatic.setProtocol(VdsProtocol.XML);
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
DbFacade.getInstance().getVdsStaticDao().update(vdsStatic);
return null;
}
});
}
}
| Java |
import {createBrowserHistory} from 'history';
import stringUtil from '@shared/util/stringUtil';
import ConfigStore from '../stores/ConfigStore';
const history = createBrowserHistory({basename: stringUtil.withoutTrailingSlash(ConfigStore.getBaseURI())});
export default history;
| Java |
/*
Creative Machines Lab Aracna Firmware
aracna.c - Main Program File
Copyright (c) Creative Machines Lab, Cornell University, 2012 - http://www.creativemachines.org
Authored by Jeremy Blum - http://www.jeremyblum.com
LICENSE: GPLv3
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/>.
*/
/** FIRMWARE REVISION */
#define FIRMWARE_VERSION 0x01
/** HARDWARE CONFIGURATION */
#define NUM_MOTORS 8
#ifndef F_CPU
#define F_CPU 16000000UL
#endif
/** INCLUDE AVR HEADERS */
#include <avr/io.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <util/delay.h>
/** INCLUDE PROGRAM HEADERS */
#include "aracna.h"
#include "macros.h"
#include "ax12.h"
#include "uart.h"
// UART Configuration and Buffers
// putchar and getchar are in uart.c
//FILE uart_str = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
#define SERIAL_STRING_LENGTH 60 //Input String Length
char input[SERIAL_STRING_LENGTH]; //complete input string
uint16_t vals[NUM_MOTORS] = {0}; //For holding the values that come over serial for each of our servos
char cmd; //the command character
// making these volatile keeps the compiler from optimizing loops of available()
volatile int ax_rx_Pointer;
volatile int ax_tx_Pointer;
volatile int ax_rx_int_Pointer;
/** Main program entry point. This routine contains the overall program flow
*/
int main(void)
{
initialize(); //Configures Ports, sets default values, etc.
//Loop Forever
for (;;)
{
//we add data starting with an '.' to the buffer until we get the newline character.
fgets(input, sizeof(input), stdin); //Get the actual input (reads up to and including newline character)
cmd = input[1]; //command char is always the first char of the input data after the '.'
//Command = 'q' - Query for the current status
if (cmd == 'q')
{
memset(input, 0, sizeof(input)); //Clear previous input
fprintf(stdout, ".q%d,%d\n", FIRMWARE_VERSION, NUM_MOTORS); //ACK w/ Firmware Version, # of Motors
}
//Command = 'l' - Command to Control Debug LED
else if (cmd == 'l')
{
if (input[2] == '1') DEBUG_LED_ON(); //Turn LED On
else if (input[2] == '0') DEBUG_LED_OFF(); //Turn LED Off
memset(input, 0, sizeof(input)); //Clear previous input
fprintf(stdout, ".l%d\n", DEBUG_LED_STATE()); //ACK
}
//Command = 'v' - Sets all motor speeds
//Comma separated entries telling all motors to set certain speeds
//Assumes motor IDs are 0 <-> NUM_MOTORS-1
else if (cmd == 'v')
{
parse_serial(); //Read the input string to an array of values
memset(input, 0, sizeof(input)); //Clear previous input
//send those speed commands
for (int i = 0; i<NUM_MOTORS; i++)
{
ax12SetRegister2(i, AX_GOAL_SPEED_L, vals[i]);
}
_delay_ms(25);
//Only after we have commanded all the speeds, can we check the status
fprintf(stdout, ".v"); //ACK Character
//Send ACK Info
for (int i = 0; i<NUM_MOTORS; i++)
{
fprintf(stdout, "%d", ax12GetRegister(i, AX_GOAL_SPEED_L, 2)); //Return velocity setting
if (i<NUM_MOTORS-1) fprintf(stdout, ","); //Print delimiter
}
fprintf(stdout, "\n"); //ACK Newline
}
//Command = 'c' - Command all the motors to a new position
//Comma separated entries telling all motors to move to positions from 0-1023
//Assumes motor IDs are 0 <-> NUM_MOTORS-1
else if (cmd == 'c')
{
parse_serial(); //Read the input string to an array of positions
memset(input, 0, sizeof(input)); //Clear previous input
//send those position commands
for (int i = 0; i<NUM_MOTORS; i++)
{
ax12SetRegister2(i, AX_GOAL_POSITION_L, vals[i]);
}
//Only after we have commanded all the positions, can we check the status
fprintf(stdout, ".c"); //ACK Character
//Send ACK Info
for (int i = 0; i<NUM_MOTORS; i++)
{
while(ax12GetRegister(i,AX_MOVING,1)); //Wait for this motor to finish moving
fprintf(stdout, "%d", ax12GetRegister(i, AX_PRESENT_POSITION_L, 2)); //Return the present position
if (i<NUM_MOTORS-1) fprintf(stdout, ","); //Print delimiter
}
fprintf(stdout, "\n"); //ACK Newline
}
}
}
/** initialize()
Sets up the UARTS, configures pin directions, says hello, then blinks at you.
*/
void initialize(void)
{
//init the UART0 to the Computer
uart_init();
stdout = &uart_output;
stdin = &uart_input;
//Initialize the AX12 UART1
ax12Init(1000000);
//Initialize Pin Directions and States for I/O
DDRB |= (DEBUG_LED_NUM);
DEBUG_LED_OFF();
//We're live. Say Hello
fprintf(stdout,".h\n");
//Blink The Board LED and all Dynamixel LEDs to show We're good to go
for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 0);
DEBUG_LED_OFF();
_delay_ms(500);
for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 1);
DEBUG_LED_ON();
_delay_ms(500);
for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 0);
DEBUG_LED_OFF();
}
/** parse_serial()
Assumes the input buffer has been populated with data of this form: ".c<val0>,<val1>,<val2>,...<val7>\n" as a char array
This function reads this buffer, and populates the "vals" array with the integer representations of 10-bit values for each motor command
*/
void parse_serial(void)
{
for (uint8_t i = 0; i < NUM_MOTORS; i++) vals[i] = 0;
//Skip leading '.' and command char
uint8_t i = 2;
uint8_t motor_num = 0;
uint8_t mtr_tmp[4] = {10, 10, 10, 10};
uint8_t mtr_tmp_pos = 0;
while (motor_num < NUM_MOTORS)
{
//look for the commas
if (input[i] == ',' || input[i] == '\n')
{
if (mtr_tmp[3] < 10) vals[motor_num] = mtr_tmp[0]*1000 + mtr_tmp[1]*100 + mtr_tmp[2]*10 + mtr_tmp[3];
else if (mtr_tmp[2] < 10) vals[motor_num] = mtr_tmp[0]*100 + mtr_tmp[1]*10 + mtr_tmp[2];
else if (mtr_tmp[1] < 10) vals[motor_num] = mtr_tmp[0]*10 + mtr_tmp[1];
else vals[motor_num] = mtr_tmp[0];
motor_num++;
for (uint8_t j = 0; j<4; j++) mtr_tmp[j] = 10;
mtr_tmp_pos = 0;
}
else
{
mtr_tmp[mtr_tmp_pos] = input[i] - '0';
mtr_tmp_pos++;
}
i++;
}
}
| Java |
# GamesInputSketcher | Java |
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
Hello {{Auth::guard('user')->user()->name}}
You are logged in!
{{ Auth()->guard('user')->user()->email }}
</div>
</div>
</div>
</div>
</div>
@endsection
| Java |
/*
* This file is part of eduVPN.
*
* eduVPN 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.
*
* eduVPN 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 eduVPN. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.eduvpn.app.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import nl.eduvpn.app.R;
import nl.eduvpn.app.adapter.viewholder.MessageViewHolder;
import nl.eduvpn.app.entity.message.Maintenance;
import nl.eduvpn.app.entity.message.Message;
import nl.eduvpn.app.entity.message.Notification;
import nl.eduvpn.app.utils.FormattingUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Adapter for serving the message views inside a list.
* Created by Daniel Zolnai on 2016-10-19.
*/
public class MessagesAdapter extends RecyclerView.Adapter<MessageViewHolder> {
private List<Message> _userMessages;
private List<Message> _systemMessages;
private List<Message> _mergedList = new ArrayList<>();
private LayoutInflater _layoutInflater;
public void setUserMessages(List<Message> userMessages) {
_userMessages = userMessages;
_regenerateList();
}
public void setSystemMessages(List<Message> systemMessages) {
_systemMessages = systemMessages;
_regenerateList();
}
private void _regenerateList() {
_mergedList.clear();
if (_userMessages != null) {
_mergedList.addAll(_userMessages);
}
if (_systemMessages != null) {
_mergedList.addAll(_systemMessages);
}
Collections.sort(_mergedList);
notifyDataSetChanged();
}
@Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(parent.getContext());
}
return new MessageViewHolder(_layoutInflater.inflate(R.layout.list_item_message, parent, false));
}
@Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
Message message = _mergedList.get(position);
if (message instanceof Maintenance) {
holder.messageIcon.setVisibility(View.VISIBLE);
Context context = holder.messageText.getContext();
String maintenanceText = FormattingUtils.getMaintenanceText(context, (Maintenance)message);
holder.messageText.setText(maintenanceText);
} else if (message instanceof Notification) {
holder.messageIcon.setVisibility(View.GONE);
holder.messageText.setText(((Notification)message).getContent());
} else {
throw new RuntimeException("Unexpected message type!");
}
}
@Override
public int getItemCount() {
return _mergedList.size();
}
}
| Java |
/* This file is part of Jellyfish.
Jellyfish 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.
Jellyfish 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 Jellyfish. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __JELLYFISH_PARSE_DNA_HPP__
#define __JELLYFISH_PARSE_DNA_HPP__
#include <iostream>
#include <vector>
#include <jellyfish/double_fifo_input.hpp>
#include <jellyfish/atomic_gcc.hpp>
#include <jellyfish/misc.hpp>
#include <jellyfish/sequence_parser.hpp>
#include <jellyfish/allocators_mmap.hpp>
#include <jellyfish/dna_codes.hpp>
#include <jellyfish/seedmod/seedmod.hpp>
namespace jellyfish {
class parse_dna : public double_fifo_input<sequence_parser::sequence_t> {
typedef std::vector<const char *> fary_t;
uint_t mer_len;
size_t buffer_size;
const fary_t files;
fary_t::const_iterator current_file;
bool have_seam;
char *seam;
allocators::mmap buffer_data;
bool canonical;
sequence_parser *fparser;
const char *Spaced_seed_cstr;
public:
/* Action to take for a given letter in fasta file:
* A, C, G, T: map to 0, 1, 2, 3. Append to kmer
* Other nucleic acid code: map to -1. reset kmer
* '\n': map to -2. ignore
* Other ASCII: map to -3. Report error.
*/
static uint64_t mer_string_to_binary(const char *in, uint_t klen) {
uint64_t res = 0;
for(uint_t i = 0; i < klen; i++) {
const uint_t c = dna_codes[(uint_t)*in++];
if(c & CODE_NOT_DNA)
return 0;
res = (res << 2) | c;
}
return res;
}
static void mer_binary_to_string(uint64_t mer, uint_t klen, char *out) {
static const char table[4] = { 'A', 'C', 'G', 'T' };
for(unsigned int i = 0 ; i < klen; i++) {
out[klen-1-i] = table[mer & (uint64_t)0x3];
mer >>= 2;
}
out[klen] = '\0';
}
static uint64_t reverse_complement(uint64_t v, uint_t length) {
v = ((v >> 2) & 0x3333333333333333UL) | ((v & 0x3333333333333333UL) << 2);
v = ((v >> 4) & 0x0F0F0F0F0F0F0F0FUL) | ((v & 0x0F0F0F0F0F0F0F0FUL) << 4);
v = ((v >> 8) & 0x00FF00FF00FF00FFUL) | ((v & 0x00FF00FF00FF00FFUL) << 8);
v = ((v >> 16) & 0x0000FFFF0000FFFFUL) | ((v & 0x0000FFFF0000FFFFUL) << 16);
v = ( v >> 32 ) | ( v << 32);
return (((uint64_t)-1) - v) >> (bsizeof(v) - (length << 1));
}
template<typename T>
parse_dna(T _files_start, T _files_end, uint_t _mer_len,
unsigned int nb_buffers, size_t _buffer_size,
const char * seed_cstr);
~parse_dna() {
delete [] seam;
}
void set_canonical(bool v = true) { canonical = v; }
virtual void fill();
class thread {
parse_dna *parser;
bucket_t *sequence;
const uint_t mer_len, lshift;
__uint128_t kmer, rkmer;
const __uint128_t masq;
uint64_t ret_mer;
uint_t cmlen;
const bool canonical;
uint64_t distinct, total;
typedef void (*error_reporter)(std::string& err);
error_reporter error_report;
public:
explicit thread(parse_dna *_parser) :
parser(_parser), sequence(0),
mer_len(_parser->mer_len), lshift(2 * (mer_len - 1)),
kmer(0), rkmer(0), ret_mer(0), masq((~(__uint128_t)(0))^((~(__uint128_t)(0))<<(2*mer_len))),
cmlen(0), canonical(parser->canonical),
distinct(0), total(0), error_report(0) {}
uint64_t get_uniq() const { return 0; }
uint64_t get_distinct() const { return distinct; }
uint64_t get_total() const { return total; }
template<typename T>
void parse(T &counter) {
cmlen = kmer = rkmer = ret_mer = 0;
while((sequence = parser->next())) {
const char *start = sequence->start;
const char * const end = sequence->end;
while(start < end) {
const uint_t c = dna_codes[(uint_t)*start++];
switch(c) {
case CODE_IGNORE: break;
case CODE_COMMENT:
report_bad_input(*(start-1));
// Fall through
case CODE_RESET:
cmlen = kmer = rkmer = 0;
break;
default:
kmer = ((kmer << 2) & masq) | c;
//rkmer = (rkmer >> 2) | ((0x3 - c) << lshift);
if(++cmlen >= mer_len) {
cmlen = mer_len;
ret_mer = 0;
kraken::squash_kmer_for_index(parser->Spaced_seed_cstr, mer_len,
kmer,ret_mer);
typename T::val_type oval;
if(canonical){
//counter->add(kmer < rkmer ? kmer : rkmer, 1, &oval);
std::cerr<<"Jellyfish with SpacedSeeds does not support canonical kmers."
<<std::endl;
exit(-1);
}else{
counter->add(ret_mer, 1, &oval);
//DEBUG
//std::cerr<<kraken::kmer_to_str(mer_len,kmer)<<" <--> "
// <<kraken::kmer_to_str(mer_len,ret_mer)
// <<std::endl;
}
distinct += oval == (typename T::val_type)0;
++total;
}
}
}
// Buffer exhausted. Get a new one
cmlen = kmer = rkmer = 0;
parser->release(sequence);
}
}
void set_error_reporter(error_reporter e) {
error_report = e;
}
private:
void report_bad_input(char c) {
if(!error_report)
return;
std::string err("Bad character in sequence: ");
err += c;
error_report(err);
}
};
friend class thread;
thread new_thread() { return thread(this); }
};
}
template<typename T>
jellyfish::parse_dna::parse_dna(T _files_start, T _files_end,
uint_t _mer_len,
unsigned int nb_buffers, size_t _buffer_size,
const char * seed_cstr) :
double_fifo_input<sequence_parser::sequence_t>(nb_buffers), mer_len(_mer_len),
buffer_size(allocators::mmap::round_to_page(_buffer_size)),
files(_files_start, _files_end), current_file(files.begin()),
have_seam(false), buffer_data(buffer_size * nb_buffers), canonical(false),
Spaced_seed_cstr(seed_cstr)
{
seam = new char[mer_len];
memset(seam, 'A', mer_len);
unsigned long i = 0;
for(bucket_iterator it = bucket_begin();
it != bucket_end(); ++it, ++i) {
it->end = it->start = (char *)buffer_data.get_ptr() + i * buffer_size;
}
assert(i == nb_buffers);
fparser = sequence_parser::new_parser(*current_file);
}
#endif
| Java |
#!/bin/sh
# Test some of cp's options and how cp handles situations in
# which a naive implementation might overwrite the source file.
# Copyright (C) 1998-2017 Free Software Foundation, Inc.
# 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/>.
. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
print_ver_ cp
# Unset CDPATH. Otherwise, output from the 'cd dir' command
# can make this test fail.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
VERSION_CONTROL=numbered; export VERSION_CONTROL
# Determine whether a hard link to a symlink points to the symlink
# itself or to its referent. For example, the link from FreeBSD6.1
# does dereference a symlink, but the one from Linux does not.
ln -s no-such dangling-slink
ln dangling-slink hard-link > /dev/null 2>&1 \
&& hard_link_to_symlink_does_the_deref=no \
|| hard_link_to_symlink_does_the_deref=yes
rm -f no-such dangling-slink hard-link
test $hard_link_to_symlink_does_the_deref = yes \
&& remove_these_sed='/^0 -[bf]*l .*sl1 ->/d; /hlsl/d' \
|| remove_these_sed='/^ELIDE NO TEST OUTPUT/d'
exec 3>&1 1> actual
# FIXME: This should be bigger: like more than 8k
contents=XYZ
for args in 'foo symlink' 'symlink foo' 'foo foo' 'sl1 sl2' \
'foo hardlink' 'hlsl sl2'; do
for options in '' -d -f -df --rem -b -bd -bf -bdf \
-l -dl -fl -dfl -bl -bdl -bfl -bdfl; do
case $args$options in
# These tests are not portable.
# They all involve making a hard link to a symbolic link.
# In the past, we've skipped the tests that are not portable,
# by doing "continue" here and eliminating the corresponding
# expected output lines below. Don't do that anymore.
'symlink foo'-dfl)
continue;;
'symlink foo'-bdl)
continue;;
'symlink foo'-bdfl)
continue;;
'sl1 sl2'-dfl)
continue;;
'sl1 sl2'-bd*l)
continue;;
'sl1 sl2'-dl)
continue;;
esac
# cont'd Instead, skip them only on systems for which link does
# dereference a symlink. Detect and skip such tests here.
case $hard_link_to_symlink_does_the_deref:$args:$options in
'yes:sl1 sl2:-fl')
continue ;;
'yes:sl1 sl2:-bl')
continue ;;
'yes:sl1 sl2:-bfl')
continue ;;
yes:hlsl*)
continue ;;
esac
rm -rf dir
mkdir dir
cd dir
echo $contents > foo
case "$args" in *symlink*) ln -s foo symlink ;; esac
case "$args" in *hardlink*) ln foo hardlink ;; esac
case "$args" in *sl1*) ln -s foo sl1;; esac
case "$args" in *sl2*) ln -s foo sl2;; esac
case "$args" in *hlsl*) ln sl2 hlsl;; esac
(
(
# echo 1>&2 cp $options $args
cp $options $args 2>_err
echo $? $options
# Normalize the program name and diagnostics in the error output,
# and put brackets around the output.
if test -s _err; then
sed '
s/^[^:]*:\([^:]*\).*/cp:\1/
1s/^/[/
$s/$/]/
' _err
fi
# Strip off all but the file names.
ls=$(ls -gG --ignore=_err . \
| sed \
-e '/^total /d' \
-e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//')
echo "($ls)"
# Make sure the original is unchanged and that
# the destination is a copy.
for f in $args; do
if test -f $f; then
case "$(cat $f)" in
"$contents") ;;
*) echo cp FAILED;;
esac
else
echo symlink-loop
fi
done
) | tr '\n' ' '
echo
) | sed 's/ *$//'
cd ..
done
echo
done
cat <<\EOF | sed "$remove_these_sed" > expected
1 [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo)
1 -d [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo)
1 -f [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo)
1 -df [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo)
0 --rem (foo symlink)
0 -b (foo symlink symlink.~1~ -> foo)
0 -bd (foo symlink symlink.~1~ -> foo)
0 -bf (foo symlink symlink.~1~ -> foo)
0 -bdf (foo symlink symlink.~1~ -> foo)
1 -l [cp: cannot create hard link 'symlink' to 'foo'] (foo symlink -> foo)
1 -dl [cp: cannot create hard link 'symlink' to 'foo'] (foo symlink -> foo)
0 -fl (foo symlink)
0 -dfl (foo symlink)
0 -bl (foo symlink symlink.~1~ -> foo)
0 -bdl (foo symlink symlink.~1~ -> foo)
0 -bfl (foo symlink symlink.~1~ -> foo)
0 -bdfl (foo symlink symlink.~1~ -> foo)
1 [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
1 -d [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
1 -f [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
1 -df [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
1 --rem [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
1 -b [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
0 -bd (foo -> foo foo.~1~ symlink -> foo) symlink-loop symlink-loop
1 -bf [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo)
0 -bdf (foo -> foo foo.~1~ symlink -> foo) symlink-loop symlink-loop
0 -l (foo symlink -> foo)
0 -dl (foo symlink -> foo)
0 -fl (foo symlink -> foo)
0 -bl (foo symlink -> foo)
0 -bfl (foo symlink -> foo)
1 [cp: 'foo' and 'foo' are the same file] (foo)
1 -d [cp: 'foo' and 'foo' are the same file] (foo)
1 -f [cp: 'foo' and 'foo' are the same file] (foo)
1 -df [cp: 'foo' and 'foo' are the same file] (foo)
1 --rem [cp: 'foo' and 'foo' are the same file] (foo)
1 -b [cp: 'foo' and 'foo' are the same file] (foo)
1 -bd [cp: 'foo' and 'foo' are the same file] (foo)
0 -bf (foo foo.~1~)
0 -bdf (foo foo.~1~)
0 -l (foo)
0 -dl (foo)
0 -fl (foo)
0 -dfl (foo)
0 -bl (foo)
0 -bdl (foo)
0 -bfl (foo foo.~1~)
0 -bdfl (foo foo.~1~)
1 [cp: 'sl1' and 'sl2' are the same file] (foo sl1 -> foo sl2 -> foo)
0 -d (foo sl1 -> foo sl2 -> foo)
1 -f [cp: 'sl1' and 'sl2' are the same file] (foo sl1 -> foo sl2 -> foo)
0 -df (foo sl1 -> foo sl2 -> foo)
0 --rem (foo sl1 -> foo sl2)
0 -b (foo sl1 -> foo sl2 sl2.~1~ -> foo)
0 -bd (foo sl1 -> foo sl2 -> foo sl2.~1~ -> foo)
0 -bf (foo sl1 -> foo sl2 sl2.~1~ -> foo)
0 -bdf (foo sl1 -> foo sl2 -> foo sl2.~1~ -> foo)
1 -l [cp: cannot create hard link 'sl2' to 'sl1'] (foo sl1 -> foo sl2 -> foo)
0 -fl (foo sl1 -> foo sl2)
0 -bl (foo sl1 -> foo sl2 sl2.~1~ -> foo)
0 -bfl (foo sl1 -> foo sl2 sl2.~1~ -> foo)
1 [cp: 'foo' and 'hardlink' are the same file] (foo hardlink)
1 -d [cp: 'foo' and 'hardlink' are the same file] (foo hardlink)
1 -f [cp: 'foo' and 'hardlink' are the same file] (foo hardlink)
1 -df [cp: 'foo' and 'hardlink' are the same file] (foo hardlink)
0 --rem (foo hardlink)
0 -b (foo hardlink hardlink.~1~)
0 -bd (foo hardlink hardlink.~1~)
0 -bf (foo hardlink hardlink.~1~)
0 -bdf (foo hardlink hardlink.~1~)
0 -l (foo hardlink)
0 -dl (foo hardlink)
0 -fl (foo hardlink)
0 -dfl (foo hardlink)
0 -bl (foo hardlink)
0 -bdl (foo hardlink)
0 -bfl (foo hardlink)
0 -bdfl (foo hardlink)
1 [cp: 'hlsl' and 'sl2' are the same file] (foo hlsl -> foo sl2 -> foo)
0 -d (foo hlsl -> foo sl2 -> foo)
1 -f [cp: 'hlsl' and 'sl2' are the same file] (foo hlsl -> foo sl2 -> foo)
0 -df (foo hlsl -> foo sl2 -> foo)
0 --rem (foo hlsl -> foo sl2)
0 -b (foo hlsl -> foo sl2 sl2.~1~ -> foo)
0 -bd (foo hlsl -> foo sl2 -> foo sl2.~1~ -> foo)
0 -bf (foo hlsl -> foo sl2 sl2.~1~ -> foo)
0 -bdf (foo hlsl -> foo sl2 -> foo sl2.~1~ -> foo)
1 -l [cp: cannot create hard link 'sl2' to 'hlsl'] (foo hlsl -> foo sl2 -> foo)
0 -dl (foo hlsl -> foo sl2 -> foo)
0 -fl (foo hlsl -> foo sl2)
0 -dfl (foo hlsl -> foo sl2 -> foo)
0 -bl (foo hlsl -> foo sl2 sl2.~1~ -> foo)
0 -bdl (foo hlsl -> foo sl2 -> foo)
0 -bfl (foo hlsl -> foo sl2 sl2.~1~ -> foo)
0 -bdfl (foo hlsl -> foo sl2 -> foo)
EOF
exec 1>&3 3>&-
compare expected actual 1>&2 || fail=1
Exit $fail
| Java |
drop table if exists hml;
| Java |
<?php
use Alchemy\Phrasea\Model\Serializer\CaptionSerializer;
use Symfony\Component\Yaml\Yaml;
/**
* @group functional
* @group legacy
*/
class caption_recordTest extends \PhraseanetTestCase
{
/**
* @var caption_record
*/
protected $object;
public function setUp()
{
parent::setUp();
$this->object = new caption_record(self::$DI['app'], self::$DI['record_1'], self::$DI['record_1']->get_databox());
}
/**
* @covers \caption_record::serializeXML
*/
public function testSerializeXML()
{
foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
$n = $databox_field->is_multi() ? 3 : 1;
for ($i = 0; $i < $n; $i ++) {
\caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8));
}
}
$xml = self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_XML);
$sxe = simplexml_load_string($xml);
$this->assertInstanceOf('SimpleXMLElement', $sxe);
foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
if ($field->get_databox_field()->is_multi()) {
$tagname = $field->get_name();
$retrieved = [];
foreach ($sxe->description->$tagname as $value) {
$retrieved[] = (string) $value;
}
$values = $field->get_values();
$this->assertEquals(count($values), count($retrieved));
foreach ($values as $val) {
$this->assertTrue(in_array($val->getValue(), $retrieved));
}
} else {
$tagname = $field->get_name();
$data = $field->get_values();
$value = array_pop($data);
$this->assertEquals($value->getValue(), (string) $sxe->description->$tagname);
}
}
}
public function testSerializeJSON()
{
foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
$n = $databox_field->is_multi() ? 3 : 1;
for ($i = 0; $i < $n; $i ++) {
\caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8));
}
}
$json = json_decode(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_JSON), true);
foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
if ($field->get_databox_field()->is_multi()) {
$tagname = $field->get_name();
$retrieved = [];
foreach ($json["record"]["description"][$tagname] as $value) {
$retrieved[] = $value;
}
$values = $field->get_values();
$this->assertEquals(count($values), count($retrieved));
foreach ($values as $val) {
$this->assertTrue(in_array($val->getValue(), $retrieved));
}
} else {
$tagname = $field->get_name();
$data = $field->get_values();
$value = array_pop($data);
$this->assertEquals($value->getValue(), $json["record"]["description"][$tagname]);
}
}
}
/**
* @covers \caption_record::serializeYAML
*/
public function testSerializeYAML()
{
foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
$n = $databox_field->is_multi() ? 3 : 1;
for ($i = 0; $i < $n; $i ++) {
\caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8));
}
}
$parser = new Yaml();
$yaml = $parser->parse(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_YAML));
foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
if ($field->get_databox_field()->is_multi()) {
$tagname = $field->get_name();
$retrieved = [];
foreach ($yaml["record"]["description"][$tagname] as $value) {
$retrieved[] = (string) $value;
}
$values = $field->get_values();
$this->assertEquals(count($values), count($retrieved));
foreach ($values as $val) {
$this->assertTrue(in_array($val->getValue(), $retrieved));
}
} else {
$tagname = $field->get_name();
$data = $field->get_values();
$value = array_pop($data);
$this->assertEquals($value->getValue(), (string) $yaml["record"]["description"][$tagname]);
}
}
}
/**
* @covers \caption_record::get_fields
* @todo Implement testGet_fields().
*/
public function testGet_fields()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_field
* @todo Implement testGet_field().
*/
public function testGet_field()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_dc_field
* @todo Implement testGet_dc_field().
*/
public function testGet_dc_field()
{
$field = null;
foreach (self::$DI['app']->getDataboxes() as $databox) {
foreach ($databox->get_meta_structure() as $meta) {
$meta->set_dces_element(new databox_Field_DCES_Contributor());
$field = $meta;
$set = true;
break;
}
break;
}
if (!$field) {
$this->markTestSkipped('Unable to set a DC field');
}
$captionField = self::$DI['record_1']->get_caption()->get_field($field->get_name());
if (!$captionField) {
self::$DI['record_1']->set_metadatas([
[
'meta_id' => null,
'meta_struct_id' => $field->get_id(),
'value' => ['HELLO MO !'],
]
]);
$value = 'HELLO MO !';
} else {
$value = $captionField->get_serialized_values();
}
$this->assertEquals($value, self::$DI['record_1']->get_caption()->get_dc_field(databox_Field_DCESAbstract::Contributor)->get_serialized_values());
}
/**
* @covers \caption_record::get_highlight_fields
* @todo Implement testGet_highlight_fields().
*/
public function testGet_highlight_fields()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_cache_key
* @todo Implement testGet_cache_key().
*/
public function testGet_cache_key()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_data_from_cache
* @todo Implement testGet_data_from_cache().
*/
public function testGet_data_from_cache()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::set_data_to_cache
* @todo Implement testSet_data_to_cache().
*/
public function testSet_data_to_cache()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::delete_data_from_cache
* @todo Implement testDelete_data_from_cache().
*/
public function testDelete_data_from_cache()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
}
| Java |
a, a:hover{color: #5FB0E4}
@font-face {font-family: Ebrima; font-weight:700; font-style:normal}
body {padding-top: 10px; background: #2b2d2e; height: 679px; background-size:cover; position:relative; color: #ffffff; letter-spacing: .05em; font-family: Ebrima, 'National Light', "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif}
.form-signIn { max-width: 400px; padding: 10px; margin: 0 auto; opacity: 1}
.form-signIn .form-control { position: relative; height: auto; padding: 10px; font-size: 16px; background-color: #fff; border: none}
.form-signIn input[type="email"], .form-signIn input[type="text"], .form-signIn input[type="password"], .form-signIn input[type="tel"]{ height: 45px; border-radius: 0; -webkit-border-radius: 0; -moz-border-radius: 0}
.form-signIn .btn{ border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px}
.btn-login, .btn-signUp{ background-color: #5FB0E4; border: none;color: #fff}
.btn-login, .btn-signUp{background-color: #5FB0E4; color: #fff}
.btn-login:hover, .btn-signUp:hover, .btn-login:active, .btn-signUp:active{color: lightgray}
.c-blue{color: #5FB0E4}
.space-top-8{margin-top:50px}
.footer-divider{border-color:#5FB0E4}
.space-top-1{margin-top: 1em}
.space-top-2{margin-top: 2em}
.space-bottom-2{margin-bottom: 2em} | Java |
from ..daltools.util.full import init
Z = [8., 1., 1.]
Rc = init([0.00000000, 0.00000000, 0.48860959])
Dtot = [0, 0, -0.76539388]
Daa = init([
[ 0.00000000, 0.00000000, -0.28357300],
[ 0.15342658, 0.00000000, 0.12734703],
[-0.15342658, 0.00000000, 0.12734703],
])
QUc = init([-7.31176220, 0., 0., -5.43243232, 0., -6.36258665])
QUN = init([4.38968295, 0., 0., 0., 0., 1.75400326])
QUaa = init([
[-3.29253618, 0.00000000, 0.00000000, -4.54316657, 0.00000000, -4.00465380],
[-0.13213704, 0.00000000, 0.24980518, -0.44463288, 0.00000000, -0.26059139],
[-0.13213704, 0.00000000,-0.24980518, -0.44463288, 0.00000000, -0.26059139]
])
Fab = init([
[-0.11E-03, 0.55E-04, 0.55E-04],
[ 0.55E-04, -0.55E-04, 0.16E-30],
[ 0.55E-04, 0.16E-30, -0.55E-04]
])
Lab = init([
[0.11E-03, 0.28E-03, 0.28E-03],
[0.28E-03, 0.17E-03, 0.22E-03],
[0.28E-03, 0.22E-03, 0.17E-03]
])
la = init([
[0.0392366,-27.2474016 , 27.2081650],
[0.0358964, 27.2214515 ,-27.2573479],
[0.01211180, -0.04775576, 0.03564396],
[0.01210615, -0.00594030, -0.00616584],
[10.69975088, -5.34987556, -5.34987532],
[-10.6565582, 5.3282791 , 5.3282791]
])
O = [
0.76145382,
-0.00001648, 1.75278523,
-0.00007538, 0.00035773, 1.39756345
]
H1O = [
3.11619527,
0.00019911, 1.25132346,
2.11363325, 0.00111442, 2.12790474
]
H1 = [
0.57935224,
0.00018083, 0.43312326,
0.11495546, 0.00004222, 0.45770123
]
H2O = [
3.11568759,
0.00019821, 1.25132443,
-2.11327482, -0.00142746, 2.12790473
]
H2H1 = [
0.04078206,
-0.00008380, -0.01712262,
-0.00000098, 0.00000084, -0.00200285
]
H2 = [
0.57930522,
0.00018221, 0.43312149,
-0.11493635, -0.00016407, 0.45770123
]
Aab = init([O, H1O, H1, H2O, H2H1, H2])
Aa = init([
[ 3.87739525, 0.00018217, 3.00410918, 0.00010384, 0.00020122, 3.52546819 ],
[ 2.15784091, 0.00023848, 1.05022368, 1.17177159, 0.00059985, 1.52065218 ],
[ 2.15754005, 0.00023941, 1.05022240, -1.17157425, -0.00087738, 1.52065217 ]
])
ff = 0.001
rMP = init([
#O
[
[-8.70343886, 0.00000000, 0.00000000, -0.39827574, -3.68114747, 0.00000000, 0.00000000, -4.58632761, 0.00000000, -4.24741556],
[-8.70343235, 0.00076124, 0.00000000, -0.39827535, -3.68114147, 0.00000000, 0.00193493, -4.58631888, 0.00000000, -4.24741290],
[-8.70343291,-0.00076166, 0.00000000, -0.39827505, -3.68114128, 0.00000000, -0.00193603, -4.58631789, 0.00000000, -4.24741229],
[-8.70343685,-0.00000006, 0.00175241, -0.39827457, -3.68114516, 0.00000000, 0.00000161, -4.58632717, 0.00053363, -4.24741642],
[-8.70343685, 0.00000000, -0.00175316, -0.39827456, -3.68114514, 0.00000000, 0.00000000, -4.58632711, -0.00053592, -4.24741639],
[-8.70166502, 0.00000000, 0.00000144, -0.39688042, -3.67884999, 0.00000000, 0.00000000, -4.58395384, 0.00000080, -4.24349307],
[-8.70520554, 0.00000000, 0.00000000, -0.39967554, -3.68344246, 0.00000000, 0.00000000, -4.58868836, 0.00000000, -4.25134640],
],
#H1O
[
[ 0.00000000, 0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, 0.43066796, 0.04316104, 0.00000000, 0.36285790],
[ 0.00150789, 0.10111974, 0.00000000, 0.11541803, 0.53753360, 0.00000000, 0.43120945, 0.04333774, 0.00000000, 0.36314215],
[-0.00150230, 0.09934695, 0.00000000, 0.11398581, 0.53667861, 0.00000000, 0.43012612, 0.04298361, 0.00000000, 0.36257249],
[ 0.00000331, 0.10023328, 0.00125017, 0.11470067, 0.53710812, -0.00006107, 0.43066944, 0.04316020, 0.00015952, 0.36285848],
[ 0.00000100, 0.10023249, -0.00125247, 0.11470042, 0.53710716, 0.00006135, 0.43066837, 0.04316018, -0.00015966, 0.36285788],
[ 0.00088692, 0.10059268, -0.00000064, 0.11590322, 0.53754715, -0.00000006, 0.43071206, 0.04334198, -0.00000015, 0.36330053],
[-0.00088334, 0.09987383, 0.00000000, 0.11350091, 0.53666602, 0.00000000, 0.43062352, 0.04297910, 0.00000000, 0.36241326],
],
#H1
[
[-0.64828057, 0.10330994, 0.00000000, 0.07188960, -0.47568174, 0.00000000, -0.03144252, -0.46920879, 0.00000000, -0.50818752],
[-0.64978846, 0.10389186, 0.00000000, 0.07204462, -0.47729337, 0.00000000, -0.03154159, -0.47074619, 0.00000000, -0.50963693],
[-0.64677827, 0.10273316, 0.00000000, 0.07173584, -0.47408263, 0.00000000, -0.03134407, -0.46768337, 0.00000000, -0.50674873],
[-0.64828388, 0.10331167, 0.00043314, 0.07189029, -0.47568875, -0.00023642, -0.03144270, -0.46921635, -0.00021728, -0.50819386],
[-0.64828157, 0.10331095, -0.00043311, 0.07188988, -0.47568608, 0.00023641, -0.03144256, -0.46921346, 0.00021729, -0.50819095],
[-0.64916749, 0.10338629, -0.00000024, 0.07234862, -0.47634698, 0.00000013, -0.03159569, -0.47003679, 0.00000011, -0.50936853],
[-0.64739723, 0.10323524, 0.00000000, 0.07143322, -0.47502412, 0.00000000, -0.03129003, -0.46838912, 0.00000000, -0.50701656],
],
#H2O
[
[ 0.00000000,-0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, -0.43066796, 0.04316104, 0.00000000, 0.36285790],
[-0.00150139,-0.09934749, 0.00000000, 0.11398482, 0.53667874, 0.00000000, -0.43012670, 0.04298387, 0.00000000, 0.36257240],
[ 0.00150826,-0.10112008, 0.00000000, 0.11541676, 0.53753350, 0.00000000, -0.43120982, 0.04333795, 0.00000000, 0.36314186],
[-0.00000130,-0.10023170, 0.00125018, 0.11470018, 0.53710620, 0.00006107, -0.43066732, 0.04316017, 0.00015952, 0.36285728],
[ 0.00000101,-0.10023249, -0.00125247, 0.11470042, 0.53710716, -0.00006135, -0.43066838, 0.04316018, -0.00015966, 0.36285788],
[ 0.00088692,-0.10059268, -0.00000064, 0.11590322, 0.53754715, 0.00000006, -0.43071206, 0.04334198, -0.00000015, 0.36330053],
[-0.00088334,-0.09987383, 0.00000000, 0.11350091, 0.53666602, 0.00000000, -0.43062352, 0.04297910, 0.00000000, 0.36241326],
],
#H2H1
[
[ 0.00000000, 0.00000000, 0.00000000, -0.00378789, 0.00148694, 0.00000000, 0.00000000, 0.00599079, 0.00000000, 0.01223822],
[ 0.00000000, 0.00004089, 0.00000000, -0.00378786, 0.00148338, 0.00000000, -0.00004858, 0.00599281, 0.00000000, 0.01224094],
[ 0.00000000,-0.00004067, 0.00000000, -0.00378785, 0.00148341, 0.00000000, 0.00004861, 0.00599277, 0.00000000, 0.01224093],
[ 0.00000000,-0.00000033, -0.00001707, -0.00378763, 0.00149017, 0.00000000, 0.00000001, 0.00599114, -0.00001229, 0.01223979],
[ 0.00000000, 0.00000000, 0.00001717, -0.00378763, 0.00149019, 0.00000000, 0.00000000, 0.00599114, 0.00001242, 0.01223980],
[ 0.00000000, 0.00000000, 0.00000000, -0.00378978, 0.00141897, 0.00000000, 0.00000000, 0.00590445, 0.00000002, 0.01210376],
[ 0.00000000, 0.00000000, 0.00000000, -0.00378577, 0.00155694, 0.00000000, 0.00000000, 0.00607799, 0.00000000, 0.01237393],
],
#H2
[
[-0.64828057,-0.10330994, 0.00000000, 0.07188960, -0.47568174, 0.00000000, 0.03144252, -0.46920879, 0.00000000, -0.50818752],
[-0.64677918,-0.10273369, 0.00000000, 0.07173576, -0.47408411, 0.00000000, 0.03134408, -0.46768486, 0.00000000, -0.50674986],
[-0.64978883,-0.10389230, 0.00000000, 0.07204446, -0.47729439, 0.00000000, 0.03154159, -0.47074717, 0.00000000, -0.50963754],
[-0.64827927,-0.10331022, 0.00043313, 0.07188947, -0.47568340, 0.00023642, 0.03144242, -0.46921057, -0.00021727, -0.50818804],
[-0.64828158,-0.10331095, -0.00043311, 0.07188988, -0.47568609, -0.00023641, 0.03144256, -0.46921348, 0.00021729, -0.50819097],
[-0.64916749,-0.10338629, -0.00000024, 0.07234862, -0.47634698, -0.00000013, 0.03159569, -0.47003679, 0.00000011, -0.50936853],
[-0.64739723,-0.10323524, 0.00000000, 0.07143322, -0.47502412, 0.00000000, 0.03129003, -0.46838912, 0.00000000, -0.50701656]
]
])
Am = init([
[8.186766009140, 0., 0.],
[0., 5.102747935447, 0.],
[0., 0., 6.565131856389]
])
Amw = init([
[11.98694996213, 0., 0.],
[0., 4.403583657738, 0.],
[0., 0., 2.835142058626]
])
R = [
[ 0.00000, 0.00000, 0.69801],
[-1.48150, 0.00000, -0.34901],
[ 1.48150, 0.00000, -0.34901]
]
Qtot = -10.0
Q = rMP[0, 0, (0, 2, 5)]
D = rMP[1:4, 0, :]
QU = rMP[4:, 0, :]
dQa = rMP[0, :, (0,2,5)]
dQab = rMP[0, :, (1, 3, 4)]
#These are string data for testing potential file
PAn0 = """AU
3 -1 0 1
1 0.000 0.000 0.698
1 -1.481 0.000 -0.349
1 1.481 0.000 -0.349
"""
PA00 = """AU
3 0 0 1
1 0.000 0.000 0.698 -0.703
1 -1.481 0.000 -0.349 0.352
1 1.481 0.000 -0.349 0.352
"""
PA10 = """AU
3 1 0 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127
"""
PA20 = """AU
3 2 0 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261
"""
PA21 = """AU
3 2 1 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 3.466
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 1.576
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 1.576
"""
PA22 = """AU
3 2 2 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 3.875 -0.000 -0.000 3.000 -0.000 3.524
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 2.156 -0.000 1.106 1.051 -0.000 1.520
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 2.156 -0.000 -1.106 1.051 -0.000 1.520
"""
OUTPUT_n0_1 = """\
---------------
Atomic domain 1
---------------
Domain center: 0.00000 0.00000 0.69801
"""
OUTPUT_00_1 = OUTPUT_n0_1 + """\
Nuclear charge: 8.00000
Electronic charge: -8.70344
Total charge: -0.70344
"""
OUTPUT_10_1 = OUTPUT_00_1 + """\
Electronic dipole -0.00000 0.00000 -0.28357
"""
OUTPUT_20_1 = OUTPUT_10_1 + """\
Electronic quadrupole -3.29254 0.00000 -0.00000 -4.54317 0.00000 -4.00466
"""
OUTPUT_01_1 = OUTPUT_00_1 + """\
Isotropic polarizablity (w=0) 3.46639
"""
OUTPUT_02_1 = OUTPUT_00_1 + """\
Electronic polarizability (w=0) 3.87468 -0.00000 3.00027 -0.00000 -0.00000 3.52422
"""
| Java |
import inctest
error = 0
try:
a = inctest.A()
except:
print "didn't find A"
print "therefore, I didn't include 'testdir/subdir1/hello.i'"
error = 1
pass
try:
b = inctest.B()
except:
print "didn't find B"
print "therefore, I didn't include 'testdir/subdir2/hello.i'"
error = 1
pass
if error == 1:
raise RuntimeError
# Check the import in subdirectory worked
if inctest.importtest1(5) != 15:
print "import test 1 failed"
raise RuntimeError
if inctest.importtest2("black") != "white":
print "import test 2 failed"
raise RuntimeError
| Java |
/***************************************************************
* This source files comes from the xLights project
* https://www.xlights.org
* https://github.com/smeighan/xLights
* See the github commit history for a record of contributing
* developers.
* Copyright claimed based on commit dates recorded in Github
* License: https://github.com/smeighan/xLights/blob/master/License.txt
**************************************************************/
#include "PlayListItemAudioPanel.h"
#include "PlayListItemAudio.h"
#include "PlayListDialog.h"
#include "PlayListSimpleDialog.h"
//(*InternalHeaders(PlayListItemAudioPanel)
#include <wx/intl.h>
#include <wx/string.h>
//*)
//(*IdInit(PlayListItemAudioPanel)
const long PlayListItemAudioPanel::ID_STATICTEXT2 = wxNewId();
const long PlayListItemAudioPanel::ID_FILEPICKERCTRL2 = wxNewId();
const long PlayListItemAudioPanel::ID_CHECKBOX2 = wxNewId();
const long PlayListItemAudioPanel::ID_SLIDER1 = wxNewId();
const long PlayListItemAudioPanel::ID_CHECKBOX1 = wxNewId();
const long PlayListItemAudioPanel::ID_STATICTEXT4 = wxNewId();
const long PlayListItemAudioPanel::ID_SPINCTRL1 = wxNewId();
const long PlayListItemAudioPanel::ID_STATICTEXT3 = wxNewId();
const long PlayListItemAudioPanel::ID_TEXTCTRL1 = wxNewId();
//*)
BEGIN_EVENT_TABLE(PlayListItemAudioPanel,wxPanel)
//(*EventTable(PlayListItemAudioPanel)
//*)
END_EVENT_TABLE()
class AudioFilePickerCtrl : public wxFilePickerCtrl
{
public:
AudioFilePickerCtrl(wxWindow *parent,
wxWindowID id,
const wxString& path = wxEmptyString,
const wxString& message = wxFileSelectorPromptStr,
const wxString& wildcard = wxFileSelectorDefaultWildcardStr,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxFLP_DEFAULT_STYLE,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxFilePickerCtrlNameStr) :
wxFilePickerCtrl(parent, id, path, message, AUDIOFILES, pos, size, style, validator, name)
{}
virtual ~AudioFilePickerCtrl() {}
};
PlayListItemAudioPanel::PlayListItemAudioPanel(wxWindow* parent, PlayListItemAudio* audio, wxWindowID id,const wxPoint& pos,const wxSize& size)
{
_audio = audio;
//(*Initialize(PlayListItemAudioPanel)
wxFlexGridSizer* FlexGridSizer1;
Create(parent, id, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("id"));
FlexGridSizer1 = new wxFlexGridSizer(0, 2, 0, 0);
FlexGridSizer1->AddGrowableCol(1);
StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("Audio File:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
FlexGridSizer1->Add(StaticText2, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
FilePickerCtrl_AudioFile = new AudioFilePickerCtrl(this, ID_FILEPICKERCTRL2, wxEmptyString, _("Audio File"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxFLP_FILE_MUST_EXIST|wxFLP_OPEN|wxFLP_USE_TEXTCTRL, wxDefaultValidator, _T("ID_FILEPICKERCTRL2"));
FlexGridSizer1->Add(FilePickerCtrl_AudioFile, 1, wxALL|wxEXPAND, 5);
FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
CheckBox_OverrideVolume = new wxCheckBox(this, ID_CHECKBOX2, _("Override Volume"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX2"));
CheckBox_OverrideVolume->SetValue(false);
FlexGridSizer1->Add(CheckBox_OverrideVolume, 1, wxALL|wxEXPAND, 5);
FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
Slider1 = new wxSlider(this, ID_SLIDER1, 100, 0, 100, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_SLIDER1"));
FlexGridSizer1->Add(Slider1, 1, wxALL|wxEXPAND, 5);
FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
CheckBox_FastStartAudio = new wxCheckBox(this, ID_CHECKBOX1, _("Fast Start Audio"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1"));
CheckBox_FastStartAudio->SetValue(false);
FlexGridSizer1->Add(CheckBox_FastStartAudio, 1, wxALL|wxEXPAND, 5);
StaticText4 = new wxStaticText(this, ID_STATICTEXT4, _("Priority:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT4"));
FlexGridSizer1->Add(StaticText4, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
SpinCtrl_Priority = new wxSpinCtrl(this, ID_SPINCTRL1, _T("5"), wxDefaultPosition, wxDefaultSize, 0, 1, 10, 5, _T("ID_SPINCTRL1"));
SpinCtrl_Priority->SetValue(_T("5"));
FlexGridSizer1->Add(SpinCtrl_Priority, 1, wxALL|wxEXPAND, 5);
StaticText3 = new wxStaticText(this, ID_STATICTEXT3, _("Delay:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3"));
FlexGridSizer1->Add(StaticText3, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
TextCtrl_Delay = new wxTextCtrl(this, ID_TEXTCTRL1, _("0.000"), wxDefaultPosition, wxDefaultSize, wxTE_RIGHT, wxDefaultValidator, _T("ID_TEXTCTRL1"));
FlexGridSizer1->Add(TextCtrl_Delay, 1, wxALL|wxEXPAND, 5);
SetSizer(FlexGridSizer1);
FlexGridSizer1->Fit(this);
FlexGridSizer1->SetSizeHints(this);
Connect(ID_FILEPICKERCTRL2,wxEVT_COMMAND_FILEPICKER_CHANGED,(wxObjectEventFunction)&PlayListItemAudioPanel::OnFilePickerCtrl2FileChanged);
Connect(ID_CHECKBOX2,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&PlayListItemAudioPanel::OnCheckBox_OverrideVolumeClick);
//*)
FilePickerCtrl_AudioFile->SetFileName(wxFileName(audio->GetAudioFile()));
TextCtrl_Delay->SetValue(wxString::Format(wxT("%.3f"), (float)audio->GetDelay() / 1000.0));
CheckBox_FastStartAudio->SetValue(audio->GetFastStartAudio());
if (audio->GetVolume() != -1)
{
CheckBox_OverrideVolume->SetValue(true);
Slider1->SetValue(audio->GetVolume());
}
else
{
CheckBox_OverrideVolume->SetValue(false);
}
ValidateWindow();
}
PlayListItemAudioPanel::~PlayListItemAudioPanel()
{
//(*Destroy(PlayListItemAudioPanel)
//*)
_audio->SetDelay(wxAtof(TextCtrl_Delay->GetValue()) * 1000);
_audio->SetFastStartAudio(CheckBox_FastStartAudio->GetValue());
if (CheckBox_OverrideVolume->GetValue())
{
_audio->SetVolume(Slider1->GetValue());
}
else
{
_audio->SetVolume(-1);
}
_audio->SetAudioFile(FilePickerCtrl_AudioFile->GetFileName().GetFullPath().ToStdString());
}
void PlayListItemAudioPanel::OnTextCtrl_DelayText(wxCommandEvent& event)
{
}
void PlayListItemAudioPanel::OnFilePickerCtrl2FileChanged(wxFileDirPickerEvent& event)
{
_audio->SetAudioFile(FilePickerCtrl_AudioFile->GetFileName().GetFullPath().ToStdString());
wxCommandEvent e(EVT_UPDATEITEMNAME);
wxPostEvent(GetParent()->GetParent()->GetParent()->GetParent(), e);
}
void PlayListItemAudioPanel::ValidateWindow()
{
if (CheckBox_OverrideVolume->GetValue())
{
Slider1->Enable();
}
else
{
Slider1->Enable(false);
}
}
void PlayListItemAudioPanel::OnCheckBox_OverrideVolumeClick(wxCommandEvent& event)
{
ValidateWindow();
}
| Java |
Что такое танец?
Для чего люди, по видимому, серьезные и спокойные, двигающиеся обычно вполне целесообразно, вдруг срываются с места и начинают производить телодвижения, весьма утомительные и явно бесполезные?
Потребность танца объясняют различным образом.
Некоторые господа дошли даже до того, что придают ему значение мистическое, молитвенное. Может быть, это и так, но в таком случае о молитве эти господа имеют довольно своеобразное представление.
Полагаю, что реальное наблюдение над танцем ответит на вопрос точнее, чем какая либо философская теория.
***
В век сентиментализма, то есть лжи, которую многие считают красивой, наши предки танцевали менуэт: мужчина и женщина с робким видом приближались друг к другу и отдалялись друг от друга.
> Жест мужчины: — О, прошу тебя!
>
> Жест женщины: — Нет, не хочу.
>
> Далее: — Я умоляю.
>
> Она: — Я боюсь.
>
> Затем: — Я умру.
>
> Она: — А... Ну, в таком случае...
На этом менуэт прерывался, заканчиваясь разве что мимолетным, почтительным объятием.
Сентиментализм (в танце) скоро приелся. Люди отбросили всю предварительную часть, которой посвящен был менуэт, и прямо перешли к его заключению, развивая его в прямой последовательности: они сразу начали бросаться в объятия друг друга.
Явился вальс.
Правда, и в этом была наглядная последовательность: сначала объятья вальса были, так сказать, схематическими, условными: мужчина держался от женщины на некотором отдалении. Затем приблизился. Затем прижался.
Вальс «modern» особенно поучителен в этом отношении.
Я оставляю без внимания польку, потому что она только грубее вальса по внешности, но суть ее та же самая. Я перехожу к танцу, называемому «кэк-уок».
Он развивался у нас на глазах и все его знают. Отмечу в нем одну особенность, которая может быть для некоторых явится новой.
В Америке — родина «кэк-уока» — высшим преступлением топа считает изнасилование негром белой женщины.
И вот самый «шикарный» кэк-уок исполняется негром и белой женщиной. Что они проделывают на сцене — вы сами видели.
Кэк-уок это менуэт XX века. Он также посвящен предварительной части, но в нем уже ясно, о чем идет речь, хотя, как и в менуэте дело не заходит дальше мимолетного объятия, которое я уже не назвал бы почтительным.
***
Разъяснителем танца поистине является матчиш, про который поется: «Матчиш хороший танец и очень жгучий, привез его испанец, брюнет могучий» и т. д.
Он настолько понятен, что его даже не решались сразу показать публике во всем объеме: сначала танцевала его женщина — solo, затем несколько женщин вместе, и только после того мужчина с женщиной.
Как в девятнадцатом веке менуэт был сменен вальсом, так и в двадцатом кэк-уок перешел в матчиш.
Рукопожатия закончились объятиями. В матчише они только более реальны, чем в вальсе. Вы видели?
В Париже, говорят, матчиш уже танцуют без костюмов.
***
Желающим в один урок постигнуть всю психологию танца я посоветовал бы посмотреть хоть один раз тетеревиный ток. Там они все увидят: начиная с менуэта, продолжая вальсом, кэк-уоком и кончая матчишем... и даже немного далее.
_Зой_
| Java |
// ************************************************************************** //
//
// BornAgain: simulate and fit scattering at grazing incidence
//
//! @file Fit/RootAdapter/GSLMultiMinimizer.h
//! @brief Declares class GSLMultiMinimizer.
//!
//! @homepage http://www.bornagainproject.org
//! @license GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
// ************************************************************************** //
#ifndef GSLMULTIMINIMIZER_H
#define GSLMULTIMINIMIZER_H
#include "MinimizerConstants.h"
#include "RootMinimizerAdapter.h"
namespace ROOT { namespace Math { class GSLMinimizer; } }
//! Wrapper for the CERN ROOT facade of the GSL multi minimizer family (gradient descent based).
//! @ingroup fitting_internal
class BA_CORE_API_ GSLMultiMinimizer : public RootMinimizerAdapter
{
public:
explicit GSLMultiMinimizer(const std::string& algorithmName = AlgorithmNames::ConjugateFR);
~GSLMultiMinimizer();
//! Sets minimizer internal print level.
void setPrintLevel(int value);
int printLevel() const;
//! Sets maximum number of iterations. This is an internal minimizer setting which has
//! no direct relation to the number of objective function calls (e.g. numberOfIteraction=5
//! might correspond to ~100 objective function calls).
void setMaxIterations(int value);
int maxIterations() const;
std::string statusToString() const override;
protected:
void propagateOptions() override;
const root_minimizer_t* rootMinimizer() const override;
private:
std::unique_ptr<ROOT::Math::GSLMinimizer> m_gsl_minimizer;
};
#endif // GSLMULTIMINIMIZER_H
| Java |
-- git
ALTER TABLE gitinfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Website`;
ALTER TABLE gitinfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`;
-- hg
ALTER TABLE hginfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Website`;
ALTER TABLE hginfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`;
-- svn
ALTER TABLE svninfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Website`;
ALTER TABLE svninfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`;
-- mantisbt
ALTER TABLE mantisbt ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Link`;
ALTER TABLE mantisbt ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`;
-- wordpress
ALTER TABLE wordpressinfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Link`;
ALTER TABLE wordpressinfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`;
| Java |
/*
* Copyright (c) 1982, 1986, 1988, 1993
* The Regents of the University of California. 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.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)syslog.h 8.1 (Berkeley) 6/2/93
*/
#ifndef _SYS_SYSLOG_H
#define _SYS_SYSLOG_H 1
#include <features.h>
#define __need___va_list
#include <stdarg.h>
#define _PATH_LOG "/dev/log"
/*
* priorities/facilities are encoded into a single 32-bit quantity, where the
* bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
* (0-big number). Both the priorities and the facilities map roughly
* one-to-one to strings in the syslogd(8) source code. This mapping is
* included in this file.
*
* priorities (these are ordered)
*/
#define LOG_EMERG 0 /* system is unusable */
#define LOG_ALERT 1 /* action must be taken immediately */
#define LOG_CRIT 2 /* critical conditions */
#define LOG_ERR 3 /* error conditions */
#define LOG_WARNING 4 /* warning conditions */
#define LOG_NOTICE 5 /* normal but significant condition */
#define LOG_INFO 6 /* informational */
#define LOG_DEBUG 7 /* debug-level messages */
#define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */
/* extract priority */
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
#define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri))
#ifdef SYSLOG_NAMES
#define INTERNAL_NOPRI 0x10 /* the "no priority" priority */
/* mark "facility" */
#define INTERNAL_MARK LOG_MAKEPRI(LOG_NFACILITIES, 0)
typedef struct _code {
char *c_name;
int c_val;
} CODE;
CODE prioritynames[] =
{
{ "alert", LOG_ALERT },
{ "crit", LOG_CRIT },
{ "debug", LOG_DEBUG },
{ "emerg", LOG_EMERG },
{ "err", LOG_ERR },
{ "error", LOG_ERR }, /* DEPRECATED */
{ "info", LOG_INFO },
{ "none", INTERNAL_NOPRI }, /* INTERNAL */
{ "notice", LOG_NOTICE },
{ "panic", LOG_EMERG }, /* DEPRECATED */
{ "warn", LOG_WARNING }, /* DEPRECATED */
{ "warning", LOG_WARNING },
{ NULL, -1 }
};
#endif
/* facility codes */
#define LOG_KERN (0<<3) /* kernel messages */
#define LOG_USER (1<<3) /* random user-level messages */
#define LOG_MAIL (2<<3) /* mail system */
#define LOG_DAEMON (3<<3) /* system daemons */
#define LOG_AUTH (4<<3) /* security/authorization messages */
#define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */
#define LOG_LPR (6<<3) /* line printer subsystem */
#define LOG_NEWS (7<<3) /* network news subsystem */
#define LOG_UUCP (8<<3) /* UUCP subsystem */
#define LOG_CRON (9<<3) /* clock daemon */
#define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */
#define LOG_FTP (11<<3) /* ftp daemon */
/* other codes through 15 reserved for system use */
#define LOG_LOCAL0 (16<<3) /* reserved for local use */
#define LOG_LOCAL1 (17<<3) /* reserved for local use */
#define LOG_LOCAL2 (18<<3) /* reserved for local use */
#define LOG_LOCAL3 (19<<3) /* reserved for local use */
#define LOG_LOCAL4 (20<<3) /* reserved for local use */
#define LOG_LOCAL5 (21<<3) /* reserved for local use */
#define LOG_LOCAL6 (22<<3) /* reserved for local use */
#define LOG_LOCAL7 (23<<3) /* reserved for local use */
#define LOG_NFACILITIES 24 /* current number of facilities */
#define LOG_FACMASK 0x03f8 /* mask to extract facility part */
/* facility of pri */
#define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3)
#ifdef SYSLOG_NAMES
CODE facilitynames[] =
{
{ "auth", LOG_AUTH },
{ "authpriv", LOG_AUTHPRIV },
{ "cron", LOG_CRON },
{ "daemon", LOG_DAEMON },
{ "ftp", LOG_FTP },
{ "kern", LOG_KERN },
{ "lpr", LOG_LPR },
{ "mail", LOG_MAIL },
{ "mark", INTERNAL_MARK }, /* INTERNAL */
{ "news", LOG_NEWS },
{ "security", LOG_AUTH }, /* DEPRECATED */
{ "syslog", LOG_SYSLOG },
{ "user", LOG_USER },
{ "uucp", LOG_UUCP },
{ "local0", LOG_LOCAL0 },
{ "local1", LOG_LOCAL1 },
{ "local2", LOG_LOCAL2 },
{ "local3", LOG_LOCAL3 },
{ "local4", LOG_LOCAL4 },
{ "local5", LOG_LOCAL5 },
{ "local6", LOG_LOCAL6 },
{ "local7", LOG_LOCAL7 },
{ NULL, -1 }
};
#endif
/*
* arguments to setlogmask.
*/
#define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */
#define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */
/*
* Option flags for openlog.
*
* LOG_ODELAY no longer does anything.
* LOG_NDELAY is the inverse of what it used to be.
*/
#define LOG_PID 0x01 /* log the pid with each message */
#define LOG_CONS 0x02 /* log on the console if errors in sending */
#define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
#define LOG_NDELAY 0x08 /* don't delay open */
#define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
#define LOG_PERROR 0x20 /* log to stderr as well */
__BEGIN_DECLS
/* Close descriptor used to write to system logger.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern void closelog (void);
/* Open connection to system logger.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern void openlog (__const char *__ident, int __option, int __facility);
/* Set the log mask level. */
extern int setlogmask (int __mask) __THROW;
/* Generate a log message using FMT string and option arguments.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern void syslog (int __pri, __const char *__fmt, ...)
__attribute__ ((__format__(__printf__, 2, 3)));
#ifdef __USE_BSD
/* Generate a log message using FMT and using arguments pointed to by AP.
This function is not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation it is a cancellation point and
therefore not marked with __THROW. */
extern void vsyslog (int __pri, __const char *__fmt, __gnuc_va_list __ap)
__attribute__ ((__format__(__printf__, 2, 0)));
#endif
__END_DECLS
#endif /* sys/syslog.h */
| Java |
from __future__ import absolute_import, print_function, division
from mitmproxy import exceptions
import pprint
def _get_name(itm):
return getattr(itm, "name", itm.__class__.__name__)
class Addons(object):
def __init__(self, master):
self.chain = []
self.master = master
master.options.changed.connect(self.options_update)
def options_update(self, options, updated):
for i in self.chain:
with self.master.handlecontext():
i.configure(options, updated)
def add(self, options, *addons):
if not addons:
raise ValueError("No addons specified.")
self.chain.extend(addons)
for i in addons:
self.invoke_with_context(i, "start")
self.invoke_with_context(
i,
"configure",
self.master.options,
self.master.options.keys()
)
def remove(self, addon):
self.chain = [i for i in self.chain if i is not addon]
self.invoke_with_context(addon, "done")
def done(self):
for i in self.chain:
self.invoke_with_context(i, "done")
def has_addon(self, name):
"""
Is an addon with this name registered?
"""
for i in self.chain:
if _get_name(i) == name:
return True
def __len__(self):
return len(self.chain)
def __str__(self):
return pprint.pformat([str(i) for i in self.chain])
def invoke_with_context(self, addon, name, *args, **kwargs):
with self.master.handlecontext():
self.invoke(addon, name, *args, **kwargs)
def invoke(self, addon, name, *args, **kwargs):
func = getattr(addon, name, None)
if func:
if not callable(func):
raise exceptions.AddonError(
"Addon handler %s not callable" % name
)
func(*args, **kwargs)
def __call__(self, name, *args, **kwargs):
for i in self.chain:
self.invoke(i, name, *args, **kwargs)
| Java |
#! /usr/bin/env python
#################################################################################################
#
# Script Name: bip.py
# Script Usage: This script is the menu system and runs everything else. Do not use other
# files unless you are comfortable with the code.
#
# It has the following:
# 1.
# 2.
# 3.
# 4.
#
# You will probably want to do the following:
# 1. Make sure the info in bip_config.py is correct.
# 2. Make sure GAM (Google Apps Manager) is installed and the path is correct.
# 3. Make sure the AD scripts in toos/ are present on the DC running run.ps1.
#
# Script Updates:
# 201709191243 - [email protected] - copied boilerplate.
#
#################################################################################################
import os # os.system for clearing screen and simple gam calls
import subprocess # subprocess.Popen is to capture gam output (needed for user info in particular)
import MySQLdb # MySQLdb is to get data from relevant tables
import csv # CSV is used to read output of drive commands that supply data in CSV form
import bip_config # declare installation specific variables
# setup for MySQLdb connection
varMySQLHost = bip_config.mysqlconfig['host']
varMySQLUser = bip_config.mysqlconfig['user']
varMySQLPassword = bip_config.mysqlconfig['password']
varMySQLDB = bip_config.mysqlconfig['db']
# setup to find GAM
varCommandGam = bip_config.gamconfig['fullpath']
#################################################################################################
#
#################################################################################################
| Java |
/*
* Copyright (c) 2013 The Interedition Development Group.
*
* This file is part of CollateX.
*
* CollateX 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.
*
* CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.interedition.text.xml;
import com.google.common.base.Objects;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLStreamReader;
import java.util.Stack;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public class WhitespaceCompressor extends ConversionFilter {
private final Stack<Boolean> spacePreservationContext = new Stack<Boolean>();
private final WhitespaceStrippingContext whitespaceStrippingContext;
private char lastChar = ' ';
public WhitespaceCompressor(WhitespaceStrippingContext whitespaceStrippingContext) {
this.whitespaceStrippingContext = whitespaceStrippingContext;
}
@Override
public void start() {
spacePreservationContext.clear();
whitespaceStrippingContext.reset();
lastChar = ' ';
}
@Override
protected void onXMLEvent(XMLStreamReader reader) {
whitespaceStrippingContext.onXMLEvent(reader);
if (reader.isStartElement()) {
spacePreservationContext.push(spacePreservationContext.isEmpty() ? false : spacePreservationContext.peek());
final Object xmlSpace = reader.getAttributeValue(XMLConstants.XML_NS_URI, "space");
if (xmlSpace != null) {
spacePreservationContext.pop();
spacePreservationContext.push("preserve".equalsIgnoreCase(xmlSpace.toString()));
}
} else if (reader.isEndElement()) {
spacePreservationContext.pop();
}
}
String compress(String text) {
final StringBuilder compressed = new StringBuilder();
final boolean preserveSpace = Objects.firstNonNull(spacePreservationContext.peek(), false);
for (int cc = 0, length = text.length(); cc < length; cc++) {
char currentChar = text.charAt(cc);
if (!preserveSpace && Character.isWhitespace(currentChar) && (Character.isWhitespace(lastChar) || whitespaceStrippingContext.isInContainerElement())) {
continue;
}
if (currentChar == '\n' || currentChar == '\r') {
currentChar = ' ';
}
compressed.append(lastChar = currentChar);
}
return compressed.toString();
}
}
| Java |
/*
* Copyright (C) 2016-2021 David Rubio Escares / Kodehawa
*
* Mantaro 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.
* Mantaro 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 Mantaro. If not, see http://www.gnu.org/licenses/
*/
package net.kodehawa.mantarobot.commands.currency.profile;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class BadgeUtils {
public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) {
BufferedImage avatar;
BufferedImage badge;
try {
avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes));
badge = ImageIO.read(new ByteArrayInputStream(badgeBytes));
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
WritableRaster raster = badge.getRaster();
if (allWhite) {
for (int xx = 0, width = badge.getWidth(); xx < width; xx++) {
for (int yy = 0, height = badge.getHeight(); yy < height; yy++) {
int[] pixels = raster.getPixel(xx, yy, (int[]) null);
pixels[0] = 255;
pixels[1] = 255;
pixels[2] = 255;
pixels[3] = pixels[3] == 255 ? 165 : 0;
raster.setPixel(xx, yy, pixels);
}
}
}
BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB);
int circleCenterX = 88, circleCenterY = 88;
int width = 32, height = 32;
int circleRadius = 40;
Graphics2D g2d = res.createGraphics();
g2d.drawImage(avatar, 0, 0, 128, 128, null);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(0, 0, 165, 165));
g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius);
g2d.drawImage(badge, startX, startY, width, height, null);
g2d.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(res, "png", baos);
} catch (IOException e) {
throw new AssertionError(e);
}
return baos.toByteArray();
}
}
| Java |
require 'polyhoraire/auth'
require 'test/unit'
require 'yaml'
class TestAuth < Test::Unit::TestCase
def setup
@config = YAML.load_file("conf/test_poly.yaml")
end
def test_connect
assert_nothing_raised do
auth = Poly::Auth.new
user = @config['credentials']['user']
password = @config['credentials']['password']
bday = @config['credentials']['bday']
auth.connect(user,password,bday)
end
end
end
| Java |
# Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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.
#
# ESPResSo++ 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/>.
r"""
********************************************
**espressopp.integrator.LangevinThermostat**
********************************************
.. function:: espressopp.integrator.LangevinThermostat(system)
:param system:
:type system:
"""
from espressopp.esutil import cxxinit
from espressopp import pmi
from espressopp.integrator.Extension import *
from _espressopp import integrator_LangevinThermostat
class LangevinThermostatLocal(ExtensionLocal, integrator_LangevinThermostat):
def __init__(self, system):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, integrator_LangevinThermostat, system)
#def enableAdress(self):
# if pmi.workerIsActive():
# self.cxxclass.enableAdress(self);
if pmi.isController :
class LangevinThermostat(Extension):
__metaclass__ = pmi.Proxy
pmiproxydefs = dict(
cls = 'espressopp.integrator.LangevinThermostatLocal',
pmiproperty = [ 'gamma', 'temperature', 'adress' ]
)
| Java |
asm(1000){
var a = 1;
};
| Java |
<?php
/**
* Modify layout using filter
*/
/**
* Available actions (by ref)
* dynamic_block_{block_name}_before where block_name is name of block e.g. header. action can have two arguments "block" and "block_settings" as array
* dynamic_block_{block_name}_before_block_items
* dynamic_block_{block_name}_after where block_name is name of block e.g. header. action can have two arguments "block" and "block_settings" as array
* If you want to disable certain block base on certain condition(s), you can add hide key to $block
* You can override render callback of block items by writing a function theme_block_item_{block_item_id} where block_item_id is id of block item e.g. widget, shortcode, post_loop etc.
*/
/**
* Manipulate block items at runtime.
* Add logos dynamically without providing any control to user.
*
* @since 1.0.0.0
*
* @param ref array $block_items list of block items in a block
* @return void
*/
function le_theme_filter_header_block_items(&$block_items)
{
if(!empty($block_items))
{
$blocks_new = array();
$blocks_new[] = array(
'id' => 'theme_logo',
'name' => 'Runtime Logos',
'title' => '',
'columns' => 3,
'runtime_id' => 'o7r7ot',
'args' => array()
);
foreach($block_items as $item)
$blocks_new[] = $item;
$block_items = $blocks_new;
}
}
add_action('dynamic_block_header_before_block_items', 'le_theme_filter_header_block_items')
?> | Java |
/*******************************************************************************
* Copyright (c) 2014 Tombenpotter.
* All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at http://www.gnu.org/licenses/gpl.html
*
* This class was made by Tombenpotter and is distributed as a part of the Electro-Magic Tools mod.
* Electro-Magic Tools is a derivative work on Thaumcraft 4 (c) Azanor 2012.
* http://www.minecraftforum.net/topic/1585216-
******************************************************************************/
package tombenpotter.emt.common.util;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
public class ResearchAspects {
public static AspectList thaumiumDrillResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.TOOL, 6).add(Aspect.MINE, 4);
public static AspectList thaumiumChainsawResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.WEAPON, 6).add(Aspect.TOOL, 4);
public static AspectList thaumicQuantumHelmet = new AspectList().add(Aspect.ARMOR, 8).add(Aspect.ENERGY, 4).add(Aspect.SENSES, 6);
public static AspectList diamondOmnitoolResearch = new AspectList().add(Aspect.ENERGY, 2).add(Aspect.TOOL, 3).add(Aspect.MINE, 2).add(Aspect.WEAPON, 2);
public static AspectList thaumiumOmnitoolResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.TOOL, 6).add(Aspect.MINE, 4).add(Aspect.WEAPON, 6);
public static AspectList thaumicNanoHelmet = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.SENSES, 8).add(Aspect.ARMOR, 6);
public static AspectList laserFocusResearch = new AspectList().add(Aspect.FIRE, 3).add(Aspect.DEATH, 2).add(Aspect.WEAPON, 3);
public static AspectList christmasFocusResearch = new AspectList().add(Aspect.COLD, 2).add(Aspect.BEAST, 5).add(Aspect.LIFE, 6);
public static AspectList shieldFocusResearch = new AspectList().add(Aspect.ARMOR, 5).add(Aspect.AIR, 2).add(Aspect.CRYSTAL, 3).add(Aspect.TRAP, 2);
public static AspectList electricGogglesResearch = new AspectList().add(Aspect.ARMOR, 8).add(Aspect.ENERGY, 5).add(Aspect.SENSES, 6);
public static AspectList potentiaGeneratorResearch = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.EXCHANGE, 4).add(Aspect.METAL, 3);
public static AspectList ignisGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.FIRE, 3);
public static AspectList auramGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.AURA, 3);
public static AspectList arborGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.TREE, 3);
public static AspectList streamChainsawResearch = new AspectList().add(Aspect.TOOL, 3).add(Aspect.TREE, 3).add(Aspect.WATER, 6).add(Aspect.ENERGY, 4);
public static AspectList rockbreakerDrillResearch = new AspectList().add(Aspect.ENERGY, 3).add(Aspect.FIRE, 2).add(Aspect.MINE, 3);
public static AspectList shieldBlockResearch = new AspectList().add(Aspect.ARMOR, 3).add(Aspect.TRAP, 2);
public static AspectList tinyUraniumResearch = new AspectList().add(Aspect.POISON, 4).add(Aspect.DEATH, 3).add(Aspect.EXCHANGE, 3);
public static AspectList thorHammerResearch = new AspectList().add(Aspect.WEAPON, 3).add(Aspect.WEATHER, 4).add(Aspect.ELDRITCH, 3);
public static AspectList superchargedThorHammerResearch = new AspectList().add(Aspect.WEAPON, 4).add(Aspect.ENERGY, 6).add(Aspect.BEAST, 4);
public static AspectList wandCharger = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.CRAFT, 2).add(Aspect.EXCHANGE, 3).add(Aspect.GREED, 5);
public static AspectList compressedSolars = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.LIGHT, 3).add(Aspect.METAL, 2);
public static AspectList solarHelmetRevealing = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.AIR, 2).add(Aspect.LIGHT, 4);
public static AspectList electricBootsTravel = new AspectList().add(Aspect.ENERGY, 2).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 2);
public static AspectList nanoBootsTravel = new AspectList().add(Aspect.ENERGY, 3).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 3);
public static AspectList quantumBootsTravel = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 4);
public static AspectList electricScribingTools = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.DARKNESS, 3).add(Aspect.CRAFT, 1);
public static AspectList etherealProcessor = new AspectList().add(Aspect.MECHANISM, 3).add(Aspect.MAGIC, 4).add(Aspect.CRAFT, 5);
public static AspectList waterSolars = new AspectList().add(Aspect.WATER, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList darkSolars = new AspectList().add(Aspect.ENTROPY, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList orderSolars = new AspectList().add(Aspect.ORDER, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList fireSolars = new AspectList().add(Aspect.FIRE, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList airSolars = new AspectList().add(Aspect.AIR, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList earthSolars = new AspectList().add(Aspect.EARTH, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList uuMInfusion = new AspectList().add(Aspect.ELDRITCH, 4).add(Aspect.MAGIC, 4).add(Aspect.CRAFT, 5);
public static AspectList portableNode = new AspectList().add(Aspect.MAGIC, 5).add(Aspect.AURA, 5).add(Aspect.GREED, 5);
public static AspectList electricHoeGrowth = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.PLANT, 4).add(Aspect.CROP, 5).add(Aspect.MAGIC, 4);
public static AspectList chargeFocus = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.ENERGY, 5).add(Aspect.MECHANISM, 4);
public static AspectList wandChargeFocus = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.AURA, 4).add(Aspect.EXCHANGE, 4).add(Aspect.GREED, 5);
public static AspectList inventoryChargingRing = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.CRYSTAL, 4).add(Aspect.MAGIC, 4);
public static AspectList armorChargingRing = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.ARMOR, 4).add(Aspect.MAGIC, 4);
public static AspectList thaumiumWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8);
public static AspectList nanoWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8).add(Aspect.ENERGY, 4);
public static AspectList quantumWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8).add(Aspect.ENERGY, 4);
public static AspectList aerGenerator = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.AIR, 3);
}
| Java |
#!/usr/bin/env python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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/>.
import argparse
import os
import subprocess
import tempfile
ACTIVE_DISTROS = ("xenial", "artful", "bionic")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("day", help="The day of the results, with format yyyymmdd")
args = parser.parse_args()
install_autopkgtest_results_formatter()
with tempfile.TemporaryDirectory(dir=os.environ.get("HOME")) as temp_dir:
clone_results_repo(temp_dir)
format_results(temp_dir, ACTIVE_DISTROS, args.day)
commit_and_push(temp_dir, args.day)
def install_autopkgtest_results_formatter():
subprocess.check_call(
["sudo", "snap", "install", "autopkgtest-results-formatter", "--edge"]
)
def clone_results_repo(dest_dir):
subprocess.check_call(
["git", "clone", "https://github.com/elopio/autopkgtest-results.git", dest_dir]
)
def format_results(dest_dir, distros, day):
subprocess.check_call(
[
"/snap/bin/autopkgtest-results-formatter",
"--destination",
dest_dir,
"--distros",
*distros,
"--day",
day,
]
)
def commit_and_push(repo_dir, day):
subprocess.check_call(
["git", "config", "--global", "user.email", "[email protected]"]
)
subprocess.check_call(["git", "config", "--global", "user.name", "snappy-m-o"])
subprocess.check_call(["git", "-C", repo_dir, "add", "--all"])
subprocess.check_call(
[
"git",
"-C",
repo_dir,
"commit",
"--message",
"Add the results for {}".format(day),
]
)
subprocess.check_call(
[
"git",
"-C",
repo_dir,
"push",
"https://{GH_TOKEN}@github.com/elopio/autopkgtest-results.git".format(
GH_TOKEN=os.environ.get("GH_TOKEN_PPA_AUTOPKGTEST_RESULTS")
),
]
)
if __name__ == "__main__":
main()
| Java |
package monitor;
public interface RunnableWithResult<T> {
public T run() ;
}
| Java |
\item Due segmenti AB ed AC sono sovrapposti come in figura. Se AB è lungo 4 cm ed AC è lungo 6 cm, che operazione fai per calcolare la lunghezza di BC?
\begin{figure}[h]
\centering
\includegraphics[width=13cm]{figure/somma_diff_segmenti.PNG}
\end{figure}
| Java |
/*
Copyright (C) 2013 Hong Jen Yee (PCMan) <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "filepropsdialog.h"
#include "ui_file-props.h"
#include "icontheme.h"
#include "utilities.h"
#include "fileoperation.h"
#include <QStringBuilder>
#include <QStringListModel>
#include <QMessageBox>
#include <qdial.h>
#include <sys/types.h>
#include <time.h>
#define DIFFERENT_UIDS ((uid)-1)
#define DIFFERENT_GIDS ((gid)-1)
#define DIFFERENT_PERMS ((mode_t)-1)
using namespace Fm;
enum {
ACCESS_NO_CHANGE = 0,
ACCESS_READ_ONLY,
ACCESS_READ_WRITE,
ACCESS_FORBID
};
FilePropsDialog::FilePropsDialog(FmFileInfoList* files, QWidget* parent, Qt::WindowFlags f):
QDialog(parent, f),
fileInfos_(fm_file_info_list_ref(files)),
singleType(fm_file_info_list_is_same_type(files)),
singleFile(fm_file_info_list_get_length(files) == 1 ? true:false),
fileInfo(fm_file_info_list_peek_head(files)),
mimeType(NULL) {
setAttribute(Qt::WA_DeleteOnClose);
ui = new Ui::FilePropsDialog();
ui->setupUi(this);
if(singleType) {
mimeType = fm_mime_type_ref(fm_file_info_get_mime_type(fileInfo));
}
FmPathList* paths = fm_path_list_new_from_file_info_list(files);
deepCountJob = fm_deep_count_job_new(paths, FM_DC_JOB_DEFAULT);
fm_path_list_unref(paths);
initGeneralPage();
initPermissionsPage();
}
FilePropsDialog::~FilePropsDialog() {
delete ui;
if(fileInfos_)
fm_file_info_list_unref(fileInfos_);
if(deepCountJob)
g_object_unref(deepCountJob);
if(fileSizeTimer) {
fileSizeTimer->stop();
delete fileSizeTimer;
fileSizeTimer = NULL;
}
}
void FilePropsDialog::initApplications() {
if(singleType && mimeType && !fm_file_info_is_dir(fileInfo)) {
ui->openWith->setMimeType(mimeType);
}
else {
ui->openWith->hide();
ui->openWithLabel->hide();
}
}
void FilePropsDialog::initPermissionsPage() {
// ownership handling
// get owner/group and mode of the first file in the list
uid = fm_file_info_get_uid(fileInfo);
gid = fm_file_info_get_gid(fileInfo);
mode_t mode = fm_file_info_get_mode(fileInfo);
ownerPerm = (mode & (S_IRUSR|S_IWUSR|S_IXUSR));
groupPerm = (mode & (S_IRGRP|S_IWGRP|S_IXGRP));
otherPerm = (mode & (S_IROTH|S_IWOTH|S_IXOTH));
execPerm = (mode & (S_IXUSR|S_IXGRP|S_IXOTH));
allNative = fm_file_info_is_native(fileInfo);
hasDir = S_ISDIR(mode);
// check if all selected files belongs to the same owner/group or have the same mode
// at the same time, check if all files are on native unix filesystems
GList* l;
for(l = fm_file_info_list_peek_head_link(fileInfos_)->next; l; l = l->next) {
FmFileInfo* fi = FM_FILE_INFO(l->data);
if(allNative && !fm_file_info_is_native(fi))
allNative = false; // not all of the files are native
mode_t fi_mode = fm_file_info_get_mode(fi);
if(S_ISDIR(fi_mode))
hasDir = true; // the files list contains dir(s)
if(uid != DIFFERENT_UIDS && uid != fm_file_info_get_uid(fi))
uid = DIFFERENT_UIDS; // not all files have the same owner
if(gid != DIFFERENT_GIDS && gid != fm_file_info_get_gid(fi))
gid = DIFFERENT_GIDS; // not all files have the same owner group
if(ownerPerm != DIFFERENT_PERMS && ownerPerm != (fi_mode & (S_IRUSR|S_IWUSR|S_IXUSR)))
ownerPerm = DIFFERENT_PERMS; // not all files have the same permission for owner
if(groupPerm != DIFFERENT_PERMS && groupPerm != (fi_mode & (S_IRGRP|S_IWGRP|S_IXGRP)))
groupPerm = DIFFERENT_PERMS; // not all files have the same permission for grop
if(otherPerm != DIFFERENT_PERMS && otherPerm != (fi_mode & (S_IROTH|S_IWOTH|S_IXOTH)))
otherPerm = DIFFERENT_PERMS; // not all files have the same permission for other
if(execPerm != DIFFERENT_PERMS && execPerm != (fi_mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
execPerm = DIFFERENT_PERMS; // not all files have the same executable permission
}
// init owner/group
initOwner();
// if all files are of the same type, and some of them are dirs => all of the items are dirs
// rwx values have different meanings for dirs
// Let's make it clear for the users
// init combo boxes for file permissions here
QStringList comboItems;
comboItems.append("---"); // no change
if(singleType && hasDir) { // all files are dirs
comboItems.append(tr("View folder content"));
comboItems.append(tr("View and modify folder content"));
ui->executable->hide();
}
else { //not all of the files are dirs
comboItems.append(tr("Read"));
comboItems.append(tr("Read and write"));
}
comboItems.append(tr("Forbidden"));
QStringListModel* comboModel = new QStringListModel(comboItems, this);
ui->ownerPerm->setModel(comboModel);
ui->groupPerm->setModel(comboModel);
ui->otherPerm->setModel(comboModel);
// owner
ownerPermSel = ACCESS_NO_CHANGE;
if(ownerPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files
if(ownerPerm & S_IRUSR) { // can read
if(ownerPerm & S_IWUSR) // can write
ownerPermSel = ACCESS_READ_WRITE;
else
ownerPermSel = ACCESS_READ_ONLY;
}
else {
if((ownerPerm & S_IWUSR) == 0) // cannot read or write
ownerPermSel = ACCESS_FORBID;
}
}
ui->ownerPerm->setCurrentIndex(ownerPermSel);
// owner and group
groupPermSel = ACCESS_NO_CHANGE;
if(groupPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files
if(groupPerm & S_IRGRP) { // can read
if(groupPerm & S_IWGRP) // can write
groupPermSel = ACCESS_READ_WRITE;
else
groupPermSel = ACCESS_READ_ONLY;
}
else {
if((groupPerm & S_IWGRP) == 0) // cannot read or write
groupPermSel = ACCESS_FORBID;
}
}
ui->groupPerm->setCurrentIndex(groupPermSel);
// other
otherPermSel = ACCESS_NO_CHANGE;
if(otherPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files
if(otherPerm & S_IROTH) { // can read
if(otherPerm & S_IWOTH) // can write
otherPermSel = ACCESS_READ_WRITE;
else
otherPermSel = ACCESS_READ_ONLY;
}
else {
if((otherPerm & S_IWOTH) == 0) // cannot read or write
otherPermSel = ACCESS_FORBID;
}
}
ui->otherPerm->setCurrentIndex(otherPermSel);
// set the checkbox to partially checked state
// when owner, group, and other have different executable flags set.
// some of them have exec, and others do not have.
execCheckState = Qt::PartiallyChecked;
if(execPerm != DIFFERENT_PERMS) { // if all files have the same executable permission
// check if the files are all executable
if((mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == (S_IXUSR|S_IXGRP|S_IXOTH)) {
// owner, group, and other all have exec permission.
execCheckState = Qt::Checked;
}
else if((mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
// owner, group, and other all have no exec permission
execCheckState = Qt::Unchecked;
}
}
ui->executable->setCheckState(execCheckState);
}
void FilePropsDialog::initGeneralPage() {
// update UI
if(singleType) { // all files are of the same mime-type
FmIcon* icon = NULL;
// FIXME: handle custom icons for some files
// FIXME: display special property pages for special files or
// some specified mime-types.
if(singleFile) { // only one file is selected.
icon = fm_file_info_get_icon(fileInfo);
}
if(mimeType) {
if(!icon) // get an icon from mime type if needed
icon = fm_mime_type_get_icon(mimeType);
ui->fileType->setText(QString::fromUtf8(fm_mime_type_get_desc(mimeType)));
ui->mimeType->setText(QString::fromUtf8(fm_mime_type_get_type(mimeType)));
}
if(icon) {
ui->iconButton->setIcon(IconTheme::icon(icon));
}
if(singleFile && fm_file_info_is_symlink(fileInfo)) {
ui->target->setText(QString::fromUtf8(fm_file_info_get_target(fileInfo)));
}
else {
ui->target->hide();
ui->targetLabel->hide();
}
} // end if(singleType)
else { // not singleType, multiple files are selected at the same time
ui->fileType->setText(tr("Files of different types"));
ui->target->hide();
ui->targetLabel->hide();
}
// FIXME: check if all files has the same parent dir, mtime, or atime
if(singleFile) { // only one file is selected
FmPath* parent_path = fm_path_get_parent(fm_file_info_get_path(fileInfo));
char* parent_str = parent_path ? fm_path_display_name(parent_path, true) : NULL;
ui->fileName->setText(QString::fromUtf8(fm_file_info_get_disp_name(fileInfo)));
if(parent_str) {
ui->location->setText(QString::fromUtf8(parent_str));
g_free(parent_str);
}
else
ui->location->clear();
ui->lastModified->setText(QString::fromUtf8(fm_file_info_get_disp_mtime(fileInfo)));
// FIXME: need to encapsulate this in an libfm API.
time_t atime;
struct tm tm;
atime = fm_file_info_get_atime(fileInfo);
localtime_r(&atime, &tm);
char buf[128];
strftime(buf, sizeof(buf), "%x %R", &tm);
ui->lastAccessed->setText(QString::fromUtf8(buf));
}
else {
ui->fileName->setText(tr("Multiple Files"));
ui->fileName->setEnabled(false);
}
initApplications(); // init applications combo box
// calculate total file sizes
fileSizeTimer = new QTimer(this);
connect(fileSizeTimer, SIGNAL(timeout()), SLOT(onFileSizeTimerTimeout()));
fileSizeTimer->start(600);
g_signal_connect(deepCountJob, "finished", G_CALLBACK(onDeepCountJobFinished), this);
fm_job_run_async(FM_JOB(deepCountJob));
}
/*static */ void FilePropsDialog::onDeepCountJobFinished(FmDeepCountJob* job, FilePropsDialog* pThis) {
pThis->onFileSizeTimerTimeout(); // update file size display
// free the job
g_object_unref(pThis->deepCountJob);
pThis->deepCountJob = NULL;
// stop the timer
if(pThis->fileSizeTimer) {
pThis->fileSizeTimer->stop();
delete pThis->fileSizeTimer;
pThis->fileSizeTimer = NULL;
}
}
void FilePropsDialog::onFileSizeTimerTimeout() {
if(deepCountJob && !fm_job_is_cancelled(FM_JOB(deepCountJob))) {
char size_str[128];
fm_file_size_to_str(size_str, sizeof(size_str), deepCountJob->total_size,
fm_config->si_unit);
// FIXME:
// OMG! It's really unbelievable that Qt developers only implement
// QObject::tr(... int n). GNU gettext developers are smarter and
// they use unsigned long instead of int.
// We cannot use Qt here to handle plural forms. So sad. :-(
QString str = QString::fromUtf8(size_str) %
QString(" (%1 B)").arg(deepCountJob->total_size);
// tr(" (%n) byte(s)", "", deepCountJob->total_size);
ui->fileSize->setText(str);
fm_file_size_to_str(size_str, sizeof(size_str), deepCountJob->total_ondisk_size,
fm_config->si_unit);
str = QString::fromUtf8(size_str) %
QString(" (%1 B)").arg(deepCountJob->total_ondisk_size);
// tr(" (%n) byte(s)", "", deepCountJob->total_ondisk_size);
ui->onDiskSize->setText(str);
}
}
void FilePropsDialog::accept() {
// applications
if(mimeType && ui->openWith->isChanged()) {
GAppInfo* currentApp = ui->openWith->selectedApp();
g_app_info_set_as_default_for_type(currentApp, fm_mime_type_get_type(mimeType), NULL);
}
// check if chown or chmod is needed
guint32 newUid = uidFromName(ui->owner->text());
guint32 newGid = gidFromName(ui->ownerGroup->text());
bool needChown = (newUid != uid || newGid != gid);
int newOwnerPermSel = ui->ownerPerm->currentIndex();
int newGroupPermSel = ui->groupPerm->currentIndex();
int newOtherPermSel = ui->otherPerm->currentIndex();
Qt::CheckState newExecCheckState = ui->executable->checkState();
bool needChmod = ((newOwnerPermSel != ownerPermSel) ||
(newGroupPermSel != groupPermSel) ||
(newOtherPermSel != otherPermSel) ||
(newExecCheckState != execCheckState));
if(needChmod || needChown) {
FmPathList* paths = fm_path_list_new_from_file_info_list(fileInfos_);
FileOperation* op = new FileOperation(FileOperation::ChangeAttr, paths);
fm_path_list_unref(paths);
if(needChown) {
// don't do chown if new uid/gid and the original ones are actually the same.
if(newUid == uid)
newUid = -1;
if(newGid == gid)
newGid = -1;
op->setChown(newUid, newGid);
}
if(needChmod) {
mode_t newMode = 0;
mode_t newModeMask = 0;
// FIXME: we need to make sure that folders with "r" permission also have "x"
// at the same time. Otherwise, it's not able to browse the folder later.
if(newOwnerPermSel != ownerPermSel && newOwnerPermSel != ACCESS_NO_CHANGE) {
// owner permission changed
newModeMask |= (S_IRUSR|S_IWUSR); // affect user bits
if(newOwnerPermSel == ACCESS_READ_ONLY)
newMode |= S_IRUSR;
else if(newOwnerPermSel == ACCESS_READ_WRITE)
newMode |= (S_IRUSR|S_IWUSR);
}
if(newGroupPermSel != groupPermSel && newGroupPermSel != ACCESS_NO_CHANGE) {
qDebug("newGroupPermSel: %d", newGroupPermSel);
// group permission changed
newModeMask |= (S_IRGRP|S_IWGRP); // affect group bits
if(newGroupPermSel == ACCESS_READ_ONLY)
newMode |= S_IRGRP;
else if(newGroupPermSel == ACCESS_READ_WRITE)
newMode |= (S_IRGRP|S_IWGRP);
}
if(newOtherPermSel != otherPermSel && newOtherPermSel != ACCESS_NO_CHANGE) {
// other permission changed
newModeMask |= (S_IROTH|S_IWOTH); // affect other bits
if(newOtherPermSel == ACCESS_READ_ONLY)
newMode |= S_IROTH;
else if(newOtherPermSel == ACCESS_READ_WRITE)
newMode |= (S_IROTH|S_IWOTH);
}
if(newExecCheckState != execCheckState && newExecCheckState != Qt::PartiallyChecked) {
// executable state changed
newModeMask |= (S_IXUSR|S_IXGRP|S_IXOTH);
if(newExecCheckState == Qt::Checked)
newMode |= (S_IXUSR|S_IXGRP|S_IXOTH);
}
op->setChmod(newMode, newModeMask);
if(hasDir) { // if there are some dirs in our selected files
QMessageBox::StandardButton r = QMessageBox::question(this,
tr("Apply changes"),
tr("Do you want to recursively apply these changes to all files and sub-folders?"),
QMessageBox::Yes|QMessageBox::No);
if(r == QMessageBox::Yes)
op->setRecursiveChattr(true);
}
}
op->setAutoDestroy(true);
op->run();
}
QDialog::accept();
}
void FilePropsDialog::initOwner() {
if(allNative) {
if(uid != DIFFERENT_UIDS)
ui->owner->setText(uidToName(uid));
if(gid != DIFFERENT_GIDS)
ui->ownerGroup->setText(gidToName(gid));
if(geteuid() != 0) { // on local filesystems, only root can do chown.
ui->owner->setEnabled(false);
ui->ownerGroup->setEnabled(false);
}
}
}
| Java |
/************************************************************************
Extended WPF Toolkit
Copyright (C) 2010-2012 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
This program can be provided to you by Xceed Software Inc. under a
proprietary commercial license agreement for use in non-Open Source
projects. The commercial version of Extended WPF Toolkit also includes
priority technical support, commercial updates, and many additional
useful WPF controls if you license Xceed Business Suite for WPF.
Visit http://xceed.com and follow @datagrid on Twitter.
**********************************************************************/
using System;
using System.Windows.Data;
using System.Windows.Media;
namespace Xceed.Wpf.Toolkit.Core.Converters
{
public class ColorToSolidColorBrushConverter : IValueConverter
{
#region IValueConverter Members
/// <summary>
/// Converts a Color to a SolidColorBrush.
/// </summary>
/// <param name="value">The Color produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted SolidColorBrush. If the method returns null, the valid null value is used.
/// </returns>
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
if( value != null )
return new SolidColorBrush( ( Color )value );
return value;
}
/// <summary>
/// Converts a SolidColorBrush to a Color.
/// </summary>
/// <remarks>Currently not used in toolkit, but provided for developer use in their own projects</remarks>
/// <param name="value">The SolidColorBrush that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
if( value != null )
return ( ( SolidColorBrush )value ).Color;
return value;
}
#endregion
}
}
| Java |
package cern.colt.matrix.tlong.impl;
public class SparseRCMLongMatrix2DViewTest extends SparseRCMLongMatrix2DTest {
public SparseRCMLongMatrix2DViewTest(String arg0) {
super(arg0);
}
protected void createMatrices() throws Exception {
A = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice();
B = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice();
Bt = new SparseRCMLongMatrix2D(NROWS, NCOLUMNS).viewDice();
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
<!-- Generated by Natural Docs, version 1.4 -->
<!-- http://www.naturaldocs.org -->
<!-- saved from url=(0026)http://www.naturaldocs.org -->
<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_FileException><div class=IEntry><a href="../files/lib/exception-file-php.html#FileException" target=_parent class=ISymbol>FileException</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults", "HTML");
searchResults.Search();
--></script></div><script language=JavaScript><!--
if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html> | Java |
package handling.handlers;
import java.awt.Point;
import client.MapleClient;
import handling.PacketHandler;
import handling.RecvPacketOpcode;
import server.MaplePortal;
import tools.data.LittleEndianAccessor;
public class UseInnerPortalHandler {
@PacketHandler(opcode = RecvPacketOpcode.USE_INNER_PORTAL)
public static void handle(MapleClient c, LittleEndianAccessor lea) {
lea.skip(1);
if (c.getPlayer() == null || c.getPlayer().getMap() == null) {
return;
}
String portalName = lea.readMapleAsciiString();
MaplePortal portal = c.getPlayer().getMap().getPortal(portalName);
if (portal == null) {
return;
}
//That "22500" should not be hard coded in this manner
if (portal.getPosition().distanceSq(c.getPlayer().getTruePosition()) > 22500.0D && !c.getPlayer().isGM()) {
return;
}
int toX = lea.readShort();
int toY = lea.readShort();
//Are there not suppose to be checks here? Can players not just PE any x and y value they want?
c.getPlayer().getMap().movePlayer(c.getPlayer(), new Point(toX, toY));
c.getPlayer().checkFollow();
}
}
| Java |
/*
Free Download Manager Copyright (c) 2003-2014 FreeDownloadManager.ORG
*/
#ifndef __COMMON_H_
#define __COMMON_H_
#include "system.h"
#include "fsinet.h"
#define SAFE_DELETE_ARRAY(a) {if (a) {delete [] a; a = NULL;}}
#endif | Java |
#ifndef REPLY_H
#define REPLY_H
#include <QNetworkReply>
class Reply : public QObject
{
Q_OBJECT
public:
int _id;
QNetworkReply *res;
Reply(int id, QNetworkReply *net){
res = net;
_id = id;
connect(res,SIGNAL(uploadProgress(qint64,qint64)),this,SLOT(progress(qint64,qint64)));
}
signals:
void percentReady(int percent,int id);
public slots:
void progress(qint64 up,qint64 to){
float per = (float)100/(float)to*(float)up;
percentReady((int)per,_id);
}
};
#endif
| Java |
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef _VITELOTTE_BEZIER_PATH_
#define _VITELOTTE_BEZIER_PATH_
#include <cassert>
#include <vector>
#include <Eigen/Geometry>
namespace Vitelotte
{
enum BezierSegmentType
{
BEZIER_EMPTY = 0,
BEZIER_LINEAR = 2,
BEZIER_QUADRATIC = 3,
BEZIER_CUBIC = 4
};
template < typename _Vector >
class BezierSegment {
public:
typedef typename _Vector::Scalar Scalar;
typedef _Vector Vector;
typedef BezierSegment<Vector> Self;
public:
inline BezierSegment()
: m_type(BEZIER_EMPTY) {}
inline BezierSegment(BezierSegmentType type, const Vector* points)
: m_type(type) {
std::copy(points, points + type, m_points);
}
inline BezierSegmentType type() const { return m_type; }
inline void setType(BezierSegmentType type) { m_type = type; }
inline const Vector& point(unsigned i) const {
assert(i < m_type);
return m_points[i];
}
inline Vector& point(unsigned i) {
assert(i < m_type);
return m_points[i];
}
inline Self getBackward() const {
Self seg;
seg.setType(type());
for(unsigned i = 0; i < type(); ++i) {
seg.point(type() - 1 - i) = point(i);
}
return seg;
}
void split(Scalar pos, Self& head, Self& tail) {
assert(m_type != BEZIER_EMPTY);
// All the points of de Casteljau Algorithm
Vector pts[10];
Vector* levels[] = {
&pts[9],
&pts[7],
&pts[4],
pts
};
// Initialize the current level.
std::copy(m_points, m_points + type(), levels[type() - 1]);
// Compute all the points
for(int level = type()-1; level >= 0; --level) {
for(int i = 0; i < level; ++i) {
levels[level-1][i] = (Scalar(1) - pos) * levels[level][i]
+ pos * levels[level][i+1];
}
}
// Set the segments
head.setType(type());
tail.setType(type());
const unsigned last = type() - 1;
for(unsigned i = 0; i < type(); ++i) {
head.point(i) = levels[last - i][0];
tail.point(i) = levels[i][i];
}
}
template < typename InIt >
void refineUniform(InIt out, unsigned nSplit) {
Self head;
Self tail = *this;
*(out++) = std::make_pair(Scalar(0), point(0));
for(unsigned i = 0; i < nSplit; ++i) {
Scalar x = Scalar(i+1) / Scalar(nSplit + 1);
tail.split(x, head, tail);
*(out++) = std::make_pair(x, tail.point(0));
}
*(out++) = std::make_pair(Scalar(1), point(type()-1));
}
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
BezierSegmentType m_type;
Vector m_points[4];
};
template < typename _Vector >
class BezierPath
{
public:
typedef _Vector Vector;
public:
static unsigned size(BezierSegmentType type) { return unsigned(type); }
public:
inline BezierPath() {}
inline unsigned nPoints() const { return m_points.size(); }
inline unsigned nSegments() const { return m_segments.size(); }
inline BezierSegmentType type(unsigned si) const { return m_segments.at(si).type; }
inline unsigned nPoints(unsigned si) const { return size(type(si)); }
inline const Vector& point(unsigned pi) const { return m_points.at(pi); }
inline Vector& point(unsigned pi) { return m_points.at(pi); }
inline const Vector& point(unsigned si, unsigned pi) const
{
assert(si < nSegments() && pi < nPoints(si));
return m_points.at(m_segments[si].firstPoint + pi);
}
inline Vector& point(unsigned si, unsigned pi)
{
assert(si < nSegments() && pi < nPoints(si));
return m_points.at(m_segments[si].firstPoint + pi);
}
inline void setFirstPoint(const Vector& point)
{
assert(nPoints() == 0);
m_points.push_back(point);
}
unsigned addSegment(BezierSegmentType type, const Vector* points)
{
assert(nPoints() != 0);
unsigned si = nSegments();
Segment s;
s.type = type;
s.firstPoint = nPoints() - 1;
m_segments.push_back(s);
for(unsigned i = 0; i < nPoints(si) - 1; ++i)
{
m_points.push_back(points[i]);
}
return si;
}
BezierSegment<Vector> getSegment(unsigned si) const {
assert(si < nSegments());
return BezierSegment<Vector>(type(si), &m_points[m_segments[si].firstPoint]);
}
private:
struct Segment {
BezierSegmentType type;
unsigned firstPoint;
};
typedef std::vector<Vector> PointList;
typedef std::vector<Segment> SegmentList;
private:
PointList m_points;
SegmentList m_segments;
};
}
#endif
| Java |
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 4.7.1
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: [email protected]
Follow: www.twitter.com/keenthemes
Dribbble: www.dribbble.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" dir="rtl">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>Metronic Admin RTL Theme #5 | User Login 3</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin RTL Theme #5 for " name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="../assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="../assets/global/css/components-rounded-rtl.min.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="../assets/global/css/plugins-rtl.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link href="../assets/pages/css/login-3-rtl.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="favicon.ico" /> </head>
<!-- END HEAD -->
<body class=" login">
<!-- BEGIN LOGO -->
<div class="logo">
<a href="index.html">
<img src="../assets/pages/img/logo-big.png" alt="" /> </a>
</div>
<!-- END LOGO -->
<!-- BEGIN LOGIN -->
<div class="content">
<!-- BEGIN LOGIN FORM -->
<form class="login-form" action="index.html" method="post">
<h3 class="form-title">Login to your account</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span> Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" /> </div>
</div>
<div class="form-actions">
<label class="rememberme mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="remember" value="1" /> Remember me
<span></span>
</label>
<button type="submit" class="btn green pull-right"> Login </button>
</div>
<div class="login-options">
<h4>Or login with</h4>
<ul class="social-icons">
<li>
<a class="facebook" data-original-title="facebook" href="javascript:;"> </a>
</li>
<li>
<a class="twitter" data-original-title="Twitter" href="javascript:;"> </a>
</li>
<li>
<a class="googleplus" data-original-title="Goole Plus" href="javascript:;"> </a>
</li>
<li>
<a class="linkedin" data-original-title="Linkedin" href="javascript:;"> </a>
</li>
</ul>
</div>
<div class="forget-password">
<h4>Forgot your password ?</h4>
<p> no worries, click
<a href="javascript:;" id="forget-password"> here </a> to reset your password. </p>
</div>
<div class="create-account">
<p> Don't have an account yet ?
<a href="javascript:;" id="register-btn"> Create an account </a>
</p>
</div>
</form>
<!-- END LOGIN FORM -->
<!-- BEGIN FORGOT PASSWORD FORM -->
<form class="forget-form" action="index.html" method="post">
<h3>Forget Password ?</h3>
<p> Enter your e-mail address below to reset your password. </p>
<div class="form-group">
<div class="input-icon">
<i class="fa fa-envelope"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="email" /> </div>
</div>
<div class="form-actions">
<button type="button" id="back-btn" class="btn grey-salsa btn-outline"> Back </button>
<button type="submit" class="btn green pull-right"> Submit </button>
</div>
</form>
<!-- END FORGOT PASSWORD FORM -->
<!-- BEGIN REGISTRATION FORM -->
<form class="register-form" action="index.html" method="post">
<h3>Sign Up</h3>
<p> Enter your personal details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Full Name</label>
<div class="input-icon">
<i class="fa fa-font"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="Full Name" name="fullname" /> </div>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Email</label>
<div class="input-icon">
<i class="fa fa-envelope"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="Email" name="email" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Address</label>
<div class="input-icon">
<i class="fa fa-check"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="Address" name="address" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">City/Town</label>
<div class="input-icon">
<i class="fa fa-location-arrow"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="City/Town" name="city" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Country</label>
<select name="country" id="country_list" class="select2 form-control">
<option value=""></option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option>
<option value="BH">Bahrain</option>
<option value="BD">Bangladesh</option>
<option value="BB">Barbados</option>
<option value="BY">Belarus</option>
<option value="BE">Belgium</option>
<option value="BZ">Belize</option>
<option value="BJ">Benin</option>
<option value="BM">Bermuda</option>
<option value="BT">Bhutan</option>
<option value="BO">Bolivia</option>
<option value="BA">Bosnia and Herzegowina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet Island</option>
<option value="BR">Brazil</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="BN">Brunei Darussalam</option>
<option value="BG">Bulgaria</option>
<option value="BF">Burkina Faso</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
<option value="CM">Cameroon</option>
<option value="CA">Canada</option>
<option value="CV">Cape Verde</option>
<option value="KY">Cayman Islands</option>
<option value="CF">Central African Republic</option>
<option value="TD">Chad</option>
<option value="CL">Chile</option>
<option value="CN">China</option>
<option value="CX">Christmas Island</option>
<option value="CC">Cocos (Keeling) Islands</option>
<option value="CO">Colombia</option>
<option value="KM">Comoros</option>
<option value="CG">Congo</option>
<option value="CD">Congo, the Democratic Republic of the</option>
<option value="CK">Cook Islands</option>
<option value="CR">Costa Rica</option>
<option value="CI">Cote d'Ivoire</option>
<option value="HR">Croatia (Hrvatska)</option>
<option value="CU">Cuba</option>
<option value="CY">Cyprus</option>
<option value="CZ">Czech Republic</option>
<option value="DK">Denmark</option>
<option value="DJ">Djibouti</option>
<option value="DM">Dominica</option>
<option value="DO">Dominican Republic</option>
<option value="EC">Ecuador</option>
<option value="EG">Egypt</option>
<option value="SV">El Salvador</option>
<option value="GQ">Equatorial Guinea</option>
<option value="ER">Eritrea</option>
<option value="EE">Estonia</option>
<option value="ET">Ethiopia</option>
<option value="FK">Falkland Islands (Malvinas)</option>
<option value="FO">Faroe Islands</option>
<option value="FJ">Fiji</option>
<option value="FI">Finland</option>
<option value="FR">France</option>
<option value="GF">French Guiana</option>
<option value="PF">French Polynesia</option>
<option value="TF">French Southern Territories</option>
<option value="GA">Gabon</option>
<option value="GM">Gambia</option>
<option value="GE">Georgia</option>
<option value="DE">Germany</option>
<option value="GH">Ghana</option>
<option value="GI">Gibraltar</option>
<option value="GR">Greece</option>
<option value="GL">Greenland</option>
<option value="GD">Grenada</option>
<option value="GP">Guadeloupe</option>
<option value="GU">Guam</option>
<option value="GT">Guatemala</option>
<option value="GN">Guinea</option>
<option value="GW">Guinea-Bissau</option>
<option value="GY">Guyana</option>
<option value="HT">Haiti</option>
<option value="HM">Heard and Mc Donald Islands</option>
<option value="VA">Holy See (Vatican City State)</option>
<option value="HN">Honduras</option>
<option value="HK">Hong Kong</option>
<option value="HU">Hungary</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran (Islamic Republic of)</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JO">Jordan</option>
<option value="KZ">Kazakhstan</option>
<option value="KE">Kenya</option>
<option value="KI">Kiribati</option>
<option value="KP">Korea, Democratic People's Republic of</option>
<option value="KR">Korea, Republic of</option>
<option value="KW">Kuwait</option>
<option value="KG">Kyrgyzstan</option>
<option value="LA">Lao People's Democratic Republic</option>
<option value="LV">Latvia</option>
<option value="LB">Lebanon</option>
<option value="LS">Lesotho</option>
<option value="LR">Liberia</option>
<option value="LY">Libyan Arab Jamahiriya</option>
<option value="LI">Liechtenstein</option>
<option value="LT">Lithuania</option>
<option value="LU">Luxembourg</option>
<option value="MO">Macau</option>
<option value="MK">Macedonia, The Former Yugoslav Republic of</option>
<option value="MG">Madagascar</option>
<option value="MW">Malawi</option>
<option value="MY">Malaysia</option>
<option value="MV">Maldives</option>
<option value="ML">Mali</option>
<option value="MT">Malta</option>
<option value="MH">Marshall Islands</option>
<option value="MQ">Martinique</option>
<option value="MR">Mauritania</option>
<option value="MU">Mauritius</option>
<option value="YT">Mayotte</option>
<option value="MX">Mexico</option>
<option value="FM">Micronesia, Federated States of</option>
<option value="MD">Moldova, Republic of</option>
<option value="MC">Monaco</option>
<option value="MN">Mongolia</option>
<option value="MS">Montserrat</option>
<option value="MA">Morocco</option>
<option value="MZ">Mozambique</option>
<option value="MM">Myanmar</option>
<option value="NA">Namibia</option>
<option value="NR">Nauru</option>
<option value="NP">Nepal</option>
<option value="NL">Netherlands</option>
<option value="AN">Netherlands Antilles</option>
<option value="NC">New Caledonia</option>
<option value="NZ">New Zealand</option>
<option value="NI">Nicaragua</option>
<option value="NE">Niger</option>
<option value="NG">Nigeria</option>
<option value="NU">Niue</option>
<option value="NF">Norfolk Island</option>
<option value="MP">Northern Mariana Islands</option>
<option value="NO">Norway</option>
<option value="OM">Oman</option>
<option value="PK">Pakistan</option>
<option value="PW">Palau</option>
<option value="PA">Panama</option>
<option value="PG">Papua New Guinea</option>
<option value="PY">Paraguay</option>
<option value="PE">Peru</option>
<option value="PH">Philippines</option>
<option value="PN">Pitcairn</option>
<option value="PL">Poland</option>
<option value="PT">Portugal</option>
<option value="PR">Puerto Rico</option>
<option value="QA">Qatar</option>
<option value="RE">Reunion</option>
<option value="RO">Romania</option>
<option value="RU">Russian Federation</option>
<option value="RW">Rwanda</option>
<option value="KN">Saint Kitts and Nevis</option>
<option value="LC">Saint LUCIA</option>
<option value="VC">Saint Vincent and the Grenadines</option>
<option value="WS">Samoa</option>
<option value="SM">San Marino</option>
<option value="ST">Sao Tome and Principe</option>
<option value="SA">Saudi Arabia</option>
<option value="SN">Senegal</option>
<option value="SC">Seychelles</option>
<option value="SL">Sierra Leone</option>
<option value="SG">Singapore</option>
<option value="SK">Slovakia (Slovak Republic)</option>
<option value="SI">Slovenia</option>
<option value="SB">Solomon Islands</option>
<option value="SO">Somalia</option>
<option value="ZA">South Africa</option>
<option value="GS">South Georgia and the South Sandwich Islands</option>
<option value="ES">Spain</option>
<option value="LK">Sri Lanka</option>
<option value="SH">St. Helena</option>
<option value="PM">St. Pierre and Miquelon</option>
<option value="SD">Sudan</option>
<option value="SR">Suriname</option>
<option value="SJ">Svalbard and Jan Mayen Islands</option>
<option value="SZ">Swaziland</option>
<option value="SE">Sweden</option>
<option value="CH">Switzerland</option>
<option value="SY">Syrian Arab Republic</option>
<option value="TW">Taiwan, Province of China</option>
<option value="TJ">Tajikistan</option>
<option value="TZ">Tanzania, United Republic of</option>
<option value="TH">Thailand</option>
<option value="TG">Togo</option>
<option value="TK">Tokelau</option>
<option value="TO">Tonga</option>
<option value="TT">Trinidad and Tobago</option>
<option value="TN">Tunisia</option>
<option value="TR">Turkey</option>
<option value="TM">Turkmenistan</option>
<option value="TC">Turks and Caicos Islands</option>
<option value="TV">Tuvalu</option>
<option value="UG">Uganda</option>
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US">United States</option>
<option value="UM">United States Minor Outlying Islands</option>
<option value="UY">Uruguay</option>
<option value="UZ">Uzbekistan</option>
<option value="VU">Vanuatu</option>
<option value="VE">Venezuela</option>
<option value="VN">Viet Nam</option>
<option value="VG">Virgin Islands (British)</option>
<option value="VI">Virgin Islands (U.S.)</option>
<option value="WF">Wallis and Futuna Islands</option>
<option value="EH">Western Sahara</option>
<option value="YE">Yemen</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
</div>
<p> Enter your account details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<div class="controls">
<div class="input-icon">
<i class="fa fa-check"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" /> </div>
</div>
</div>
<div class="form-group">
<label class="mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="tnc" /> I agree to the
<a href="javascript:;">Terms of Service </a> &
<a href="javascript:;">Privacy Policy </a>
<span></span>
</label>
<div id="register_tnc_error"> </div>
</div>
<div class="form-actions">
<button id="register-back-btn" type="button" class="btn grey-salsa btn-outline"> Back </button>
<button type="submit" id="register-submit-btn" class="btn green pull-right"> Sign Up </button>
</div>
</form>
<!-- END REGISTRATION FORM -->
</div>
<!-- END LOGIN -->
<!--[if lt IE 9]>
<script src="../assets/global/plugins/respond.min.js"></script>
<script src="../assets/global/plugins/excanvas.min.js"></script>
<script src="../assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<!-- BEGIN CORE PLUGINS -->
<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="../assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="../assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../assets/pages/scripts/login.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS -->
<!-- END THEME LAYOUT SCRIPTS -->
</body>
</html> | Java |
<html>
<head><title>download de dados</title></head>
<body>
<h3>Dados anuais por órgão</h3>
<p><a href="2008/orgaos.json">2008</a></p>
<p><a href="2009/orgaos.json">2009</a></p>
<p><a href="2010/orgaos.json">2010</a></p>
<p><a href="2011/orgaos.json">2011</a></p>
<p><a href="2012/orgaos.json">2012</a></p>
<p><a href="2013/orgaos.json">2013</a></p>
</body>
</html>
| Java |
// This file is part of Hermes2D.
//
// Hermes2D is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Hermes2D 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 Hermes2D. If not, see <http://www.gnu.org/licenses/>.
#include "curved.h"
#include <algorithm>
#include "global.h"
#include "shapeset/shapeset_h1_all.h"
#include "shapeset/shapeset_common.h"
#include "shapeset/precalc.h"
#include "mesh.h"
#include "quad_all.h"
#include "matrix.h"
#include "algebra/dense_matrix_operations.h"
using namespace Hermes::Algebra::DenseMatrixOperations;
namespace Hermes
{
namespace Hermes2D
{
HERMES_API Quad1DStd g_quad_1d_std;
HERMES_API Quad2DStd g_quad_2d_std;
H1ShapesetJacobi ref_map_shapeset;
PrecalcShapesetAssembling ref_map_pss_static(&ref_map_shapeset);
CurvMapStatic::CurvMapStatic()
{
int order = ref_map_shapeset.get_max_order();
this->edge_proj_matrix_size = order - 1;
// Edges.
this->edge_proj_matrix = new_matrix<double>(edge_proj_matrix_size, edge_proj_matrix_size);
edge_p = malloc_with_check<double>(edge_proj_matrix_size);
// Bubbles - triangles.
this->tri_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_TRIANGLE);
bubble_proj_matrix_tri = new_matrix<double>(tri_bubble_np, tri_bubble_np);
bubble_tri_p = malloc_with_check<double>(tri_bubble_np);
// Bubbles - quads.
order = H2D_MAKE_QUAD_ORDER(order, order);
this->quad_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_QUAD);
bubble_proj_matrix_quad = new_matrix<double>(quad_bubble_np, quad_bubble_np);
bubble_quad_p = malloc_with_check<double>(quad_bubble_np);
this->precalculate_cholesky_projection_matrices_bubble();
this->precalculate_cholesky_projection_matrix_edge();
}
CurvMapStatic::~CurvMapStatic()
{
free_with_check(edge_proj_matrix, true);
free_with_check(bubble_proj_matrix_tri, true);
free_with_check(bubble_proj_matrix_quad, true);
free_with_check(edge_p);
free_with_check(bubble_tri_p);
free_with_check(bubble_quad_p);
}
double** CurvMapStatic::calculate_bubble_projection_matrix(short* indices, ElementMode2D mode)
{
unsigned short nb;
double** mat;
if (mode == HERMES_MODE_TRIANGLE)
{
mat = this->bubble_proj_matrix_tri;
nb = this->tri_bubble_np;
}
else
{
mat = this->bubble_proj_matrix_quad;
nb = this->quad_bubble_np;
}
PrecalcShapesetAssembling ref_map_pss_static_temp(&ref_map_shapeset);
ref_map_pss_static_temp.set_active_element(ref_map_pss_static.get_active_element());
for (unsigned short i = 0; i < nb; i++)
{
for (unsigned short j = i; j < nb; j++)
{
short ii = indices[i], ij = indices[j];
unsigned short o = ref_map_shapeset.get_order(ii, mode) + ref_map_shapeset.get_order(ij, mode);
o = std::max(H2D_GET_V_ORDER(o), H2D_GET_H_ORDER(o));
ref_map_pss_static.set_active_shape(ii);
ref_map_pss_static.set_quad_order(o, H2D_FN_VAL);
const double* fni = ref_map_pss_static.get_fn_values();
ref_map_pss_static_temp.set_active_shape(ij);
ref_map_pss_static_temp.set_quad_order(o, H2D_FN_VAL);
const double* fnj = ref_map_pss_static_temp.get_fn_values();
double3* pt = g_quad_2d_std.get_points(o, mode);
double val = 0.0;
for (unsigned short k = 0; k < g_quad_2d_std.get_num_points(o, mode); k++)
val += pt[k][2] * (fni[k] * fnj[k]);
mat[i][j] = mat[j][i] = val;
}
}
return mat;
}
void CurvMapStatic::precalculate_cholesky_projection_matrices_bubble()
{
// *** triangles ***
// calculate projection matrix of maximum order
{
Element e;
e.nvert = 3;
e.cm = nullptr;
e.id = -1;
ref_map_pss_static.set_active_element(&e);
short* indices = ref_map_shapeset.get_bubble_indices(ref_map_shapeset.get_max_order(), HERMES_MODE_TRIANGLE);
curvMapStatic.bubble_proj_matrix_tri = calculate_bubble_projection_matrix(indices, HERMES_MODE_TRIANGLE);
// cholesky factorization of the matrix
choldc(curvMapStatic.bubble_proj_matrix_tri, this->tri_bubble_np, curvMapStatic.bubble_tri_p);
}
// *** quads ***
// calculate projection matrix of maximum order
{
Element e;
e.nvert = 4;
e.cm = nullptr;
e.id = -1;
ref_map_pss_static.set_active_element(&e);
short *indices = ref_map_shapeset.get_bubble_indices(H2D_MAKE_QUAD_ORDER(ref_map_shapeset.get_max_order(), ref_map_shapeset.get_max_order()), HERMES_MODE_QUAD);
curvMapStatic.bubble_proj_matrix_quad = calculate_bubble_projection_matrix(indices, HERMES_MODE_QUAD);
// cholesky factorization of the matrix
choldc(curvMapStatic.bubble_proj_matrix_quad, this->quad_bubble_np, curvMapStatic.bubble_quad_p);
}
}
void CurvMapStatic::precalculate_cholesky_projection_matrix_edge()
{
// calculate projection matrix of maximum order
for (int i = 0; i < this->edge_proj_matrix_size; i++)
{
for (int j = i; j < this->edge_proj_matrix_size; j++)
{
int o = i + j + 4;
double2* pt = g_quad_1d_std.get_points(o);
double val = 0.0;
for (int k = 0; k < g_quad_1d_std.get_num_points(o); k++)
{
double fi = 0;
double fj = 0;
double x = pt[k][0];
switch (i + 2)
{
case 0:
fi = l0(x);
break;
case 1:
fi = l1(x);
break;
case 2:
fi = l2(x);
break;
case 3:
fi = l3(x);
break;
case 4:
fi = l4(x);
break;
case 5:
fi = l5(x);
break;
case 6:
fi = l6(x);
break;
case 7:
fi = l7(x);
break;
case 8:
fi = l8(x);
break;
case 9:
fi = l9(x);
break;
case 10:
fi = l10(x);
break;
case 11:
fi = l11(x);
break;
}
switch (j + 2)
{
case 0:
fj = l0(x);
break;
case 1:
fj = l1(x);
break;
case 2:
fj = l2(x);
break;
case 3:
fj = l3(x);
break;
case 4:
fj = l4(x);
break;
case 5:
fj = l5(x);
break;
case 6:
fj = l6(x);
break;
case 7:
fj = l7(x);
break;
case 8:
fj = l8(x);
break;
case 9:
fj = l9(x);
break;
case 10:
fj = l10(x);
break;
case 11:
fj = l11(x);
break;
}
val += pt[k][1] * (fi * fj);
}
this->edge_proj_matrix[i][j] = this->edge_proj_matrix[j][i] = val;
}
}
// Cholesky factorization of the matrix
choldc(this->edge_proj_matrix, this->edge_proj_matrix_size, this->edge_p);
}
CurvMapStatic curvMapStatic;
Curve::Curve(CurvType type) : type(type)
{
}
Curve::~Curve()
{
}
Arc::Arc() : Curve(ArcType)
{
kv[0] = kv[1] = kv[2] = 0;
kv[3] = kv[4] = kv[5] = 1;
}
Arc::Arc(double angle) : Curve(ArcType), angle(angle)
{
kv[0] = kv[1] = kv[2] = 0;
kv[3] = kv[4] = kv[5] = 1;
}
Arc::Arc(const Arc* other) : Curve(ArcType)
{
this->angle = other->angle;
memcpy(this->kv, other->kv, 6 * sizeof(double));
memcpy(this->pt, other->pt, 3 * sizeof(double3));
}
Nurbs::Nurbs() : Curve(NurbsType)
{
pt = nullptr;
kv = nullptr;
};
Nurbs::~Nurbs()
{
free_with_check(pt);
free_with_check(kv);
};
Nurbs::Nurbs(const Nurbs* other) : Curve(NurbsType)
{
this->degree = other->degree;
this->nk = other->nk;
this->np = other->np;
this->kv = malloc_with_check<double>(nk);
this->pt = malloc_with_check<double3>(np);
}
static double lambda_0(double x, double y)
{
return -0.5 * (x + y);
}
static double lambda_1(double x, double y)
{
return 0.5 * (x + 1);
}
static double lambda_2(double x, double y)
{
return 0.5 * (y + 1);
}
CurvMap::CurvMap() : ref_map_pss(&ref_map_shapeset)
{
coeffs = nullptr;
ctm = nullptr;
memset(curves, 0, sizeof(Curve*)* H2D_MAX_NUMBER_EDGES);
this->parent = nullptr;
this->sub_idx = 0;
}
CurvMap::CurvMap(const CurvMap* cm) : ref_map_pss(&ref_map_shapeset)
{
this->nc = cm->nc;
this->order = cm->order;
/// \todo Find out if this is safe.
this->ctm = cm->ctm;
this->coeffs = malloc_with_check<double2>(nc, true);
memcpy(coeffs, cm->coeffs, sizeof(double2)* nc);
this->toplevel = cm->toplevel;
if (this->toplevel)
{
for (int i = 0; i < 4; i++)
{
if (cm->curves[i])
{
if (cm->curves[i]->type == NurbsType)
this->curves[i] = new Nurbs((Nurbs*)cm->curves[i]);
else
this->curves[i] = new Arc((Arc*)cm->curves[i]);
}
else
this->curves[i] = nullptr;
}
this->parent = nullptr;
this->sub_idx = 0;
}
else
{
memset(curves, 0, sizeof(Curve*)* H2D_MAX_NUMBER_EDGES);
this->parent = cm->parent;
this->sub_idx = cm->sub_idx;
}
}
CurvMap::~CurvMap()
{
this->free();
}
void CurvMap::free()
{
free_with_check(this->coeffs, true);
if (toplevel)
{
for (int i = 0; i < 4; i++)
if (curves[i])
{
delete curves[i];
curves[i] = nullptr;
}
}
}
double CurvMap::nurbs_basis_fn(unsigned short i, unsigned short k, double t, double* knot)
{
if (k == 0)
{
return (t >= knot[i] && t <= knot[i + 1] && knot[i] < knot[i + 1]) ? 1.0 : 0.0;
}
else
{
double N1 = nurbs_basis_fn(i, k - 1, t, knot);
double N2 = nurbs_basis_fn(i + 1, k - 1, t, knot);
if ((N1 > HermesEpsilon) || (N2 > HermesEpsilon))
{
double result = 0.0;
if ((N1 > HermesEpsilon) && knot[i + k] != knot[i])
result += ((t - knot[i]) / (knot[i + k] - knot[i])) * N1;
if ((N2 > HermesEpsilon) && knot[i + k + 1] != knot[i + 1])
result += ((knot[i + k + 1] - t) / (knot[i + k + 1] - knot[i + 1])) * N2;
return result;
}
else
return 0.0;
}
}
void CurvMap::nurbs_edge(Element* e, Curve* curve, int edge, double t, double& x,
double& y)
{
// Nurbs curves are parametrized from 0 to 1.
t = (t + 1.0) / 2.0;
// Start point A, end point B.
double2 A = { e->vn[edge]->x, e->vn[edge]->y };
double2 B = { e->vn[e->next_vert(edge)]->x, e->vn[e->next_vert(edge)]->y };
// Vector pointing from A to B.
double2 v = { B[0] - A[0], B[1] - A[1] };
// Straight line.
if (!curve)
{
x = A[0] + t * v[0];
y = A[1] + t * v[1];
}
else
{
double3* cp;
int degree, np;
double* kv;
if (curve->type == ArcType)
{
cp = ((Arc*)curve)->pt;
np = ((Arc*)curve)->np;
degree = ((Arc*)curve)->degree;
kv = ((Arc*)curve)->kv;
}
else
{
cp = ((Nurbs*)curve)->pt;
np = ((Nurbs*)curve)->np;
degree = ((Nurbs*)curve)->degree;
kv = ((Nurbs*)curve)->kv;
}
// sum of basis fns and weights
double sum = 0.0;
x = y = 0.0;
for (int i = 0; i < np; i++)
{
double basis = nurbs_basis_fn(i, degree, t, kv);
sum += cp[i][2] * basis;
double x_i = cp[i][0];
double y_i = cp[i][1];
double w_i = cp[i][2];
x += w_i * basis * x_i;
y += w_i * basis * y_i;
}
x /= sum;
y /= sum;
}
}
const double2 CurvMap::ref_vert[2][H2D_MAX_NUMBER_VERTICES] =
{
{ { -1.0, -1.0 }, { 1.0, -1.0 }, { -1.0, 1.0 }, { 0.0, 0.0 } },
{ { -1.0, -1.0 }, { 1.0, -1.0 }, { 1.0, 1.0 }, { -1.0, 1.0 } }
};
void CurvMap::nurbs_edge_0(Element* e, Curve* curve, unsigned short edge, double t, double& x, double& y, double& n_x, double& n_y, double& t_x, double& t_y)
{
unsigned short va = edge;
unsigned short vb = e->next_vert(edge);
nurbs_edge(e, curve, edge, t, x, y);
x -= 0.5 * ((1 - t) * (e->vn[va]->x) + (1 + t) * (e->vn[vb]->x));
y -= 0.5 * ((1 - t) * (e->vn[va]->y) + (1 + t) * (e->vn[vb]->y));
double k = 4.0 / ((1 - t) * (1 + t));
x *= k;
y *= k;
}
void CurvMap::calc_ref_map_tri(Element* e, Curve** curve, double xi_1, double xi_2, double& x, double& y)
{
double fx, fy;
x = y = 0.0;
double l[3] = { lambda_0(xi_1, xi_2), lambda_1(xi_1, xi_2), lambda_2(xi_1, xi_2) };
for (unsigned char j = 0; j < e->get_nvert(); j++)
{
int va = j;
int vb = e->next_vert(j);
double la = l[va];
double lb = l[vb];
// vertex part
x += e->vn[j]->x * la;
y += e->vn[j]->y * la;
if (!(((ref_vert[0][va][0] == xi_1) && (ref_vert[0][va][1] == xi_2)) || ((ref_vert[0][vb][0] == xi_1) && (ref_vert[0][vb][1] == xi_2))))
{
// edge part
double t = lb - la;
double n_x, n_y, t_x, t_y;
nurbs_edge_0(e, curve[j], j, t, fx, fy, n_x, n_y, t_x, t_y);
x += fx * lb * la;
y += fy * lb * la;
}
}
}
void CurvMap::calc_ref_map_quad(Element* e, Curve** curve, double xi_1, double xi_2,
double& x, double& y)
{
double ex[H2D_MAX_NUMBER_EDGES], ey[H2D_MAX_NUMBER_EDGES];
nurbs_edge(e, curve[0], 0, xi_1, ex[0], ey[0]);
nurbs_edge(e, curve[1], 1, xi_2, ex[1], ey[1]);
nurbs_edge(e, curve[2], 2, -xi_1, ex[2], ey[2]);
nurbs_edge(e, curve[3], 3, -xi_2, ex[3], ey[3]);
x = (1 - xi_2) / 2.0 * ex[0] + (1 + xi_1) / 2.0 * ex[1] +
(1 + xi_2) / 2.0 * ex[2] + (1 - xi_1) / 2.0 * ex[3] -
(1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->x - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->x -
(1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->x - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->x;
y = (1 - xi_2) / 2.0 * ey[0] + (1 + xi_1) / 2.0 * ey[1] +
(1 + xi_2) / 2.0 * ey[2] + (1 - xi_1) / 2.0 * ey[3] -
(1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->y - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->y -
(1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->y - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->y;
}
void CurvMap::calc_ref_map(Element* e, Curve** curve, double xi_1, double xi_2, double2& f)
{
if (e->get_mode() == HERMES_MODE_QUAD)
calc_ref_map_quad(e, curve, xi_1, xi_2, f[0], f[1]);
else
calc_ref_map_tri(e, curve, xi_1, xi_2, f[0], f[1]);
}
void CurvMap::edge_coord(Element* e, unsigned short edge, double t, double2& x) const
{
unsigned short mode = e->get_mode();
double2 a, b;
a[0] = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0];
a[1] = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1];
b[0] = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0];
b[1] = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1];
for (int i = 0; i < 2; i++)
{
x[i] = a[i] + (t + 1.0) / 2.0 * (b[i] - a[i]);
}
}
void CurvMap::calc_edge_projection(Element* e, unsigned short edge, Curve** nurbs, unsigned short order, double2* proj) const
{
unsigned short i, j, k;
unsigned short mo1 = g_quad_1d_std.get_max_order();
unsigned char np = g_quad_1d_std.get_num_points(mo1);
unsigned short ne = order - 1;
unsigned short mode = e->get_mode();
assert(np <= 15 && ne <= 10);
double2 fn[15];
double rhside[2][10];
memset(rhside[0], 0, sizeof(double)* ne);
memset(rhside[1], 0, sizeof(double)* ne);
double a_1, a_2, b_1, b_2;
a_1 = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0];
a_2 = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1];
b_1 = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0];
b_2 = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1];
// values of nonpolynomial function in two vertices
double2 fa, fb;
calc_ref_map(e, nurbs, a_1, a_2, fa);
calc_ref_map(e, nurbs, b_1, b_2, fb);
double2* pt = g_quad_1d_std.get_points(mo1);
// over all integration points
for (j = 0; j < np; j++)
{
double2 x;
double t = pt[j][0];
edge_coord(e, edge, t, x);
calc_ref_map(e, nurbs, x[0], x[1], fn[j]);
for (k = 0; k < 2; k++)
fn[j][k] = fn[j][k] - (fa[k] + (t + 1) / 2.0 * (fb[k] - fa[k]));
}
double2* result = proj + e->get_nvert() + edge * (order - 1);
for (k = 0; k < 2; k++)
{
for (i = 0; i < ne; i++)
{
for (j = 0; j < np; j++)
{
double t = pt[j][0];
double fi = 0;
switch (i + 2)
{
case 0:
fi = l0(t);
break;
case 1:
fi = l1(t);
break;
case 2:
fi = l2(t);
break;
case 3:
fi = l3(t);
break;
case 4:
fi = l4(t);
break;
case 5:
fi = l5(t);
break;
case 6:
fi = l6(t);
break;
case 7:
fi = l7(t);
break;
case 8:
fi = l8(t);
break;
case 9:
fi = l9(t);
break;
case 10:
fi = l10(t);
break;
case 11:
fi = l11(t);
break;
}
rhside[k][i] += pt[j][1] * (fi * fn[j][k]);
}
}
// solve
cholsl(curvMapStatic.edge_proj_matrix, ne, curvMapStatic.edge_p, rhside[k], rhside[k]);
for (i = 0; i < ne; i++)
result[i][k] = rhside[k][i];
}
}
void CurvMap::old_projection(Element* e, unsigned short order, double2* proj, double* old[2])
{
unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode());
unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode());
unsigned short nvert = e->get_nvert();
for (unsigned int k = 0; k < nvert; k++) // loop over vertices
{
// vertex basis functions in all integration points
int index_v = ref_map_shapeset.get_vertex_index(k, e->get_mode());
ref_map_pss.set_active_shape(index_v);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double* vd = ref_map_pss.get_fn_values();
for (int m = 0; m < 2; m++) // part 0 or 1
for (int j = 0; j < np; j++)
old[m][j] += proj[k][m] * vd[j];
for (int ii = 0; ii < order - 1; ii++)
{
// edge basis functions in all integration points
int index_e = ref_map_shapeset.get_edge_index(k, 0, ii + 2, e->get_mode());
ref_map_pss.set_active_shape(index_e);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double* ed = ref_map_pss.get_fn_values();
for (int m = 0; m < 2; m++) //part 0 or 1
for (int j = 0; j < np; j++)
old[m][j] += proj[nvert + k * (order - 1) + ii][m] * ed[j];
}
}
}
void CurvMap::calc_bubble_projection(Element* e, Curve** curve, unsigned short order, double2* proj)
{
ref_map_pss.set_active_element(e);
unsigned short i, j, k;
unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode());
unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode());
unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order;
unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode());
double2* fn = new double2[np];
memset(fn, 0, np * sizeof(double2));
double* rhside[2];
double* old[2];
for (i = 0; i < 2; i++)
{
rhside[i] = new double[nb];
old[i] = new double[np];
memset(rhside[i], 0, sizeof(double)* nb);
memset(old[i], 0, sizeof(double)* np);
}
// compute known part of projection (vertex and edge part)
old_projection(e, order, proj, old);
// fn values of both components of nonpolynomial function
double3* pt = g_quad_2d_std.get_points(mo2, e->get_mode());
for (j = 0; j < np; j++) // over all integration points
{
double2 a;
a[0] = ctm->m[0] * pt[j][0] + ctm->t[0];
a[1] = ctm->m[1] * pt[j][1] + ctm->t[1];
calc_ref_map(e, curve, a[0], a[1], fn[j]);
}
double2* result = proj + e->get_nvert() + e->get_nvert() * (order - 1);
for (k = 0; k < 2; k++)
{
for (i = 0; i < nb; i++) // loop over bubble basis functions
{
// bubble basis functions in all integration points
int index_i = ref_map_shapeset.get_bubble_indices(qo, e->get_mode())[i];
ref_map_pss.set_active_shape(index_i);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double *bfn = ref_map_pss.get_fn_values();
for (j = 0; j < np; j++) // over all integration points
rhside[k][i] += pt[j][2] * (bfn[j] * (fn[j][k] - old[k][j]));
}
// solve
if (e->get_mode() == HERMES_MODE_TRIANGLE)
cholsl(curvMapStatic.bubble_proj_matrix_tri, nb, curvMapStatic.bubble_tri_p, rhside[k], rhside[k]);
else
cholsl(curvMapStatic.bubble_proj_matrix_quad, nb, curvMapStatic.bubble_quad_p, rhside[k], rhside[k]);
for (i = 0; i < nb; i++)
result[i][k] = rhside[k][i];
}
for (i = 0; i < 2; i++)
{
delete[] rhside[i];
delete[] old[i];
}
delete[] fn;
}
void CurvMap::update_refmap_coeffs(Element* e)
{
ref_map_pss.set_quad_2d(&g_quad_2d_std);
ref_map_pss.set_active_element(e);
// allocate projection coefficients
unsigned char nvert = e->get_nvert();
unsigned char ne = order - 1;
unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order;
unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode());
this->nc = nvert + nvert*ne + nb;
this->coeffs = realloc_with_check<double2>(this->coeffs, nc);
// WARNING: do not change the format of the array 'coeffs'. If it changes,
// RefMap::set_active_element() has to be changed too.
Curve** curves;
if (toplevel == false)
{
ref_map_pss.set_active_element(e);
ref_map_pss.set_transform(this->sub_idx);
curves = parent->cm->curves;
}
else
{
ref_map_pss.reset_transform();
curves = e->cm->curves;
}
ctm = ref_map_pss.get_ctm();
// calculation of new_ projection coefficients
// vertex part
for (unsigned char i = 0; i < nvert; i++)
{
coeffs[i][0] = e->vn[i]->x;
coeffs[i][1] = e->vn[i]->y;
}
if (!e->cm->toplevel)
e = e->cm->parent;
// edge part
for (unsigned char edge = 0; edge < nvert; edge++)
calc_edge_projection(e, edge, curves, order, coeffs);
//bubble part
calc_bubble_projection(e, curves, order, coeffs);
}
void CurvMap::get_mid_edge_points(Element* e, double2* pt, unsigned short n)
{
Curve** curves = this->curves;
Transformable tran;
tran.set_active_element(e);
if (toplevel == false)
{
tran.set_transform(this->sub_idx);
e = e->cm->parent;
curves = e->cm->curves;
}
ctm = tran.get_ctm();
double xi_1, xi_2;
for (unsigned short i = 0; i < n; i++)
{
xi_1 = ctm->m[0] * pt[i][0] + ctm->t[0];
xi_2 = ctm->m[1] * pt[i][1] + ctm->t[1];
calc_ref_map(e, curves, xi_1, xi_2, pt[i]);
}
}
CurvMap* CurvMap::create_son_curv_map(Element* e, int son)
{
// if the top three bits of part are nonzero, we would overflow
// -- make the element non-curvilinear
if (e->cm->sub_idx & 0xe000000000000000ULL)
return nullptr;
// if the parent element is already almost straight-edged,
// the son will be even more straight-edged
if (e->iro_cache == 0)
return nullptr;
CurvMap* cm = new CurvMap;
if (e->cm->toplevel == false)
{
cm->parent = e->cm->parent;
cm->sub_idx = (e->cm->sub_idx << 3) + son + 1;
}
else
{
cm->parent = e;
cm->sub_idx = (son + 1);
}
cm->toplevel = false;
cm->order = 4;
return cm;
}
}
} | Java |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
namespace Microsoft.Xna.Framework.Content.Pipeline.Graphics
{
/// <summary>
/// Provides properties for managing a bone weight.
/// </summary>
public struct BoneWeight
{
string boneName;
float weight;
/// <summary>
/// Gets the name of the bone.
/// </summary>
public string BoneName
{
get
{
return boneName;
}
}
/// <summary>
/// Gets the amount of bone influence, ranging from zero to one. The complete set of weights in a BoneWeightCollection should sum to one.
/// </summary>
public float Weight
{
get
{
return weight;
}
internal set
{
weight = value;
}
}
/// <summary>
/// Initializes a new instance of BoneWeight with the specified name and weight.
/// </summary>
/// <param name="boneName">Name of the bone.</param>
/// <param name="weight">Amount of influence, ranging from zero to one.</param>
public BoneWeight(string boneName, float weight)
{
this.boneName = boneName;
this.weight = weight;
}
}
}
| Java |
<!--!
This file is a part of MediaDrop (http://www.mediadrop.net),
Copyright 2009-2014 MediaDrop contributors
For the exact contribution history, see the git revision log.
The source code contained in this file is licensed under the GPLv3 or
(at your option) any later version.
See LICENSE.txt in the main project directory, for more information.
-->
<form xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude"
id="${id}"
name="${name}"
action="${action}"
method="${method}"
class="${css_class}"
py:attrs="attrs">
<xi:include href="../helpers.html" />
<span py:if="error and not error.error_dict" class="field-error" py:content="error" />
<table class="field-list" py:attrs="list_attrs">
<tbody>
<py:for each="i, field in enumerate(fields)"
py:with="required = field.is_required and ' required' or None;
help_url = getattr(field, 'help_url', None);
is_submit = getattr(field, 'type', None) == 'submit';
render_label = show_labels and not field.suppress_label;
render_error = error is not None and not field.show_error;">
<tr py:if="field.name == 'url'">
<td>
<br />
<div class="field-error"
py:if="'_the_form' in tmpl_context.form_errors"
py:content="tmpl_context.form_errors['_the_form']">
Display the error from the media controller, if any
</div>
</td>
</tr>
<tr class="title" py:if="render_label and not (is_submit or field.show_error)">
<td>
<label py:if="render_label" py:content="field.label_text and _(field.label_text) or None" id="${field.id}-label" class="form-label" for="${field.id}" />
<a py:if="field.help_text and help_url" py:content="field.help_text and _(field.help_text) or None" href="${help_url}" class="field-help" />
<span py:if="field.help_text and not help_url" py:content="field.help_text and _(field.help_text) or None" class="field-help" />
<span py:if="not field.show_error" class="field-error" py:content="error_for(field)" />
</td>
</tr>
<tr>
<td class="${render_error and (error_for(field) is not None and 'err' or 'noerr') or ''}">
${field.display(value_for(field), **args_for(field))}
<!-- The following 4 elements are used only by the SwiffUploadManager javascript -->
<div py:if="field.name == 'file'" id="bottombar">
<button id="browse-button" class="mcore-btn f-lft"><span>Choose a file to upload</span></button>
<div id="file-info" class="f-lft" />
</div>
</td>
</tr>
<tr py:if="field.name == 'description'" class="${field.name}-rel">
<td py:content="xhtml_description('description')" />
</tr>
</py:for>
</tbody>
</table>
</form>
| Java |
using WowPacketParser.Enums;
using WowPacketParser.Hotfix;
namespace WowPacketParserModule.V8_0_1_27101.Hotfix
{
[HotfixStructure(DB2Hash.WorldEffect, HasIndexInData = false)]
public class WorldEffectEntry
{
public uint QuestFeedbackEffectID { get; set; }
public byte WhenToDisplay { get; set; }
public sbyte TargetType { get; set; }
public int TargetAsset { get; set; }
public uint PlayerConditionID { get; set; }
public ushort CombatConditionID { get; set; }
}
}
| Java |
<?php
/**
* ObjectManager config with interception processing
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Interception\ObjectManager\Config;
use Magento\Framework\Interception\ObjectManager\ConfigInterface;
use Magento\Framework\ObjectManager\DefinitionInterface;
use Magento\Framework\ObjectManager\RelationsInterface;
use Magento\Framework\ObjectManager\InterceptableValidator;
class Developer extends \Magento\Framework\ObjectManager\Config\Config implements ConfigInterface
{
/**
* @var InterceptableValidator
*/
private $interceptableValidator;
/**
* @param RelationsInterface $relations
* @param DefinitionInterface $definitions
* @param InterceptableValidator $interceptableValidator
*/
public function __construct(
RelationsInterface $relations = null,
DefinitionInterface $definitions = null,
InterceptableValidator $interceptableValidator = null
) {
$this->interceptableValidator = $interceptableValidator ?: new InterceptableValidator();
parent::__construct($relations, $definitions);
}
/**
* @var \Magento\Framework\Interception\ConfigInterface
*/
protected $interceptionConfig;
/**
* Set Interception config
*
* @param \Magento\Framework\Interception\ConfigInterface $interceptionConfig
* @return void
*/
public function setInterceptionConfig(\Magento\Framework\Interception\ConfigInterface $interceptionConfig)
{
$this->interceptionConfig = $interceptionConfig;
}
/**
* Retrieve instance type with interception processing
*
* @param string $instanceName
* @return string
*/
public function getInstanceType($instanceName)
{
$type = parent::getInstanceType($instanceName);
if ($this->interceptionConfig && $this->interceptionConfig->hasPlugins($instanceName)
&& $this->interceptableValidator->validate($instanceName)
) {
return $type . '\\Interceptor';
}
return $type;
}
/**
* Retrieve instance type without interception processing
*
* @param string $instanceName
* @return string
*/
public function getOriginalInstanceType($instanceName)
{
return parent::getInstanceType($instanceName);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.