code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/*\ |*| |*| :: cookies.js :: |*| |*| A complete cookies reader/writer framework with full unicode support. |*| |*| Revision #1 - September 4, 2014 |*| |*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| |*| Syntaxes: |*| |*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) |*| * docCookies.getItem(name) |*| * docCookies.removeItem(name[, path[, domain]]) |*| * docCookies.hasItem(name) |*| * docCookies.keys() |*| \*/ export default { getItem: function (sKey) { if (!sKey) { return null; } return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { if (!sKey) { return false; } return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } };
thinhhung610/my-blog
js/vendor/cookie.js
JavaScript
isc
2,508
module Scubaru VERSION = "0.0.1" end
JoshAshby/scubaru
lib/scubaru/version.rb
Ruby
mit
39
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/devtools/containeranalysis/v1alpha1/bill_of_materials.proto package containeranalysis // import "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1alpha1" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Instruction set architectures supported by various package managers. type PackageManager_Architecture int32 const ( // Unknown architecture PackageManager_ARCHITECTURE_UNSPECIFIED PackageManager_Architecture = 0 // X86 architecture PackageManager_X86 PackageManager_Architecture = 1 // X64 architecture PackageManager_X64 PackageManager_Architecture = 2 ) var PackageManager_Architecture_name = map[int32]string{ 0: "ARCHITECTURE_UNSPECIFIED", 1: "X86", 2: "X64", } var PackageManager_Architecture_value = map[string]int32{ "ARCHITECTURE_UNSPECIFIED": 0, "X86": 1, "X64": 2, } func (x PackageManager_Architecture) String() string { return proto.EnumName(PackageManager_Architecture_name, int32(x)) } func (PackageManager_Architecture) EnumDescriptor() ([]byte, []int) { return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 0} } // PackageManager provides metadata about available / installed packages. type PackageManager struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PackageManager) Reset() { *m = PackageManager{} } func (m *PackageManager) String() string { return proto.CompactTextString(m) } func (*PackageManager) ProtoMessage() {} func (*PackageManager) Descriptor() ([]byte, []int) { return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0} } func (m *PackageManager) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PackageManager.Unmarshal(m, b) } func (m *PackageManager) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_PackageManager.Marshal(b, m, deterministic) } func (dst *PackageManager) XXX_Merge(src proto.Message) { xxx_messageInfo_PackageManager.Merge(dst, src) } func (m *PackageManager) XXX_Size() int { return xxx_messageInfo_PackageManager.Size(m) } func (m *PackageManager) XXX_DiscardUnknown() { xxx_messageInfo_PackageManager.DiscardUnknown(m) } var xxx_messageInfo_PackageManager proto.InternalMessageInfo // This represents a particular channel of distribution for a given package. // e.g. Debian's jessie-backports dpkg mirror type PackageManager_Distribution struct { // The cpe_uri in [cpe format](https://cpe.mitre.org/specification/) // denoting the package manager version distributing a package. CpeUri string `protobuf:"bytes,1,opt,name=cpe_uri,json=cpeUri,proto3" json:"cpe_uri,omitempty"` // The CPU architecture for which packages in this distribution // channel were built Architecture PackageManager_Architecture `protobuf:"varint,2,opt,name=architecture,proto3,enum=google.devtools.containeranalysis.v1alpha1.PackageManager_Architecture" json:"architecture,omitempty"` // The latest available version of this package in // this distribution channel. LatestVersion *VulnerabilityType_Version `protobuf:"bytes,3,opt,name=latest_version,json=latestVersion,proto3" json:"latest_version,omitempty"` // A freeform string denoting the maintainer of this package. Maintainer string `protobuf:"bytes,4,opt,name=maintainer,proto3" json:"maintainer,omitempty"` // The distribution channel-specific homepage for this package. Url string `protobuf:"bytes,6,opt,name=url,proto3" json:"url,omitempty"` // The distribution channel-specific description of this package. Description string `protobuf:"bytes,7,opt,name=description,proto3" json:"description,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PackageManager_Distribution) Reset() { *m = PackageManager_Distribution{} } func (m *PackageManager_Distribution) String() string { return proto.CompactTextString(m) } func (*PackageManager_Distribution) ProtoMessage() {} func (*PackageManager_Distribution) Descriptor() ([]byte, []int) { return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 0} } func (m *PackageManager_Distribution) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PackageManager_Distribution.Unmarshal(m, b) } func (m *PackageManager_Distribution) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_PackageManager_Distribution.Marshal(b, m, deterministic) } func (dst *PackageManager_Distribution) XXX_Merge(src proto.Message) { xxx_messageInfo_PackageManager_Distribution.Merge(dst, src) } func (m *PackageManager_Distribution) XXX_Size() int { return xxx_messageInfo_PackageManager_Distribution.Size(m) } func (m *PackageManager_Distribution) XXX_DiscardUnknown() { xxx_messageInfo_PackageManager_Distribution.DiscardUnknown(m) } var xxx_messageInfo_PackageManager_Distribution proto.InternalMessageInfo func (m *PackageManager_Distribution) GetCpeUri() string { if m != nil { return m.CpeUri } return "" } func (m *PackageManager_Distribution) GetArchitecture() PackageManager_Architecture { if m != nil { return m.Architecture } return PackageManager_ARCHITECTURE_UNSPECIFIED } func (m *PackageManager_Distribution) GetLatestVersion() *VulnerabilityType_Version { if m != nil { return m.LatestVersion } return nil } func (m *PackageManager_Distribution) GetMaintainer() string { if m != nil { return m.Maintainer } return "" } func (m *PackageManager_Distribution) GetUrl() string { if m != nil { return m.Url } return "" } func (m *PackageManager_Distribution) GetDescription() string { if m != nil { return m.Description } return "" } // An occurrence of a particular package installation found within a // system's filesystem. // e.g. glibc was found in /var/lib/dpkg/status type PackageManager_Location struct { // The cpe_uri in [cpe format](https://cpe.mitre.org/specification/) // denoting the package manager version distributing a package. CpeUri string `protobuf:"bytes,1,opt,name=cpe_uri,json=cpeUri,proto3" json:"cpe_uri,omitempty"` // The version installed at this location. Version *VulnerabilityType_Version `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` // The path from which we gathered that this package/version is installed. Path string `protobuf:"bytes,3,opt,name=path,proto3" json:"path,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PackageManager_Location) Reset() { *m = PackageManager_Location{} } func (m *PackageManager_Location) String() string { return proto.CompactTextString(m) } func (*PackageManager_Location) ProtoMessage() {} func (*PackageManager_Location) Descriptor() ([]byte, []int) { return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 1} } func (m *PackageManager_Location) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PackageManager_Location.Unmarshal(m, b) } func (m *PackageManager_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_PackageManager_Location.Marshal(b, m, deterministic) } func (dst *PackageManager_Location) XXX_Merge(src proto.Message) { xxx_messageInfo_PackageManager_Location.Merge(dst, src) } func (m *PackageManager_Location) XXX_Size() int { return xxx_messageInfo_PackageManager_Location.Size(m) } func (m *PackageManager_Location) XXX_DiscardUnknown() { xxx_messageInfo_PackageManager_Location.DiscardUnknown(m) } var xxx_messageInfo_PackageManager_Location proto.InternalMessageInfo func (m *PackageManager_Location) GetCpeUri() string { if m != nil { return m.CpeUri } return "" } func (m *PackageManager_Location) GetVersion() *VulnerabilityType_Version { if m != nil { return m.Version } return nil } func (m *PackageManager_Location) GetPath() string { if m != nil { return m.Path } return "" } // This represents a particular package that is distributed over // various channels. // e.g. glibc (aka libc6) is distributed by many, at various versions. type PackageManager_Package struct { // The name of the package. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The various channels by which a package is distributed. Distribution []*PackageManager_Distribution `protobuf:"bytes,10,rep,name=distribution,proto3" json:"distribution,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PackageManager_Package) Reset() { *m = PackageManager_Package{} } func (m *PackageManager_Package) String() string { return proto.CompactTextString(m) } func (*PackageManager_Package) ProtoMessage() {} func (*PackageManager_Package) Descriptor() ([]byte, []int) { return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 2} } func (m *PackageManager_Package) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PackageManager_Package.Unmarshal(m, b) } func (m *PackageManager_Package) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_PackageManager_Package.Marshal(b, m, deterministic) } func (dst *PackageManager_Package) XXX_Merge(src proto.Message) { xxx_messageInfo_PackageManager_Package.Merge(dst, src) } func (m *PackageManager_Package) XXX_Size() int { return xxx_messageInfo_PackageManager_Package.Size(m) } func (m *PackageManager_Package) XXX_DiscardUnknown() { xxx_messageInfo_PackageManager_Package.DiscardUnknown(m) } var xxx_messageInfo_PackageManager_Package proto.InternalMessageInfo func (m *PackageManager_Package) GetName() string { if m != nil { return m.Name } return "" } func (m *PackageManager_Package) GetDistribution() []*PackageManager_Distribution { if m != nil { return m.Distribution } return nil } // This represents how a particular software package may be installed on // a system. type PackageManager_Installation struct { // Output only. The name of the installed package. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // All of the places within the filesystem versions of this package // have been found. Location []*PackageManager_Location `protobuf:"bytes,2,rep,name=location,proto3" json:"location,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PackageManager_Installation) Reset() { *m = PackageManager_Installation{} } func (m *PackageManager_Installation) String() string { return proto.CompactTextString(m) } func (*PackageManager_Installation) ProtoMessage() {} func (*PackageManager_Installation) Descriptor() ([]byte, []int) { return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 3} } func (m *PackageManager_Installation) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PackageManager_Installation.Unmarshal(m, b) } func (m *PackageManager_Installation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_PackageManager_Installation.Marshal(b, m, deterministic) } func (dst *PackageManager_Installation) XXX_Merge(src proto.Message) { xxx_messageInfo_PackageManager_Installation.Merge(dst, src) } func (m *PackageManager_Installation) XXX_Size() int { return xxx_messageInfo_PackageManager_Installation.Size(m) } func (m *PackageManager_Installation) XXX_DiscardUnknown() { xxx_messageInfo_PackageManager_Installation.DiscardUnknown(m) } var xxx_messageInfo_PackageManager_Installation proto.InternalMessageInfo func (m *PackageManager_Installation) GetName() string { if m != nil { return m.Name } return "" } func (m *PackageManager_Installation) GetLocation() []*PackageManager_Location { if m != nil { return m.Location } return nil } func init() { proto.RegisterType((*PackageManager)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager") proto.RegisterType((*PackageManager_Distribution)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Distribution") proto.RegisterType((*PackageManager_Location)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Location") proto.RegisterType((*PackageManager_Package)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Package") proto.RegisterType((*PackageManager_Installation)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Installation") proto.RegisterEnum("google.devtools.containeranalysis.v1alpha1.PackageManager_Architecture", PackageManager_Architecture_name, PackageManager_Architecture_value) } func init() { proto.RegisterFile("google/devtools/containeranalysis/v1alpha1/bill_of_materials.proto", fileDescriptor_bill_of_materials_ffdc7b89323081b5) } var fileDescriptor_bill_of_materials_ffdc7b89323081b5 = []byte{ // 522 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xd1, 0x8a, 0xd3, 0x4e, 0x14, 0xc6, 0xff, 0x49, 0x97, 0x76, 0xf7, 0xb4, 0xff, 0x52, 0xe6, 0xc6, 0x10, 0x16, 0x29, 0x0b, 0x42, 0xf1, 0x22, 0x61, 0x57, 0x59, 0x04, 0x41, 0xe8, 0x76, 0xbb, 0x6b, 0x41, 0xa5, 0xc4, 0x76, 0x11, 0xbd, 0x08, 0xa7, 0xe9, 0x98, 0x0e, 0x3b, 0x9d, 0x09, 0x93, 0x49, 0xa1, 0xd7, 0xde, 0x89, 0x0f, 0xe0, 0xb5, 0x0f, 0xa5, 0xaf, 0x23, 0x99, 0x24, 0x92, 0xb2, 0x2a, 0xbb, 0xac, 0x77, 0x27, 0xf3, 0x85, 0xdf, 0xf9, 0xce, 0x77, 0x66, 0xe0, 0x2c, 0x96, 0x32, 0xe6, 0xd4, 0x5f, 0xd2, 0x8d, 0x96, 0x92, 0xa7, 0x7e, 0x24, 0x85, 0x46, 0x26, 0xa8, 0x42, 0x81, 0x7c, 0x9b, 0xb2, 0xd4, 0xdf, 0x1c, 0x23, 0x4f, 0x56, 0x78, 0xec, 0x2f, 0x18, 0xe7, 0xa1, 0xfc, 0x18, 0xae, 0x51, 0x53, 0xc5, 0x90, 0xa7, 0x5e, 0xa2, 0xa4, 0x96, 0xe4, 0x71, 0xc1, 0xf0, 0x2a, 0x86, 0x77, 0x83, 0xe1, 0x55, 0x0c, 0xf7, 0xb0, 0xec, 0x87, 0x09, 0xf3, 0x51, 0x08, 0xa9, 0x51, 0x33, 0x29, 0x4a, 0x92, 0x7b, 0x71, 0x07, 0x37, 0x09, 0x46, 0xd7, 0x18, 0xd3, 0x70, 0x93, 0xf1, 0x5c, 0x5f, 0x30, 0xce, 0xf4, 0xb6, 0xe0, 0x1c, 0xfd, 0x68, 0x42, 0x77, 0x5a, 0xe8, 0xaf, 0x51, 0x60, 0x4c, 0x95, 0xfb, 0xdd, 0x86, 0xce, 0x39, 0x4b, 0xb5, 0x62, 0x8b, 0x2c, 0x6f, 0x49, 0x1e, 0x40, 0x2b, 0x4a, 0x68, 0x98, 0x29, 0xe6, 0x58, 0x7d, 0x6b, 0x70, 0x10, 0x34, 0xa3, 0x84, 0xce, 0x15, 0x23, 0xd7, 0xd0, 0x41, 0x15, 0xad, 0x98, 0xa6, 0x91, 0xce, 0x14, 0x75, 0xec, 0xbe, 0x35, 0xe8, 0x9e, 0x5c, 0x7a, 0xb7, 0x9f, 0xd2, 0xdb, 0xed, 0xed, 0x0d, 0x6b, 0xb8, 0x60, 0x07, 0x4e, 0x38, 0x74, 0x39, 0x6a, 0x9a, 0xea, 0x70, 0x43, 0x55, 0xca, 0xa4, 0x70, 0x1a, 0x7d, 0x6b, 0xd0, 0x3e, 0x19, 0xdf, 0xa5, 0xdd, 0x55, 0x3d, 0x82, 0xd9, 0x36, 0xa1, 0xde, 0x55, 0x01, 0x0b, 0xfe, 0x2f, 0xe0, 0xe5, 0x27, 0x79, 0x08, 0xb0, 0x46, 0x56, 0x72, 0x9c, 0x3d, 0x33, 0x76, 0xed, 0x84, 0xf4, 0xa0, 0x91, 0x29, 0xee, 0x34, 0x8d, 0x90, 0x97, 0xa4, 0x0f, 0xed, 0x25, 0x4d, 0x23, 0xc5, 0x92, 0x3c, 0x34, 0xa7, 0x65, 0x94, 0xfa, 0x91, 0xfb, 0xd5, 0x82, 0xfd, 0x57, 0x32, 0xc2, 0xbf, 0x87, 0x1a, 0x42, 0xab, 0x1a, 0xd0, 0xfe, 0x97, 0x03, 0x56, 0x54, 0x42, 0x60, 0x2f, 0x41, 0xbd, 0x32, 0xf1, 0x1d, 0x04, 0xa6, 0x76, 0x3f, 0x5b, 0xd0, 0x2a, 0x57, 0x91, 0xeb, 0x02, 0xd7, 0xb4, 0xb4, 0x65, 0xea, 0x7c, 0xd3, 0xcb, 0xda, 0x95, 0x70, 0xa0, 0xdf, 0x18, 0xb4, 0xef, 0xb5, 0xe9, 0xfa, 0x0d, 0x0b, 0x76, 0xe0, 0xee, 0x27, 0x0b, 0x3a, 0x13, 0x91, 0x6a, 0xe4, 0xbc, 0xc8, 0xea, 0x77, 0x8e, 0x42, 0xd8, 0xe7, 0x65, 0x96, 0x8e, 0x6d, 0xdc, 0x8c, 0xee, 0xe1, 0xa6, 0x5a, 0x4b, 0xf0, 0x0b, 0x7a, 0xf4, 0x02, 0x3a, 0xf5, 0xdb, 0x48, 0x0e, 0xc1, 0x19, 0x06, 0xa3, 0x97, 0x93, 0xd9, 0x78, 0x34, 0x9b, 0x07, 0xe3, 0x70, 0xfe, 0xe6, 0xed, 0x74, 0x3c, 0x9a, 0x5c, 0x4c, 0xc6, 0xe7, 0xbd, 0xff, 0x48, 0x0b, 0x1a, 0xef, 0x9e, 0x9d, 0xf6, 0x2c, 0x53, 0x9c, 0x3e, 0xed, 0xd9, 0x67, 0x5f, 0x2c, 0x78, 0x14, 0xc9, 0x75, 0x65, 0xea, 0xcf, 0x5e, 0xa6, 0xd6, 0xfb, 0x0f, 0xe5, 0x4f, 0xb1, 0xe4, 0x28, 0x62, 0x4f, 0xaa, 0xd8, 0x8f, 0xa9, 0x30, 0x2f, 0xd4, 0x2f, 0x24, 0x4c, 0x58, 0x7a, 0x9b, 0xc7, 0xfe, 0xfc, 0x86, 0xf4, 0xcd, 0x6e, 0x5c, 0x8e, 0x86, 0x8b, 0xa6, 0xa1, 0x3d, 0xf9, 0x19, 0x00, 0x00, 0xff, 0xff, 0xfa, 0x4f, 0xa4, 0x56, 0xc7, 0x04, 0x00, 0x00, }
object88/langd
vendor/google.golang.org/genproto/googleapis/devtools/containeranalysis/v1alpha1/bill_of_materials.pb.go
GO
mit
16,890
<?php namespace yanivgal\Exceptions; use Exception; class CronomJobException extends Exception { }
yanivgal/Cronom
src/Exceptions/CronomJobException.php
PHP
mit
101
module Fonenode class SmsOutbox < SmsList def initialize(client) super(client) @path = "sms/outbox" @box_type = Sms::OUTBOUND end end end
digitalnatives/fonenode
lib/fonenode/sms_outbox.rb
Ruby
mit
169
import {Response} from './Response'; import {Settlement} from './Settlement'; export interface ReportResponse extends Response { settlements: Settlement[]; }
solinor/paymenthighway-javascript-lib
ts/src/model/response/ReportResponse.ts
TypeScript
mit
163
'use strict'; // Proxy URL (optional) const proxyUrl = 'drupal.dev'; // API keys const TINYPNG_KEY = ''; // fonts const fontList = []; // vendors const jsVendorList = []; const cssVendorList = []; // paths to relevant directories const dirs = { src: './src', dest: './dist' }; // paths to file sources const sources = { js: `${dirs.src}/**/*.js`, scss: `${dirs.src}/**/*.scss`, coreScss: `${dirs.src}/scss/main.scss`, img: `./img/**/*.{png,jpg}`, font: fontList, jsVendor: jsVendorList, cssVendor: cssVendorList }; // paths to file destinations const dests = { js: `${dirs.dest}/js`, css: `${dirs.dest}/css`, img: `${dirs.dest}/img`, sigFile: `./img/.tinypng-sigs`, font: `${dirs.dest}/fonts`, vendor: `${dirs.dest}/vendors` }; // plugins import gulp from 'gulp'; import browserSync from 'browser-sync'; import gulpLoadPlugins from 'gulp-load-plugins'; // auto-load plugins const $ = gulpLoadPlugins(); /**************************************** Gulp Tasks *****************************************/ // launch browser sync as a standalone local server gulp.task('browser-sync-local', browserSyncLocal()); // browser-sync task for starting the server by proxying a local url gulp.task('browser-sync-proxy', browserSyncProxy()); // copy vendor CSS gulp.task('css-vendors', cssVendors()); // copy fonts gulp.task('fonts', fonts()); // Lint Javascript Task gulp.task('js-lint', javascriptLint()); // Concatenate and Minify Vendor JS gulp.task('js-vendors', javascriptVendors()); // lint sass task gulp.task('sass-lint', sassLint()); // Concatenate & Minify JS gulp.task('scripts', ['js-lint'], scripts()); // compile, prefix, and minify the sass gulp.task('styles', styles()); // compress and combine svg icons gulp.task('svg', svg()); // Unit testing gulp.task('test', test()); // compress png and jpg images via tinypng API gulp.task('tinypng', tinypng()); // Watch Files For Changes gulp.task('watch', watch()); // default task builds src, opens up a standalone server, and watches for changes gulp.task('default', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // local task builds src, opens up a standalone server, and watches for changes gulp.task('local', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // proxy task builds src, opens up a proxy server, and watches for changes gulp.task('proxy', [ 'fonts', 'styles', 'scripts', 'browser-sync-proxy', 'watch' ]); // builds everything gulp.task('build', [ 'fonts', 'styles', 'scripts', 'css-vendors', 'js-vendors' ]); // builds the vendor files gulp.task('vendors', [ 'css-vendors', 'js-vendors' ]); // compresses imagery gulp.task('images', [ 'svg', 'tinypng' ]); /**************************************** Task Logic *****************************************/ function browserSyncLocal () { return () => { browserSync.init({ server: '../../../../' }); }; } function browserSyncProxy () { return () => { browserSync.init({ proxy: proxyUrl }); }; } function cssVendors () { return () => { return gulp.src(sources.cssVendor) .pipe(gulp.dest(dests.vendor)); }; } function fonts () { return () => { gulp.src(sources.font) .pipe(gulp.dest(dests.font)); }; } function javascriptLint () { return () => { return gulp.src(sources.js) .pipe($.jshint({esversion: 6})) .pipe($.jshint.reporter('jshint-stylish')); }; } function javascriptVendors () { return () => { return gulp.src(sources.jsVendor) .pipe($.plumber()) .pipe($.concat('vendors.min.js')) .pipe($.uglify()) .pipe(gulp.dest(dests.vendor)); }; } function sassLint () { return () => { return gulp.src(sources.scss) .pipe($.sassLint()) .pipe($.sassLint.format()) .pipe($.sassLint.failOnError()); }; } function scripts () { return () => { return gulp.src(sources.js) .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe($.concat('main.js')) .pipe($.babel()) .pipe(gulp.dest(dests.js)) .pipe($.rename({suffix: '.min'})) .pipe($.uglify()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.js)) .pipe(browserSync.stream()); }; } function styles () { return () => { return gulp.src(sources.coreScss) .pipe($.sourcemaps.init()) .pipe($.sass().on('error', $.sass.logError)) .pipe($.autoprefixer(["> 1%", "last 2 versions"], { cascade: true })) .pipe(gulp.dest(dests.css)) .pipe($.rename({suffix: '.min'})) .pipe($.cleanCss()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.css)) .pipe(browserSync.stream()); }; } function svg () { return () => { return gulp.src('./img/icons/*.svg') .pipe($.svgmin()) .pipe($.svgstore()) .pipe(gulp.dest('./img/icons')); }; } function test (done) { return () => { let server = new karma.Server('./karma.conf.js', done); server.start(); }; } function tinypng () { return () => { return gulp.src(sources.img) .pipe($.tinypngCompress({ key: TINYPNG_KEY, sigFile: dests.sigFile })) .pipe(gulp.dest(dests.img)); }; } function watch () { return () => { gulp.watch(sources.js, ['scripts']); gulp.watch(sources.scss, ['styles']); gulp.watch('**/*.php', browserSync.reload); }; }
TricomB2B/tricom-drupal-7-base
gulpfile.babel.js
JavaScript
mit
5,441
<?php /* * This File is part of the Lucid\Common\Data package * * (c) iwyg <mail@thomas-appel.com> * * For full copyright and license information, please refer to the LICENSE file * that was distributed with this package. */ namespace Lucid\Common\Struct; use SplPriorityQueue; /** * @class PriorityQueue * @see \SplPriorityQueue * * @package Lucid\Common\Data * @version $Id$ * @author iwyg <mail@thomas-appel.com> */ class PriorityQueue extends SplPriorityQueue { /** * queueOrder * * @var int */ private $queueOrder; /** * Constructor. */ public function __construct() { $this->queueOrder = PHP_INT_MAX; } /** * {@inheritdoc} */ public function insert($datum, $priority) { if (is_int($priority)) { $priority = [$priority, $this->queueOrder--]; } parent::insert($datum, $priority); } }
iwyg/common
src/Struct/PriorityQueue.php
PHP
mit
933
'use strict'; const debug = require('debug')('WechatController'); const EventEmitter = require('events').EventEmitter; const Cache = require('../../service/Cache'); const Wechat = require('../../service/Wechat'); const config = require('../../config'); const _ = require('lodash'); const async = require('async'); /* 微信公众平台连接认证 */ exports.wechatValidation = function (req, res, next) { let signature = req.query.signature; let timestamp = req.query.timestamp; let nonce = req.query.nonce; let echostr = req.query.echostr; let flag = Wechat.validateSignature(signature, timestamp, nonce); if (flag) return res.send(echostr); else return res.send({success: false}); }; /* 更新access token */ exports.updateAccessToken = function (req, res, next) { Wechat.updateAccessToken(); res.send('updateAccessToken'); }; /* 接收来自微信的消息推送 */ exports.processWechatEvent = function (req, res, next) { let content = req.body.xml; console.log('Event received. Event: %s', JSON.stringify(content)); res.send('success'); if(!content) return; try { let fromOpenId = content.FromUserName[0], toOpenId = content.ToUserName[0], createTime = content.CreateTime[0], event = content.Event ? content.Event[0] : "", eventKey = content.EventKey ? content.EventKey[0] : "", msgType = content.MsgType[0], msgId = content.MsgID ? content.MsgID[0] : "", status = content.Status ? content.Status[0] : "", ticket = content.Ticket ? content.Ticket[0] : null; if(msgType === 'event') { const WechatEvent = req.app.db.models.WechatEvent; let wechatEvent = new WechatEvent({ event: content }); wechatEvent.save((err) => { if(err) console.error(err, err.stack); handleEvent(req, res, fromOpenId, event, eventKey, msgId, status, ticket); }); } } catch(e) { console.error(e, e.stack); } }; function handleEvent(req, res, openId, name, key, msgId, status, ticket) { const Subscriber = req.app.db.models.Subscriber; const InvitationCard = req.app.db.models.InvitationCard; name = String(name).toLowerCase(); if(name === 'scan') { if(ticket) { InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => { if(err) return console.error(err); if(cardDoc && cardDoc.invitationTask.status === 'OPEN') { if(cardDoc.openId === openId) { return Wechat.sendText(openId, "你不能扫描自己的任务卡"); } else { Subscriber.findOne({ openId, subscribe: true }).exec((err, subscriberDoc) => { if(err) return console.error(err); if(subscriberDoc) return Wechat.sendText(openId, "你已经关注,不能被邀请"); }); } } }); } } if(name === 'click') { if(key.indexOf('invitationTask') === 0) { let taskId = key.split('-')[1]; require('../../service/InvitationCard').sendCard(openId, taskId); } if(key.indexOf('message') === 0) { let replyQueueId = key.split('-')[1]; let ReplyQueue = req.app.db.models.ReplyQueue; let ReplyQueueLog = req.app.db.models.ReplyQueueLog; function sendMessages(messageGroup) { async.eachSeries(messageGroup, function(message, callback) { if(message.type === 'text') { return Wechat.sendText(openId, message.content).then((data) => { setTimeout(callback, 1000); }).catch(callback); } if(message.type === 'image') { return Wechat.sendImage(openId, message.mediaId).then((data) => { setTimeout(callback, 5000); }).catch(callback); } }, function(err) { err && console.log(err); }); } ReplyQueueLog.findOne({ openId, replyQueue: replyQueueId}).exec((err, log) => { if(log) { let nextIndex = log.clickCount; if(nextIndex > log.messageGroupsSnapshot.length-1) { nextIndex = log.messageGroupsSnapshot.length-1; } else { ReplyQueueLog.findByIdAndUpdate(log._id, { clickCount: nextIndex + 1 }, { new: true }).exec(); } sendMessages(log.messageGroupsSnapshot[nextIndex]) } else { ReplyQueue.findById(replyQueueId).exec((err, replyQueue) => { new ReplyQueueLog({ openId: openId, replyQueue: replyQueueId, messageGroupsSnapshot: replyQueue.messageGroups, clickCount: 1 }).save(); sendMessages(replyQueue.messageGroups[0]); }); } }); } } if(name === 'subscribe') { const workflow = new EventEmitter(); let introducer = null; let card = null; // 检查扫码标记 workflow.on('checkTicket', () => { debug('Event: checkTicket'); if(ticket) return workflow.emit('findNewUser'); // 在数据库中寻找该"新"用户 return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情 }); // 在数据库中寻找该用户 workflow.on('findNewUser', () => { debug('Event: findNewUser'); Subscriber.findOne({ openId }).exec((err, doc) => { if(err) return workflow.emit('error', err); // 错误 if(!doc) return workflow.emit('getTaskAndCard'); // 查找邀请卡和任务配置 InvitationCard.findOne({ openId, qrTicket: ticket }).exec((err, selfScanedCardDoc) => { if(err) return workflow.emit('error', err); // 错误 if(selfScanedCardDoc) return Wechat.sendText(openId, "你不能扫描自己的任务卡"); if(doc.subscribe) return Wechat.sendText(openId, "你已经关注,不能被邀请"); Wechat.sendText(openId, "你已经被邀请过,不能被再次邀请"); }); return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情 }); }); workflow.on('getTaskAndCard', () => { debug('Event: getTaskAndCard'); InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => { if(err) return workflow.emit('error', err); // 错误 if(!cardDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请卡,获得"新"用户详情 if(!cardDoc.invitationTask) return workflow.emit('getSubscriberInfo'); // 邀请卡任务不存在,获得"新"用户详情 if(cardDoc.invitationTask.status !== 'OPEN') return workflow.emit('getSubscriberInfo'); // 邀请卡任务已关闭,获得"新"用户详情 card = cardDoc.toJSON(); Subscriber.findOne({ openId: cardDoc.openId }).exec((err, introducerDoc) => { if(err) return workflow.emit('error', err); // 错误 if(!introducerDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请人,获得"新"用户详情 introducer = introducerDoc.toJSON(); return workflow.emit('invitedCountPlus'); // 增加邀请量 }); }); }); workflow.on('invitedCountPlus', () => { debug('Event: invitedCountPlus'); InvitationCard.findOneAndUpdate({ qrTicket: ticket }, { $inc: { invitedCount: 1 }}, function(err, doc) { if(err) return workflow.emit('error', err); // 错误 console.log(`[WechatController] Add Invitation: ${ticket}`); workflow.emit('getSubscriberInfo'); }); }); workflow.on('getSubscriberInfo', () => { debug('Event: getSubscriberInfo'); Wechat.getSubscriberInfo(openId).then((info) => { let newData = { openId: info.openid, groupId: info.groupid, unionId: info.unionid, subscribe: info.subscribe ? true : false, subscribeTime: new Date(info.subscribe_time * 1000), nickname: info.nickname, remark: info.remark, gender: info.sex, headImgUrl: info.headimgurl, city: info.city, province: info.province, country: info.country, language: info.language }; if(introducer) { newData.introducer = introducer._id; if(card.invitationTask.invitedFeedback) { let invitedCount = card.invitedCount + 1; let remainCount = card.invitationTask.threshold - invitedCount; let invitedFeedback = card.invitationTask.invitedFeedback; if(remainCount > 0) { invitedFeedback = invitedFeedback.replace(/###/g, info.nickname) invitedFeedback = invitedFeedback.replace(/#invited#/g, invitedCount + ''); invitedFeedback = invitedFeedback.replace(/#remain#/g, remainCount + '') Wechat.sendText(introducer.openId, invitedFeedback); } } } Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){ if(err) return workflow.emit('error', err); // 错误 console.log(`[WechatController] New Subscriber: ${openId}`); }); }).catch((err) => { if(err) return workflow.emit('error', err); // 错误 }) }); // 错误 workflow.on('error', (err, wechatMessage) => { debug('Event: error'); if(err) { console.error(err, err.stack); } else { console.error('Undefined Error Event'); } }); workflow.emit('checkTicket'); } if(name === 'unsubscribe') { let Subscriber = req.app.db.models.Subscriber; let newData = { subscribe: false }; Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){ if (err) return console.error(err); console.log(`[WechatController] Unsubscribe: ${openId}`); }); } if(name === 'templatesendjobfinish') { let TemplateSendLog = req.app.db.models.TemplateSendLog; status = _.upperFirst(status); TemplateSendLog.findOneAndUpdate({ msgId: msgId }, { status : status }, function(err, doc){ if (err) return console.log(err); console.log(`[WechatController] TEMPLATESENDJOBFINISH: ${msgId}`); }); } }
xwang1024/bomblab
lib/controller/wechat/index.js
JavaScript
mit
10,120
<?php namespace Nemundo\Package\Bootstrap\Table; use Nemundo\Html\Table\Table; class BootstrapTable extends Table { /** * @var bool */ public $smallTable = false; /** * @var bool */ public $hover = false; /** * @var bool */ public $inverse = false; /** * @var bool */ public $striped = false; public function getContent() { $this->addCssClass('table'); if ($this->smallTable) { $this->addCssClass('table-sm'); } if ($this->hover) { $this->addCssClass('table-hover'); } if ($this->inverse) { $this->addCssClass('table-inverse'); } if ($this->striped) { $this->addCssClass('table-striped'); } return parent::getContent(); } }
nemundo/framework
src/Package/Bootstrap/Table/BootstrapTable.php
PHP
mit
853
// get the languange parameter in the URL (i for case insensitive; //exec for test for a match in a string and return thr first match) function getURLParameter(key) { var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search); return result && result[1] || ''; } // function toggleLang(lang) { var lang = lang || 'de'; document.location = document.location.pathname + '?lang=' + lang; } // set UR var lang = getURLParameter('lang') || 'de'; $('#lang').ready(function() { $('#lang li').each(function() { var li = $(this)[0]; if (li.id == lang) $(this).addClass('selected'); }); });
geoadmin/web-storymaps
htdocs/common/js/toggleLang.js
JavaScript
mit
624
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Leave Group Types Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PLTDataSet : EduHubDataSet<PLT> { /// <inheritdoc /> public override string Name { get { return "PLT"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal PLTDataSet(EduHubContext Context) : base(Context) { Index_LEAVE_CODE = new Lazy<NullDictionary<string, IReadOnlyList<PLT>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_CODE)); Index_LEAVE_GROUP = new Lazy<NullDictionary<string, IReadOnlyList<PLT>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_GROUP)); Index_LEAVE_GROUP_LEAVE_CODE = new Lazy<Dictionary<Tuple<string, string>, PLT>>(() => this.ToDictionary(i => Tuple.Create(i.LEAVE_GROUP, i.LEAVE_CODE))); Index_PLTKEY = new Lazy<Dictionary<string, PLT>>(() => this.ToDictionary(i => i.PLTKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="PLT" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="PLT" /> fields for each CSV column header</returns> internal override Action<PLT, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<PLT, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "PLTKEY": mapper[i] = (e, v) => e.PLTKEY = v; break; case "LEAVE_GROUP": mapper[i] = (e, v) => e.LEAVE_GROUP = v; break; case "LEAVE_CODE": mapper[i] = (e, v) => e.LEAVE_CODE = v; break; case "CALC_METHOD": mapper[i] = (e, v) => e.CALC_METHOD = v; break; case "PERIOD_ALLOT01": mapper[i] = (e, v) => e.PERIOD_ALLOT01 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT02": mapper[i] = (e, v) => e.PERIOD_ALLOT02 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT03": mapper[i] = (e, v) => e.PERIOD_ALLOT03 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT04": mapper[i] = (e, v) => e.PERIOD_ALLOT04 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT05": mapper[i] = (e, v) => e.PERIOD_ALLOT05 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT06": mapper[i] = (e, v) => e.PERIOD_ALLOT06 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT07": mapper[i] = (e, v) => e.PERIOD_ALLOT07 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT08": mapper[i] = (e, v) => e.PERIOD_ALLOT08 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT09": mapper[i] = (e, v) => e.PERIOD_ALLOT09 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT10": mapper[i] = (e, v) => e.PERIOD_ALLOT10 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT11": mapper[i] = (e, v) => e.PERIOD_ALLOT11 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_ALLOT12": mapper[i] = (e, v) => e.PERIOD_ALLOT12 = v == null ? (double?)null : double.Parse(v); break; case "PERIOD_LENGTH01": mapper[i] = (e, v) => e.PERIOD_LENGTH01 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH02": mapper[i] = (e, v) => e.PERIOD_LENGTH02 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH03": mapper[i] = (e, v) => e.PERIOD_LENGTH03 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH04": mapper[i] = (e, v) => e.PERIOD_LENGTH04 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH05": mapper[i] = (e, v) => e.PERIOD_LENGTH05 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH06": mapper[i] = (e, v) => e.PERIOD_LENGTH06 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH07": mapper[i] = (e, v) => e.PERIOD_LENGTH07 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH08": mapper[i] = (e, v) => e.PERIOD_LENGTH08 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH09": mapper[i] = (e, v) => e.PERIOD_LENGTH09 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH10": mapper[i] = (e, v) => e.PERIOD_LENGTH10 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH11": mapper[i] = (e, v) => e.PERIOD_LENGTH11 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_LENGTH12": mapper[i] = (e, v) => e.PERIOD_LENGTH12 = v == null ? (short?)null : short.Parse(v); break; case "PERIOD_UNITS": mapper[i] = (e, v) => e.PERIOD_UNITS = v; break; case "ANNUAL_ENTITLEMENT": mapper[i] = (e, v) => e.ANNUAL_ENTITLEMENT = v == null ? (double?)null : double.Parse(v); break; case "ROLL_OVER": mapper[i] = (e, v) => e.ROLL_OVER = v; break; case "ROLL_PERCENT": mapper[i] = (e, v) => e.ROLL_PERCENT = v == null ? (double?)null : double.Parse(v); break; case "LEAVE_LOADING": mapper[i] = (e, v) => e.LEAVE_LOADING = v; break; case "LOADING_PERCENT": mapper[i] = (e, v) => e.LOADING_PERCENT = v == null ? (double?)null : double.Parse(v); break; case "ACTIVE": mapper[i] = (e, v) => e.ACTIVE = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="PLT" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="PLT" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="PLT" /> entities</param> /// <returns>A merged <see cref="IEnumerable{PLT}"/> of entities</returns> internal override IEnumerable<PLT> ApplyDeltaEntities(IEnumerable<PLT> Entities, List<PLT> DeltaEntities) { HashSet<Tuple<string, string>> Index_LEAVE_GROUP_LEAVE_CODE = new HashSet<Tuple<string, string>>(DeltaEntities.Select(i => Tuple.Create(i.LEAVE_GROUP, i.LEAVE_CODE))); HashSet<string> Index_PLTKEY = new HashSet<string>(DeltaEntities.Select(i => i.PLTKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.PLTKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_LEAVE_GROUP_LEAVE_CODE.Remove(Tuple.Create(entity.LEAVE_GROUP, entity.LEAVE_CODE)); overwritten = overwritten || Index_PLTKEY.Remove(entity.PLTKEY); if (entity.PLTKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<PLT>>> Index_LEAVE_CODE; private Lazy<NullDictionary<string, IReadOnlyList<PLT>>> Index_LEAVE_GROUP; private Lazy<Dictionary<Tuple<string, string>, PLT>> Index_LEAVE_GROUP_LEAVE_CODE; private Lazy<Dictionary<string, PLT>> Index_PLTKEY; #endregion #region Index Methods /// <summary> /// Find PLT by LEAVE_CODE field /// </summary> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param> /// <returns>List of related PLT entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PLT> FindByLEAVE_CODE(string LEAVE_CODE) { return Index_LEAVE_CODE.Value[LEAVE_CODE]; } /// <summary> /// Attempt to find PLT by LEAVE_CODE field /// </summary> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param> /// <param name="Value">List of related PLT entities</param> /// <returns>True if the list of related PLT entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLEAVE_CODE(string LEAVE_CODE, out IReadOnlyList<PLT> Value) { return Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out Value); } /// <summary> /// Attempt to find PLT by LEAVE_CODE field /// </summary> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param> /// <returns>List of related PLT entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PLT> TryFindByLEAVE_CODE(string LEAVE_CODE) { IReadOnlyList<PLT> value; if (Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find PLT by LEAVE_GROUP field /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param> /// <returns>List of related PLT entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PLT> FindByLEAVE_GROUP(string LEAVE_GROUP) { return Index_LEAVE_GROUP.Value[LEAVE_GROUP]; } /// <summary> /// Attempt to find PLT by LEAVE_GROUP field /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param> /// <param name="Value">List of related PLT entities</param> /// <returns>True if the list of related PLT entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLEAVE_GROUP(string LEAVE_GROUP, out IReadOnlyList<PLT> Value) { return Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out Value); } /// <summary> /// Attempt to find PLT by LEAVE_GROUP field /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param> /// <returns>List of related PLT entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PLT> TryFindByLEAVE_GROUP(string LEAVE_GROUP) { IReadOnlyList<PLT> value; if (Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out value)) { return value; } else { return null; } } /// <summary> /// Find PLT by LEAVE_GROUP and LEAVE_CODE fields /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param> /// <returns>Related PLT entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PLT FindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE) { return Index_LEAVE_GROUP_LEAVE_CODE.Value[Tuple.Create(LEAVE_GROUP, LEAVE_CODE)]; } /// <summary> /// Attempt to find PLT by LEAVE_GROUP and LEAVE_CODE fields /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param> /// <param name="Value">Related PLT entity</param> /// <returns>True if the related PLT entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE, out PLT Value) { return Index_LEAVE_GROUP_LEAVE_CODE.Value.TryGetValue(Tuple.Create(LEAVE_GROUP, LEAVE_CODE), out Value); } /// <summary> /// Attempt to find PLT by LEAVE_GROUP and LEAVE_CODE fields /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param> /// <returns>Related PLT entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PLT TryFindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE) { PLT value; if (Index_LEAVE_GROUP_LEAVE_CODE.Value.TryGetValue(Tuple.Create(LEAVE_GROUP, LEAVE_CODE), out value)) { return value; } else { return null; } } /// <summary> /// Find PLT by PLTKEY field /// </summary> /// <param name="PLTKEY">PLTKEY value used to find PLT</param> /// <returns>Related PLT entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PLT FindByPLTKEY(string PLTKEY) { return Index_PLTKEY.Value[PLTKEY]; } /// <summary> /// Attempt to find PLT by PLTKEY field /// </summary> /// <param name="PLTKEY">PLTKEY value used to find PLT</param> /// <param name="Value">Related PLT entity</param> /// <returns>True if the related PLT entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPLTKEY(string PLTKEY, out PLT Value) { return Index_PLTKEY.Value.TryGetValue(PLTKEY, out Value); } /// <summary> /// Attempt to find PLT by PLTKEY field /// </summary> /// <param name="PLTKEY">PLTKEY value used to find PLT</param> /// <returns>Related PLT entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PLT TryFindByPLTKEY(string PLTKEY) { PLT value; if (Index_PLTKEY.Value.TryGetValue(PLTKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a PLT table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[PLT]( [PLTKEY] varchar(16) NOT NULL, [LEAVE_GROUP] varchar(8) NULL, [LEAVE_CODE] varchar(8) NULL, [CALC_METHOD] varchar(8) NULL, [PERIOD_ALLOT01] float NULL, [PERIOD_ALLOT02] float NULL, [PERIOD_ALLOT03] float NULL, [PERIOD_ALLOT04] float NULL, [PERIOD_ALLOT05] float NULL, [PERIOD_ALLOT06] float NULL, [PERIOD_ALLOT07] float NULL, [PERIOD_ALLOT08] float NULL, [PERIOD_ALLOT09] float NULL, [PERIOD_ALLOT10] float NULL, [PERIOD_ALLOT11] float NULL, [PERIOD_ALLOT12] float NULL, [PERIOD_LENGTH01] smallint NULL, [PERIOD_LENGTH02] smallint NULL, [PERIOD_LENGTH03] smallint NULL, [PERIOD_LENGTH04] smallint NULL, [PERIOD_LENGTH05] smallint NULL, [PERIOD_LENGTH06] smallint NULL, [PERIOD_LENGTH07] smallint NULL, [PERIOD_LENGTH08] smallint NULL, [PERIOD_LENGTH09] smallint NULL, [PERIOD_LENGTH10] smallint NULL, [PERIOD_LENGTH11] smallint NULL, [PERIOD_LENGTH12] smallint NULL, [PERIOD_UNITS] varchar(6) NULL, [ANNUAL_ENTITLEMENT] float NULL, [ROLL_OVER] varchar(1) NULL, [ROLL_PERCENT] float NULL, [LEAVE_LOADING] varchar(1) NULL, [LOADING_PERCENT] float NULL, [ACTIVE] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [PLT_Index_PLTKEY] PRIMARY KEY CLUSTERED ( [PLTKEY] ASC ) ); CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] ( [LEAVE_CODE] ASC ); CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] ( [LEAVE_GROUP] ASC ); CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] ( [LEAVE_GROUP] ASC, [LEAVE_CODE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_CODE') ALTER INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP') ALTER INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP_LEAVE_CODE') ALTER INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_CODE') ALTER INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP') ALTER INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP_LEAVE_CODE') ALTER INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="PLT"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="PLT"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<PLT> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<Tuple<string, string>> Index_LEAVE_GROUP_LEAVE_CODE = new List<Tuple<string, string>>(); List<string> Index_PLTKEY = new List<string>(); foreach (var entity in Entities) { Index_LEAVE_GROUP_LEAVE_CODE.Add(Tuple.Create(entity.LEAVE_GROUP, entity.LEAVE_CODE)); Index_PLTKEY.Add(entity.PLTKEY); } builder.AppendLine("DELETE [dbo].[PLT] WHERE"); // Index_LEAVE_GROUP_LEAVE_CODE builder.Append("("); for (int index = 0; index < Index_LEAVE_GROUP_LEAVE_CODE.Count; index++) { if (index != 0) builder.Append(" OR "); // LEAVE_GROUP if (Index_LEAVE_GROUP_LEAVE_CODE[index].Item1 == null) { builder.Append("([LEAVE_GROUP] IS NULL"); } else { var parameterLEAVE_GROUP = $"@p{parameterIndex++}"; builder.Append("([LEAVE_GROUP]=").Append(parameterLEAVE_GROUP); command.Parameters.Add(parameterLEAVE_GROUP, SqlDbType.VarChar, 8).Value = Index_LEAVE_GROUP_LEAVE_CODE[index].Item1; } // LEAVE_CODE if (Index_LEAVE_GROUP_LEAVE_CODE[index].Item2 == null) { builder.Append(" AND [LEAVE_CODE] IS NULL)"); } else { var parameterLEAVE_CODE = $"@p{parameterIndex++}"; builder.Append(" AND [LEAVE_CODE]=").Append(parameterLEAVE_CODE).Append(")"); command.Parameters.Add(parameterLEAVE_CODE, SqlDbType.VarChar, 8).Value = Index_LEAVE_GROUP_LEAVE_CODE[index].Item2; } } builder.AppendLine(") OR"); // Index_PLTKEY builder.Append("[PLTKEY] IN ("); for (int index = 0; index < Index_PLTKEY.Count; index++) { if (index != 0) builder.Append(", "); // PLTKEY var parameterPLTKEY = $"@p{parameterIndex++}"; builder.Append(parameterPLTKEY); command.Parameters.Add(parameterPLTKEY, SqlDbType.VarChar, 16).Value = Index_PLTKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the PLT data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the PLT data set</returns> public override EduHubDataSetDataReader<PLT> GetDataSetDataReader() { return new PLTDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the PLT data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the PLT data set</returns> public override EduHubDataSetDataReader<PLT> GetDataSetDataReader(List<PLT> Entities) { return new PLTDataReader(new EduHubDataSetLoadedReader<PLT>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class PLTDataReader : EduHubDataSetDataReader<PLT> { public PLTDataReader(IEduHubDataSetReader<PLT> Reader) : base (Reader) { } public override int FieldCount { get { return 38; } } public override object GetValue(int i) { switch (i) { case 0: // PLTKEY return Current.PLTKEY; case 1: // LEAVE_GROUP return Current.LEAVE_GROUP; case 2: // LEAVE_CODE return Current.LEAVE_CODE; case 3: // CALC_METHOD return Current.CALC_METHOD; case 4: // PERIOD_ALLOT01 return Current.PERIOD_ALLOT01; case 5: // PERIOD_ALLOT02 return Current.PERIOD_ALLOT02; case 6: // PERIOD_ALLOT03 return Current.PERIOD_ALLOT03; case 7: // PERIOD_ALLOT04 return Current.PERIOD_ALLOT04; case 8: // PERIOD_ALLOT05 return Current.PERIOD_ALLOT05; case 9: // PERIOD_ALLOT06 return Current.PERIOD_ALLOT06; case 10: // PERIOD_ALLOT07 return Current.PERIOD_ALLOT07; case 11: // PERIOD_ALLOT08 return Current.PERIOD_ALLOT08; case 12: // PERIOD_ALLOT09 return Current.PERIOD_ALLOT09; case 13: // PERIOD_ALLOT10 return Current.PERIOD_ALLOT10; case 14: // PERIOD_ALLOT11 return Current.PERIOD_ALLOT11; case 15: // PERIOD_ALLOT12 return Current.PERIOD_ALLOT12; case 16: // PERIOD_LENGTH01 return Current.PERIOD_LENGTH01; case 17: // PERIOD_LENGTH02 return Current.PERIOD_LENGTH02; case 18: // PERIOD_LENGTH03 return Current.PERIOD_LENGTH03; case 19: // PERIOD_LENGTH04 return Current.PERIOD_LENGTH04; case 20: // PERIOD_LENGTH05 return Current.PERIOD_LENGTH05; case 21: // PERIOD_LENGTH06 return Current.PERIOD_LENGTH06; case 22: // PERIOD_LENGTH07 return Current.PERIOD_LENGTH07; case 23: // PERIOD_LENGTH08 return Current.PERIOD_LENGTH08; case 24: // PERIOD_LENGTH09 return Current.PERIOD_LENGTH09; case 25: // PERIOD_LENGTH10 return Current.PERIOD_LENGTH10; case 26: // PERIOD_LENGTH11 return Current.PERIOD_LENGTH11; case 27: // PERIOD_LENGTH12 return Current.PERIOD_LENGTH12; case 28: // PERIOD_UNITS return Current.PERIOD_UNITS; case 29: // ANNUAL_ENTITLEMENT return Current.ANNUAL_ENTITLEMENT; case 30: // ROLL_OVER return Current.ROLL_OVER; case 31: // ROLL_PERCENT return Current.ROLL_PERCENT; case 32: // LEAVE_LOADING return Current.LEAVE_LOADING; case 33: // LOADING_PERCENT return Current.LOADING_PERCENT; case 34: // ACTIVE return Current.ACTIVE; case 35: // LW_DATE return Current.LW_DATE; case 36: // LW_TIME return Current.LW_TIME; case 37: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // LEAVE_GROUP return Current.LEAVE_GROUP == null; case 2: // LEAVE_CODE return Current.LEAVE_CODE == null; case 3: // CALC_METHOD return Current.CALC_METHOD == null; case 4: // PERIOD_ALLOT01 return Current.PERIOD_ALLOT01 == null; case 5: // PERIOD_ALLOT02 return Current.PERIOD_ALLOT02 == null; case 6: // PERIOD_ALLOT03 return Current.PERIOD_ALLOT03 == null; case 7: // PERIOD_ALLOT04 return Current.PERIOD_ALLOT04 == null; case 8: // PERIOD_ALLOT05 return Current.PERIOD_ALLOT05 == null; case 9: // PERIOD_ALLOT06 return Current.PERIOD_ALLOT06 == null; case 10: // PERIOD_ALLOT07 return Current.PERIOD_ALLOT07 == null; case 11: // PERIOD_ALLOT08 return Current.PERIOD_ALLOT08 == null; case 12: // PERIOD_ALLOT09 return Current.PERIOD_ALLOT09 == null; case 13: // PERIOD_ALLOT10 return Current.PERIOD_ALLOT10 == null; case 14: // PERIOD_ALLOT11 return Current.PERIOD_ALLOT11 == null; case 15: // PERIOD_ALLOT12 return Current.PERIOD_ALLOT12 == null; case 16: // PERIOD_LENGTH01 return Current.PERIOD_LENGTH01 == null; case 17: // PERIOD_LENGTH02 return Current.PERIOD_LENGTH02 == null; case 18: // PERIOD_LENGTH03 return Current.PERIOD_LENGTH03 == null; case 19: // PERIOD_LENGTH04 return Current.PERIOD_LENGTH04 == null; case 20: // PERIOD_LENGTH05 return Current.PERIOD_LENGTH05 == null; case 21: // PERIOD_LENGTH06 return Current.PERIOD_LENGTH06 == null; case 22: // PERIOD_LENGTH07 return Current.PERIOD_LENGTH07 == null; case 23: // PERIOD_LENGTH08 return Current.PERIOD_LENGTH08 == null; case 24: // PERIOD_LENGTH09 return Current.PERIOD_LENGTH09 == null; case 25: // PERIOD_LENGTH10 return Current.PERIOD_LENGTH10 == null; case 26: // PERIOD_LENGTH11 return Current.PERIOD_LENGTH11 == null; case 27: // PERIOD_LENGTH12 return Current.PERIOD_LENGTH12 == null; case 28: // PERIOD_UNITS return Current.PERIOD_UNITS == null; case 29: // ANNUAL_ENTITLEMENT return Current.ANNUAL_ENTITLEMENT == null; case 30: // ROLL_OVER return Current.ROLL_OVER == null; case 31: // ROLL_PERCENT return Current.ROLL_PERCENT == null; case 32: // LEAVE_LOADING return Current.LEAVE_LOADING == null; case 33: // LOADING_PERCENT return Current.LOADING_PERCENT == null; case 34: // ACTIVE return Current.ACTIVE == null; case 35: // LW_DATE return Current.LW_DATE == null; case 36: // LW_TIME return Current.LW_TIME == null; case 37: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // PLTKEY return "PLTKEY"; case 1: // LEAVE_GROUP return "LEAVE_GROUP"; case 2: // LEAVE_CODE return "LEAVE_CODE"; case 3: // CALC_METHOD return "CALC_METHOD"; case 4: // PERIOD_ALLOT01 return "PERIOD_ALLOT01"; case 5: // PERIOD_ALLOT02 return "PERIOD_ALLOT02"; case 6: // PERIOD_ALLOT03 return "PERIOD_ALLOT03"; case 7: // PERIOD_ALLOT04 return "PERIOD_ALLOT04"; case 8: // PERIOD_ALLOT05 return "PERIOD_ALLOT05"; case 9: // PERIOD_ALLOT06 return "PERIOD_ALLOT06"; case 10: // PERIOD_ALLOT07 return "PERIOD_ALLOT07"; case 11: // PERIOD_ALLOT08 return "PERIOD_ALLOT08"; case 12: // PERIOD_ALLOT09 return "PERIOD_ALLOT09"; case 13: // PERIOD_ALLOT10 return "PERIOD_ALLOT10"; case 14: // PERIOD_ALLOT11 return "PERIOD_ALLOT11"; case 15: // PERIOD_ALLOT12 return "PERIOD_ALLOT12"; case 16: // PERIOD_LENGTH01 return "PERIOD_LENGTH01"; case 17: // PERIOD_LENGTH02 return "PERIOD_LENGTH02"; case 18: // PERIOD_LENGTH03 return "PERIOD_LENGTH03"; case 19: // PERIOD_LENGTH04 return "PERIOD_LENGTH04"; case 20: // PERIOD_LENGTH05 return "PERIOD_LENGTH05"; case 21: // PERIOD_LENGTH06 return "PERIOD_LENGTH06"; case 22: // PERIOD_LENGTH07 return "PERIOD_LENGTH07"; case 23: // PERIOD_LENGTH08 return "PERIOD_LENGTH08"; case 24: // PERIOD_LENGTH09 return "PERIOD_LENGTH09"; case 25: // PERIOD_LENGTH10 return "PERIOD_LENGTH10"; case 26: // PERIOD_LENGTH11 return "PERIOD_LENGTH11"; case 27: // PERIOD_LENGTH12 return "PERIOD_LENGTH12"; case 28: // PERIOD_UNITS return "PERIOD_UNITS"; case 29: // ANNUAL_ENTITLEMENT return "ANNUAL_ENTITLEMENT"; case 30: // ROLL_OVER return "ROLL_OVER"; case 31: // ROLL_PERCENT return "ROLL_PERCENT"; case 32: // LEAVE_LOADING return "LEAVE_LOADING"; case 33: // LOADING_PERCENT return "LOADING_PERCENT"; case 34: // ACTIVE return "ACTIVE"; case 35: // LW_DATE return "LW_DATE"; case 36: // LW_TIME return "LW_TIME"; case 37: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "PLTKEY": return 0; case "LEAVE_GROUP": return 1; case "LEAVE_CODE": return 2; case "CALC_METHOD": return 3; case "PERIOD_ALLOT01": return 4; case "PERIOD_ALLOT02": return 5; case "PERIOD_ALLOT03": return 6; case "PERIOD_ALLOT04": return 7; case "PERIOD_ALLOT05": return 8; case "PERIOD_ALLOT06": return 9; case "PERIOD_ALLOT07": return 10; case "PERIOD_ALLOT08": return 11; case "PERIOD_ALLOT09": return 12; case "PERIOD_ALLOT10": return 13; case "PERIOD_ALLOT11": return 14; case "PERIOD_ALLOT12": return 15; case "PERIOD_LENGTH01": return 16; case "PERIOD_LENGTH02": return 17; case "PERIOD_LENGTH03": return 18; case "PERIOD_LENGTH04": return 19; case "PERIOD_LENGTH05": return 20; case "PERIOD_LENGTH06": return 21; case "PERIOD_LENGTH07": return 22; case "PERIOD_LENGTH08": return 23; case "PERIOD_LENGTH09": return 24; case "PERIOD_LENGTH10": return 25; case "PERIOD_LENGTH11": return 26; case "PERIOD_LENGTH12": return 27; case "PERIOD_UNITS": return 28; case "ANNUAL_ENTITLEMENT": return 29; case "ROLL_OVER": return 30; case "ROLL_PERCENT": return 31; case "LEAVE_LOADING": return 32; case "LOADING_PERCENT": return 33; case "ACTIVE": return 34; case "LW_DATE": return 35; case "LW_TIME": return 36; case "LW_USER": return 37; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
garysharp/EduHub.Data
src/EduHub.Data/Entities/PLTDataSet.cs
C#
mit
43,736
package iso20022 // Details of the standing settlement instruction to be applied. type StandingSettlementInstruction9 struct { // Specifies what settlement standing instruction database is to be used to derive the settlement parties involved in the transaction. SettlementStandingInstructionDatabase *SettlementStandingInstructionDatabase3Choice `xml:"SttlmStgInstrDB"` // Vendor of the Settlement Standing Instruction database requested to be consulted. Vendor *PartyIdentification32Choice `xml:"Vndr,omitempty"` // Delivering parties, other than the seller, needed for deriving the standing settlement instruction (for example, depository) or provided for information purposes (for example, instructing party settlement chain). OtherDeliveringSettlementParties *SettlementParties23 `xml:"OthrDlvrgSttlmPties,omitempty"` // Receiving parties, other than the buyer, needed for deriving the standing settlement instruction (for example, depository) or provided for information purposes (for example, instructing party settlement chain). OtherReceivingSettlementParties *SettlementParties23 `xml:"OthrRcvgSttlmPties,omitempty"` } func (s *StandingSettlementInstruction9) AddSettlementStandingInstructionDatabase() *SettlementStandingInstructionDatabase3Choice { s.SettlementStandingInstructionDatabase = new(SettlementStandingInstructionDatabase3Choice) return s.SettlementStandingInstructionDatabase } func (s *StandingSettlementInstruction9) AddVendor() *PartyIdentification32Choice { s.Vendor = new(PartyIdentification32Choice) return s.Vendor } func (s *StandingSettlementInstruction9) AddOtherDeliveringSettlementParties() *SettlementParties23 { s.OtherDeliveringSettlementParties = new(SettlementParties23) return s.OtherDeliveringSettlementParties } func (s *StandingSettlementInstruction9) AddOtherReceivingSettlementParties() *SettlementParties23 { s.OtherReceivingSettlementParties = new(SettlementParties23) return s.OtherReceivingSettlementParties }
fgrid/iso20022
StandingSettlementInstruction9.go
GO
mit
1,985
'use strict'; var _get = require('babel-runtime/helpers/get')['default']; var _inherits = require('babel-runtime/helpers/inherits')['default']; var _createClass = require('babel-runtime/helpers/create-class')['default']; var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default']; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; Object.defineProperty(exports, '__esModule', { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _EnhancedSwitch = require('./EnhancedSwitch'); var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch); var Radio = (function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); _get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments); } _createClass(Radio, [{ key: 'getValue', value: function getValue() { return this.refs.enhancedSwitch.getValue(); } }, { key: 'setChecked', value: function setChecked(newCheckedValue) { this.refs.enhancedSwitch.setSwitched(newCheckedValue); } }, { key: 'isChecked', value: function isChecked() { return this.refs.enhancedSwitch.isSwitched(); } }, { key: 'render', value: function render() { var enhancedSwitchProps = { ref: 'enhancedSwitch', inputType: 'radio' }; // labelClassName return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps)); } }]); return Radio; })(_react2['default'].Component); exports['default'] = Radio; module.exports = exports['default'];
andres81/auth-service
frontend/node_modules/react-icheck/lib/Radio.js
JavaScript
mit
1,815
""" Util classes ------------ Classes which represent data types useful for the package pySpatialTools. """ ## Spatial elements collectors from spatialelements import SpatialElementsCollection, Locations ## Membership relations from Membership import Membership
tgquintela/pySpatialTools
pySpatialTools/utils/util_classes/__init__.py
Python
mit
266
!(function(root) { function Grapnel(opts) { "use strict"; var self = this; // Scope reference this.events = {}; // Event Listeners this.state = null; // Router state object this.options = opts || {}; // Options this.options.env = this.options.env || (!!(Object.keys(root).length === 0 && process && process.browser !== true) ? 'server' : 'client'); this.options.mode = this.options.mode || (!!(this.options.env !== 'server' && this.options.pushState && root.history && root.history.pushState) ? 'pushState' : 'hashchange'); this.version = '0.6.4'; // Version if ('function' === typeof root.addEventListener) { root.addEventListener('hashchange', function() { self.trigger('hashchange'); }); root.addEventListener('popstate', function(e) { // Make sure popstate doesn't run on init -- this is a common issue with Safari and old versions of Chrome if (self.state && self.state.previousState === null) return false; self.trigger('navigate'); }); } return this; }; /** * Create a RegExp Route from a string * This is the heart of the router and I've made it as small as possible! * * @param {String} Path of route * @param {Array} Array of keys to fill * @param {Bool} Case sensitive comparison * @param {Bool} Strict mode */ Grapnel.regexRoute = function(path, keys, sensitive, strict) { if (path instanceof RegExp) return path; if (path instanceof Array) path = '(' + path.join('|') + ')'; // Build route RegExp path = path.concat(strict ? '' : '/?') .replace(/\/\(/g, '(?:/') .replace(/\+/g, '__plus__') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) { keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || ''); }) .replace(/([\/.])/g, '\\$1') .replace(/__plus__/g, '(.+)') .replace(/\*/g, '(.*)'); return new RegExp('^' + path + '$', sensitive ? '' : 'i'); }; /** * ForEach workaround utility * * @param {Array} to iterate * @param {Function} callback */ Grapnel._forEach = function(a, callback) { if (typeof Array.prototype.forEach === 'function') return Array.prototype.forEach.call(a, callback); // Replicate forEach() return function(c, next) { for (var i = 0, n = this.length; i < n; ++i) { c.call(next, this[i], i, this); } }.call(a, callback); }; /** * Add an route and handler * * @param {String|RegExp} route name * @return {self} Router */ Grapnel.prototype.get = Grapnel.prototype.add = function(route) { var self = this, middleware = Array.prototype.slice.call(arguments, 1, -1), handler = Array.prototype.slice.call(arguments, -1)[0], request = new Request(route); var invoke = function RouteHandler() { // Build request parameters var req = request.parse(self.path()); // Check if matches are found if (req.match) { // Match found var extra = { route: route, params: req.params, req: req, regex: req.match }; // Create call stack -- add middleware first, then handler var stack = new CallStack(self, extra).enqueue(middleware.concat(handler)); // Trigger main event self.trigger('match', stack, req); // Continue? if (!stack.runCallback) return self; // Previous state becomes current state stack.previousState = self.state; // Save new state self.state = stack; // Prevent this handler from being called if parent handler in stack has instructed not to propagate any more events if (stack.parent() && stack.parent().propagateEvent === false) { stack.propagateEvent = false; return self; } // Call handler stack.callback(); } // Returns self return self; }; // Event name var eventName = (self.options.mode !== 'pushState' && self.options.env !== 'server') ? 'hashchange' : 'navigate'; // Invoke when route is defined, and once again when app navigates return invoke().on(eventName, invoke); }; /** * Fire an event listener * * @param {String} event name * @param {Mixed} [attributes] Parameters that will be applied to event handler * @return {self} Router */ Grapnel.prototype.trigger = function(event) { var self = this, params = Array.prototype.slice.call(arguments, 1); // Call matching events if (this.events[event]) { Grapnel._forEach(this.events[event], function(fn) { fn.apply(self, params); }); } return this; }; /** * Add an event listener * * @param {String} event name (multiple events can be called when separated by a space " ") * @param {Function} callback * @return {self} Router */ Grapnel.prototype.on = Grapnel.prototype.bind = function(event, handler) { var self = this, events = event.split(' '); Grapnel._forEach(events, function(event) { if (self.events[event]) { self.events[event].push(handler); } else { self.events[event] = [handler]; } }); return this; }; /** * Allow event to be called only once * * @param {String} event name(s) * @param {Function} callback * @return {self} Router */ Grapnel.prototype.once = function(event, handler) { var ran = false; return this.on(event, function() { if (ran) return false; ran = true; handler.apply(this, arguments); handler = null; return true; }); }; /** * @param {String} Route context (without trailing slash) * @param {[Function]} Middleware (optional) * @return {Function} Adds route to context */ Grapnel.prototype.context = function(context) { var self = this, middleware = Array.prototype.slice.call(arguments, 1); return function() { var value = arguments[0], submiddleware = (arguments.length > 2) ? Array.prototype.slice.call(arguments, 1, -1) : [], handler = Array.prototype.slice.call(arguments, -1)[0], prefix = (context.slice(-1) !== '/' && value !== '/' && value !== '') ? context + '/' : context, path = (value.substr(0, 1) !== '/') ? value : value.substr(1), pattern = prefix + path; return self.add.apply(self, [pattern].concat(middleware).concat(submiddleware).concat([handler])); } }; /** * Navigate through history API * * @param {String} Pathname * @return {self} Router */ Grapnel.prototype.navigate = function(path) { return this.path(path).trigger('navigate'); }; Grapnel.prototype.path = function(pathname) { var self = this, frag; if ('string' === typeof pathname) { // Set path if (self.options.mode === 'pushState') { frag = (self.options.root) ? (self.options.root + pathname) : pathname; root.history.pushState({}, null, frag); } else if (root.location) { root.location.hash = (self.options.hashBang ? '!' : '') + pathname; } else { root._pathname = pathname || ''; } return this; } else if ('undefined' === typeof pathname) { // Get path if (self.options.mode === 'pushState') { frag = root.location.pathname.replace(self.options.root, ''); } else if (self.options.mode !== 'pushState' && root.location) { frag = (root.location.hash) ? root.location.hash.split((self.options.hashBang ? '#!' : '#'))[1] : ''; } else { frag = root._pathname || ''; } return frag; } else if (pathname === false) { // Clear path if (self.options.mode === 'pushState') { root.history.pushState({}, null, self.options.root || '/'); } else if (root.location) { root.location.hash = (self.options.hashBang) ? '!' : ''; } return self; } }; /** * Create routes based on an object * * @param {Object} [Options, Routes] * @param {Object Routes} * @return {self} Router */ Grapnel.listen = function() { var opts, routes; if (arguments[0] && arguments[1]) { opts = arguments[0]; routes = arguments[1]; } else { routes = arguments[0]; } // Return a new Grapnel instance return (function() { // TODO: Accept multi-level routes for (var key in routes) { this.add.call(this, key, routes[key]); } return this; }).call(new Grapnel(opts || {})); }; /** * Create a call stack that can be enqueued by handlers and middleware * * @param {Object} Router * @param {Object} Extend * @return {self} CallStack */ function CallStack(router, extendObj) { this.stack = CallStack.global.slice(0); this.router = router; this.runCallback = true; this.callbackRan = false; this.propagateEvent = true; this.value = router.path(); for (var key in extendObj) { this[key] = extendObj[key]; } return this; }; /** * Build request parameters and allow them to be checked against a string (usually the current path) * * @param {String} Route * @return {self} Request */ function Request(route) { this.route = route; this.keys = []; this.regex = Grapnel.regexRoute(route, this.keys); }; // This allows global middleware CallStack.global = []; /** * Prevent a callback from being called * * @return {self} CallStack */ CallStack.prototype.preventDefault = function() { this.runCallback = false; }; /** * Prevent any future callbacks from being called * * @return {self} CallStack */ CallStack.prototype.stopPropagation = function() { this.propagateEvent = false; }; /** * Get parent state * * @return {Object} Previous state */ CallStack.prototype.parent = function() { var hasParentEvents = !!(this.previousState && this.previousState.value && this.previousState.value == this.value); return (hasParentEvents) ? this.previousState : false; }; /** * Run a callback (calls to next) * * @return {self} CallStack */ CallStack.prototype.callback = function() { this.callbackRan = true; this.timeStamp = Date.now(); this.next(); }; /** * Add handler or middleware to the stack * * @param {Function|Array} Handler or a array of handlers * @param {Int} Index to start inserting * @return {self} CallStack */ CallStack.prototype.enqueue = function(handler, atIndex) { var handlers = (!Array.isArray(handler)) ? [handler] : ((atIndex < handler.length) ? handler.reverse() : handler); while (handlers.length) { this.stack.splice(atIndex || this.stack.length + 1, 0, handlers.shift()); } return this; }; /** * Call to next item in stack -- this adds the `req`, `event`, and `next()` arguments to all middleware * * @return {self} CallStack */ CallStack.prototype.next = function() { var self = this; return this.stack.shift().call(this.router, this.req, this, function next() { self.next.call(self); }); }; /** * Match a path string -- returns a request object if there is a match -- returns false otherwise * * @return {Object} req */ Request.prototype.parse = function(path) { var match = path.match(this.regex), self = this; var req = { params: {}, keys: this.keys, matches: (match || []).slice(1), match: match }; // Build parameters Grapnel._forEach(req.matches, function(value, i) { var key = (self.keys[i] && self.keys[i].name) ? self.keys[i].name : i; // Parameter key will be its key or the iteration index. This is useful if a wildcard (*) is matched req.params[key] = (value) ? decodeURIComponent(value) : undefined; }); return req; }; // Append utility constructors to Grapnel Grapnel.CallStack = CallStack; Grapnel.Request = Request; if ('function' === typeof root.define && !root.define.amd.grapnel) { root.define(function(require, exports, module) { root.define.amd.grapnel = true; return Grapnel; }); } else if ('object' === typeof module && 'object' === typeof module.exports) { module.exports = exports = Grapnel; } else { root.Grapnel = Grapnel; } }).call({}, ('object' === typeof window) ? window : this); /* var router = new Grapnel({ pushState : true, hashBang : true }); router.get('/products/:category/:id?', function(req){ var id = req.params.id, category = req.params.category console.log(category, id); }); router.get('/tiempo', function(req){ console.log("tiempo!"); $("#matikbirdpath").load("views/rooms.html", function(res){ console.log(res); console.log("hola"); }); }); router.get('/', function(req){ console.log(req.user); console.log("hola!"); $("#matikbirdpath").load("views/rooms.html", function(res){ console.log(res); console.log("hola"); }); }); router.navigate('/'); */ NProgress.start(); var routes = { '/' : function(req, e){ $("#matikbirdpath").load("views/main.html", function(res){ console.log(res); NProgress.done(); }); }, '/dashboard' : function(req, e){ $("#matikbirdpath").load("views/dashboard.html", function(res){ console.log(res); NProgress.done(); }); }, '/calendario' : function(req, e){ $("#matikbirdpath").load("views/calendario.html", function(res){ console.log(res); console.log("hola"); }); }, '/now' : function(req, e){ $("#matikbirdpath").load("views/clase_ahora.html", function(res){ console.log(res); console.log("hola"); }); }, '/category/:id' : function(req, e){ // Handle route }, '/*' : function(req, e){ if(!e.parent()){ $("#matikbirdpath").load("views/main.html", function(res){ console.log(res); NProgress.done(); }); } } } var router = Grapnel.listen({ pushState : true, hashBang: true }, routes);
matikbird/matikbird.github.io
portfolio/copylee/assets/mtk-route.js
JavaScript
mit
16,205
package com.isme.zteui.cache; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.android.volley.toolbox.ImageLoader.ImageCache; /** * Title: Volley 的缓存类</br><br> * Description: </br><br> * Copyright: Copyright(c)2003</br><br> * Company: ihalma </br><br> * @author and</br><br> * @version 1 </br><br> * data: 2015-3-17</br> */ public class BitmapLruCache implements ImageCache { private LruCache<String, Bitmap> mCache; /** * 最大缓存 10 M */ public BitmapLruCache() { int maxSize = 1024 * 1024 * 10; //最大缓存10M mCache = new LruCache<String, Bitmap>(maxSize){ @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } }; } @Override public Bitmap getBitmap(String url) { return mCache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { mCache.put(url, bitmap); } }
heyugtan/zteUI
ZTEUI/src/com/isme/zteui/cache/BitmapLruCache.java
Java
mit
944
# frozen_string_literal: true module Hackbot module Interactions module Concerns module Triggerable extend ActiveSupport::Concern SLACK_TEAM_ID = Rails.application.secrets.default_slack_team_id class_methods do # This constructs a fake Slack event to start the interaction with. # It'll be sent to the interaction's start method. def trigger(user_id, team = nil, channel_id = nil) team ||= Hackbot::Team.find_by(team_id: SLACK_TEAM_ID) event = FakeSlackEventService.new(team, user_id, channel_id).event interaction = create(event: event, team: team) interaction.handle interaction.save! interaction end end end end end end
hackclub/api
app/models/hackbot/interactions/concerns/triggerable.rb
Ruby
mit
794
module Fog module Compute class Google class Mock def insert_network(_network_name, _ip_range, _options = {}) Fog::Mock.not_implemented end end class Real def insert_network(network_name, ip_range, options = {}) api_method = @compute.networks.insert parameters = { "project" => @project } body_object = { "name" => network_name, "IPv4Range" => ip_range } body_object["description"] = options[:description] if options[:description] body_object["gatewayIPv4"] = options[:gateway_ipv4] if options[:gateway_ipv4] request(api_method, parameters, body_object) end end end end end
plribeiro3000/fog-google
lib/fog/compute/google/requests/insert_network.rb
Ruby
mit
771
package warhammerrpg.database.exception; import warhammerrpg.core.exception.WarhammerRpgException; public class DatabaseException extends WarhammerRpgException { public DatabaseException(Exception originalExceptionObject) { super(originalExceptionObject); } public DatabaseException() { super(); } }
tomaszkowalczyk94/warhammer-rpg-helper
src/main/java/warhammerrpg/database/exception/DatabaseException.java
Java
mit
335
package org.ethereum.android.service; import android.os.Message; public interface ConnectorHandler { boolean handleMessage(Message message); void onConnectorConnected(); void onConnectorDisconnected(); String getID(); }
BlockchainSociety/ethereumj-android
ethereumj-core-android/src/main/java/org/ethereum/android/service/ConnectorHandler.java
Java
mit
240
package gwent const ( // AbilityNone means unit card has no ability at all AbilityNone = iota ) // CardUnit is single unit used for combat type CardUnit struct { UnitType CardType UnitRange CardRange UnitFaction CardFaction UnitPower, UnitAbility int UnitHero bool BasicCard } // Play puts unit card to table func (c *CardUnit) Play(p *Player, target Card) { c.PutOnTable(p) } // PutOnTable puts unit card to table func (c *CardUnit) PutOnTable(p *Player) { //Add card to proper row switch c.Range() { case RangeClose: p.RowClose = append(p.RowClose, c) case RangeRanged: p.RowRanged = append(p.RowRanged, c) case RangeSiege: p.RowSiege = append(p.RowSiege, c) } } // Type reports type of this unit card func (c *CardUnit) Type() CardType { return c.UnitType } // Faction reports faction of this unit card func (c *CardUnit) Faction() CardFaction { return c.UnitFaction } // Range reports range of this unit card func (c *CardUnit) Range() CardRange { return c.UnitRange } // Power reports power of this unit card func (c *CardUnit) Power(p *Player) int { pwr := c.UnitPower //Apply weather if not a hero card if !c.Hero() && ((c.Range() == RangeClose && p.Game.WeatherClose) || (c.Range() == RangeRanged && p.Game.WeatherRanged) || (c.Range() == RangeSiege && p.Game.WeatherSiege)) { pwr = 1 } //Apply horn if available if (c.Range() == RangeClose && p.HornClose) || (c.Range() == RangeRanged && p.HornRanged) || (c.Range() == RangeSiege && p.HornSiege) { pwr *= 2 } return pwr } // Hero reports if this unit card is hero card func (c *CardUnit) Hero() bool { return c.UnitHero } // Targettable reports if this card can be targetted or not func (c *CardUnit) Targettable() bool { //TODO: Treat by unit ability return false }
bobesa/gwent
gwent/card.unit.go
GO
mit
1,807
class Foo { [prop1]: string; }
motiz88/astring-flow
test/data/roundtrip/flow-parser-tests/test-046.js
JavaScript
mit
30
package medtronic import ( "bytes" "fmt" "log" "github.com/ecc1/medtronic/packet" ) // Command represents a pump command. type Command byte //go:generate stringer -type Command const ( ack Command = 0x06 nak Command = 0x15 cgmWriteTimestamp Command = 0x28 setBasalPatternA Command = 0x30 setBasalPatternB Command = 0x31 setClock Command = 0x40 setMaxBolus Command = 0x41 bolus Command = 0x42 selectBasalPattern Command = 0x4A setAbsoluteTempBasal Command = 0x4C suspend Command = 0x4D button Command = 0x5B wakeup Command = 0x5D setPercentTempBasal Command = 0x69 setMaxBasal Command = 0x6E setBasalRates Command = 0x6F clock Command = 0x70 pumpID Command = 0x71 battery Command = 0x72 reservoir Command = 0x73 firmwareVersion Command = 0x74 errorStatus Command = 0x75 historyPage Command = 0x80 carbUnits Command = 0x88 glucoseUnits Command = 0x89 carbRatios Command = 0x8A insulinSensitivities Command = 0x8B glucoseTargets512 Command = 0x8C model Command = 0x8D settings512 Command = 0x91 basalRates Command = 0x92 basalPatternA Command = 0x93 basalPatternB Command = 0x94 tempBasal Command = 0x98 glucosePage Command = 0x9A isigPage Command = 0x9B calibrationFactor Command = 0x9C lastHistoryPage Command = 0x9D glucoseTargets Command = 0x9F settings Command = 0xC0 cgmPageCount Command = 0xCD status Command = 0xCE vcntrPage Command = 0xD5 ) // NoResponseError indicates that no response to a command was received. type NoResponseError Command func (e NoResponseError) Error() string { return fmt.Sprintf("no response to %v", Command(e)) } // NoResponse checks whether the pump has a NoResponseError. func (pump *Pump) NoResponse() bool { _, ok := pump.Error().(NoResponseError) return ok } // InvalidCommandError indicates that the pump rejected a command as invalid. type InvalidCommandError struct { Command Command PumpError PumpError } // PumpError represents an error response from the pump. type PumpError byte //go:generate stringer -type PumpError // Pump error codes. const ( CommandRefused PumpError = 0x08 SettingOutOfRange PumpError = 0x09 BolusInProgress PumpError = 0x0C InvalidHistoryPageNumber PumpError = 0x0D ) func (e InvalidCommandError) Error() string { return fmt.Sprintf("%v error: %v", e.Command, e.PumpError) } // BadResponseError indicates an unexpected response to a command. type BadResponseError struct { Command Command Data []byte } func (e BadResponseError) Error() string { return fmt.Sprintf("unexpected response to %v: % X", e.Command, e.Data) } // BadResponse sets the pump's error state to a BadResponseError. func (pump *Pump) BadResponse(cmd Command, data []byte) { pump.SetError(BadResponseError{Command: cmd, Data: data}) } const ( shortPacketLength = 6 // excluding CRC byte longPacketLength = 70 // excluding CRC byte encodedLongPacketLength = 107 payloadLength = 64 fragmentLength = payloadLength + 1 // including sequence number doneBit = 1 << 7 maxNAKs = 10 ) var ( shortPacket = make([]byte, shortPacketLength) longPacket = make([]byte, longPacketLength) ackPacket []byte ) func precomputePackets() { addr := PumpAddress() shortPacket[0] = packet.Pump copy(shortPacket[1:4], addr) longPacket[0] = packet.Pump copy(longPacket[1:4], addr) ackPacket = shortPumpPacket(ack) } // shortPumpPacket constructs a 7-byte packet with the specified command code: // device type (0xA7) // 3 bytes of pump ID // command code // length of parameters (0) // CRC-8 (added by packet.Encode) func shortPumpPacket(cmd Command) []byte { p := shortPacket p[4] = byte(cmd) p[5] = 0 return packet.Encode(p) } // longPumpPacket constructs a 71-byte packet with // the specified command code and parameters: // device type (0xA7) // 3 bytes of pump ID // command code // length of parameters (or fragment number if non-zero) // 64 bytes of parameters plus zero padding // CRC-8 (added by packet.Encode) func longPumpPacket(cmd Command, fragNum int, params []byte) []byte { p := longPacket p[4] = byte(cmd) if fragNum == 0 { p[5] = byte(len(params)) } else { // Use a fragment number instead of the length. p[5] = uint8(fragNum) } copy(p[6:], params) // Zero-pad the remainder of the packet. for i := 6 + len(params); i < longPacketLength; i++ { p[i] = 0 } return packet.Encode(p) } // Execute sends a command and parameters to the pump and returns its response. // Commands with parameters require an initial exchange with no parameters, // followed by an exchange with the actual arguments. func (pump *Pump) Execute(cmd Command, params ...byte) []byte { if len(params) == 0 { return pump.perform(cmd, cmd, shortPumpPacket(cmd)) } pump.perform(cmd, ack, shortPumpPacket(cmd)) if pump.NoResponse() { pump.SetError(fmt.Errorf("%v command not performed", cmd)) return nil } t := pump.Timeout() defer pump.SetTimeout(t) pump.SetTimeout(2 * t) return pump.perform(cmd, ack, longPumpPacket(cmd, 0, params)) } // ExtendedRequest sends a command and a sequence of parameter packets // to the pump and returns its response. func (pump *Pump) ExtendedRequest(cmd Command, params ...byte) []byte { seqNum := 1 i := 0 var result []byte done := false for !done && pump.Error() == nil { j := i + payloadLength if j >= len(params) { done = true j = len(params) } if seqNum == 1 { pump.perform(cmd, ack, shortPumpPacket(cmd)) if pump.NoResponse() { pump.SetError(fmt.Errorf("%v command not performed", cmd)) break } } p := longPumpPacket(cmd, seqNum, params[i:j]) data := pump.perform(cmd, ack, p) result = append(result, data...) seqNum++ i = j } if done { t := pump.Timeout() defer pump.SetTimeout(t) pump.SetTimeout(2 * t) p := longPumpPacket(cmd, seqNum|doneBit, nil) data := pump.perform(cmd, ack, p) result = append(result, data...) } return result } // ExtendedResponse sends a command and parameters to the pump and // collects the sequence of packets that make up its response. func (pump *Pump) ExtendedResponse(cmd Command, params ...byte) []byte { var result []byte data := pump.Execute(cmd, params...) expected := 1 retries := pump.Retries() defer pump.SetRetries(retries) pump.SetRetries(1) for pump.Error() == nil { if len(data) != fragmentLength { pump.SetError(fmt.Errorf("%v: received %d-byte response", cmd, len(data))) break } seqNum := int(data[0] &^ doneBit) if seqNum != expected { pump.SetError(fmt.Errorf("%v: received response %d instead of %d", cmd, seqNum, expected)) break } result = append(result, data[1:]...) if data[0]&doneBit != 0 { break } // Acknowledge this fragment. data = pump.perform(ack, cmd, ackPacket) expected++ } return result } // History pages are returned as a series of 65-byte fragments: // sequence number (1 to numFragments) // 64 bytes of payload // The caller must send an ACK to receive the next fragment // or a NAK to have the current one retransmitted. // The 0x80 bit is set in the sequence number of the final fragment. // The page consists of the concatenated payloads. // The final 2 bytes are the CRC-16 of the preceding data. type pageStructure struct { paramBytes int // 1 or 4 numFragments int // 16 or 32 fragments of 64 bytes each } var pageData = map[Command]pageStructure{ historyPage: { paramBytes: 1, numFragments: 16, }, glucosePage: { paramBytes: 4, numFragments: 16, }, isigPage: { paramBytes: 4, numFragments: 32, }, vcntrPage: { paramBytes: 1, numFragments: 16, }, } // Download requests the given history page from the pump. func (pump *Pump) Download(cmd Command, page int) []byte { maxTries := pump.Retries() defer pump.SetRetries(maxTries) pump.SetRetries(1) for tries := 0; tries < maxTries; tries++ { pump.SetError(nil) data := pump.tryDownload(cmd, page) if pump.Error() == nil { logTries(cmd, tries) return data } } return nil } func (pump *Pump) tryDownload(cmd Command, page int) []byte { data := pump.execPage(cmd, page) if pump.Error() != nil { return nil } numFragments := pageData[cmd].numFragments results := make([]byte, 0, numFragments*payloadLength) seq := 1 for { payload, n := pump.checkFragment(page, data, seq, numFragments) if pump.Error() != nil { return nil } if n == seq { results = append(results, payload...) seq++ } if n == numFragments { return pump.checkPageCRC(page, results) } // Acknowledge the current fragment and receive the next. next := pump.perform(ack, cmd, ackPacket) if pump.Error() != nil { if !pump.NoResponse() { return nil } next = pump.handleNoResponse(cmd, page, seq) } data = next } } func (pump *Pump) execPage(cmd Command, page int) []byte { n := pageData[cmd].paramBytes switch n { case 1: return pump.Execute(cmd, byte(page)) case 4: return pump.Execute(cmd, marshalUint32(uint32(page))...) default: log.Panicf("%v: unexpected parameter size (%d bytes)", cmd, n) } panic("unreachable") } // checkFragment verifies that a fragment has the expected sequence number // and returns the payload and sequence number. func (pump *Pump) checkFragment(page int, data []byte, expected int, numFragments int) ([]byte, int) { if len(data) != fragmentLength { pump.SetError(fmt.Errorf("history page %d: unexpected fragment length (%d)", page, len(data))) return nil, 0 } seqNum := int(data[0] &^ doneBit) if seqNum > expected { // Missed fragment. pump.SetError(fmt.Errorf("history page %d: received fragment %d instead of %d", page, seqNum, expected)) return nil, 0 } if seqNum < expected { // Skip duplicate responses. return nil, seqNum } // This is the next fragment. done := data[0]&doneBit != 0 if (done && seqNum != numFragments) || (!done && seqNum == numFragments) { pump.SetError(fmt.Errorf("history page %d: unexpected final sequence number (%d)", page, seqNum)) return nil, seqNum } return data[1:], seqNum } // handleNoResponse sends NAKs to request retransmission of the expected fragment. func (pump *Pump) handleNoResponse(cmd Command, page int, expected int) []byte { for count := 0; count < maxNAKs; count++ { pump.SetError(nil) data := pump.perform(nak, cmd, shortPumpPacket(nak)) if pump.Error() == nil { seqNum := int(data[0] &^ doneBit) format := "history page %d: received fragment %d after %d NAK" if count != 0 { format += "s" } log.Printf(format, page, seqNum, count+1) return data } if !pump.NoResponse() { return nil } } pump.SetError(fmt.Errorf("history page %d: lost fragment %d", page, expected)) return nil } // checkPageCRC verifies the history page CRC and returns the page data with the CRC removed. // In a 2048-byte ISIG page, the CRC-16 is stored in the last 4 bytes: [high 0 low 0] func (pump *Pump) checkPageCRC(page int, data []byte) []byte { if len(data) != cap(data) { pump.SetError(fmt.Errorf("history page %d: unexpected size (%d)", page, len(data))) return nil } var dataCRC uint16 switch cap(data) { case 1024: dataCRC = twoByteUint(data[1022:]) data = data[:1022] case 2048: dataCRC = uint16(data[2044])<<8 | uint16(data[2046]) data = data[:2044] default: log.Panicf("unexpected history page size (%d)", cap(data)) } calcCRC := packet.CRC16(data) if calcCRC != dataCRC { pump.SetError(fmt.Errorf("history page %d: computed CRC %04X but received %04X", page, calcCRC, dataCRC)) return nil } return data } func (pump *Pump) perform(cmd Command, resp Command, p []byte) []byte { if pump.Error() != nil { return nil } maxTries := pump.retries if len(p) == encodedLongPacketLength { // Don't attempt state-changing commands more than once. maxTries = 1 } for tries := 0; tries < maxTries; tries++ { pump.SetError(nil) response, rssi := pump.Radio.SendAndReceive(p, pump.Timeout()) if pump.Error() != nil { continue } if len(response) == 0 { pump.SetError(NoResponseError(cmd)) continue } data, err := packet.Decode(response) if err != nil { pump.SetError(err) continue } if pump.unexpected(cmd, resp, data) { return nil } logTries(cmd, tries) pump.rssi = rssi return data[5:] } if pump.Error() == nil { panic("perform") } return nil } func logTries(cmd Command, tries int) { if tries == 0 { return } r := "retries" if tries == 1 { r = "retry" } log.Printf("%v command required %d %s", cmd, tries, r) } func (pump *Pump) unexpected(cmd Command, resp Command, data []byte) bool { if len(data) < 6 { pump.BadResponse(cmd, data) return true } if !bytes.Equal(data[:4], shortPacket[:4]) { pump.BadResponse(cmd, data) return true } switch Command(data[4]) { case cmd: return false case resp: return false case ack: if cmd == cgmWriteTimestamp || cmd == wakeup { return false } pump.BadResponse(cmd, data) return true case nak: pump.SetError(InvalidCommandError{ Command: cmd, PumpError: PumpError(data[5]), }) return true default: pump.BadResponse(cmd, data) return true } }
ecc1/medtronic
command.go
GO
mit
13,574
(function () { "use strict"; angular.module('projectManagerSPA').controller('userLoginController', ['authenticationService', '$scope', '$state',function (authenticationService, $scope, $state) { $scope.logIn = function () { authenticationService.logIn($scope.username, $scope.password, function () { $state.go('organizationList'); }); }; $scope.logOut = function () { $state.go('userLogout'); }; }]); })();
ivanthescientist/ProjectManager
src/main/resources/public/js/controller/user.login.controller.js
JavaScript
mit
503
require 'spec_helper' describe ChequeFormatter do describe ".date_to_ddmmyy" do subject { ChequeFormatter.date_to_ddmmyy(date) } context "5-Nov-2011" do let(:date) { "5-Nov-2011" } it { should == '051111' } end context "2011-11-05" do let(:date) { "5-Nov-2011" } it { should == '051111' } end end describe ".amount_to_text" do # Source: http://www.moneysense.gov.sg/resource/publications/quick_tips/Graphicised%20cheque%20-%20FINAL.pdf subject { ChequeFormatter.amount_to_text(number) } context "handles negative numbers" do let(:number) { -1000 } it { should == 'One Thousand And Cents Zero Only' } end context "1000" do let(:number) { 1000 } it { should == 'One Thousand And Cents Zero Only' } end context "1001" do let(:number) { 1001 } it { should == 'One Thousand And One And Cents Zero Only' } end context "1010" do let(:number) { 1010 } it { should == 'One Thousand And Ten And Cents Zero Only' } end context "1100" do let(:number) { 1100 } it { should == 'One Thousand One Hundred And Cents Zero Only' } end context "1303.53" do let(:number) { 1303.53 } it { should == 'One Thousand Three Hundred And Three And Cents Fifty Three Only' } end end describe ".amount_to_number" do subject { ChequeFormatter.amount_to_number(number) } context "handles negative numbers" do let(:number) { -1000 } it { should == '1,000.00' } end context "1" do let(:number) { 1 } it { should == '1.00' } end context "10" do let(:number) { 10 } it { should == '10.00' } end context "100" do let(:number) { 100 } it { should == '100.00' } end context "1000" do let(:number) { 1000 } it { should == '1,000.00' } end context "1000000" do let(:number) { 1000000 } it { should == '1,000,000.00' } end context "1000000.50" do let(:number) { 1000000.50 } it { should == '1,000,000.50' } end end end
pivotalexperimental/cheques
spec/lib/cheque_formatter_spec.rb
Ruby
mit
2,124
/// <reference types="react-scripts" /> declare module "office-ui-fabric-react/lib/Modal" { const Modal: React.StatelessComponent<IModalProps>; }
azu/faao
src/react-app-env.d.ts
TypeScript
mit
150
#include "forms/transactioncontrol.h" #include "forms/graphicbutton.h" #include "forms/label.h" #include "forms/listbox.h" #include "forms/scrollbar.h" #include "forms/ui.h" #include "framework/data.h" #include "framework/framework.h" #include "framework/logger.h" #include "framework/renderer.h" #include "game/state/city/base.h" #include "game/state/city/building.h" #include "game/state/city/research.h" #include "game/state/city/vehicle.h" #include "game/state/city/vequipment.h" #include "game/state/gamestate.h" #include "game/state/rules/aequipmenttype.h" #include "game/state/rules/city/vammotype.h" #include "game/state/shared/organisation.h" #include "game/ui/general/messagebox.h" namespace OpenApoc { sp<Image> TransactionControl::bgLeft; sp<Image> TransactionControl::bgRight; sp<Image> TransactionControl::purchaseBoxIcon; sp<Image> TransactionControl::purchaseXComIcon; sp<Image> TransactionControl::purchaseArrow; sp<Image> TransactionControl::alienContainedDetain; sp<Image> TransactionControl::alienContainedKill; sp<Image> TransactionControl::scrollLeft; sp<Image> TransactionControl::scrollRight; sp<Image> TransactionControl::transactionShade; sp<BitmapFont> TransactionControl::labelFont; bool TransactionControl::resourcesInitialised = false; void TransactionControl::initResources() { bgLeft = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 45)); bgRight = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 46)); purchaseBoxIcon = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 47)); purchaseXComIcon = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 48)); purchaseArrow = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 52)); alienContainedDetain = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 75)); alienContainedKill = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 76)); scrollLeft = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 53)); scrollRight = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 54)); transactionShade = fw().data->loadImage("city/transaction-shade.png"); labelFont = ui().getFont("smalfont"); resourcesInitialised = true; } void TransactionControl::setScrollbarValues() { if (tradeState.getLeftIndex() == tradeState.getRightIndex()) { scrollBar->setMinimum(0); scrollBar->setMaximum(0); scrollBar->setValue(0); } else { scrollBar->setMinimum(0); scrollBar->setMaximum(tradeState.getLeftStock() + tradeState.getRightStock()); scrollBar->setValue(tradeState.getBalance()); } updateValues(); } void TransactionControl::setIndexLeft(int index) { tradeState.setLeftIndex(index); setScrollbarValues(); } void TransactionControl::setIndexRight(int index) { tradeState.setRightIndex(index); setScrollbarValues(); } void TransactionControl::updateValues() { if (scrollBar->getMaximum() != 0) { if (manufacturerHostile || manufacturerUnavailable) { int defaultRightStock = tradeState.getRightStock(); if ((tradeState.getLeftIndex() == ECONOMY_IDX && scrollBar->getValue() > defaultRightStock) || (tradeState.getRightIndex() == ECONOMY_IDX && scrollBar->getValue() < defaultRightStock)) { tradeState.cancelOrder(); scrollBar->setValue(tradeState.getBalance()); auto message_box = mksp<MessageBox>( manufacturerName, manufacturerHostile ? tr("Order canceled by the hostile manufacturer.") : tr("Manufacturer has no intact buildings in this city to " "deliver goods from."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } } // TODO: remove linked if (tradeState.getBalance() != scrollBar->getValue()) { tradeState.setBalance(scrollBar->getValue()); if (linked) { for (auto &c : *linked) { if (auto c_sp = c.lock()) { c_sp->suspendUpdates = true; c_sp->scrollBar->setValue(scrollBar->getValue()); c_sp->updateValues(); c_sp->suspendUpdates = false; } } } if (!suspendUpdates) { this->pushFormEvent(FormEventType::ScrollBarChange, nullptr); } } } int curDeltaRight = tradeState.getLROrder(); int curDeltaLeft = -curDeltaRight; stockLeft->setText(format("%d", tradeState.getLeftStock(true))); stockRight->setText(format("%d", tradeState.getRightStock(true))); deltaLeft->setText(format("%s%d", curDeltaLeft > 0 ? "+" : "", curDeltaLeft)); deltaRight->setText(format("%s%d", curDeltaRight > 0 ? "+" : "", curDeltaRight)); deltaLeft->setVisible(tradeState.getLeftIndex() != ECONOMY_IDX && curDeltaLeft != 0); deltaRight->setVisible(tradeState.getRightIndex() != ECONOMY_IDX && curDeltaRight != 0); setDirty(); } void TransactionControl::link(sp<TransactionControl> c1, sp<TransactionControl> c2) { if (c1->linked && c2->linked) { LogError("Cannot link two already linked transaction controls!"); return; } if (!c2->linked) { if (!c1->linked) { c1->linked = mksp<std::list<wp<TransactionControl>>>(); c1->linked->emplace_back(c1); } c1->linked->emplace_back(c2); c2->linked = c1->linked; } if (!c1->linked && c2->linked) { c2->linked->emplace_back(c1); c1->linked = c2->linked; } // we assume c1 is older than c2, so we update c2 to match c1 c2->scrollBar->setValue(c1->scrollBar->getValue()); c2->updateValues(); } const sp<std::list<wp<TransactionControl>>> &TransactionControl::getLinked() const { return linked; } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<Agent> agent, int indexLeft, int indexRight) { // The agent or agent's vehicle should be on a base auto currentBuilding = agent->currentVehicle ? agent->currentVehicle->currentBuilding : agent->currentBuilding; if (!currentBuilding || !currentBuilding->base) { return nullptr; } std::vector<int> initialStock; // Fill out stock { initialStock.resize(9); // Stock of agents always zero on all bases except where it belongs int baseIndex = 0; for (auto &b : state.player_bases) { if (b.first == agent->homeBuilding->base.id) { initialStock[baseIndex] = 1; break; } baseIndex++; } } Type type; switch (agent->type->role) { case AgentType::Role::BioChemist: type = Type::BioChemist; break; case AgentType::Role::Engineer: type = Type::Engineer; break; case AgentType::Role::Physicist: type = Type::Physicist; break; case AgentType::Role::Soldier: type = Type::Soldier; break; default: LogError("Unknown type of agent %s.", agent.id); } int price = 0; int storeSpace = 0; bool isAmmo = false; bool isBio = false; bool isPerson = true; bool researched = true; auto manufacturer = agent->owner; bool manufacturerHostile = false; bool manufacturerUnavailable = false; return createControl(agent.id, type, agent->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<AEquipmentType> agentEquipmentType, int indexLeft, int indexRight) { bool isBio = agentEquipmentType->bioStorage; int price = 0; int storeSpace = agentEquipmentType->store_space; bool researched = isBio ? true : state.research.isComplete(agentEquipmentType); std::vector<int> initialStock; bool hasStock = false; // Fill out stock { initialStock.resize(9); int baseIndex = 0; for (auto &b : state.player_bases) { int divisor = (agentEquipmentType->type == AEquipmentType::Type::Ammo && !isBio) ? agentEquipmentType->max_ammo : 1; initialStock[baseIndex] = isBio ? b.second->inventoryBioEquipment[agentEquipmentType.id] : b.second->inventoryAgentEquipment[agentEquipmentType.id]; initialStock[baseIndex] = (initialStock[baseIndex] + divisor - 1) / divisor; if (initialStock[baseIndex] > 0) { hasStock = true; } baseIndex++; } } // Fill out economy data if (!agentEquipmentType->bioStorage) { bool economyUnavailable = true; if (state.economy.find(agentEquipmentType.id) != state.economy.end()) { auto &economy = state.economy[agentEquipmentType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week || !researched; } if (!hasStock && economyUnavailable) { return nullptr; } } else if (!hasStock) { return nullptr; } auto manufacturer = agentEquipmentType->manufacturer; bool isAmmo = agentEquipmentType->type == AEquipmentType::Type::Ammo; bool isPerson = false; auto canBuy = isBio ? Organisation::PurchaseResult::OK : agentEquipmentType->manufacturer->canPurchaseFrom( state, state.current_base->building, false); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(agentEquipmentType.id, isBio ? Type::AgentEquipmentBio : Type::AgentEquipmentCargo, agentEquipmentType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<VEquipmentType> vehicleEquipmentType, int indexLeft, int indexRight) { int price = 0; int storeSpace = vehicleEquipmentType->store_space; bool researched = state.research.isComplete(vehicleEquipmentType); std::vector<int> initialStock; bool hasStock = false; // Fill out stock { initialStock.resize(9); int baseIndex = 0; for (auto &b : state.player_bases) { initialStock[baseIndex] = b.second->inventoryVehicleEquipment[vehicleEquipmentType.id]; if (initialStock[baseIndex] > 0) { hasStock = true; } baseIndex++; } } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicleEquipmentType.id) != state.economy.end()) { auto &economy = state.economy[vehicleEquipmentType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week || !researched; } if (!hasStock && economyUnavailable) { return nullptr; } } auto manufacturer = vehicleEquipmentType->manufacturer; bool isAmmo = false; bool isBio = false; bool isPerson = false; // Expecting all bases to be in one city auto canBuy = vehicleEquipmentType->manufacturer->canPurchaseFrom( state, state.current_base->building, false); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(vehicleEquipmentType.id, Type::VehicleEquipment, vehicleEquipmentType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<VAmmoType> vehicleAmmoType, int indexLeft, int indexRight) { int price = 0; int storeSpace = vehicleAmmoType->store_space; std::vector<int> initialStock; bool hasStock = false; // Fill out stock { initialStock.resize(9); int baseIndex = 0; for (auto &b : state.player_bases) { initialStock[baseIndex] = b.second->inventoryVehicleAmmo[vehicleAmmoType.id]; if (initialStock[baseIndex] > 0) { hasStock = true; } baseIndex++; } } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicleAmmoType.id) != state.economy.end()) { auto &economy = state.economy[vehicleAmmoType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week; } if (!hasStock && economyUnavailable) { return nullptr; } } auto manufacturer = vehicleAmmoType->manufacturer; bool isAmmo = true; bool isBio = false; bool isPerson = false; bool researched = true; // Expecting all bases to be in one city auto canBuy = vehicleAmmoType->manufacturer->canPurchaseFrom(state, state.current_base->building, false); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(vehicleAmmoType.id, Type::VehicleAmmo, vehicleAmmoType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<VehicleType> vehicleType, int indexLeft, int indexRight) { // No sense in transfer if (indexLeft != ECONOMY_IDX && indexRight != ECONOMY_IDX) { return nullptr; } int price = 0; int storeSpace = 0; std::vector<int> initialStock; // Fill out stock { initialStock.resize(9); // Stock of vehicle types always zero } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicleType.id) != state.economy.end()) { auto &economy = state.economy[vehicleType.id]; int week = state.gameTime.getWeek(); initialStock[ECONOMY_IDX] = economy.currentStock; price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week; } if (economyUnavailable) { return nullptr; } } auto manufacturer = vehicleType->manufacturer; bool isAmmo = false; bool isBio = false; bool isPerson = false; bool researched = true; // Expecting all bases to be in one city auto canBuy = vehicleType->manufacturer->canPurchaseFrom(state, state.current_base->building, true); bool manufacturerHostile = canBuy == Organisation::PurchaseResult::OrgHostile; bool manufacturerUnavailable = manufacturer != state.getPlayer() && canBuy == Organisation::PurchaseResult::OrgHasNoBuildings; return createControl(vehicleType.id, Type::VehicleType, vehicleType->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(GameState &state, StateRef<Vehicle> vehicle, int indexLeft, int indexRight) { // Only parked on base vehicles can be sold if (!vehicle->currentBuilding || !vehicle->currentBuilding->base) { return nullptr; } int price = 0; int storeSpace = 0; std::vector<int> initialStock; // Fill out stock { initialStock.resize(9); // Stock of vehicle types always zero on all bases except where it belongs int baseIndex = 0; for (auto &b : state.player_bases) { if (b.first == vehicle->homeBuilding->base.id) { initialStock[baseIndex] = 1; break; } baseIndex++; } } // Fill out economy data { bool economyUnavailable = true; if (state.economy.find(vehicle->type.id) != state.economy.end()) { auto &economy = state.economy[vehicle->type.id]; int week = state.gameTime.getWeek(); price = economy.currentPrice; economyUnavailable = economy.weekAvailable == 0 || economy.weekAvailable > week; } if (economyUnavailable) { // Nothing, we can still sell it for parts or transfer! } } LogWarning("Vehicle type %s starting price %d", vehicle->type.id, price); // Add price of ammo and equipment for (auto &e : vehicle->equipment) { if (state.economy.find(e->type.id) != state.economy.end()) { price += state.economy[e->type.id].currentPrice; if (e->ammo > 0 && state.economy.find(e->type->ammo_type.id) != state.economy.end()) { price += e->ammo * state.economy[e->type->ammo_type.id].currentPrice; } LogWarning("Vehicle type %s price increased to %d after counting %s", vehicle->type.id, price, e->type.id); } } // Subtract price of default equipment for (auto &e : vehicle->type->initial_equipment_list) { if (state.economy.find(e.second.id) != state.economy.end()) { price -= state.economy[e.second.id].currentPrice; LogWarning("Vehicle type %s price decreased to %d after counting %s", vehicle->type.id, price, e.second.id); } } LogWarning("Vehicle type %s final price %d", vehicle->type.id, price); auto manufacturer = vehicle->type->manufacturer; bool isAmmo = false; bool isBio = false; bool isPerson = false; bool researched = true; bool manufacturerHostile = false; bool manufacturerUnavailable = false; return createControl(vehicle.id, Type::Vehicle, vehicle->name, manufacturer, isAmmo, isBio, isPerson, researched, manufacturerHostile, manufacturerUnavailable, price, storeSpace, initialStock, indexLeft, indexRight); } sp<TransactionControl> TransactionControl::createControl(const UString &id, Type type, const UString &name, StateRef<Organisation> manufacturer, bool isAmmo, bool isBio, bool isPerson, bool researched, bool manufacturerHostile, bool manufacturerUnavailable, int price, int storeSpace, std::vector<int> &initialStock, int indexLeft, int indexRight) { auto control = mksp<TransactionControl>(); control->itemId = id; control->itemType = type; control->manufacturer = manufacturer; control->isAmmo = isAmmo; control->isBio = isBio; control->isPerson = isPerson; control->researched = researched; control->manufacturerHostile = manufacturerHostile; control->manufacturerUnavailable = manufacturerUnavailable; control->storeSpace = storeSpace; control->tradeState.setInitialStock(std::forward<std::vector<int>>(initialStock)); control->tradeState.setLeftIndex(indexLeft); control->tradeState.setRightIndex(indexRight); // If we create a non-purchase control we never become one so clear the values if (isBio || !researched || (indexLeft != ECONOMY_IDX && indexRight != ECONOMY_IDX)) { control->manufacturerName = ""; control->price = 0; } else { control->manufacturerName = manufacturer->name; control->price = price; } // Setup vars control->Size = Vec2<int>{173 + 178 - 2, 47}; // Setup resources if (!resourcesInitialised) { initResources(); } // Add controls // Name const UString &labelName = researched ? tr(name) : tr("Alien Artifact"); if (labelName.length() > 0) { auto label = control->createChild<Label>(labelName, labelFont); label->Location = {isAmmo ? 32 : 11, 3}; label->Size = {256, 16}; label->TextHAlign = HorizontalAlignment::Left; label->TextVAlign = VerticalAlignment::Centre; } // Manufacturer if (control->manufacturerName.length() > 0) { auto label = control->createChild<Label>(tr(control->manufacturerName), labelFont); if (manufacturerHostile || manufacturerUnavailable) { label->Tint = {255, 50, 25}; } label->Location = {34, 3}; label->Size = {256, 16}; label->TextHAlign = HorizontalAlignment::Right; label->TextVAlign = VerticalAlignment::Centre; } // Price if (price != 0 && (indexLeft == ECONOMY_IDX || indexRight == ECONOMY_IDX)) { auto label = control->createChild<Label>(format("$%d", control->price), labelFont); label->Location = {290, 3}; label->Size = {47, 16}; label->TextHAlign = HorizontalAlignment::Right; label->TextVAlign = VerticalAlignment::Centre; } // Stock (values set in updateValues) control->stockLeft = control->createChild<Label>("", labelFont); control->stockLeft->Location = {11, 26}; control->stockLeft->Size = {32, 14}; control->stockLeft->TextHAlign = HorizontalAlignment::Right; control->stockLeft->TextVAlign = VerticalAlignment::Centre; control->stockRight = control->createChild<Label>("", labelFont); control->stockRight->Location = {303, 26}; control->stockRight->Size = {32, 14}; control->stockRight->TextHAlign = HorizontalAlignment::Right; control->stockRight->TextVAlign = VerticalAlignment::Centre; // Delta (values set in updateValues) control->deltaLeft = control->createChild<Label>("", labelFont); control->deltaLeft->Location = {50, 26}; control->deltaLeft->Size = {32, 14}; control->deltaLeft->TextHAlign = HorizontalAlignment::Right; control->deltaLeft->TextVAlign = VerticalAlignment::Centre; control->deltaRight = control->createChild<Label>("", labelFont); control->deltaRight->Location = {264, 26}; control->deltaRight->Size = {30, 14}; control->deltaRight->TextHAlign = HorizontalAlignment::Right; control->deltaRight->TextVAlign = VerticalAlignment::Centre; // ScrollBar control->scrollBar = control->createChild<ScrollBar>(); control->scrollBar->Location = {102, 24}; control->scrollBar->Size = {147, 20}; control->scrollBar->setMinimum(0); control->scrollBar->setMaximum(0); // ScrollBar buttons auto buttonScrollLeft = control->createChild<GraphicButton>(nullptr, scrollLeft); buttonScrollLeft->Size = scrollLeft->size; buttonScrollLeft->Location = {87, 24}; buttonScrollLeft->ScrollBarPrev = control->scrollBar; auto buttonScrollRight = control->createChild<GraphicButton>(nullptr, scrollRight); buttonScrollRight->Size = scrollRight->size; buttonScrollRight->Location = {247, 24}; buttonScrollRight->ScrollBarNext = control->scrollBar; // Callback control->setupCallbacks(); // Finally set the values control->setScrollbarValues(); return control; } void TransactionControl::setupCallbacks() { std::function<void(FormsEvent * e)> onScrollChange = [this](FormsEvent *) { if (!this->suspendUpdates) { this->updateValues(); } }; scrollBar->addCallback(FormEventType::ScrollBarChange, onScrollChange); } int TransactionControl::getCrewDelta(int index) const { return isPerson ? -tradeState.shipmentsTotal(index) : 0; } int TransactionControl::getCargoDelta(int index) const { return !isBio && !isPerson ? -tradeState.shipmentsTotal(index) * storeSpace : 0; } int TransactionControl::getBioDelta(int index) const { return isBio ? -tradeState.shipmentsTotal(index) * storeSpace : 0; } int TransactionControl::getPriceDelta() const { int delta = 0; for (int i = 0; i < 8; i++) { delta += tradeState.shipmentsTotal(i) * price; } return delta; } void TransactionControl::onRender() { Control::onRender(); static Vec2<int> bgLeftPos = {0, 2}; static Vec2<int> bgRightPos = {172, 2}; static Vec2<int> ammoPos = {4, 2}; static Vec2<int> iconLeftPos = {58, 24}; static Vec2<int> iconRightPos = {270, 24}; static Vec2<int> iconSize = {22, 20}; // Draw BG fw().renderer->draw(bgLeft, bgLeftPos); fw().renderer->draw(bgRight, bgRightPos); // Draw Ammo Arrow if (isAmmo) { fw().renderer->draw(purchaseArrow, ammoPos); } // Draw Icons if (!deltaLeft->isVisible()) { sp<Image> icon; if (isBio) { icon = tradeState.getLeftIndex() == ECONOMY_IDX ? alienContainedKill : alienContainedDetain; } else { icon = tradeState.getLeftIndex() == ECONOMY_IDX ? purchaseBoxIcon : purchaseXComIcon; } auto iconPos = iconLeftPos + (iconSize - (Vec2<int>)icon->size) / 2; fw().renderer->draw(icon, iconPos); } if (!deltaRight->isVisible()) { sp<Image> icon; if (isBio) { icon = tradeState.getRightIndex() == ECONOMY_IDX ? alienContainedKill : alienContainedDetain; } else { icon = tradeState.getRightIndex() == ECONOMY_IDX ? purchaseBoxIcon : purchaseXComIcon; } auto iconPos = iconRightPos + (iconSize - (Vec2<int>)icon->size) / 2; fw().renderer->draw(icon, iconPos); } } void TransactionControl::postRender() { Control::postRender(); // Draw shade if inactive static Vec2<int> shadePos = {0, 0}; if (tradeState.getLeftIndex() == tradeState.getRightIndex() || (tradeState.getLeftStock() == 0 && tradeState.getRightStock() == 0)) { fw().renderer->draw(transactionShade, shadePos); } } void TransactionControl::unloadResources() { bgLeft.reset(); bgRight.reset(); purchaseBoxIcon.reset(); purchaseXComIcon.reset(); purchaseArrow.reset(); alienContainedDetain.reset(); alienContainedKill.reset(); scrollLeft.reset(); scrollRight.reset(); transactionShade.reset(); Control::unloadResources(); } /** * Get the sum of shipment orders from the base (economy). * @param from - 0-7 for bases, 8 for economy * @param exclude - 0-7 for bases, 8 for economy, -1 don't exclude (by default) * @return - sum of shipment orders */ int TransactionControl::Trade::shipmentsFrom(const int from, const int exclude) const { int total = 0; if (shipments.find(from) != shipments.end()) { for (auto &s : shipments.at(from)) { if (s.first != exclude && s.second > 0) { total += s.second; } } } return total; } /** * Get total shipment orders from(+) and to(-) the base (economy). * @param baseIdx - 0-7 for bases, 8 for economy * @return - total sum of shipment orders */ int TransactionControl::Trade::shipmentsTotal(const int baseIdx) const { int total = 0; if (shipments.find(baseIdx) != shipments.end()) { for (auto &s : shipments.at(baseIdx)) { total += s.second; } } return total; } /** * Get shipment order. * @param from - 0-7 for bases, 8 for economy * @param to - 0-7 for bases, 8 for economy * @return - the shipment order */ int TransactionControl::Trade::getOrder(const int from, const int to) const { if (shipments.find(from) != shipments.end()) { auto &order = shipments.at(from); if (order.find(to) != order.end()) { return order.at(to); } } return 0; } /** * Cancel shipment order. * @param from - 0-7 for bases, 8 for economy * @param to - 0-7 for bases, 8 for economy */ void TransactionControl::Trade::cancelOrder(const int from, const int to) { if (shipments.find(from) != shipments.end()) { shipments.at(from).erase(to); if (shipments.at(from).empty()) shipments.erase(from); } if (shipments.find(to) != shipments.end()) { shipments.at(to).erase(from); if (shipments.at(to).empty()) shipments.erase(to); } } /** * Get current stock. * @param baseIdx - index of the base (economy) * @param oppositeIdx - index of the opposite base (economy) * @param currentStock - true for current, false for default (by default) * @return - the stock */ int TransactionControl::Trade::getStock(const int baseIdx, const int oppositeIdx, bool currentStock) const { return initialStock[baseIdx] - shipmentsFrom(baseIdx, oppositeIdx) - (currentStock ? getOrder(baseIdx, oppositeIdx) : 0); } /** * ScrollBar support. Set current value. * @param balance - scrollBar->getValue() * @return - order from left to right side */ int TransactionControl::Trade::setBalance(const int balance) { int orderLR = balance - getRightStock(); if (orderLR == 0) { cancelOrder(); } else { shipments[leftIdx][rightIdx] = orderLR; shipments[rightIdx][leftIdx] = -orderLR; } return orderLR; } }; // namespace OpenApoc
FranciscoDA/OpenApoc
forms/transactioncontrol.cpp
C++
mit
29,041
<?php namespace Upc\Cards\Bundle\CardsBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Upc\Cards\Bundle\CardsBundle\Entity\GroupCategory; use Symfony\Component\HttpFoundation\Request; /** * Description of CategoriaCrudController * * @author javier olivares */ class GroupCategoryCrudController extends Controller { /** * @Route("/", name="admin_gcategorias_list") * @Template("") */ public function listAction(Request $request) { $form = $this->createForm('gcategory_search', null); $form->handleRequest($request); $criteria = $form->getData() ? $form->getData() : array(); foreach ($criteria as $key => $value) { if (!$value) { unset($criteria[$key]); } } $em = $this->getDoctrine() ->getRepository('CardsBundle:GroupCategory'); $query = $em->findBy($criteria); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $this->get('request')->query->get('page', 1)/* page number */, 5/* limit per page */ ); return array( 'pagination' => $pagination, 'form' => $form->createView() ); } /** * @Route("/add", name="admin_gcategorias_add") * @Template("") */ public function newAction(Request $request) { $object = new GroupCategory(); $object->setCreatedAt( new \DateTime("now")); $form = $this->createForm('group_category', $object); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($object); $em->flush(); $this->get('session')->getFlashBag()->add( 'gcategoria', 'Registro grabado satisfactoriamente' ); $nextAction = $form->get('saveAndAdd')->isClicked() ? 'admin_gcategorias_add' : 'admin_gcategorias_list'; return $this->redirect($this->generateUrl($nextAction)); } return array( 'form' => $form->createView() ); } /** * @Route("/{pk}", name="admin_gcategorias_edit") * @Template("") */ public function editAction(Request $request, $pk) { $object = $this->getDoctrine()->getRepository('CardsBundle:GroupCategory')->find($pk); $form = $this->createForm('group_category', $object); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($object); $em->flush(); $this->get('session')->getFlashBag()->add( 'gcategoria', 'Registro modificado satisfactoriamente' ); $nextAction = $form->get('saveAndAdd')->isClicked() ? 'admin_gcategorias_add' : 'admin_gcategorias_list'; return $this->redirect($this->generateUrl($nextAction)); } return array( 'form' => $form->createView() ); } } ?>
devupc/cards
src/Upc/Cards/Bundle/CardsBundle/Controller/GroupCategoryCrudController.php
PHP
mit
3,369
var map; var infoWindow; // A variável markersData guarda a informação necessária a cada marcador // Para utilizar este código basta alterar a informação contida nesta variável var markersData = [ { lat: -3.741262, lng: -38.539389, nome: "Campus do Pici - Universidade Federal do Ceará", endereco:"Av. Mister Hull, s/n", telefone: "(85) 3366-9500" // não colocar virgula no último item de cada maracdor }, { lat: -3.780833, lng: -38.469656, nome: "Colosso Lake Lounge", endereco:"Rua Hermenegildo Sá Cavalcante, s/n", telefone: "(85) 98160-0088" // não colocar virgula no último item de cada maracdor } // não colocar vírgula no último marcador ]; function initialize() { var mapOptions = { center: new google.maps.LatLng(40.601203,-8.668173), zoom: 9, mapTypeId: 'roadmap', }; map = new google.maps.Map(document.getElementById('map-slackline'), mapOptions); // cria a nova Info Window com referência à variável infowindow // o conteúdo da Info Window será atribuído mais tarde infoWindow = new google.maps.InfoWindow(); // evento que fecha a infoWindow com click no mapa google.maps.event.addListener(map, 'click', function() { infoWindow.close(); }); // Chamada para a função que vai percorrer a informação // contida na variável markersData e criar os marcadores a mostrar no mapa displayMarkers(); } google.maps.event.addDomListener(window, 'load', initialize); // Esta função vai percorrer a informação contida na variável markersData // e cria os marcadores através da função createMarker function displayMarkers(){ // esta variável vai definir a área de mapa a abranger e o nível do zoom // de acordo com as posições dos marcadores var bounds = new google.maps.LatLngBounds(); // Loop que vai estruturar a informação contida em markersData // para que a função createMarker possa criar os marcadores for (var i = 0; i < markersData.length; i++){ var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng); var nome = markersData[i].nome; var endereco = markersData[i].endereco; var telefone = markersData[i].telefone; createMarker(latlng, nome, endereco, telefone); // Os valores de latitude e longitude do marcador são adicionados à // variável bounds bounds.extend(latlng); } // Depois de criados todos os marcadores // a API através da sua função fitBounds vai redefinir o nível do zoom // e consequentemente a área do mapa abrangida. map.fitBounds(bounds); } // Função que cria os marcadores e define o conteúdo de cada Info Window. function createMarker(latlng, nome, endereco, telefone){ var marker = new google.maps.Marker({ map: map, position: latlng, title: nome }); // Evento que dá instrução à API para estar alerta ao click no marcador. // Define o conteúdo e abre a Info Window. google.maps.event.addListener(marker, 'click', function() { // Variável que define a estrutura do HTML a inserir na Info Window. var iwContent = '<div id="iw_container">' + '<div class="iw_title">' + nome + '</div>' + '<div class="iw_content">' + endereco + '<br />' + telefone + '<br />'; // O conteúdo da variável iwContent é inserido na Info Window. infoWindow.setContent(iwContent); // A Info Window é aberta. infoWindow.open(map, marker); }); }
KatharineAmaral29/ArenaSports
js/mapslackline.js
JavaScript
mit
3,584
<?php require_once(APPPATH . 'views/header.php'); ?> <link rel="stylesheet" href="<?= base_url(); ?>assets/css/fullcalendar.css" /> <link rel="stylesheet" href="<?= base_url(); ?>css/mine.css" /> <style> .form-horizontal .controls { margin-left: 12px; } </style> <div class="page-content"> <div class="row-fluid"> <iframe id="frame" name="frame" frameborder="no" border="0" scrolling="no" height="750" width="450" class="span12" src="<?php echo base_url() . "index.php/management/"; ?>"> </iframe> <div class="row-fluid"> <div id="accordion2" class="accordion"> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseOne"> <div class="accordion-inner"> <div class="row-fluid"> <div class="span12"> <!--PAGE CONTENT BEGINS--> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="widget-main"> <input type="file" id="id-input-file-2" /> <input multiple="" type="file" id="id-input-file-3" /> <label> <input type="checkbox" name="file-format" id="id-file-format" /> <span class="lbl"> Allow only images</span> </label> </div> <div class="control-group"> <label class="control-label" for="form-field-username">First name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="First name" value="<?php echo 'name'; ?>" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-first">Last name</label> <div class="controls"> <input class="input-small" type="text" id="form-field-first" placeholder="First Name" /> <input class="input-small" type="text" id="form-field-last" placeholder="Othername" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Please enter your emails one by one</label> <div class="controls"> <label class="text-error">enter primary e-mail first</label> <input type="text" name="tags" id="form-field-tags" placeholder="info@gmail.com" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Please enter your contacts one by one</label> <div class="controls"> <label class="text-error">enter primary contact first</label> <input type="text" name="tags" id="form-field-tags" placeholder="+2567893213394" /> </div> </div></div> <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-sex">Sex</label> <div class="controls"> <select data-placeholder="Choose a sex..."> <option value="" /> <option value="male" />male <option value="female" />female </select> </div> </div> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Birth</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-sex">Location</label> <div class="controls" id="locationField"> <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input> </div> </div> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Country</label> <div class="controls"> <div class="controls" id="address"> <input id="country" type="text" /> <input class="field" id="street_number" type="hidden" disabled="true"></input> <input class="field" id="route"type="hidden" disabled="true"></input> <input class="field" id="locality" type="hidden" disabled="true"></input> <input class="field" type="hidden" id="administrative_area_level_1" disabled="true"></input> <input class="field" type="hidden" id="postal_code"></input> </div> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass1">New Password</label> <div class="controls"> <input type="password" id="form-field-pass1" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass2">Confirm Password</label> <div class="controls"> <input type="password" id="form-field-pass2" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div></div> </div><!--PAGE CONTENT ENDS--> </div><!--/.span--> </div><!--/.row-fluid--> <div class="accordion-group"> <div class="accordion-body collapse " id="collapseTwo"> <div class="accordion-inner"> <div class="widget-box"> <div class="widget-header header-color-blue"> <h5 class="bigger lighter"> <i class="icon-table"></i> Users and cohorts </h5> <div class="widget-toolbar widget-toolbar-light no-border"> <select id="simple-colorpicker-1" class="hide"> <option selected="" data-class="blue" value="#307ECC" />#307ECC <option data-class="blue2" value="#5090C1" />#5090C1 <option data-class="blue3" value="#6379AA" />#6379AA <option data-class="green" value="#82AF6F" />#82AF6F <option data-class="green2" value="#2E8965" />#2E8965 <option data-class="green3" value="#5FBC47" />#5FBC47 <option data-class="red" value="#E2755F" />#E2755F <option data-class="red2" value="#E04141" />#E04141 <option data-class="red3" value="#D15B47" />#D15B47 <option data-class="orange" value="#FFC657" />#FFC657 <option data-class="purple" value="#7E6EB0" />#7E6EB0 <option data-class="pink" value="#CE6F9E" />#CE6F9E <option data-class="dark" value="#404040" />#404040 <option data-class="grey" value="#848484" />#848484 <option data-class="default" value="#EEE" />#EEE </select> </div> </div> <div class="widget-body"> <div class="widget-main no-padding"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th> <i class="icon-user"></i> User </th> <th> <i>@</i> Email </th> <th class="hidden-480">Status</th> </tr> </thead> <tbody> <tr> <td class="">Alex</td> <td> <a href="#">alex@email.com</a> </td> <td class="hidden-480"> <span class="label label-warning">Pending</span> </td> </tr> <tr> <td class="">Fred</td> <td> <a href="#">fred@email.com</a> </td> <td class="hidden-480"> <span class="label label-success arrowed-in arrowed-in-right">Approved</span> </td> </tr> <tr> <td class="">Jack</td> <td> <a href="#">jack@email.com</a> </td> <td class="hidden-480"> <span class="label label-warning">Pending</span> </td> </tr> <tr> <td class="">John</td> <td> <a href="#">john@email.com</a> </td> <td class="hidden-480"> <span class="label label-inverse arrowed">Blocked</span> </td> </tr> <tr> <td class="">James</td> <td> <a href="#">james@email.com</a> </td> <td class="hidden-480"> <span class="label label-info arrowed-in arrowed-in-right">Online</span> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseTracks"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-username">Name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="" value="" /> </div> </div> <label for="form-field-8">Details</label> <textarea class="span12" id="form-field-8" placeholder="Default Text"></textarea> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Registration</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseCohorts"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-username">Name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="" value="" /> </div> </div> <label for="form-field-8">Details</label> <textarea class="span12" id="form-field-8" placeholder="Default Text"></textarea> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Registration</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseAdverts"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-info span6"> <div class="widget-main"> <input type="file" id="id-input-file-2" /> <input multiple="" type="file" id="id-input-file-3" /> <label> <input type="checkbox" name="file-format" id="id-file-format" /> <span class="lbl"> Allow only images</span> </label> </div> <div class="control-group"> <label class="control-label" for="form-field-username">Title</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="" value="" /> </div> </div> <div class="control-group"> <label class="control-label" for="id-date-picker-1">Date of Display</label> <div class="controls"> <input class="date-picker" id="id-date-picker-1" type="text" data-date-format="dd-mm-yyyy" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseCountry"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-success span6"> <div class="control-group"> <label class="control-label" for="form-field-tags">Select the country flag</label> <div class="controls"> <input type="file" id="id-input-file-2" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Country name</label> <div class="controls"> <input type="text" name="tags" id="form-field-tags" placeholder="Uganda" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-body collapse" id="collapseUser"> <div class="accordion-inner"> <form class="form-horizontal" > <div class="alert alert-block alert-success span6"> <div class="control-group"> <label class="control-label" for="form-field-username">First name</label> <div class="controls"> <input type="text" id="form-field-username" placeholder="First name" value="<?php echo 'name'; ?>" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-first">Last name</label> <div class="controls"> <input class="input-small" type="text" id="form-field-first" placeholder="First Name" /> <input class="input-small" type="text" id="form-field-last" placeholder="Othername" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">E-mail</label> <div class="controls"> <input type="text" name="tags" id="form-field-tags" placeholder="info@gmail.com" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-tags">Contacts</label> <div class="controls"> <input type="text" name="tags" id="form-field-tags" placeholder="+2567893213394" /> </div> </div></div> <div class="alert alert-block alert-info span6"> <div class="control-group"> <label class="control-label" for="form-field-sex">Location</label> <div class="controls" id="locationField"> <input id="autocomplete" placeholder="Select your country" type="text"></input> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass1">New Password</label> <div class="controls"> <input type="password" id="form-field-pass1" /> </div> </div> <div class="control-group"> <label class="control-label" for="form-field-pass2">Confirm Password</label> <div class="controls"> <input type="password" id="form-field-pass2" /> </div> </div> <div class=""> <button class="btn btn-info" type="button"> <i class="icon-ok bigger-110"></i> Submit </button> &nbsp; &nbsp; &nbsp; <button class="btn" type="reset"> <i class="icon-undo bigger-110"></i> Reset </button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div><!--/span--> </div><!--/row--> </div><!--/.page-content--> <div class="ace-settings-container" id="ace-settings-container"> <div class="btn btn-app btn-mini btn-warning ace-settings-btn" id="ace-settings-btn"> <i class="icon-cog bigger-150"></i> </div> <div class="ace-settings-box" id="ace-settings-box"> <div> <div class="pull-left"> <select id="skin-colorpicker" class="hide"> <option data-class="default" value="#438EB9" />#438EB9 <option data-class="skin-1" value="#222A2D" />#222A2D <option data-class="skin-2" value="#C6487E" />#C6487E <option data-class="skin-3" value="#D0D0D0" />#D0D0D0 </select> </div> <span>&nbsp; Choose Skin</span> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-header" /> <label class="lbl" for="ace-settings-header"> Fixed Header</label> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-sidebar" /> <label class="lbl" for="ace-settings-sidebar"> Fixed Sidebar</label> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-breadcrumbs" /> <label class="lbl" for="ace-settings-breadcrumbs"> Fixed Breadcrumbs</label> </div> <div> <input type="checkbox" class="ace-checkbox-2" id="ace-settings-rtl" /> <label class="lbl" for="ace-settings-rtl"> Right To Left (rtl)</label> </div> </div> </div><!--/#ace-settings-container--> </div><!--/.main-content--> <?php require_once(APPPATH . 'views/footer.php'); ?> <script type="text/javascript"> $(function () { $('#id-disable-check').on('click', function () { var inp = $('#form-input-readonly').get(0); if (inp.hasAttribute('disabled')) { inp.setAttribute('readonly', 'true'); inp.removeAttribute('disabled'); inp.value = "This text field is readonly!"; } else { inp.setAttribute('disabled', 'disabled'); inp.removeAttribute('readonly'); inp.value = "This text field is disabled!"; } }); $(".chzn-select").chosen(); $('[data-rel=tooltip]').tooltip({container: 'body'}); $('[data-rel=popover]').popover({container: 'body'}); $('textarea[class*=autosize]').autosize({append: "\n"}); $('textarea[class*=limited]').each(function () { var limit = parseInt($(this).attr('data-maxlength')) || 100; $(this).inputlimiter({ "limit": limit, remText: '%n character%s remaining...', limitText: 'max allowed : %n.' }); }); $.mask.definitions['~'] = '[+-]'; $('.input-mask-date').mask('99/99/9999'); $('.input-mask-phone').mask('(999) 999-9999'); $('.input-mask-eyescript').mask('~9.99 ~9.99 999'); $(".input-mask-product").mask("a*-999-a999", {placeholder: " ", completed: function () { alert("You typed the following: " + this.val()); }}); $("#input-size-slider").css('width', '200px').slider({ value: 1, range: "min", min: 1, max: 6, step: 1, slide: function (event, ui) { var sizing = ['', 'input-mini', 'input-small', 'input-medium', 'input-large', 'input-xlarge', 'input-xxlarge']; var val = parseInt(ui.value); $('#form-field-4').attr('class', sizing[val]).val('.' + sizing[val]); } }); $("#input-span-slider").slider({ value: 1, range: "min", min: 1, max: 11, step: 1, slide: function (event, ui) { var val = parseInt(ui.value); $('#form-field-5').attr('class', 'span' + val).val('.span' + val).next().attr('class', 'span' + (12 - val)).val('.span' + (12 - val)); } }); $("#slider-range").css('height', '200px').slider({ orientation: "vertical", range: true, min: 0, max: 100, values: [17, 67], slide: function (event, ui) { var val = ui.values[$(ui.handle).index() - 1] + ""; if (!ui.handle.firstChild) { $(ui.handle).append("<div class='tooltip right in' style='display:none;left:15px;top:-8px;'><div class='tooltip-arrow'></div><div class='tooltip-inner'></div></div>"); } $(ui.handle.firstChild).show().children().eq(1).text(val); } }).find('a').on('blur', function () { $(this.firstChild).hide(); }); $("#slider-range-max").slider({ range: "max", min: 1, max: 10, value: 2 }); $("#eq > span").css({width: '90%', 'float': 'left', margin: '15px'}).each(function () { // read initial values from markup and remove that var value = parseInt($(this).text(), 10); $(this).empty().slider({ value: value, range: "min", animate: true }); }); $('#id-input-file-1 , #id-input-file-2').ace_file_input({ no_file: 'No File ...', btn_choose: 'Choose', btn_change: 'Change', droppable: false, onchange: null, thumbnail: false //| true | large //whitelist:'gif|png|jpg|jpeg' //blacklist:'exe|php' //onchange:'' // }); $('#id-input-file-3').ace_file_input({ style: 'well', btn_choose: 'Drop files here or click to choose', btn_change: null, no_icon: 'icon-cloud-upload', droppable: true, thumbnail: 'small' //,icon_remove:null//set null, to hide remove/reset button /**,before_change:function(files, dropped) { //Check an example below //or examples/file-upload.html return true; }*/ /**,before_remove : function() { return true; }*/ , preview_error: function (filename, error_code) { //name of the file that failed //error_code values //1 = 'FILE_LOAD_FAILED', //2 = 'IMAGE_LOAD_FAILED', //3 = 'THUMBNAIL_FAILED' //alert(error_code); } }).on('change', function () { //console.log($(this).data('ace_input_files')); //console.log($(this).data('ace_input_method')); }); //dynamically change allowed formats by changing before_change callback function $('#id-file-format').removeAttr('checked').on('change', function () { var before_change var btn_choose var no_icon if (this.checked) { btn_choose = "Drop images here or click to choose"; no_icon = "icon-picture"; before_change = function (files, dropped) { var allowed_files = []; for (var i = 0; i < files.length; i++) { var file = files[i]; if (typeof file === "string") { //IE8 and browsers that don't support File Object if (!(/\.(jpe?g|png|gif|bmp)$/i).test(file)) return false; } else { var type = $.trim(file.type); if ((type.length > 0 && !(/^image\/(jpe?g|png|gif|bmp)$/i).test(type)) || (type.length == 0 && !(/\.(jpe?g|png|gif|bmp)$/i).test(file.name))//for android's default browser which gives an empty string for file.type ) continue;//not an image so don't keep this file } allowed_files.push(file); } if (allowed_files.length == 0) return false; return allowed_files; } } else { btn_choose = "Drop files here or click to choose"; no_icon = "icon-cloud-upload"; before_change = function (files, dropped) { return files; } } var file_input = $('#id-input-file-3'); file_input.ace_file_input('update_settings', {'before_change': before_change, 'btn_choose': btn_choose, 'no_icon': no_icon}) file_input.ace_file_input('reset_input'); }); $('#spinner1').ace_spinner({value: 0, min: 0, max: 200, step: 10, btn_up_class: 'btn-info', btn_down_class: 'btn-info'}) .on('change', function () { //alert(this.value) }); $('#spinner2').ace_spinner({value: 0, min: 0, max: 10000, step: 100, icon_up: 'icon-caret-up', icon_down: 'icon-caret-down'}); $('#spinner3').ace_spinner({value: 0, min: -100, max: 100, step: 10, icon_up: 'icon-plus', icon_down: 'icon-minus', btn_up_class: 'btn-success', btn_down_class: 'btn-danger'}); $('.date-picker').datepicker().next().on(ace.click_event, function () { $(this).prev().focus(); }); $('#id-date-range-picker-1').daterangepicker().prev().on(ace.click_event, function () { $(this).next().focus(); }); $('#timepicker1').timepicker({ minuteStep: 1, showSeconds: true, showMeridian: false }) $('#colorpicker1').colorpicker(); $('#simple-colorpicker-1').ace_colorpicker(); $(".knob").knob(); //we could just set the data-provide="tag" of the element inside HTML, but IE8 fails! var tag_input = $('#form-field-tags'); if (!(/msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase()))) tag_input.tag({placeholder: tag_input.attr('placeholder')}); else { //display a textarea for old IE, because it doesn't support this plugin or another one I tried! tag_input.after('<textarea id="' + tag_input.attr('id') + '" name="' + tag_input.attr('name') + '" rows="3">' + tag_input.val() + '</textarea>').remove(); //$('#form-field-tags').autosize({append: "\n"}); } ///////// $('#modal-form input[type=file]').ace_file_input({ style: 'well', btn_choose: 'Drop files here or click to choose', btn_change: null, no_icon: 'icon-cloud-upload', droppable: true, thumbnail: 'large' }) //chosen plugin inside a modal will have a zero width because the select element is originally hidden //and its width cannot be determined. //so we set the width after modal is show $('#modal-form').on('show', function () { $(this).find('.chzn-container').each(function () { $(this).find('a:first-child').css('width', '200px'); $(this).find('.chzn-drop').css('width', '210px'); $(this).find('.chzn-search input').css('width', '200px'); }); }) /** //or you can activate the chosen plugin after modal is shown //this way select element has a width now and chosen works as expected $('#modal-form').on('shown', function () { $(this).find('.modal-chosen').chosen(); }) */ }); </script>
WereDouglas/epitrack
application/views/management.php
PHP
mit
41,131
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function _default() { return function ({ addUtilities, variants }) { addUtilities({ '.bg-clip-border': { 'background-clip': 'border-box' }, '.bg-clip-padding': { 'background-clip': 'padding-box' }, '.bg-clip-content': { 'background-clip': 'content-box' }, '.bg-clip-text': { 'background-clip': 'text' } }, variants('backgroundClip')); }; }
matryer/bitbar
xbarapp.com/node_modules/tailwindcss/lib/plugins/backgroundClip.js
JavaScript
mit
550
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | Hooks | ------------------------------------------------------------------------- | This file lets you define "hooks" to extend CI without hacking the core | files. Please see the user guide for info: | | http://codeigniter.com/user_guide/general/hooks.html | */ $hook['pre_system'] = array( 'function' => 'auth_constants', 'filename' => 'auth_constants.php', 'filepath' => 'hooks' );
GazmanDevelopment/docman
application/config/hooks.php
PHP
mit
542
# frozen_string_literal: true module ProductMutationHelper def coerce_pricing_structure_input(input) return nil unless input value_field = case input[:pricing_strategy] when 'fixed' :fixed_value when 'scheduled_value' :scheduled_value end PricingStructure.new(pricing_strategy: input[:pricing_strategy], value: input[value_field]) end def create_or_update_variants(product, product_variants_fields) (product_variants_fields || []).each_with_index do |product_variant_fields, i| product_variant_attrs = product_variant_fields.merge(position: i + 1) variant_id = product_variant_attrs.delete(:id) product_variant_attrs[:override_pricing_structure] = coerce_pricing_structure_input(product_variant_fields[:override_pricing_structure]) if variant_id variant = product.product_variants.find { |v| v.id.to_s == variant_id } variant.update!(product_variant_attrs) else product.product_variants.create!(product_variant_attrs) end end end end
neinteractiveliterature/intercode
app/graphql/product_mutation_helper.rb
Ruby
mit
1,074
/* * Copyright (c) 2003-2009 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme.curve; import java.io.IOException; import com.jme.math.Vector3f; import com.jme.scene.Controller; import com.jme.scene.Spatial; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; /** * <code>CurveController</code> defines a controller that moves a supplied * <code>Spatial</code> object along a curve. Attributes of the curve are set * such as the up vector (if not set, the spacial object will roll along the * curve), the orientation precision defines how accurate the orientation of the * spatial will be. * @author Mark Powell * @version $Id: CurveController.java 4131 2009-03-19 20:15:28Z blaine.dev $ */ public class CurveController extends Controller { private static final long serialVersionUID = 1L; private Spatial mover; private Curve curve; private Vector3f up; private float orientationPrecision = 0.1f; private float currentTime = 0.0f; private float deltaTime = 0.0f; private boolean cycleForward = true; private boolean autoRotation = false; /** * Constructor instantiates a new <code>CurveController</code> object. * The curve object that the controller operates on and the spatial object * that is moved is specified during construction. * @param curve the curve to operate on. * @param mover the spatial to move. */ public CurveController(Curve curve, Spatial mover) { this.curve = curve; this.mover = mover; setUpVector(new Vector3f(0,1,0)); setMinTime(0); setMaxTime(Float.MAX_VALUE); setRepeatType(Controller.RT_CLAMP); setSpeed(1.0f); } /** * Constructor instantiates a new <code>CurveController</code> object. * The curve object that the controller operates on and the spatial object * that is moved is specified during construction. The game time to * start and the game time to finish is also supplied. * @param curve the curve to operate on. * @param mover the spatial to move. * @param minTime the time to start the controller. * @param maxTime the time to end the controller. */ public CurveController( Curve curve, Spatial mover, float minTime, float maxTime) { this.curve = curve; this.mover = mover; setMinTime(minTime); setMaxTime(maxTime); setRepeatType(Controller.RT_CLAMP); } /** * * <code>setUpVector</code> sets the locking vector for the spatials up * vector. This prevents rolling along the curve and allows for a better * tracking. * @param up the vector to lock as the spatials up vector. */ public void setUpVector(Vector3f up) { this.up = up; } /** * * <code>setOrientationPrecision</code> sets a precision value for the * spatials orientation. The smaller the number the higher the precision. * By default 0.1 is used, and typically does not require changing. * @param value the precision value of the spatial's orientation. */ public void setOrientationPrecision(float value) { orientationPrecision = value; } /** * * <code>setAutoRotation</code> determines if the object assigned to * the controller will rotate with the curve or just following the * curve. * @param value true if the object is to rotate with the curve, false * otherwise. */ public void setAutoRotation(boolean value) { autoRotation = value; } /** * * <code>isAutoRotating</code> returns true if the object is rotating with * the curve and false if it is not. * @return true if the object is following the curve, false otherwise. */ public boolean isAutoRotating() { return autoRotation; } /** * <code>update</code> moves a spatial along the given curve for along a * time period. * @see com.jme.scene.Controller#update(float) */ public void update(float time) { if(mover == null || curve == null || up == null) { return; } currentTime += time * getSpeed(); if (currentTime >= getMinTime() && currentTime <= getMaxTime()) { if (getRepeatType() == RT_CLAMP) { deltaTime = currentTime - getMinTime(); mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else if (getRepeatType() == RT_WRAP) { deltaTime = (currentTime - getMinTime()) % 1.0f; if (deltaTime > 1) { currentTime = 0; deltaTime = 0; } mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else if (getRepeatType() == RT_CYCLE) { float prevTime = deltaTime; deltaTime = (currentTime - getMinTime()) % 1.0f; if (prevTime > deltaTime) { cycleForward = !cycleForward; } if (cycleForward) { mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else { mover.setLocalTranslation( curve.getPoint(1.0f - deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( 1.0f - deltaTime, orientationPrecision, up)); } } } else { return; } } } public void reset() { this.currentTime = 0; } public void write(JMEExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(mover, "mover", null); capsule.write(curve, "Curve", null); capsule.write(up, "up", null); capsule.write(orientationPrecision, "orientationPrecision", 0.1f); capsule.write(cycleForward, "cycleForward", true); capsule.write(autoRotation, "autoRotation", false); } public void read(JMEImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); mover = (Spatial)capsule.readSavable("mover", null); curve = (Curve)capsule.readSavable("curve", null); up = (Vector3f)capsule.readSavable("up", null); orientationPrecision = capsule.readFloat("orientationPrecision", 0.1f); cycleForward = capsule.readBoolean("cycleForward", true); autoRotation = capsule.readBoolean("autoRotation", false); } }
accelazh/ThreeBodyProblem
lib/jME2_0_1-Stable/src/com/jme/curve/CurveController.java
Java
mit
9,311
using BizHawk.Common; namespace BizHawk.Emulation.Cores.Nintendo.NES { //AKA half of mapper 034 (the other half is AVE_NINA_001 which is entirely different..) public sealed class BxROM : NES.NESBoardBase { //configuration int prg_bank_mask_32k; int chr_bank_mask_8k; //state int prg_bank_32k; int chr_bank_8k; public override void SyncState(Serializer ser) { base.SyncState(ser); ser.Sync(nameof(prg_bank_32k), ref prg_bank_32k); ser.Sync(nameof(chr_bank_8k), ref chr_bank_8k); } public override bool Configure(NES.EDetectionOrigin origin) { switch (Cart.board_type) { case "AVE-NINA-07": // wally bear and the gang // it's not the NINA_001 but something entirely different; actually a colordreams with VRAM // this actually works AssertPrg(32,128); AssertChr(0,16); AssertWram(0); AssertVram(0,8); break; case "IREM-BNROM": //Mashou (J).nes case "NES-BNROM": //Deadly Towers (U) AssertPrg(128,256); AssertChr(0); AssertWram(0,8); AssertVram(8); break; default: return false; } prg_bank_mask_32k = Cart.prg_size / 32 - 1; chr_bank_mask_8k = Cart.chr_size / 8 - 1; SetMirrorType(Cart.pad_h, Cart.pad_v); return true; } public override byte ReadPRG(int addr) { addr |= (prg_bank_32k << 15); return ROM[addr]; } public override void WritePRG(int addr, byte value) { value = HandleNormalPRGConflict(addr, value); prg_bank_32k = value & prg_bank_mask_32k; chr_bank_8k = ((value >> 4) & 0xF) & chr_bank_mask_8k; } public override byte ReadPPU(int addr) { if (addr<0x2000) { if (VRAM != null) { return VRAM[addr]; } else { return VROM[addr | (chr_bank_8k << 13)]; } } else { return base.ReadPPU(addr); } } } }
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BxROM.cs
C#
mit
1,817
/** * Created by quanpower on 14-8-20. */ var config = require('./../config'); var redis = require('./redis'); var _ = require('lodash'); function cacheDevice(device){ if(device){ var cloned = _.clone(device); redis.set('DEVICE_' + device.uuid, JSON.stringify(cloned),function(){ //console.log('cached', uuid); }); } } function noop(){} if(config.redis){ module.exports = cacheDevice; } else{ module.exports = noop; }
SmartLinkCloud/IOT-platform
lib/cacheDevice.js
JavaScript
mit
479
""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r
yavalvas/yav_com
build/matplotlib/lib/matplotlib/tight_bbox.py
Python
mit
2,604
# Require any additional compass plugins here. require 'sass-globbing' # Set this to the root of your project when deployed: http_path = "/" css_dir = "_includes/css" sass_dir = "_includes/sass" images_dir = "assets/img" javascripts_dir = "assets/js" relative_assets = true # Compilation pour la prod : environment = :production output_style = :compressed # Compilation durant le dev : # environment = :development #output_style = :expanded # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via compass helper functions. Uncomment: # relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: # line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: # preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
chipisan/blog
config.rb
Ruby
mit
1,100
/** * morningstar-base-charts * * Copyright © 2016 . All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import defaultClasses from "../config/classes.js"; import ChartBase from "./chartBase.js"; import { ChartUtils } from "../utils/utils.js"; /** * Horizontal Bar Chart Implementation * * @extends {ChartBase} */ class HorizontalBarChart extends ChartBase{ /** * Creates an instance of HorizontalBarChart. * * @param {any} options */ constructor(options) { super(options); } /** * @override */ render(options) { var axes = this.axes, yScale = axes.axis("y").scale(), xScale = axes.axis("x").scale(), data = this.data[0].values, chartArea = this.layer, barHeight = yScale.rangeBand(), barPadding = 6, hasNegative = ChartUtils.hasNegative(data), animation = (options && !options.animation) ? false : true;; var getClass = d => { if(hasNegative){ return d >= 0 ? "h-bar-positive" : "h-bar-negative"; } return "h-bar"; }; var draw = selection => { selection.attr("class", getClass) .attr("x", (d) => xScale(Math.min(0, d))) .attr("y", 6) .attr("transform", (d, i) => "translate(0," + i * barHeight + ")") .attr("width", d => animation ? 0 : Math.abs(xScale(d) - xScale(0)) ) .attr("height", barHeight - barPadding); return selection; }; var bar = chartArea.selectAll("rect").data(data); bar.call(draw) .enter().append("rect").call(draw); bar.exit().remove(); if (animation) { bar.transition().duration(300) .attr("width", d => Math.abs(xScale(d) - xScale(0))); } } /** * * * @param {any} index */ onMouseover(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 0.5); } /** * * * @param {any} index */ onMouseout(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 1); } /** * * * @param {any} data */ _formatData(data) { var xDomain = this.axes.axis("x").scale().domain(); this._categories = data.map(value => value.name); this.data = xDomain.map(function (series, i) { var item = { series }; item.values = data.map(value => { return { series: series, category: value.name, value: value.values[i], index: value.index }; }); return item; }); } } export default HorizontalBarChart;
jmconde/charts
src/js/charts/horizontal.js
JavaScript
mit
3,156
<?php namespace Wowo\NewsletterBundle\Newsletter\Placeholders; use Wowo\NewsletterBundle\Newsletter\Placeholders\Exception\InvalidPlaceholderMappingException; class PlaceholderProcessor implements PlaceholderProcessorInterface { protected $mapping; protected $referenceClass; protected $placeholder_delimiter_left = '{{'; protected $placeholder_delimiter_right = '}}'; protected $placeholder_regex = '#delim_lef\s*placeholder\s*delim_right#'; public function setMapping(array $mapping) { $this->mapping = $mapping; } public function setReferenceClass($referenceClass) { if (!class_exists($referenceClass)) { throw new \InvalidArgumentException(sprintf('Class %s doesn\'t exist!', $referenceClass)); } $this->referenceClass = $referenceClass; } public function process($object, $body) { if (null == $this->mapping) { throw new \BadMethodCallException('Placeholders mapping ain\'t configured yet'); } if (get_class($object) != $this->referenceClass) { throw new \InvalidArgumentException(sprintf('Object passed to method isn\'t an instance of referenceClass (%s != %s)', get_class($object), $this->referenceClass)); } $this->validatePlaceholders(); foreach ($this->mapping as $placeholder => $source) { $value = $this->getPlaceholderValue($object, $source); $body = $this->replacePlaceholder($placeholder, $value, $body); } return $body; } /** * Get value from object based on source (property or method). It claims that validation were done * * @param mixed $object * @param mixed $source * @access protected * @return void */ protected function getPlaceholderValue($object, $source) { $rc = new \ReflectionClass(get_class($object)); if ($rc->hasProperty($source)) { return $object->$source; } else { return call_user_func(array($object, $source)); } } protected function replacePlaceholder($placeholder, $value, $body) { $regex = str_replace( array('delim_lef', 'delim_right', 'placeholder'), array($this->placeholder_delimiter_left, $this->placeholder_delimiter_right, $placeholder), $this->placeholder_regex ); return preg_replace($regex, $value, $body); } /** * It looks firstly for properties, then for method (getter) * */ protected function validatePlaceholders() { $rc = new \ReflectionClass($this->referenceClass); foreach ($this->mapping as $placeholder => $source) { if ($rc->hasProperty($source)) { $rp = new \ReflectionProperty($this->referenceClass, $source); if (!$rp->isPublic()) { throw new InvalidPlaceholderMappingException( sprintf('A placeholder %s defines source %s as a property, but it isn\'t public visible', $placeholder, $source), InvalidPlaceholderMappingException::NON_PUBLIC_PROPERTY); } } elseif($rc->hasMethod($source)) { $rm = new \ReflectionMethod($this->referenceClass, $source); if (!$rm->isPublic()) { throw new InvalidPlaceholderMappingException( sprintf('A placeholder %s defines source %s as a method (getter), but it isn\'t public visible', $placeholder, $source), InvalidPlaceholderMappingException::NON_PUBLIC_METHOD); } } else { throw new InvalidPlaceholderMappingException( sprintf('Unable to map placeholder %s with source %s', $placeholder, $source), InvalidPlaceholderMappingException::UNABLE_TO_MAP); } } } }
mortenthorpe/gladturdev
vendor/wowo/wowo-newsletter-bundle/Wowo/NewsletterBundle/Newsletter/Placeholders/PlaceholderProcessor.php
PHP
mit
3,955
# -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main()
kklmn/xrt
examples/withShadow/04_06/04_dE_VCM_bending.py
Python
mit
4,894
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'application#hello' root 'application#goodbye' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
tkakisu/rails_tutorial
chapter1/config/routes.rb
Ruby
mit
1,634
using System.Net; using FluentAssertions; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Links; public sealed class AtomicAbsoluteLinksTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>> { private const string HostPrefix = "http://localhost"; private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext; private readonly OperationsFakers _fakers = new(); public AtomicAbsoluteLinksTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext) { _testContext = testContext; testContext.UseController<OperationsController>(); // These routes need to be registered in ASP.NET for rendering links to resource/relationship endpoints. testContext.UseController<TextLanguagesController>(); testContext.UseController<RecordCompaniesController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); }); } [Fact] public async Task Update_resource_with_side_effects_returns_absolute_links() { // Arrange TextLanguage existingLanguage = _fakers.TextLanguage.Generate(); RecordCompany existingCompany = _fakers.RecordCompany.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingLanguage, existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "update", data = new { type = "textLanguages", id = existingLanguage.StringId, attributes = new { } } }, new { op = "update", data = new { type = "recordCompanies", id = existingCompany.StringId, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { string languageLink = $"{HostPrefix}/textLanguages/{existingLanguage.StringId}"; resource.ShouldNotBeNull(); resource.Links.ShouldNotBeNull(); resource.Links.Self.Should().Be(languageLink); resource.Relationships.ShouldContainKey("lyrics").With(value => { value.ShouldNotBeNull(); value.Links.ShouldNotBeNull(); value.Links.Self.Should().Be($"{languageLink}/relationships/lyrics"); value.Links.Related.Should().Be($"{languageLink}/lyrics"); }); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { string companyLink = $"{HostPrefix}/recordCompanies/{existingCompany.StringId}"; resource.ShouldNotBeNull(); resource.Links.ShouldNotBeNull(); resource.Links.Self.Should().Be(companyLink); resource.Relationships.ShouldContainKey("tracks").With(value => { value.ShouldNotBeNull(); value.Links.ShouldNotBeNull(); value.Links.Self.Should().Be($"{companyLink}/relationships/tracks"); value.Links.Related.Should().Be($"{companyLink}/tracks"); }); }); } [Fact] public async Task Update_resource_with_side_effects_and_missing_resource_controller_hides_links() { // Arrange Playlist existingPlaylist = _fakers.Playlist.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Playlists.Add(existingPlaylist); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "update", data = new { type = "playlists", id = existingPlaylist.StringId, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(1); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.ShouldNotBeNull(); resource.Links.Should().BeNull(); resource.Relationships.Should().BeNull(); }); } }
json-api-dotnet/JsonApiDotNetCore
test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Links/AtomicAbsoluteLinksTests.cs
C#
mit
5,903
#include "WebForm.h" WebForm::WebForm(void) :__pWeb(null), __phonegapCommand(null) { geolocation = null; device = null; accel = null; network = null; console = null; compass = null; contacts = null; } WebForm::~WebForm(void) { } bool WebForm::Initialize() { return true; } result WebForm::OnInitializing(void) { result r = E_SUCCESS; // TODO: Add your initialization code here r = CreateWebControl(); if (IsFailed(r)) { AppLog("CreateMainForm() has failed.\n"); goto CATCH; } __pWeb->LoadUrl("file:///Res/index.html"); //__pWeb->LoadUrl("file:///Res/mobile-spec/index.html"); return r; CATCH: return false; } result WebForm::OnTerminating(void) { result r = E_SUCCESS; // delete __phonegapCommand; // delete geolocation; // delete device; // delete accel; // delete network; // delete console; // delete compass; // delete contacts; // delete notification; // delete camera; return r; } void WebForm::OnActionPerformed(const Osp::Ui::Control& source, int actionId) { switch(actionId) { default: break; } } void WebForm::LaunchBrowser(const String& url) { ArrayList* pDataList = null; pDataList = new ArrayList(); pDataList->Construct(); String* pData = null; pData = new String(L"url:"); pData->Append(url); AppLogDebug("Launching Stock Browser with %S", pData->GetPointer()); pDataList->Add(*pData); AppControl* pAc = AppManager::FindAppControlN(APPCONTROL_BROWSER, ""); if(pAc) { pAc->Start(pDataList, null); delete pAc; } pDataList->RemoveAll(true); delete pDataList; } bool WebForm::OnLoadingRequested (const Osp::Base::String& url, WebNavigationType type) { AppLogDebug("URL REQUESTED %S", url.GetPointer()); if(url.StartsWith("gap://", 0)) { // __phonegapCommand = null; __phonegapCommand = new String(url); // FIXME: for some reason this does not work if we return true. Web freezes. // __pWeb->StopLoading(); // String* test; // test = __pWeb->EvaluateJavascriptN(L"'test'"); // AppLogDebug("String is %S", test->GetPointer()); // delete test; // return true; return false; } else if(url.StartsWith("http://", 0) || url.StartsWith("https://", 0)) { AppLogDebug("Non PhoneGap command. External URL. Launching WebBrowser"); LaunchBrowser(url); return false; } return false; } void WebForm::OnLoadingCompleted() { // Setting DeviceInfo to initialize PhoneGap (should be done only once) and firing onNativeReady event String* deviceInfo; deviceInfo = __pWeb->EvaluateJavascriptN(L"window.device.uuid"); if(deviceInfo->IsEmpty()) { device->SetDeviceInfo(); __pWeb->EvaluateJavascriptN("PhoneGap.onNativeReady.fire();"); } else { //AppLogDebug("DeviceInfo = %S;", deviceInfo->GetPointer()); } delete deviceInfo; // Analyzing PhoneGap command if(__phonegapCommand) { if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Geolocation", 0)) { geolocation->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Accelerometer", 0)) { accel->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Network", 0)) { network->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.DebugConsole", 0)) { console->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Compass", 0)) { compass->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Contacts", 0)) { contacts->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Notification", 0)) { notification->Run(*__phonegapCommand); } else if(__phonegapCommand->StartsWith(L"gap://com.phonegap.Camera", 0)) { camera->Run(*__phonegapCommand); } // Tell the JS code that we got this command, and we're ready for another __pWeb->EvaluateJavascriptN(L"PhoneGap.queue.ready = true;"); delete __phonegapCommand; __phonegapCommand = null; } else { AppLogDebug("Non PhoneGap command completed"); } } result WebForm::CreateWebControl(void) { result r = E_SUCCESS; int screen_width = 0; int screen_height = 0; /*screen*/ r = SystemInfo::GetValue("ScreenWidth", screen_width); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); r = SystemInfo::GetValue("ScreenHeight", screen_height); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); /*Web*/ __pWeb = new Web(); r = __pWeb->Construct(Rectangle(0, 0, screen_width, screen_height - 38)); TryCatch(r == E_SUCCESS, ,"Web is not constructed\n "); r = this->AddControl(*__pWeb); TryCatch(r == E_SUCCESS, ,"Web is not attached\n "); __pWeb->SetLoadingListener(this); __pWeb->SetFocus(); if(__pWeb) { geolocation = new GeoLocation(__pWeb); device = new Device(__pWeb); accel = new Accelerometer(__pWeb); network = new Network(__pWeb); console = new DebugConsole(__pWeb); compass = new Compass(__pWeb); contacts = new Contacts(__pWeb); notification = new Notification(__pWeb); camera = new Kamera(__pWeb); } return r; CATCH: AppLog("Error = %s\n", GetErrorMessage(r)); return r; }
johnwargo/phonegap-essentials-code
chapter04/HelloWorld/src/WebForm.cpp
C++
mit
5,118
import { flatArgs } from './Query'; import type { Entity } from '../binding'; import type { Filter } from './Filter'; import { JsonMap } from '../util'; import type { GeoPoint } from '../GeoPoint'; /** * The Condition interface defines all existing query filters */ export interface Condition<T extends Entity> { /** * An object that contains filter rules which will be merged with the current filters of this query * * @param conditions - Additional filters for this query * @return The resulting Query */ where(conditions: JsonMap): Filter<T>; /** * Adds a equal filter to the field. All other other filters on the field will be discarded * @param field The field to filter * @param value The value used to filter * @return The resulting Query */ equal(field: string, value: any): Filter<T> /** * Adds a not equal filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/ne/ */ notEqual(field: string, value: any): Filter<T> /** * Adds a greater than filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gt/ */ greaterThan(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a greater than or equal to filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gte/ */ greaterThanOrEqualTo(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a less than filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lt/ */ lessThan(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a less than or equal to filter to the field * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lte/ */ lessThanOrEqualTo(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a between filter to the field. This is a shorthand for an less than and greater than filter. * @param field The field to filter * @param greaterValue The field value must be greater than this value * @param lessValue The field value must be less than this value * @return The resulting Query */ between( field: string, greaterValue: number | string | Date | Entity, lessValue: number | string | Date | Entity ): Filter<T> /** * Adds a “in” filter to the field * * The field value must be equal to one of the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/in/ */ in(field: string, ...args: any[]): Filter<T> /** * Adds an “in” filter to the field * * The field value must be equal to one of the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/in/ */ in(field: string, ...args: any[]): Filter<T> /** * Adds a “not in” filter to the field * * The field value must not be equal to any of the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/nin/ */ notIn(field: string, ...args: any[]): Filter<T> /** * Adds a “is null” filter to the field * * The field value must be null. * * @param field The field to filter * @return The resulting Query */ isNull(field: string): Filter<T> /** * Adds a “is not null” filter to the field * * The field value must not be null. * * @param field The field to filter * @return The resulting Query */ isNotNull(field: string): Filter<T> /** * Adds a contains all filter to the collection field * * The collection must contain all the given values. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/all/ */ containsAll(field: string, ...args: any[]): Filter<T> /** * Adds a modulo filter to the field * * The field value divided by divisor must be equal to the remainder. * * @param field The field to filter * @param divisor The divisor of the modulo filter * @param remainder The remainder of the modulo filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/mod/ */ mod(field: string, divisor: number, remainder: number): Filter<T> /** * Adds a regular expression filter to the field * * The field value must matches the regular expression. * <p>Note: Only anchored expressions (Expressions that starts with an ^) and the multiline flag are supported.</p> * * @param field The field to filter * @param regExp The regular expression of the filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/regex/ */ matches(field: string, regExp: string | RegExp): Filter<T> /** * Adds a size filter to the collection field * * The collection must have exactly size members. * * @param field The field to filter * @param size The collections size to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/size/ */ size(field: string, size: number): Filter<T> /** * Adds a geopoint based near filter to the GeoPoint field * * The GeoPoint must be within the maximum distance * to the given GeoPoint. Returns from nearest to farthest. * * @param field The field to filter * @param geoPoint The GeoPoint to filter * @param maxDistance Tha maximum distance to filter in meters * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/nearSphere/ */ near(field: string, geoPoint: GeoPoint, maxDistance: number): Filter<T> /** * Adds a GeoPoint based polygon filter to the GeoPoint field * * The GeoPoint must be contained within the given polygon. * * @param field The field to filter * @param geoPoints The geoPoints that describes the polygon of the filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/geoWithin/ */ withinPolygon(field: string, ...geoPoints: GeoPoint[] | GeoPoint[][]): Filter<T> /** * Adds a equal filter to the field * * All other other filters on the field will be discarded. * * @method * @param field The field to filter * @param value The value used to filter */ eq(field: string, value: any): Filter<T> /** * Adds a not equal filter to the field * * @method * @param field The field to filter * @param value The value used to filter * * @see http://docs.mongodb.org/manual/reference/operator/query/ne/ */ ne(field: string, value: any): Filter<T> /** * Adds a less than filter to the field * * Shorthand for {@link Condition#lessThan}. * * @method * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lt/ */ lt(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a less than or equal to filter to the field * * Shorthand for {@link Condition#lessThanOrEqualTo}. * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/lte/ */ le(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a greater than filter to the field * * Shorthand for {@link Condition#greaterThan}. * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gt/ */ gt(field: string, value: number | string | Date | Entity): Filter<T> /** * Adds a greater than or equal to filter to the field * * Shorthand for {@link Condition#greaterThanOrEqualTo}. * * @param field The field to filter * @param value The value used to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/gte/ */ ge(field: string, value: number | string | Date | Entity): Filter<T> /** * The collection must contains one of the given values * * Adds a contains any filter to the collection field. * Alias for {@link Condition#in}. * * @param field The field to filter * @param args The field value or values to filter * @return The resulting Query * * @see http://docs.mongodb.org/manual/reference/operator/query/in/ */ containsAny(field: string, ...args: any[]): Filter<T> /** * Adds a filter to this query * * @param field * @param filter * @param value * @return The resulting Query */ addFilter(field: string | null, filter: string | null, value: any): Filter<T> } // eslint-disable-next-line @typescript-eslint/no-redeclare export const Condition: Partial<Condition<any>> = { where(this: Condition<any>, conditions) { return this.addFilter(null, null, conditions); }, equal(this: Condition<any>, field, value) { return this.addFilter(field, null, value); }, notEqual(this: Condition<any>, field, value) { return this.addFilter(field, '$ne', value); }, greaterThan(this: Condition<any>, field, value) { return this.addFilter(field, '$gt', value); }, greaterThanOrEqualTo(this: Condition<any>, field, value) { return this.addFilter(field, '$gte', value); }, lessThan(this: Condition<any>, field, value) { return this.addFilter(field, '$lt', value); }, lessThanOrEqualTo(this: Condition<any>, field, value) { return this.addFilter(field, '$lte', value); }, between(this: Condition<any>, field, greaterValue, lessValue) { return this .addFilter(field, '$gt', greaterValue) .addFilter(field, '$lt', lessValue); }, in(this: Condition<any>, field: string, ...args: any[]) { return this.addFilter(field, '$in', flatArgs(args)); }, notIn(this: Condition<any>, field, ...args: any[]) { return this.addFilter(field, '$nin', flatArgs(args)); }, isNull(this: Condition<any>, field) { return this.equal(field, null); }, isNotNull(this: Condition<any>, field) { return this.addFilter(field, '$exists', true) .addFilter(field, '$ne', null); }, containsAll(this: Condition<any>, field, ...args: any[]) { return this.addFilter(field, '$all', flatArgs(args)); }, mod(this: Condition<any>, field, divisor, remainder) { return this.addFilter(field, '$mod', [divisor, remainder]); }, matches(this: Condition<any>, field, regExp) { const reg = regExp instanceof RegExp ? regExp : new RegExp(regExp); if (reg.ignoreCase) { throw new Error('RegExp.ignoreCase flag is not supported.'); } if (reg.global) { throw new Error('RegExp.global flag is not supported.'); } if (reg.source.indexOf('^') !== 0) { throw new Error('regExp must be an anchored expression, i.e. it must be started with a ^.'); } const result = this.addFilter(field, '$regex', reg.source); if (reg.multiline) { result.addFilter(field, '$options', 'm'); } return result; }, size(this: Condition<any>, field, size) { return this.addFilter(field, '$size', size); }, near(this: Condition<any>, field, geoPoint, maxDistance) { return this.addFilter(field, '$nearSphere', { $geometry: { type: 'Point', coordinates: [geoPoint.longitude, geoPoint.latitude], }, $maxDistance: maxDistance, }); }, withinPolygon(this: Condition<any>, field, ...args: any[]) { const geoPoints = flatArgs(args); return this.addFilter(field, '$geoWithin', { $geometry: { type: 'Polygon', coordinates: [geoPoints.map((geoPoint) => [geoPoint.longitude, geoPoint.latitude])], }, }); }, }; // aliases Object.assign(Condition, { eq: Condition.equal, ne: Condition.notEqual, lt: Condition.lessThan, le: Condition.lessThanOrEqualTo, gt: Condition.greaterThan, ge: Condition.greaterThanOrEqualTo, containsAny: Condition.in, });
Baqend/js-sdk
lib/query/Condition.ts
TypeScript
mit
13,300
package googlechat import "time" // ChatMessage is message type from Pub/Sub events type ChatMessage struct { Type string `json:"type"` EventTime time.Time `json:"eventTime"` Token string `json:"token"` Message struct { Name string `json:"name"` Sender struct { Name string `json:"name"` DisplayName string `json:"displayName"` AvatarURL string `json:"avatarUrl"` Email string `json:"email"` Type string `json:"type"` } `json:"sender"` CreateTime time.Time `json:"createTime"` Text string `json:"text"` Thread struct { Name string `json:"name"` RetentionSettings struct { State string `json:"state"` } `json:"retentionSettings"` } `json:"thread"` Space struct { Name string `json:"name"` Type string `json:"type"` } `json:"space"` ArgumentText string `json:"argumentText"` } `json:"message"` User struct { Name string `json:"name"` DisplayName string `json:"displayName"` AvatarURL string `json:"avatarUrl"` Email string `json:"email"` Type string `json:"type"` } `json:"user"` Space struct { Name string `json:"name"` Type string `json:"type"` DisplayName string `json:"displayName"` } `json:"space"` ConfigCompleteRedirectURL string `json:"configCompleteRedirectUrl"` } // ReplyThread is a part of reply messages type ReplyThread struct { Name string `json:"name,omitempty"` } // ReplyMessage is partial hangouts format of messages used // For details see // https://developers.google.com/hangouts/chat/reference/rest/v1/spaces.messages#Message type ReplyMessage struct { Text string `json:"text"` Thread *ReplyThread `json:"thread,omitempty"` }
go-chat-bot/bot
google-chat/chat_msg.go
GO
mit
1,746
/** * This is a "mini-app" that encapsulates router definitions. See more * at: http://expressjs.com/guide/routing.html (search for "express.Router") * */ var router = require('express').Router({ mergeParams: true }); module.exports = router; // Don't just use, but also export in case another module needs to use these as well. router.callbacks = require('./controllers/hello'); router.models = require('./models'); //-- For increased module encapsulation, you could also serve templates with module-local //-- paths, but using shared layouts and partials may become tricky / impossible //var hbs = require('hbs'); //app.set('views', __dirname + '/views'); //app.set('view engine', 'handlebars'); //app.engine('handlebars', hbs.__express); // Module's Routes. Please note this is actually under /hello, because module is attached under /hello router.get('/', router.callbacks.sayHello);
KalenAnson/nodebootstrap
lib/hello/hello.js
JavaScript
mit
903
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.action_mailer.default_url_options = { host: '127.0.0.1:3000' } end
kfrost32/AdventureAnswers
config/environments/development.rb
Ruby
mit
1,673
import WebhookNotification, { LinkClick, LinkClickCount, MessageTrackingData, WebhookDelta, WebhookObjectAttributes, WebhookObjectData, } from '../src/models/webhook-notification'; import { WebhookTriggers } from '../src/models/webhook'; describe('Webhook Notification', () => { test('Should deserialize from JSON properly', done => { const webhookNotificationJSON = { deltas: [ { date: 1602623196, object: 'message', type: 'message.created', object_data: { namespace_id: 'aaz875kwuvxik6ku7pwkqp3ah', account_id: 'aaz875kwuvxik6ku7pwkqp3ah', object: 'message', attributes: { action: 'save_draft', job_status_id: 'abc1234', thread_id: '2u152dt4tnq9j61j8seg26ni6', received_date: 1602623166, }, id: '93mgpjynqqu5fohl2dvv6ray7', metadata: { sender_app_id: 64280, link_data: [ { url: 'https://nylas.com/', count: 1, }, ], timestamp: 1602623966, recents: [ { ip: '24.243.155.85', link_index: 0, id: 0, user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', timestamp: 1602623980, }, ], message_id: '4utnziee7bu2ohak56wfxe39p', payload: 'Tracking enabled', }, }, }, ], }; const webhookNotification = new WebhookNotification().fromJSON( webhookNotificationJSON ); expect(webhookNotification.deltas.length).toBe(1); const webhookDelta = webhookNotification.deltas[0]; expect(webhookDelta instanceof WebhookDelta).toBe(true); expect(webhookDelta.date).toEqual(new Date(1602623196 * 1000)); expect(webhookDelta.object).toEqual('message'); expect(webhookDelta.type).toEqual(WebhookTriggers.MessageCreated); const webhookDeltaObjectData = webhookDelta.objectData; expect(webhookDeltaObjectData instanceof WebhookObjectData).toBe(true); expect(webhookDeltaObjectData.id).toEqual('93mgpjynqqu5fohl2dvv6ray7'); expect(webhookDeltaObjectData.accountId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.namespaceId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.object).toEqual('message'); const webhookDeltaObjectAttributes = webhookDeltaObjectData.objectAttributes; expect( webhookDeltaObjectAttributes instanceof WebhookObjectAttributes ).toBe(true); expect(webhookDeltaObjectAttributes.action).toEqual('save_draft'); expect(webhookDeltaObjectAttributes.jobStatusId).toEqual('abc1234'); expect(webhookDeltaObjectAttributes.threadId).toEqual( '2u152dt4tnq9j61j8seg26ni6' ); expect(webhookDeltaObjectAttributes.receivedDate).toEqual( new Date(1602623166 * 1000) ); const webhookMessageTrackingData = webhookDeltaObjectData.metadata; expect(webhookMessageTrackingData instanceof MessageTrackingData).toBe( true ); expect(webhookMessageTrackingData.messageId).toEqual( '4utnziee7bu2ohak56wfxe39p' ); expect(webhookMessageTrackingData.payload).toEqual('Tracking enabled'); expect(webhookMessageTrackingData.timestamp).toEqual( new Date(1602623966 * 1000) ); expect(webhookMessageTrackingData.senderAppId).toBe(64280); expect(webhookMessageTrackingData.linkData.length).toBe(1); expect(webhookMessageTrackingData.recents.length).toBe(1); const linkData = webhookMessageTrackingData.linkData[0]; expect(linkData instanceof LinkClickCount).toBe(true); expect(linkData.url).toEqual('https://nylas.com/'); expect(linkData.count).toBe(1); const recents = webhookMessageTrackingData.recents[0]; expect(recents instanceof LinkClick).toBe(true); expect(recents.id).toBe(0); expect(recents.ip).toEqual('24.243.155.85'); expect(recents.userAgent).toEqual( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ); expect(recents.timestamp).toEqual(new Date(1602623980 * 1000)); expect(recents.linkIndex).toBe(0); done(); }); });
nylas/nylas-nodejs
__tests__/webhook-notification-spec.js
JavaScript
mit
4,538
using HoloToolkit.Unity; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Networking; public class AuthorizationManager : Singleton<AuthorizationManager> { [SerializeField] private string clientId = "c4ced10f-ce0f-4155-b6f7-a4c40ffa410c"; private string clientSecret; [SerializeField] private string debugToken; private string accessToken; private string authorizationCode; const string learningLayersAuthorizationEndpoint = "https://api.learning-layers.eu/o/oauth2/authorize"; const string learningLayersTokenEndpoint = "https://api.learning-layers.eu/o/oauth2/token"; const string learningLayersUserInfoEndpoint = "https://api.learning-layers.eu/o/oauth2/userinfo"; const string scopes = "openid%20profile%20email"; const string gamrRedirectURI = "gamr://"; public string AccessToken { get { return accessToken; } } private void Start() { // skip the login by using the debug token if (Application.isEditor) { if (accessToken == null || accessToken == "") { accessToken = debugToken; AddAccessTokenToHeader(); RestManager.Instance.GET(learningLayersUserInfoEndpoint + "?access_token=" + accessToken, GetUserInfoForDebugToken); } } else // else: fetch the client secret { TextAsset secretAsset = (TextAsset)Resources.Load("values/client_secret"); clientSecret = secretAsset.text; } } private void GetUserInfoForDebugToken(UnityWebRequest req) { if (req.responseCode == 200) { string json = req.downloadHandler.text; Debug.Log(json); UserInfo info = JsonUtility.FromJson<UserInfo>(json); InformationManager.Instance.UserInfo = info; } else if (req.responseCode == 401) { Debug.LogError("Unauthorized: access token is wrong"); } } public void Login() { if (Application.isEditor) { SceneManager.LoadScene("Scene", LoadSceneMode.Single); return; } Application.OpenURL(learningLayersAuthorizationEndpoint + "?response_type=code&scope=" + scopes + "&client_id=" + clientId + "&redirect_uri=" + gamrRedirectURI); } public void Logout() { accessToken = ""; SceneManager.LoadScene("Login", LoadSceneMode.Single); } private void StartedByProtocol(Uri uri) { if (uri.Fragment != null) { char[] splitters = { '?', '&' }; string[] arguments = uri.AbsoluteUri.Split(splitters); foreach (string argument in arguments) { if (argument.StartsWith("code=")) { authorizationCode = argument.Replace("code=", ""); Debug.Log("authorizationCode: " + authorizationCode); // now exchange authorization code for access token RestManager.Instance.POST(learningLayersTokenEndpoint + "?code=" + authorizationCode + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + gamrRedirectURI + "&grant_type=authorization_code", (req) => { string json = req.downloadHandler.text; Debug.Log("Token json: " + json); AuthorizationFlowAnswer answer = JsonUtility.FromJson<AuthorizationFlowAnswer>(json); if (!string.IsNullOrEmpty(answer.error)) { MessageBox.Show(answer.error_description, MessageBoxType.ERROR); } else { // extract access token and check it accessToken = answer.access_token; Debug.Log("The access token is " + accessToken); AddAccessTokenToHeader(); CheckAccessToken(); } } ); break; } } } } private void AddAccessTokenToHeader() { if (RestManager.Instance.StandardHeader.ContainsKey("access_token")) { RestManager.Instance.StandardHeader["access_token"] = accessToken; } else { RestManager.Instance.StandardHeader.Add("access_token", accessToken); } } private void CheckAccessToken() { RestManager.Instance.GET(learningLayersUserInfoEndpoint + "?access_token=" + accessToken, OnLogin); } private void OnLogin(UnityWebRequest result) { if (result.responseCode == 200) { string json = result.downloadHandler.text; Debug.Log(json); UserInfo info = JsonUtility.FromJson<UserInfo>(json); InformationManager.Instance.UserInfo = info; GamificationFramework.Instance.ValidateLogin(LoginValidated); } else { MessageBox.Show(LocalizationManager.Instance.ResolveString("Error while retrieving the user data. Login failed"), MessageBoxType.ERROR); } } private void LoginValidated(UnityWebRequest req) { if (req.responseCode == 200) { SceneManager.LoadScene("Scene", LoadSceneMode.Single); } else if (req.responseCode == 401) { MessageBox.Show(LocalizationManager.Instance.ResolveString("The login could not be validated"), MessageBoxType.ERROR); } else { MessageBox.Show(LocalizationManager.Instance.ResolveString("An error concerning the user data occured. The login failed.\nCode: ") + req.responseCode + "\n" + req.downloadHandler.text, MessageBoxType.ERROR); } } }
rwth-acis/GaMR
Frontend/GaMR/Assets/Scripts/Login/AuthorizationManager.cs
C#
mit
6,336
/* * Copyright (C) 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.longluo.demo.qrcode.zxing.client.android.encode; /** * Encapsulates some simple formatting logic, to aid refactoring in {@link ContactEncoder}. * * @author Sean Owen */ interface Formatter { /** * @param value value to format * @param index index of value in a list of values to be formatted * @return formatted value */ CharSequence format(CharSequence value, int index); }
longluo/AndroidDemo
app/src/main/java/com/longluo/demo/qrcode/zxing/client/android/encode/Formatter.java
Java
mit
1,015
import deepFreeze from 'deep-freeze'; import { arrayToMap, mapKeysToArray } from './mapUtils'; describe('arrayToMap', () => { it('should create map from 2D array', () => { const a = [ ['key1', 'value1'], ['key2', 'value2'] ]; deepFreeze(a); const result = arrayToMap(a); expect(result.size).toBe(2); expect(result.get('key1')).toBe('value1'); expect(result.get('key2')).toBe('value2'); }); it('should create empty map from empty array', () => { const result = arrayToMap([]); expect(result.size).toBe(0); }); }); describe('mapKeysToArray', () => { it('should create array from map keys in order', () => { const map = new Map(); map.set('a', 'value1'); map.set('c', 'value2'); map.set('1', 'value3'); map.set('b', 'value4'); map.set('2', 'value5'); const result = mapKeysToArray(map); expect(result).toEqual(['a', 'c', '1', 'b', '2']); }); it('should create empty array from new map', () => { const map = new Map(); const result = mapKeysToArray(map); expect(result).toEqual([]); }); });
TrueWill/embracer
src/utils/mapUtils.test.js
JavaScript
mit
1,107
namespace SimShift.Data { public enum Ets2DataAuxilliary : int { CruiseControl = 0, Wipers = 1, ParkBrake = 2, MotorBrake = 3, ElectricEnabled = 4, EngineEnabled = 5, BlinkerLeftActive = 6, BlinkerRightActive = 7, BlinkerLeftOn = 8, BlinkerRightOn = 9, LightsParking = 10, LightsBeamLow = 11, LightsBeamHigh = 12, LightsAuxFront = 13, LightsAuxRoof = 14, LightsBeacon = 15, LightsBrake = 16, LightsReverse = 17, BatteryVoltageWarning = 18, AirPressureWarning = 19, AirPressureEmergency = 20, AdblueWarning = 21, OilPressureWarning = 22, WaterTemperatureWarning = 23, } }
zappybiby/SimShift
SimShift/SimShift/Data/Ets2DataAuxilliary.cs
C#
mit
797
<h2>This is my home page</h2> <p>some text here</p>
OrifInformatique/ci_tuto
application/views/pages/home.php
PHP
mit
51
/** * */ package com.kant.datastructure.queues; import com.kant.sortingnsearching.MyUtil; /** * @author shaskant * */ public class GenerateBinaryNumbers1toN { /** * * @param n * @return * @throws OverFlowException * @throws UnderFlowException */ public String[] solve(int n) throws OverFlowException, UnderFlowException { String[] result = new String[n]; System.out.println("input # " + n); Queue<String> dequeue = new QueueListImplementation<String>(); dequeue.enQueue("1"); for (int count = 0; count < n; count++) { result[count] = dequeue.deQueue(); dequeue.enQueue(result[count]+"0"); dequeue.enQueue(result[count]+"1"); } return result; } /** * * @param args * @throws OverFlowException * @throws UnderFlowException */ public static void main(String[] args) throws OverFlowException, UnderFlowException { GenerateBinaryNumbers1toN prob = new GenerateBinaryNumbers1toN(); System.out.print("output # "); MyUtil.printArrayType(prob.solve(10)); } }
thekant/myCodeRepo
src/com/kant/datastructure/queues/GenerateBinaryNumbers1toN.java
Java
mit
1,022
// Binary-search solution for balance. // O(n * log (max coordinate / epsilon)) // David Garcia Soriano. #include <algorithm> #include <cstdio> #include <cmath> using namespace std; const int maxn = 50000; const double eps = 1e-11, infinity = 1e300; double px[maxn], py[maxn]; int n; bool possible(double d, double& px1, double& px2) { double x1 = -infinity, x2 = infinity; for (int i = 0; i < n; ++i) { if (d < py[i]) return false; double p = sqrt(d * d - py[i] * py[i]), a = px[i] - p, b = px[i] + p; x1 = max(x1, a); x2 = min(x2, b); if (x1 > x2) return false; } px1 = x1; px2 = x2; return true; } int main() { while (scanf("%i", &n) == 1 && n > 0) { double a, b = 0, x1, x2; for (int i = 0; i < n; ++i) { scanf("%lf%lf", &px[i], &py[i]); if (py[i] < 0) py[i] = -py[i]; b = max(b, py[i]); } if (b == 0) { if (n == 1) { printf("%.9lf %.9lf\n", px[0], .0); continue; } b = 1; } while (!possible(b, x1, x2)) b *= 2; a = b / 2; while (possible(a, x1, x2)) a /= 2; for (int i = 0; i < 100 && (b - a > eps || x2 - x1 > eps); ++i) { double m = (a + b) / 2; if (possible(m, x1, x2)) b = m; else a = m; } printf("%.9lf %.9lf\n", (x1 + x2) / 2, b); } return 0; }
Emunt/contest_problems
Java/PC2/Solutions/TrickTreat/balance.cpp
C++
mit
1,320
require 'log4r' module VagrantPlugins module G5K module Network class Nat def initialize(env, driver, oar_driver) @logger = Log4r::Logger.new("vagrant::network::nat") # command driver is unused @env = env @driver = driver @oar_driver = oar_driver @net = env[:machine].provider_config.net end def generate_net() fwd_ports = @net[:ports].map do |p| "hostfwd=tcp::#{p}" end.join(',') net = "-net nic,model=virtio -net user,#{fwd_ports}" @logger.debug("Generated net string : #{net}") return "NAT #{net}" end def check_state(job_id) return nil end def attach() # noop end def detach() # noop end def vm_ssh_info(vmid) # get forwarded port 22 ports = @net[:ports] ssh_fwd = ports.select{ |x| x.split(':')[1] == '22'}.first if ssh_fwd.nil? @env[:ui].error "SSH port 22 must be forwarded" raise Error "SSh port 22 isn't forwarded" end ssh_fwd = ssh_fwd.split('-:')[0] # get node hosting the vm job = @oar_driver.check_job(@env[:machine].id) ssh_info = { :host => job["assigned_network_address"].first, :port => ssh_fwd } @logger.debug(ssh_info) ssh_info end end end end end
msimonin/vagrant-g5k
lib/vagrant-g5k/network/nat.rb
Ruby
mit
1,523
<?php namespace Gitlab\Clients; class DeployKeyClient extends AbstractClient { /** * @param int $projectId * @return \Psr\Http\Message\ResponseInterface */ public function listDeployKeys($projectId) { return $this->getRequest(sprintf('projects/%u/keys', $projectId)); } /** * @param int $projectId * @param int $keyId * @return \Psr\Http\Message\ResponseInterface */ public function getDeployKey($projectId, $keyId) { return $this->getRequest(sprintf('projects/%u/keys/%u', $projectId, $keyId)); } /** * @param int $projectId * @param array|null $data * @return \Psr\Http\Message\ResponseInterface */ public function createDeployKey($projectId, array $data = null) { return $this->postRequest(sprintf('projects/%u/keys', $projectId), $data); } /** * @param int $projectId * @param int $keyId * @return \Psr\Http\Message\ResponseInterface */ public function deleteDeployKey($projectId, $keyId) { return $this->deleteRequest(sprintf('projects/%u/keys/%u', $projectId, $keyId)); } }
AlexKovalevych/gitlab-api
src/Clients/DeployKeyClient.php
PHP
mit
1,173
from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text="Enter your post if you hold one. If not, enter 'Member'") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False)
compsoc-ssc/compsocssc
general/models.py
Python
mit
2,517
import complexism as cx import complexism.agentbased.statespace as ss import epidag as dag dbp = cx.read_dbp_script(cx.load_txt('../scripts/SIR_BN.txt')) pc = dag.quick_build_parameter_core(cx.load_txt('../scripts/pSIR.txt')) dc = dbp.generate_model('M1', **pc.get_samplers()) ag = ss.StSpAgent('Helen', dc['Sus'], pc) model = cx.SingleIndividualABM('M1', ag) model.add_observing_attribute('State') print(cx.simulate(model, None, 0, 10, 1))
TimeWz667/Kamanian
example/OOP/O2.4 SS, Single agent model.py
Python
mit
446
from __future__ import division, print_function from abc import ABCMeta, abstractmethod import matplotlib as mpl mpl.use('TkAgg') from matplotlib.ticker import MaxNLocator, Formatter, Locator from matplotlib.widgets import Slider, Button import matplotlib.patches as patches import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from tadtool.tad import GenomicRegion, sub_matrix_regions, sub_data_regions, \ data_array, insulation_index, sub_vector_regions, sub_regions, \ call_tads_insulation_index, directionality_index, call_tads_directionality_index, normalised_insulation_index import math import copy import numpy as np from bisect import bisect_left from future.utils import string_types try: import Tkinter as tk import tkFileDialog as filedialog except ImportError: import tkinter as tk from tkinter import filedialog class BasePlotter(object): __metaclass__ = ABCMeta def __init__(self, title): self._ax = None self.cax = None self.title = title @abstractmethod def _plot(self, region=None, **kwargs): raise NotImplementedError("Subclasses need to override _plot function") @abstractmethod def plot(self, region=None, **kwargs): raise NotImplementedError("Subclasses need to override plot function") @property def fig(self): return self._ax.figure @property def ax(self): if not self._ax: _, self._ax = plt.subplots() return self._ax @ax.setter def ax(self, value): self._ax = value class GenomeCoordFormatter(Formatter): """ Process axis tick labels to give nice representations of genomic coordinates """ def __init__(self, chromosome, display_scale=True): """ :param chromosome: :class:`~kaic.data.genomic.GenomicRegion` or string :param display_scale: Boolean Display distance scale at bottom right """ if isinstance(chromosome, GenomicRegion): self.chromosome = chromosome.chromosome else: self.chromosome = chromosome self.display_scale = display_scale def _format_val(self, x, prec_offset=0): if x == 0: oom_loc = 0 else: oom_loc = int(math.floor(math.log10(abs(x)))) view_range = self.axis.axes.get_xlim() oom_range = int(math.floor(math.log10(abs(view_range[1] - view_range[0])))) if oom_loc >= 3: return "{:.{prec}f}kb".format(x/1000, prec=max(0, 3 + prec_offset - oom_range)) return "{:.0f}b".format(x) def __call__(self, x, pos=None): """ Return label for tick at coordinate x. Relative position of ticks can be specified with pos. First tick gets chromosome name. """ s = self._format_val(x, prec_offset=1) if pos == 0 or x == 0: return "{}:{}".format(self.chromosome, s) return s def get_offset(self): """ Return information about the distances between tick bars and the size of the view window. Is called by matplotlib and displayed in lower right corner of plots. """ if not self.display_scale: return "" view_range = self.axis.axes.get_xlim() view_dist = abs(view_range[1] - view_range[0]) tick_dist = self.locs[2] - self.locs[1] minor_tick_dist = tick_dist/5 minor_tick_dist_str = self._format_val(minor_tick_dist, prec_offset=2) tick_dist_str = self._format_val(tick_dist, prec_offset=1) view_dist_str = self._format_val(view_dist) return "{}|{}|{}".format(minor_tick_dist_str, tick_dist_str, view_dist_str) class GenomeCoordLocator(MaxNLocator): """ Choose locations of genomic coordinate ticks on the plot axis. Behaves like default Matplotlib locator, except that it always places a tick at the start and the end of the window. """ def __call__(self): vmin, vmax = self.axis.get_view_interval() ticks = self.tick_values(vmin, vmax) # Make sure that first and last tick are the start # and the end of the genomic range plotted. If next # ticks are too close, remove them. ticks[0] = vmin ticks[-1] = vmax if ticks[1] - vmin < (vmax - vmin)/(self._nbins*3): ticks = np.delete(ticks, 1) if vmax - ticks[-2] < (vmax - vmin)/(self._nbins*3): ticks = np.delete(ticks, -2) return self.raise_if_exceeds(np.array(ticks)) class MinorGenomeCoordLocator(Locator): """ Choose locations of minor tick marks between major tick labels. Modification of the Matplotlib AutoMinorLocator, except that it uses the distance between 2nd and 3rd major mark as reference, instead of 2nd and 3rd. """ def __init__(self, n): self.ndivs = n def __call__(self): majorlocs = self.axis.get_majorticklocs() try: majorstep = majorlocs[2] - majorlocs[1] except IndexError: # Need at least two major ticks to find minor tick locations # TODO: Figure out a way to still be able to display minor # ticks without two major ticks visible. For now, just display # no ticks at all. majorstep = 0 if self.ndivs is None: if majorstep == 0: # TODO: Need a better way to figure out ndivs ndivs = 1 else: x = int(np.round(10 ** (np.log10(majorstep) % 1))) if x in [1, 5, 10]: ndivs = 5 else: ndivs = 4 else: ndivs = self.ndivs minorstep = majorstep / ndivs vmin, vmax = self.axis.get_view_interval() if vmin > vmax: vmin, vmax = vmax, vmin if len(majorlocs) > 0: t0 = majorlocs[1] tmin = ((vmin - t0) // minorstep + 1) * minorstep tmax = ((vmax - t0) // minorstep + 1) * minorstep locs = np.arange(tmin, tmax, minorstep) + t0 cond = np.abs((locs - t0) % majorstep) > minorstep / 10.0 locs = locs.compress(cond) else: locs = [] return self.raise_if_exceeds(np.array(locs)) class BasePlotter1D(BasePlotter): __metaclass__ = ABCMeta def __init__(self, title): BasePlotter.__init__(self, title=title) def plot(self, region=None, ax=None, **kwargs): if isinstance(region, string_types): region = GenomicRegion.from_string(region) if ax: self.ax = ax # set genome tick formatter self.ax.xaxis.set_major_formatter(GenomeCoordFormatter(region)) self.ax.xaxis.set_major_locator(GenomeCoordLocator(nbins=5)) self.ax.xaxis.set_minor_locator(MinorGenomeCoordLocator(n=5)) self.ax.set_title(self.title) self._plot(region, **kwargs) self.ax.set_xlim(region.start, region.end) return self.fig, self.ax def prepare_normalization(norm="lin", vmin=None, vmax=None): if isinstance(norm, mpl.colors.Normalize): norm.vmin = vmin norm.vmax = vmax return norm if norm == "log": return mpl.colors.LogNorm(vmin=vmin, vmax=vmax) elif norm == "lin": return mpl.colors.Normalize(vmin=vmin, vmax=vmax) else: raise ValueError("'{}'' not a valid normalization method.".format(norm)) class BasePlotterHic(object): __metaclass__ = ABCMeta def __init__(self, hic_matrix, regions=None, colormap='RdBu', norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): if regions is None: for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.hic_matrix = hic_matrix self.colormap = copy.copy(mpl.cm.get_cmap(colormap)) if blend_masked: self.colormap.set_bad(self.colormap(0)) self._vmin = vmin self._vmax = vmax self.norm = prepare_normalization(norm=norm, vmin=vmin, vmax=vmax) self.colorbar = None self.slider = None self.show_colorbar = show_colorbar def add_colorbar(self, ax=None): ax = self.cax if ax is None else ax cmap_data = mpl.cm.ScalarMappable(norm=self.norm, cmap=self.colormap) cmap_data.set_array([self.vmin, self.vmax]) self.colorbar = plt.colorbar(cmap_data, cax=ax, orientation="vertical") @property def vmin(self): return self._vmin if self._vmin else np.nanmin(self.hic_matrix) @property def vmax(self): return self._vmax if self._vmax else np.nanmax(self.hic_matrix) class HicPlot(BasePlotter1D, BasePlotterHic): def __init__(self, hic_matrix, regions=None, title='', colormap='viridis', max_dist=None, norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): BasePlotter1D.__init__(self, title=title) BasePlotterHic.__init__(self, hic_matrix, regions=regions, colormap=colormap, vmin=vmin, vmax=vmax, show_colorbar=show_colorbar, norm=norm, blend_masked=blend_masked) self.max_dist = max_dist self.hicmesh = None def _plot(self, region=None, cax=None): if region is None: raise ValueError("Cannot plot triangle plot for whole genome.") hm, sr = sub_matrix_regions(self.hic_matrix, self.regions, region) hm[np.tril_indices(hm.shape[0])] = np.nan # Remove part of matrix further away than max_dist if self.max_dist is not None: for i in range(hm.shape[0]): i_region = sr[i] for j in range(hm.shape[1]): j_region = sr[j] if j_region.start-i_region.end > self.max_dist: hm[i, j] = np.nan hm_masked = np.ma.MaskedArray(hm, mask=np.isnan(hm)) # prepare an array of the corner coordinates of the Hic-matrix # Distances have to be scaled by sqrt(2), because the diagonals of the bins # are sqrt(2)*len(bin_size) sqrt2 = math.sqrt(2) bin_coords = np.r_[[(x.start - 1) for x in sr], sr[-1].end]/sqrt2 X, Y = np.meshgrid(bin_coords, bin_coords) # rotatate coordinate matrix 45 degrees sin45 = math.sin(math.radians(45)) X_, Y_ = X*sin45 + Y*sin45, X*sin45 - Y*sin45 # shift x coords to correct start coordinate and center the diagonal directly on the # x-axis X_ -= X_[1, 0] - (sr[0].start - 1) Y_ -= .5*np.min(Y_) + .5*np.max(Y_) # create plot self.hicmesh = self.ax.pcolormesh(X_, Y_, hm_masked, cmap=self.colormap, norm=self.norm) # set limits and aspect ratio #self.ax.set_aspect(aspect="equal") ylim_max = 0.5*(region.end-region.start) if self.max_dist is not None and self.max_dist/2 < ylim_max: ylim_max = self.max_dist/2 self.ax.set_ylim(0, ylim_max) # remove y ticks self.ax.set_yticks([]) # hide background patch self.ax.patch.set_visible(False) if self.show_colorbar: self.add_colorbar(cax) def set_clim(self, vmin, vmax): self.hicmesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.colorbar.vmax = vmax self.colorbar.draw_all() class DataArrayPlot(BasePlotter1D): def __init__(self, data, window_sizes=None, regions=None, title='', midpoint=None, colormap='coolwarm_r', vmax=None, current_window_size=0, log_y=True): if regions is None: regions = [] for i in range(data.shape[1]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions BasePlotter1D.__init__(self, title=title) self.da = data if window_sizes is None: window_sizes = [] try: l = len(data) except TypeError: l = data.shape[0] for i in range(l): window_sizes.append(i) self.window_sizes = window_sizes self.colormap = colormap self.midpoint = midpoint self.mesh = None self.vmax = vmax self.window_size_line = None self.current_window_size = current_window_size self.log_y = log_y def _plot(self, region=None, cax=None): da_sub, regions_sub = sub_data_regions(self.da, self.regions, region) da_sub_masked = np.ma.MaskedArray(da_sub, mask=np.isnan(da_sub)) bin_coords = np.r_[[(x.start - 1) for x in regions_sub], regions_sub[-1].end] x, y = np.meshgrid(bin_coords, self.window_sizes) self.mesh = self.ax.pcolormesh(x, y, da_sub_masked, cmap=self.colormap, vmax=self.vmax) self.colorbar = plt.colorbar(self.mesh, cax=cax, orientation="vertical") self.window_size_line = self.ax.axhline(self.current_window_size, color='red') if self.log_y: self.ax.set_yscale("log") self.ax.set_ylim((np.nanmin(self.window_sizes), np.nanmax(self.window_sizes))) def set_clim(self, vmin, vmax): self.mesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.colorbar.vmax = vmax self.colorbar.draw_all() def update(self, window_size): self.window_size_line.set_ydata(window_size) class TADPlot(BasePlotter1D): def __init__(self, regions, title='', color='black'): BasePlotter1D.__init__(self, title=title) self.regions = regions self.color = color self.current_region = None def _plot(self, region=None, cax=None): self.current_region = region try: sr, start_ix, end_ix = sub_regions(self.regions, region) trans = self.ax.get_xaxis_transform() for r in sr: region_patch = patches.Rectangle( (r.start, .2), width=abs(r.end - r.start), height=.6, transform=trans, facecolor=self.color, edgecolor='white', linewidth=2. ) self.ax.add_patch(region_patch) except ValueError: pass self.ax.axis('off') def update(self, regions): self.regions = regions self.ax.cla() self.plot(region=self.current_region, ax=self.ax) class DataLinePlot(BasePlotter1D): def __init__(self, data, regions=None, title='', init_row=0, is_symmetric=False): BasePlotter1D.__init__(self, title=title) if regions is None: regions = [] for i in range(len(data)): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.init_row = init_row self.data = data self.sr = None self.da_sub = None self.regions = regions self.current_region = None self.line = None self.current_ix = init_row self.current_cutoff = None self.cutoff_line = None self.cutoff_line_mirror = None self.is_symmetric = is_symmetric def _new_region(self, region): self.current_region = region self.da_sub, self.sr = sub_data_regions(self.data, self.regions, region) def _plot(self, region=None, cax=None): self._new_region(region) bin_coords = [(x.start - 1) for x in self.sr] ds = self.da_sub[self.init_row] self.line, = self.ax.plot(bin_coords, ds) if not self.is_symmetric: self.current_cutoff = (self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) / 2 + self.ax.get_ylim()[0] else: self.current_cutoff = self.ax.get_ylim()[1]/ 2 self.ax.axhline(0.0, linestyle='dashed', color='grey') self.cutoff_line = self.ax.axhline(self.current_cutoff, color='r') if self.is_symmetric: self.cutoff_line_mirror = self.ax.axhline(-1*self.current_cutoff, color='r') self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds))) def update(self, ix=None, cutoff=None, region=None, update_canvas=True): if region is not None: self._new_region(region) if ix is not None and ix != self.current_ix: ds = self.da_sub[ix] self.current_ix = ix self.line.set_ydata(ds) self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds))) if cutoff is None: if not self.is_symmetric: self.update(cutoff=(self.ax.get_ylim()[1]-self.ax.get_ylim()[0])/2 + self.ax.get_ylim()[0], update_canvas=False) else: self.update(cutoff=self.ax.get_ylim()[1] / 2, update_canvas=False) if update_canvas: self.fig.canvas.draw() if cutoff is not None and cutoff != self.current_cutoff: if self.is_symmetric: self.current_cutoff = abs(cutoff) else: self.current_cutoff = cutoff self.cutoff_line.set_ydata(self.current_cutoff) if self.is_symmetric: self.cutoff_line_mirror.set_ydata(-1*self.current_cutoff) if update_canvas: self.fig.canvas.draw() class TADtoolPlot(object): def __init__(self, hic_matrix, regions=None, data=None, window_sizes=None, norm='lin', max_dist=3000000, max_percentile=99.99, algorithm='insulation', matrix_colormap=None, data_colormap=None, log_data=True): self.hic_matrix = hic_matrix if regions is None: regions = [] for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.norm = norm self.fig = None self.max_dist = max_dist self.algorithm = algorithm self.svmax = None self.min_value = np.nanmin(self.hic_matrix[np.nonzero(self.hic_matrix)]) self.min_value_data = None self.hic_plot = None self.tad_plot = None self.data_plot = None self.line_plot = None self.sdata = None self.data_ax = None self.line_ax = None self.da = None self.ws = None self.current_window_size = None self.window_size_text = None self.tad_cutoff_text = None self.max_percentile = max_percentile self.tad_regions = None self.current_da_ix = None self.button_save_tads = None self.button_save_vector = None self.button_save_matrix = None self.log_data = log_data if algorithm == 'insulation': self.tad_algorithm = insulation_index self.tad_calling_algorithm = call_tads_insulation_index self.is_symmetric = False if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = 'plasma' elif algorithm == 'ninsulation': self.tad_algorithm = normalised_insulation_index self.tad_calling_algorithm = call_tads_insulation_index self.is_symmetric = True if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = LinearSegmentedColormap.from_list('myreds', ['blue', 'white', 'red']) elif algorithm == 'directionality': self.tad_algorithm = directionality_index self.tad_calling_algorithm = call_tads_directionality_index self.is_symmetric = True if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = LinearSegmentedColormap.from_list('myreds', ['blue', 'white', 'red']) if data is None: self.da, self.ws = data_array(hic_matrix=self.hic_matrix, regions=self.regions, tad_method=self.tad_algorithm, window_sizes=window_sizes) else: self.da = data if window_sizes is None: raise ValueError("window_sizes parameter cannot be None when providing data!") self.ws = window_sizes def vmax_slider_update(self, val): self.hic_plot.set_clim(self.min_value, val) def data_slider_update(self, val): if self.is_symmetric: self.data_plot.set_clim(-1*val, val) else: self.data_plot.set_clim(self.min_value_data, val) def on_click_save_tads(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: with open(save_path, 'w') as o: for region in self.tad_regions: o.write("%s\t%d\t%d\n" % (region.chromosome, region.start-1, region.end)) def on_click_save_vector(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: da_sub = self.da[self.current_da_ix] with open(save_path, 'w') as o: for i, region in enumerate(self.regions): o.write("%s\t%d\t%d\t.\t%e\n" % (region.chromosome, region.start-1, region.end, da_sub[i])) def on_click_save_matrix(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: with open(save_path, 'w') as o: # write regions for i, region in enumerate(self.regions): o.write("%s:%d-%d" % (region.chromosome, region.start-1, region.end)) if i < len(self.regions)-1: o.write("\t") else: o.write("\n") # write matrix n_rows = self.da.shape[0] n_cols = self.da.shape[1] for i in range(n_rows): window_size = self.ws[i] o.write("%d\t" % window_size) for j in range(n_cols): o.write("%e" % self.da[i, j]) if j < n_cols-1: o.write("\t") else: o.write("\n") def plot(self, region=None): # set up plotting grid self.fig = plt.figure(figsize=(10, 10)) # main plots grid_size = (32, 15) hic_vmax_slider_ax = plt.subplot2grid(grid_size, (0, 0), colspan=13) hic_ax = plt.subplot2grid(grid_size, (1, 0), rowspan=9, colspan=13) hp_cax = plt.subplot2grid(grid_size, (1, 14), rowspan=9, colspan=1) tad_ax = plt.subplot2grid(grid_size, (10, 0), rowspan=1, colspan=13, sharex=hic_ax) line_ax = plt.subplot2grid(grid_size, (12, 0), rowspan=6, colspan=13, sharex=hic_ax) line_cax = plt.subplot2grid(grid_size, (12, 13), rowspan=6, colspan=2) data_vmax_slider_ax = plt.subplot2grid(grid_size, (19, 0), colspan=13) data_ax = plt.subplot2grid(grid_size, (20, 0), rowspan=9, colspan=13, sharex=hic_ax) da_cax = plt.subplot2grid(grid_size, (20, 14), rowspan=9, colspan=1) # buttons save_tads_ax = plt.subplot2grid(grid_size, (31, 0), rowspan=1, colspan=4) self.button_save_tads = Button(save_tads_ax, 'Save TADs') self.button_save_tads.on_clicked(self.on_click_save_tads) save_vector_ax = plt.subplot2grid(grid_size, (31, 5), rowspan=1, colspan=4) self.button_save_vector = Button(save_vector_ax, 'Save current values') self.button_save_vector.on_clicked(self.on_click_save_vector) save_matrix_ax = plt.subplot2grid(grid_size, (31, 10), rowspan=1, colspan=4) self.button_save_matrix = Button(save_matrix_ax, 'Save matrix') self.button_save_matrix.on_clicked(self.on_click_save_matrix) # add subplot content max_value = np.nanpercentile(self.hic_matrix, self.max_percentile) init_value = .2*max_value # HI-C VMAX SLIDER self.svmax = Slider(hic_vmax_slider_ax, 'vmax', self.min_value, max_value, valinit=init_value, color='grey') self.svmax.on_changed(self.vmax_slider_update) # HI-C self.hic_plot = HicPlot(self.hic_matrix, self.regions, max_dist=self.max_dist, norm=self.norm, vmax=init_value, vmin=self.min_value, colormap=self.matrix_colormap) self.hic_plot.plot(region, ax=hic_ax, cax=hp_cax) # generate data array self.min_value_data = np.nanmin(self.da[np.nonzero(self.da)]) max_value_data = np.nanpercentile(self.da, self.max_percentile) init_value_data = .5*max_value_data # LINE PLOT da_ix = int(self.da.shape[0]/2) self.current_da_ix = da_ix self.line_plot = DataLinePlot(self.da, regions=self.regions, init_row=da_ix, is_symmetric=self.is_symmetric) self.line_plot.plot(region, ax=line_ax) self.line_ax = line_ax # line info self.current_window_size = self.ws[da_ix] line_cax.text(.1, .8, 'Window size', fontweight='bold') self.window_size_text = line_cax.text(.3, .6, str(self.current_window_size)) line_cax.text(.1, .4, 'TAD cutoff', fontweight='bold') self.tad_cutoff_text = line_cax.text(.3, .2, "%.5f" % self.line_plot.current_cutoff) line_cax.axis('off') # TAD PLOT self.tad_regions = self.tad_calling_algorithm(self.da[da_ix], self.line_plot.current_cutoff, self.regions) self.tad_plot = TADPlot(self.tad_regions) self.tad_plot.plot(region=region, ax=tad_ax) # DATA ARRAY self.data_plot = DataArrayPlot(self.da, self.ws, self.regions, vmax=init_value_data, colormap=self.data_plot_color, current_window_size=self.ws[da_ix], log_y=self.log_data) self.data_plot.plot(region, ax=data_ax, cax=da_cax) # DATA ARRAY SLIDER if self.is_symmetric: self.sdata = Slider(data_vmax_slider_ax, 'vmax', 0.0, max_value_data, valinit=init_value_data, color='grey') else: self.sdata = Slider(data_vmax_slider_ax, 'vmax', self.min_value_data, max_value_data, valinit=init_value_data, color='grey') self.sdata.on_changed(self.data_slider_update) self.data_slider_update(init_value_data) # clean up hic_ax.xaxis.set_visible(False) line_ax.xaxis.set_visible(False) # enable hover self.data_ax = data_ax cid = self.fig.canvas.mpl_connect('button_press_event', self.on_click) return self.fig, (hic_vmax_slider_ax, hic_ax, line_ax, data_ax, hp_cax, da_cax) def on_click(self, event): if event.inaxes == self.data_ax or event.inaxes == self.line_ax: if event.inaxes == self.data_ax: ws_ix = bisect_left(self.ws, event.ydata) self.current_window_size = self.ws[ws_ix] self.current_da_ix = ws_ix self.data_plot.update(window_size=self.ws[ws_ix]) self.line_plot.update(ix=ws_ix, update_canvas=False) self.tad_cutoff_text.set_text("%.5f" % self.line_plot.current_cutoff) self.window_size_text.set_text(str(self.current_window_size)) elif event.inaxes == self.line_ax: if self.is_symmetric: self.line_plot.update(cutoff=abs(event.ydata), update_canvas=False) else: self.line_plot.update(cutoff=abs(event.ydata), update_canvas=False) self.tad_cutoff_text.set_text("%.5f" % self.line_plot.current_cutoff) # update TADs self.tad_regions = self.tad_calling_algorithm(self.da[self.current_da_ix], self.line_plot.current_cutoff, self.regions) self.tad_plot.update(self.tad_regions) self.fig.canvas.draw()
vaquerizaslab/tadtool
tadtool/plot.py
Python
mit
28,848
<?php /** * Namesilo DNS Management * * @copyright Copyright (c) 2013, Phillips Data, Inc. * @license http://opensource.org/licenses/mit-license.php MIT License * @package namesilo.commands */ class NamesiloDomainsDns { /** * @var NamesiloApi */ private $api; /** * Sets the API to use for communication * * @param NamesiloApi $api The API to use for communication */ public function __construct(NamesiloApi $api) { $this->api = $api; } /** * Sets domain to use our default DNS servers. Required for free services * like Host record management, URL forwarding, email forwarding, dynamic * dns and other value added services. * * @param array $vars An array of input params including: * - SLD SLD of the DomainName * - TLD TLD of the DomainName * @return NamesiloResponse */ public function setDefault(array $vars) { return $this->api->submit("namesilo.domains.dns.setDefault", $vars); } /** * Sets domain to use custom DNS servers. NOTE: Services like URL forwarding, * Email forwarding, Dynamic DNS will not work for domains using custom * nameservers. * * https://www.namesilo.com/api_reference.php#changeNameServers */ public function setCustom(array $vars) { return $this->api->submit("changeNameServers", $vars); } /** * Gets a list of DNS servers associated with the requested domain. * * https://www.namesilo.com/api_reference.php#getDomainInfo */ public function getList(array $vars) { return $this->api->submit("getDomainInfo", $vars); } /** * Retrieves DNS host record settings for the requested domain. * * https://www.namesilo.com/api_reference.php#dnsListRecords */ public function getHosts(array $vars) { return $this->api->submit("dnsListRecords", $vars); } /** * Sets DNS host records settings for the requested domain. * * https://www.namesilo.com/api_reference.php#dnsAddRecord */ public function setHosts(array $vars) { return $this->api->submit("dnsAddRecord", $vars); } /** * Gets email forwarding settings for the requested domain. * * https://www.namesilo.com/api_reference.php#listEmailForwards */ public function getEmailForwarding(array $vars) { return $this->api->submit("listEmailForwards", $vars); } /** * Sets email forwarding for a domain name. * * https://www.namesilo.com/api_reference.php#configureEmailForward */ public function setEmailForwarding(array $vars) { return $this->api->submit("configureEmailForward", $vars); } } ?>
mrrsm/Blesta-Namesilo
apis/commands/domains_dns.php
PHP
mit
2,513
namespace Pioneer.Blog.Models { public class Contact { public int ContactId { get; set; } public string Email { get; set; } } }
PioneerCode/pioneer-blog
src/Pioneer.Blog/Models/Contact.cs
C#
mit
159
package com.baomidou.hibernateplus.spring.vo; import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.baomidou.hibernateplus.entity.Convert; /** * <p> * Vdemo * </p> * * @author Caratacus * @date 2016-12-2 */ public class Vdemo extends Convert implements Serializable { protected Long id; private String demo1; private String demo2; private String demo3; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDemo1() { return demo1; } public void setDemo1(String demo1) { this.demo1 = demo1; } public String getDemo2() { return demo2; } public void setDemo2(String demo2) { this.demo2 = demo2; } public String getDemo3() { return demo3; } public void setDemo3(String demo3) { this.demo3 = demo3; } }
baomidou/hibernate-plus
hibernate-plus/src/test/java/com/baomidou/hibernateplus/spring/vo/Vdemo.java
Java
mit
1,066
import cProfile from pathlib import Path def main(args, results_dir: Path, scenario_dir: Path): try: scenario_dir.mkdir(parents=True) except FileExistsError: pass cProfile.runctx( 'from dmprsim.scenarios.python_profile import main;' 'main(args, results_dir, scenario_dir)', globals=globals(), locals=locals(), filename=str(results_dir / 'profile.pstats'), )
reisub-de/dmpr-simulator
dmprsim/analyze/profile_core.py
Python
mit
432
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace Trafikverket.NET { /// <summary> /// Timetable information, represents a single train at a location /// </summary> public class TrainAnnouncement { /// <summary> /// Get ObjectType as string /// </summary> public static string ObjectTypeName { get { return "TrainAnnouncement"; } } /// <summary> /// Get or set unique id for the activity /// </summary> [XmlElement("ActivityId")] public string ActivityId { get; set; } /// <summary> /// Get or set type of activity, either "Ankomst" or "Angang" /// </summary> [XmlElement("ActivityType")] public string ActivityType { get; set; } /// <summary> /// Get or set if the activity is advertised in the time table /// </summary> [XmlElement("Advertised")] public bool Advertised { get; set; } /// <summary> /// Get or set advertised time in time table /// </summary> [XmlElement("AdvertisedTimeAtLocation")] public DateTime AdvertisedTimeAtLocation { get; set; } /// <summary> /// Get or set announced train number /// </summary> [XmlElement("AdvertisedTrainIdent")] public string AdvertisedTrainIdent { get; set; } /// <summary> /// Get or set booking information, e.g. "Vagn 4 obokad" /// </summary> [XmlElement("Booking")] public List<string> Booking { get; set; } /// <summary> /// Get or set if the activity is cancelled /// </summary> [XmlElement("Canceled")] public bool Canceled { get; set; } /// <summary> /// Get or set if this data post has been deleted /// </summary> [XmlElement("Deleted")] public bool Deleted { get; set; } /// <summary> /// Get or set possible deviation texts, e.g. "Buss ersätter" /// </summary> [XmlElement("Deviation")] public List<string> Deviation { get; set; } /// <summary> /// Get or set estimated time for arrival or departure /// </summary> [XmlElement("EstimatedTimeAtLocation")] public DateTime? EstimatedTimeAtLocation { get; set; } /// <summary> /// Get or set if the estimated time is preliminary /// </summary> [XmlElement("EstimatedTimeIsPreliminary")] public bool EstimatedTimeIsPreliminary { get; set; } /// <summary> /// Get or set from stations, sorted by order and priority to be displayed /// </summary> [XmlElement("FromLocation")] public List<string> FromLocation { get; set; } /// <summary> /// Get or set name of traffic information owner /// </summary> [XmlElement("InformationOwner")] public string InformationOwner { get; set; } /// <summary> /// Get or set signature for the station /// </summary> [XmlElement("LocationSignature")] public string LocationSignature { get; set; } /// <summary> /// Get or set url to traffic owners mobile website /// </summary> [XmlElement("MobileWebLink")] public string MobileWebLink { get; set; } /// <summary> /// Get or set modified time for this data post /// </summary> [XmlElement("ModifiedTime")] public DateTime Modified { get; set; } /// <summary> /// Get or set other announcement text, e.g. "Trevlig resa!", "Ingen påstigning", etc. /// </summary> [XmlElement("OtherInformation")] public List<string> OtherInformation { get; set; } /// <summary> /// Get or set description of the train, e.g. "Tågkompaniet", "SJ", "InterCity" etc. /// </summary> [XmlElement("ProductInformation")] public List<string> ProductInformation { get; set; } /// <summary> /// Get or set announced departure date /// </summary> [XmlElement("ScheduledDepartureDateTime")] public DateTime? ScheduledDeparture { get; set; } /// <summary> /// Get or set additional product information, e.g. "Bistro" etc. /// </summary> [XmlElement("Service")] public List<string> Service { get; set; } /// <summary> /// Get or set when train arrived or departed /// </summary> [XmlElement("TimeAtLocation")] public DateTimeOffset TimeAtLocation { get; set; } /// <summary> /// Get or set to locations, in order after priority in which to be displayed /// </summary> [XmlElement("ToLocation")] public List<string> ToLocation { get; set; } /// <summary> /// Get or set track at the station /// </summary> [XmlElement("TrackAtLocation")] public string TrackAtLocation { get; set; } /// <summary> /// Get or set train compisition, e.g. "Vagnsordning 7, 6, 5, 4, 2, 1" /// </summary> [XmlElement("TrainComposition")] public List<string> TrainComposition { get; set; } /// <summary> /// Get or set type of traffic, values "Tåg", "Direktbuss", "Extrabuss", "Ersättningsbuss", or "Taxi". /// </summary> [XmlElement("TypeOfTraffic")] public string TypeOfTraffic { get; set; } /// <summary> /// Get or set url to traffic owners website /// </summary> [XmlElement("WebLink")] public string WebLink { get; set; } } }
mrjfalk/Trafikverket.NET
src/Trafikverket.NET/Responses/DataModels/TrainAnnouncement.cs
C#
mit
5,935
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pasteurizer : Clickable { [SerializeField] private Transform positionMark; private Vector3 initial; [SerializeField] private GameObject milkObject; public override void OnStart() { base.OnStart(); initial = transform.position; } public void Show() { StartCoroutine(Coroutines.AnimatePosition(gameObject, positionMark.position, 20f)); } public void Hide() { StartCoroutine(Coroutines.AnimatePosition(gameObject, initial, 20f)); } public void MilkDragged() { GetComponent<Animator>().Play("barn_pasturiserWorking"); AkSoundEngine.PostEvent("PasturisingMachine", gameObject); } public void OnWorkingAnimationEnd() { milkObject.SetActive(true); } }
TeamTorchBear/Guzzlesaurus
Assets/Scripts/Barn/Pasteurizer.cs
C#
mit
872
require('./node') require('./console')
Jam3/hihat
lib/prelude/node-console.js
JavaScript
mit
39
/* * Author: Brendan Le Foll <brendan.le.foll@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var m = require("mraa") console.log("mraa version: " + m.getVersion()); var x = new m.Gpio(8) x.dir(m.DIR_OUT) x.write(1)
rwaldron/mraa
examples/javascript/example.js
JavaScript
mit
1,305
<?php $view->extend('EmVistaBundle::base.html.php'); ?> <?php $view['slots']->start('body') ?> <div class="container"> <form method="post" action="<?php echo $view['router']->generate('submissao_iniciar') ?>"> <div class="row"> <div class="col-sm-12"> <h3>Termos de uso</h3> <p class="text-info">Antes de continuar, é necessário que leia e concorde com os termos de uso do cultura crowdfunding.</p> </div> </div> <div class="row"> <div class="col-sm-12" style="height: 300px;overflow: auto; "> <?php echo $termosUso->getTermoUso(); ?> </div> </div> <div class="form-actions" style="text-align: center"> <button type="submit" class="btn btn-success">Li e concordo com os termos acima.</button> </div> </form> </div> <?php $view['slots']->stop(); ?>
brunonm/emvista
src/EmVista/EmVistaBundle/Resources/views/Submissao/termosUso.html.php
PHP
mit
920
package main import ( "flag" "fmt" "github.com/ammario/fastpass" ) func cmdGet(fp *fastpass.FastPass) { search := flag.Arg(0) if len(flag.Args()) != 1 { usage() } results := fp.Entries.SortByName() if search != "" { results = fp.Entries.SortByBestMatch(search) } if len(results) == 0 { fail("no results found") } e := results[0] e.Stats.Hit() if len(results) > 1 { fmt.Printf("similar: ") for i, r := range results[1:] { //show a maximum of five suggestions if i > 5 { break } fmt.Printf("%v ", r.Name) } fmt.Printf("\n") } copyPassword(e) }
ammario/fastpass
cmd/fp/cmd_get.go
GO
mit
599
from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context)
vault/bugit
viewer/views.py
Python
mit
3,804
import {Component, OnInit} from '@angular/core'; @Component({ selector: 'sqap-about', templateUrl: './about.component.html', styleUrls: ['./about.component.scss'] }) export class AboutComponent implements OnInit { constructor() { } ngOnInit() { console.log('hello `About` component'); } }
MarcinMilewski/sqap
sqap-ui/src/main/frontend/app/about/about.component.ts
TypeScript
mit
311
<?php /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2012 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | | Nikita Vershinin <endeveit@gmail.com> | +------------------------------------------------------------------------+ */ namespace Phalcon\Error; class Error { /** * @var array */ protected $_attributes; /** * Class constructor sets the attributes. * * @param array $options */ public function __construct(array $options = array()) { $defaults = array( 'type' => -1, 'message' => 'No error message', 'file' => '', 'line' => '', 'exception' => null, 'isException' => false, 'isError' => false, ); $options = array_merge($defaults, $options); foreach ($options as $option => $value) { $this->_attributes[$option] = $value; } } /** * Magic method to retrieve the attributes. * * @param string $method * @param array $args * @return mixed */ public function __call($method, $args) { return isset($this->_attributes[$method]) ? $this->_attributes[$method] : null; } }
le51/foundation
app/library/Phalcon/Error/Error.php
PHP
mit
2,269
import classnames from 'classnames'; import cloneDeep from 'lodash/cloneDeep'; import React from 'react'; import { HTMLFieldProps, connectField, filterDOMProps, joinName, useField, } from 'uniforms'; export type ListAddFieldProps = HTMLFieldProps< unknown, HTMLSpanElement, { initialCount?: number } >; function ListAdd({ disabled, initialCount, name, readOnly, value, ...props }: ListAddFieldProps) { const nameParts = joinName(null, name); const parentName = joinName(nameParts.slice(0, -1)); const parent = useField< { initialCount?: number; maxCount?: number }, unknown[] >(parentName, { initialCount }, { absoluteName: true })[0]; const limitNotReached = !disabled && !(parent.maxCount! <= parent.value!.length); function onAction(event: React.KeyboardEvent | React.MouseEvent) { if ( limitNotReached && !readOnly && (!('key' in event) || event.key === 'Enter') ) { parent.onChange(parent.value!.concat([cloneDeep(value)])); } } return ( <i {...filterDOMProps(props)} className={classnames( 'ui', props.className, limitNotReached ? 'link' : 'disabled', 'fitted add icon', )} onClick={onAction} onKeyDown={onAction} role="button" tabIndex={0} /> ); } export default connectField<ListAddFieldProps>(ListAdd, { initialValue: false, kind: 'leaf', });
vazco/uniforms
packages/uniforms-semantic/src/ListAddField.tsx
TypeScript
mit
1,438
import * as Lint from 'tslint'; import * as ts from 'typescript'; const RULE_FAILURE = `Undecorated class defines fields with Angular decorators. Undecorated ` + `classes with Angular fields cannot be extended in Ivy since no definition is generated. ` + `Add a "@Directive" decorator to fix this.`; /** * Rule that doesn't allow undecorated class declarations with fields using Angular * decorators. */ export class Rule extends Lint.Rules.TypedRule { applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { return this.applyWithWalker( new Walker(sourceFile, this.getOptions(), program.getTypeChecker())); } } class Walker extends Lint.RuleWalker { constructor( sourceFile: ts.SourceFile, options: Lint.IOptions, private _typeChecker: ts.TypeChecker) { super(sourceFile, options); } visitClassDeclaration(node: ts.ClassDeclaration) { if (this._hasAngularDecorator(node)) { return; } for (let member of node.members) { if (member.decorators && this._hasAngularDecorator(member)) { this.addFailureAtNode(node, RULE_FAILURE); return; } } } /** Checks if the specified node has an Angular decorator. */ private _hasAngularDecorator(node: ts.Node): boolean { return !!node.decorators && node.decorators.some(d => { if (!ts.isCallExpression(d.expression) || !ts.isIdentifier(d.expression.expression)) { return false; } const moduleImport = this._getModuleImportOfIdentifier(d.expression.expression); return moduleImport ? moduleImport.startsWith('@angular/core') : false; }); } /** Gets the module import of the given identifier if imported. */ private _getModuleImportOfIdentifier(node: ts.Identifier): string | null { const symbol = this._typeChecker.getSymbolAtLocation(node); if (!symbol || !symbol.declarations || !symbol.declarations.length) { return null; } const decl = symbol.declarations[0]; if (!ts.isImportSpecifier(decl)) { return null; } const importDecl = decl.parent.parent.parent; const moduleSpecifier = importDecl.moduleSpecifier; return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : null; } }
trimox/angular-mdc-web
tools/tslint-rules/noUndecoratedClassWithNgFieldsRule.ts
TypeScript
mit
2,257
/*! fingoCarousel.js © heoyunjee, 2016 */ function(global, $){ 'use strict'; /** * width: carousel width * height: carousel height * margin: tabpanel margin * count: how many tabpanels will move when you click button * col: how many columns in carousel mask * row: how many rows in carousel mask * infinite: infinite carousel or not(true or false) * index: index of active tabpanel */ // Default Options var defaults = { 'width': 1240, 'height': 390, 'margin': 0, 'count': 1, 'col': 1, 'row': 1, 'infinite': false, 'index': 0 }; // Constructor Function var Carousel = function(widget, options) { // Public this.$widget = $(widget); this.settings = $.extend({}, defaults, options); this.carousel_infinite = false; this.carousel_row = 0; this.carousel_width = 0; this.carousel_height = 0; this.carousel_count = 0; this.carousel_col = 0; this.carousel_content_margin = 0; this.active_index = 0; this.carousel_one_tab = 0; this.carousel_content_width = 0; this.carousel_content_height= 0; this.$carousel = null; this.$carousel_headline = null; this.$carousel_tablist = null; this.$carousel_tabs = null; this.$carousel_button_group = null; this.$carousel_mask = null; this.$carousel_tabpanels = null; this.$carousel_tabpanel_imgs = null; this.$carousel_tabpanel_content_videos = null; this.start_tabpanel_index = 0; // 초기 설정 this.init(); // 이벤트 연결 this.events(); }; // Prototype Object Carousel.prototype = { 'init': function() { var $this = this; var $widget = this.$widget; // 캐러셀 내부 구성 요소 참조 this.$carousel = $widget; this.$carousel_headline = this.$carousel.children(':header:first'); this.$carousel_tablist = this.$carousel.children('ul').wrap('<div/>').parent(); this.$carousel_tabs = this.$carousel_tablist.find('a'); this.$carousel_tabpanels = this.$carousel.children().find('figure'); this.$carousel_content = this.$carousel_tabpanels.children().parent(); this.$carousel_tabpanel_imgs = this.$carousel.children().last().find('img').not('.icon'); this.$carousel_tabpanel_content_videos = this.$carousel.children().last().find('iframe'); this.setResponsive(); this.carousel_width = this.settings.width; this.carousel_height = this.settings.height; this.carousel_infinite = this.settings.infinite; this.carousel_row = this.settings.row; this.carousel_count = this.settings.count; this.carousel_col = this.settings.col; this.carousel_content_margin = this.settings.margin; this.start_tabpanel_index = this.settings.index; // 동적으로 캐러셀 구조 생성/추가 this.createPrevNextButtons(); this.createCarouselMask(); // 역할별 스타일링 되는 클래스 설정 this.settingClass(); this.settingSliding(); }, 'createPrevNextButtons': function() { var button_group = ['<div>', '<button type="button"></button>', '<button type="button"></button>', '</div>'].join(''); this.$carousel_button_group = $(button_group).insertAfter( this.$carousel_tablist ); }, 'createCarouselMask': function() { this.$carousel_tabpanels.parent().closest('div').wrap('<div/>'); this.$carousel_mask = this.$carousel.children().last(); }, 'settingClass': function() { this.$carousel.addClass('ui-carousel'); this.$carousel_headline.addClass('ui-carousel-headline'); this.$carousel_tablist.addClass('ui-carousel-tablist'); this.$carousel_tabs.addClass('ui-carousel-tab'); this.$carousel_button_group.addClass('ui-carousel-button-group'); this.$carousel_button_group.children().first().addClass('ui-carousel-prev-button'); this.$carousel_button_group.children().last().addClass('ui-carousel-next-button'); this.$carousel_tabpanels.addClass('ui-carousel-tabpanel'); this.$carousel_tabpanels.parent().closest('div').addClass('ui-carousel-tabpanel-wrapper'); this.$carousel_mask.addClass('ui-carousel-mask'); this.$carousel_tabpanel_imgs.addClass('ui-carousel-image'); this.$carousel_tabpanel_content_videos.addClass('ui-carousel-video'); if(this.carousel_row === 2) { var j = 1; var j2 = 1; for(var i = 0, l = this.$carousel_tabpanels.length; i < l; i++) { if(i%2===1){ this.$carousel_tabpanels.eq(i).addClass('top-2'); this.$carousel_tabpanels.eq(i).addClass('left-' + j); j++; } else { this.$carousel_tabpanels.eq(i).addClass('top-1'); this.$carousel_tabpanels.eq(i).addClass('left-' + j2); j2++; } } } }, 'settingSliding': function() { var $carousel = this.$carousel; var $tabpanel = this.$carousel_tabpanels; var $tabpanel_wrapper = $tabpanel.parent(); var $carousel_mask = this.$carousel_mask; var carousel_tabpannel_width = ($carousel_mask.width() - (this.carousel_col - 1) * this.carousel_content_margin) / this.carousel_col; this.carousel_content_width = this.$carousel_tabpanel_imgs.eq(0).width(); // carousel 높이 설정 $carousel.height(this.carousel_height); // Set carousel tabpanel(div or img) size and margin if(this.settings.col === 1) { $tabpanel.width($carousel.width()); } else { $tabpanel .width(this.carousel_content_width) .css('margin-right', this.carousel_content_margin); } // Set carousel tabpanel wrapper width $tabpanel_wrapper.width(($tabpanel.width() + this.carousel_content_margin) * ($tabpanel.length + 1)); // Set carousel one tab mask width this.carousel_one_tab = ($tabpanel.width() + this.carousel_content_margin) * this.carousel_count; if(this.start_tabpanel_index !== 0) { for(var i = 0, l = this.start_tabpanel_index + 1; i < l; i++) { this.$carousel_tabpanels.last().parent().prepend(this.$carousel_tabpanels.eq($tabpanel.length - (i + 1))); } } // Carousel 상태 초기화 if(this.carousel_infinite === true) { // tabpanel active 상태 초기화 this.$carousel_tabpanels.eq(this.active_index).radioClass('active'); // tabpanel wrapper 위치 초기화 $tabpanel_wrapper.css('left', -this.carousel_one_tab); } else if(this.carousel_col !== 1){ // Infinite Carousel이 아닐때 // prevBtn 비활성화 this.prevBtnDisable(); } // 인디케이터 active 상태 초기화 this.$carousel_tabs.eq(this.active_index).parent().radioClass('active'); }, 'prevBtnActive': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'false') .css({'opacity': 1, 'display': 'block'}); }, 'prevBtnDisable': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'true') .css({'opacity': 0, 'display': 'none'}); }, 'events': function() { var widget = this; var $carousel = widget.$carousel; var $tabs = widget.$carousel_tabs; var $buttons = widget.$carousel_button_group.children(); // buttons event $buttons.on('click', function() { if ( this.className === 'ui-carousel-prev-button' ) { widget.prevPanel(); } else { widget.nextPanel(); } }); // tabs event $.each($tabs, function(index) { var $tab = $tabs.eq(index); $tab.on('click', $.proxy(widget.viewTabpanel, widget, index, null)); }); }, 'setActiveIndex': function(index) { // 활성화된 인덱스를 사용자가 클릭한 인덱스로 변경 this.active_index = index; // tab 최대 개수 var carousel_tabs_max = (this.$carousel_tabpanels.length / (this.carousel_count * this.carousel_row)) - 1; // 한 마스크 안에 패널이 다 채워지지 않을 경우 if((this.$carousel_tabpanels.length % (this.carousel_count * this.carousel_row)) !== 0) { carousel_tabs_max = carousel_tabs_max + 1; } // 처음 또는 마지막 인덱스에 해당할 경우 마지막 또는 처음으로 변경하는 조건 처리 if ( this.active_index < 0 ) { this.active_index = carousel_tabs_max; } if ( this.active_index > carousel_tabs_max ) { this.active_index = 0; } return this.active_index; }, 'nextPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index + 1); this.viewTabpanel(active_index, 'next'); } }, 'prevPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index - 1); this.viewTabpanel(active_index, 'prev'); } }, 'viewTabpanel': function(index, btn, e) { // 사용자가 클릭을 하는 행위가 발생하면 이벤트 객체를 받기 때문에 // 조건 확인을 통해 브라우저의 기본 동작 차단 if (e) { e.preventDefault(); } this.active_index = index; var $carousel_wrapper = this.$carousel_tabpanels.eq(index).parent(); var one_width = this.carousel_one_tab; // Infinite Carousel if(this.carousel_infinite === true) { // index에 해당되는 탭패널 활성화 this.$carousel_tabpanels.eq(index).radioClass('active'); // next 버튼 눌렀을때 if(btn === 'next') { $carousel_wrapper.stop().animate({ 'left': -one_width * 2 }, 500, 'easeOutExpo', function() { $carousel_wrapper.append($carousel_wrapper.children().first()); $carousel_wrapper.css('left', -one_width); this.animating = false; }); // prev 버튼 눌렀을때 } else if(btn === 'prev') { $carousel_wrapper.stop().animate({ 'left': 0 }, 500, 'easeOutExpo', function() { $carousel_wrapper.prepend($carousel_wrapper.children().last()); $carousel_wrapper.css('left', -one_width); }); } } else if(this.carousel_infinite === false) { if(this.carousel_col !== 1) { if(index === 0) { this.prevBtnDisable(); } else { this.prevBtnActive(); } } $carousel_wrapper.stop().animate({ 'left': index * -this.carousel_one_tab }, 600, 'easeOutExpo'); } // 인디케이터 라디오클래스 활성화 this.$carousel_tabs.eq(index).parent().radioClass('active'); }, 'setResponsive': function() { if(global.innerWidth <= 750) { this.settings.width = this.settings.width.mobile || this.settings.width; this.settings.height = this.settings.height.mobile || this.settings.height; this.settings.margin = this.settings.margin.mobile || this.settings.margin; this.settings.count = this.settings.count.mobile || this.settings.count; this.settings.col = this.settings.col.mobile || this.settings.col; this.settings.row = this.settings.row.mobile || this.settings.row; if(this.settings.infinite.mobile !== undefined) { this.settings.infinite = this.settings.infinite.mobile; } this.settings.index = 0; } else if(global.innerWidth <= 1024) { this.settings.width = this.settings.width.tablet || this.settings.width; this.settings.height = this.settings.height.tablet || this.settings.height; this.settings.margin = this.settings.margin.tablet || this.settings.margin; this.settings.count = this.settings.count.tablet || this.settings.count; this.settings.col = this.settings.col.tablet || this.settings.col; this.settings.row = this.settings.row.tablet || this.settings.row; if(this.settings.infinite.tablet !== undefined) { this.settings.infinite = this.settings.infinite.tablet; } this.settings.index = this.settings.index.tablet || this.settings.index; } else { this.settings.width = this.settings.width.desktop || this.settings.width; this.settings.height = this.settings.height.desktop || this.settings.height; this.settings.margin = this.settings.margin.desktop || this.settings.margin; this.settings.count = this.settings.count.desktop || this.settings.count; this.settings.col = this.settings.col.desktop || this.settings.col; this.settings.row = this.settings.row.desktop || this.settings.row; if(this.settings.infinite.desktop !== undefined) { this.settings.infinite = this.settings.infinite.desktop; } this.settings.index = this.settings.index.desktop || this.settings.index; } } }; // jQuery Plugin $.fn.fingoCarousel = function(options){ var $collection = this; // jQuery {} return $.each($collection, function(idx){ var $this = $collection.eq(idx); var _instance = new Carousel( this, options ); // 컴포넌트 화 $this.data('fingoCarousel', _instance); }); }; })(this, this.jQuery);
ooyunjee/fingoCarousel
fingo.carousel.js
JavaScript
mit
13,831
<?php use \SeedDataInterface as SeedDataInterface; abstract class BaseSeedData implements SeedDataInterface{ public function markMigration(){ $data = []; $data['class_name'] = get_called_class(); $seedMigration = SeedMigrationModel::createObject($data,SeedMigrationModel::$attributes); SeedMigrationModel::getMapper()->setModel($seedMigration)->save(); } }
poupouxios/custom-light-mvc
db/seed-data/BaseSeedData.php
PHP
mit
403
class upnp_soaprequest { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_soaprequest;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/UPnP.SOAPRequest.js
JavaScript
mit
569
module.exports = { schedule_inputError: "Not all required inputs are present in the request", reminder_newscheduleSuccess: "A new mail has been successfully saved and scheduled", schedule_ShdlError: "The scheduleAt should be a timestamp (like : 1411820580000) and should be in the future", gbl_oops: "Oops something went wrong", gbl_success: "success" };
karankohli13/sendgrid-scheduler
messages/messages.js
JavaScript
mit
375
package xsmeral.semnet.sink; import java.util.Properties; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.sail.rdbms.RdbmsStore; /** * Factory of {@link RdbmsStore} repositories. * <br /> * Takes parameters corresponding to RdbmsStore {@linkplain RdbmsStore#RdbmsStore(java.lang.String, java.lang.String, java.lang.String, java.lang.String) constructor}: * <ul> * <li><code>driver</code> - FQN of JDBC driver</li> * <li><code>url</code> - JDBC URL</li> * <li><code>user</code> - DB user name</li> * <li><code>password</code> - DB password</li> * </ul> * @author Ron Šmeral (xsmeral@fi.muni.cz) */ public class RdbmsStoreFactory extends RepositoryFactory { @Override public void initialize() throws RepositoryException { Properties props = getProperties(); String jdbcDriver = props.getProperty("driver"); String url = props.getProperty("url"); String user = props.getProperty("user"); String pwd = props.getProperty("password"); if (jdbcDriver == null || url == null || user == null || pwd == null) { throw new RepositoryException("Invalid parameters for repository"); } else { Repository repo = new SailRepository(new RdbmsStore(jdbcDriver, url, user, pwd)); repo.initialize(); setRepository(repo); } } }
rsmeral/semnet
SemNet/src/xsmeral/semnet/sink/RdbmsStoreFactory.java
Java
mit
1,465
<?php namespace Tecnotek\ExpedienteBundle\Controller; use Tecnotek\ExpedienteBundle\Entity\User; use Tecnotek\ExpedienteBundle\Entity\Route; use Tecnotek\ExpedienteBundle\Entity\Buseta; use Tecnotek\ExpedienteBundle\Entity\Period; use Tecnotek\ExpedienteBundle\Entity\Grade; use Tecnotek\ExpedienteBundle\Entity\Course; use Tecnotek\ExpedienteBundle\Entity\CourseEntry; use Tecnotek\ExpedienteBundle\Entity\CourseClass; use Tecnotek\ExpedienteBundle\Entity\StudentQualification; use Tecnotek\ExpedienteBundle\Entity\SubCourseEntry; use Tecnotek\ExpedienteBundle\Entity\AssignedTeacher; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class SuperAdminController extends Controller { public function indexAction($name = "John Doe") { return $this->render('TecnotekExpedienteBundle::index.html.twig', array('name' => $name)); } public function administradorListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_ADMIN'"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(users) FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_ADMIN'"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/list.html.twig', array( 'pagination' => $pagination, 'isTeacher' => true, 'rowsPerPage' => $rowsPerPage )); } public function administradorCreateAction() { $entity = new User(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/new.html.twig', array('entity' => $entity, 'form' => $form->createView())); } public function administradorShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/show.html.twig', array('entity' => $entity, 'form' => $form->createView())); } public function administradorSaveAction(){ $entity = new User(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $role = $em->getRepository('TecnotekExpedienteBundle:Role')-> findOneBy(array('role' => 'ROLE_ADMIN')); $entity->getUserRoles()->add($role); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_administrador', array('id' => $entity->getId()))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView() )); } } public function administradorDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_administrador')); } public function administradorUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->get('request')->request; $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $request->get('userId')); if ( isset($entity) ) { $entity->setFirstname($request->get('firstname')); $entity->setLastname($request->get('lastname')); $entity->setUsername($request->get('username')); $entity->setEmail($request->get('email')); $entity->setActive(($request->get('active') == "on")); $em->persist($entity); $em->flush(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/show.html.twig', array('entity' => $entity, 'form' => $form->createView())); } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_administrador')); } } /* Metodos para CRUD de Coordinador */ public function coordinadorListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_COORDINADOR'"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(users) FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_COORDINADOR'"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/list.html.twig', array( 'pagination' => $pagination, 'isTeacher' => true, 'rowsPerPage' => $rowsPerPage )); } public function coordinadorCreateAction() { $entity = new User(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/new.html.twig', array('entity' => $entity, 'form' => $form->createView())); } public function coordinadorShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/show.html.twig', array('entity' => $entity, 'form' => $form->createView())); } public function coordinadorSaveAction(){ $entity = new User(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $role = $em->getRepository('TecnotekExpedienteBundle:Role')-> findOneBy(array('role' => 'ROLE_COORDINADOR')); $entity->getUserRoles()->add($role); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_coordinador', array('id' => $entity->getId()))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView() )); } } public function coordinadorDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_coordinador')); } public function coordinadorUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->get('request')->request; $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $request->get('userId')); if ( isset($entity) ) { $entity->setFirstname($request->get('firstname')); $entity->setLastname($request->get('lastname')); $entity->setUsername($request->get('username')); $entity->setEmail($request->get('email')); $entity->setActive(($request->get('active') == "on")); $em->persist($entity); $em->flush(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/show.html.twig', array('entity' => $entity, 'form' => $form->createView())); } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_coordinador')); } } /* Final de los metodos para CRUD de Coordinador*/ /* Metodos para CRUD de Profesor */ public function profesorListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_PROFESOR'"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(users) FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_PROFESOR'"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/list.html.twig', array( 'pagination' => $pagination, 'isTeacher' => true, 'rowsPerPage' => $rowsPerPage )); } public function profesorCreateAction() { $entity = new User(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/new.html.twig', array('entity' => $entity, 'form' => $form->createView())); } public function profesorShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/show.html.twig', array('entity' => $entity, 'form' => $form->createView())); } public function profesorSaveAction(){ $entity = new User(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $role = $em->getRepository('TecnotekExpedienteBundle:Role')-> findOneBy(array('role' => 'ROLE_PROFESOR')); $entity->getUserRoles()->add($role); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_profesor', array('id' => $entity->getId()))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView() )); } } public function profesorDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_profesor')); } public function profesorUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->get('request')->request; $entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $request->get('userId')); if ( isset($entity) ) { $entity->setFirstname($request->get('firstname')); $entity->setLastname($request->get('lastname')); $entity->setUsername($request->get('username')); $entity->setEmail($request->get('email')); $entity->setActive(($request->get('active') == "on")); $em->persist($entity); $em->flush(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/show.html.twig', array('entity' => $entity, 'form' => $form->createView())); } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_profesor')); } } /* Final de los metodos para CRUD de Profesor*/ /* Metodos para CRUD de routes */ public function routeListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT routes FROM TecnotekExpedienteBundle:Route routes"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(routes) FROM TecnotekExpedienteBundle:Route routes"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/list.html.twig', array( 'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 2 )); } public function routeCreateAction() { $entity = new Route(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/new.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2)); } public function routeShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity); if($entity->getRouteType() == 1) { $students = $entity->getStudents(); } else { //Get Students From Other Table $students = $em->getRepository("TecnotekExpedienteBundle:StudentToRoute")->findByRoute($id); } $routes = $em->getRepository("TecnotekExpedienteBundle:Route")->findAll(); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/show.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2, 'students' => $students, 'routes' => $routes)); } public function routeSaveAction(){ $entity = new Route(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_route', array('id' => $entity->getId()))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2 )); } } public function routeDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_route')); } public function routeEditAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/edit.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2)); } public function routeUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->get('request')->request; $entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find( $request->get('id')); if ( isset($entity) ) { $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_route_show_simple') . "/" . $entity->getId()); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/edit.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2 )); } } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_route')); } } /* Final de los metodos para CRUD de routes*/ /* Metodos para CRUD de buses */ public function busListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT buses FROM TecnotekExpedienteBundle:Buseta buses"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(buses) FROM TecnotekExpedienteBundle:Buseta buses"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/list.html.twig', array( 'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 2 )); } public function busCreateAction() { $entity = new Buseta(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/new.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2)); } public function busShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/show.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2)); } public function busEditAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/edit.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2)); } public function busSaveAction(){ $entity = new Buseta(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_bus', array('id' => $entity->getId(), 'menuIndex' => 2))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2 )); } } public function busDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_bus')); } public function busUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->getRequest(); $entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find($request->get('id')); if ( isset($entity) ) { $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_bus_show_simple') . "/" . $entity->getId()); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/edit.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 2 )); } } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_bus')); } } /* Final de los metodos para CRUD de buses*/ /* Metodos para CRUD de periods */ public function periodListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT period FROM TecnotekExpedienteBundle:Period period"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(periods) FROM TecnotekExpedienteBundle:Period periods"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/list.html.twig', array( 'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 5 )); } public function periodCreateAction() { $entity = new Period(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/new.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function periodShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/show.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function periodEditAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/edit.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function periodSaveAction(){ $entity = new Period(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_period', array('id' => $entity->getId(), 'menuIndex' => 5))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5 )); } } public function periodDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_period')); } public function periodUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->getRequest(); $entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($request->get('id')); if ( isset($entity) ) { $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_period_show_simple') . "/" . $entity->getId()); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/edit.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 5 )); } } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_period')); } } /* Final de los metodos para CRUD de periods */ /* Metodos para CRUD de grades */ public function gradeListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT entity FROM TecnotekExpedienteBundle:Grade entity"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(entity) FROM TecnotekExpedienteBundle:Grade entity"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/list.html.twig', array( 'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 5 )); } public function gradeCreateAction() { $entity = new Grade(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/new.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function gradeShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/show.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function gradeEditAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/edit.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function gradeSaveAction(){ $entity = new Grade(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_grade', array('id' => $entity->getId(), 'menuIndex' => 5))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5 )); } } public function gradeDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_grade')); } public function gradeUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->getRequest(); $entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find($request->get('id')); if ( isset($entity) ) { $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_grade_show_simple') . "/" . $entity->getId()); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/edit.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 5 )); } } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_grade')); } } /* Final de los metodos para CRUD de Grades */ /* Metodos para CRUD de courses */ public function courseListAction($rowsPerPage = 10) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT entity FROM TecnotekExpedienteBundle:Course entity"; $query = $em->createQuery($dql); $param = $this->get('request')->query->get('rowsPerPage'); if(isset($param) && $param != "") $rowsPerPage = $param; $dql2 = "SELECT count(entity) FROM TecnotekExpedienteBundle:Course entity"; $page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $page/*page number*/, $rowsPerPage/*limit per page*/ ); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/list.html.twig', array( 'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 5 )); } public function courseCreateAction() { $entity = new Course(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/new.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function courseShowAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/show.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function courseEditAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find($id); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/edit.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5)); } public function courseSaveAction(){ $entity = new Course(); $request = $this->getRequest(); $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_course', array('id' => $entity->getId(), 'menuIndex' => 5))); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 5 )); } } public function courseDeleteAction($id){ $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find( $id ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('_expediente_sysadmin_course')); } public function courseUpdateAction(){ $em = $this->getDoctrine()->getEntityManager(); $request = $this->getRequest(); $entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find($request->get('id')); if ( isset($entity) ) { $form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('_expediente_sysadmin_course_show_simple') . "/" . $entity->getId()); } else { return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/edit.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 5 )); } } else { return $this->redirect($this->generateUrl('_expediente_sysadmin_course')); } } /* Final de los metodos para CRUD de Courses */ public function adminPeriodAction($id) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($id); $grades = $em->getRepository("TecnotekExpedienteBundle:Grade")->findAll(); $institutions = $em->getRepository("TecnotekExpedienteBundle:Institution")->findAll(); $dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_PROFESOR' ORDER BY users.firstname"; $query = $em->createQuery($dql); $teachers = $query->getResult(); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/admin.html.twig', array('entity' => $entity, 'grades' => $grades, 'teachers' => $teachers, 'institutions' => $institutions, 'menuIndex' => 5)); } public function createEditGroupAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $name = $request->get('name'); $teacherId = $request->get('teacherId'); $groupId = $request->get('groupId'); $periodId = $request->get('periodId'); $gradeId = $request->get('gradeId'); $institutionId = $request->get('institutionId'); $translator = $this->get("translator"); if( isset($name) && isset($teacherId) && isset($groupId) && isset($gradeId) && isset($periodId)) { //Validate Parameters if( strlen(trim($name)) < 1) { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } else { $em = $this->getDoctrine()->getEntityManager(); if($groupId == 0) {//New Group $group = new \Tecnotek\ExpedienteBundle\Entity\Group(); $group->setPeriod($em->getRepository("TecnotekExpedienteBundle:Period")->find($periodId)); $group->setGrade($em->getRepository("TecnotekExpedienteBundle:Grade")->find($gradeId)); } else {//Edit Group $group = $em->getRepository("TecnotekExpedienteBundle:Group")->find($groupId); } $group->setName($name); $teacher = $em->getRepository("TecnotekExpedienteBundle:User")->find($teacherId); $group->setTeacher($teacher); $institution = $em->getRepository("TecnotekExpedienteBundle:Institution")->find($institutionId); $group->setInstitution($institution); $em->persist($group); if($groupId == 0) {//New Group //Get groups of period-grade to assigned teacher $dql = "SELECT g FROM TecnotekExpedienteBundle:CourseClass g WHERE g.period = " . $periodId . " AND g.grade = " . $gradeId; $query = $em->createQuery($dql); $courses = $query->getResult(); foreach( $courses as $courseClass ) { $assignedTeacher = new \Tecnotek\ExpedienteBundle\Entity\AssignedTeacher(); $assignedTeacher->setCourseClass($courseClass); $assignedTeacher->setGroup($group); $assignedTeacher->setTeacher($teacher); $em->persist($assignedTeacher); } } $em->flush(); return new Response(json_encode(array('error' => false, 'message' =>$translator->trans("messages.confirmation.password.change") ,'groupId' => $group->getId() ))); } } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::changeUserPasswordAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadPeriodInfoAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $gradeId = $request->get('gradeId'); $translator = $this->get("translator"); if( isset($gradeId) && isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); //Get Groups $sql = "SELECT g.id, g.name, g.user_id as 'teacherId', CONCAT(u.firstname,' ',u.lastname) as 'teacherName', institution.name as 'institutionName', institution.id as 'institutionId'" . " FROM tek_groups g" . " JOIN tek_users u ON u.id = g.user_id" . " LEFT JOIN tek_institutions institution ON institution.id = g.institution_id" . " WHERE g.period_id = " . $periodId . " AND g.grade_id = " . $gradeId . " ORDER BY g.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $groups = $stmt->fetchAll(); //Get Courses $sql = "SELECT cc.id, c.name, cc.user_id as 'teacherId', (CONCAT(u.firstname, ' ', u.lastname)) as 'teacherName', c.id as 'courseId' " . " FROM tek_courses c, tek_course_class cc, tek_users u" . " WHERE cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . " AND cc.course_id = c.id AND u.id = cc.user_id" . " ORDER BY c.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'groups' => $groups, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::changeUserPasswordAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function removeGroupAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $groupId = $request->get('groupId'); $translator = $this->get("translator"); if( isset($groupId) ) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:Group")->find( $groupId ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::removeGroupAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function removeEntryAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $entryId = $request->get('entryId'); $translator = $this->get("translator"); if( isset($entryId) ) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:CourseEntry")->find( $entryId ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::removeEntryAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function courseAssociationRemoveAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $associationId = $request->get('associationId'); $translator = $this->get("translator"); if( isset($associationId) ) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:CourseClass")->find( $associationId ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::removeGroupAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadAvailableCoursesAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $gradeId = $request->get('gradeId'); $translator = $this->get("translator"); if( isset($gradeId) && isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); //Get Courses $sql = "SELECT c.id, c.name" . " FROM tek_courses c" . " WHERE c.id not in (select cc.course_id from tek_course_class cc where cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . ")" . " ORDER BY c.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadAvailableCoursesAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function associateCourseAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $gradeId = $request->get('gradeId'); $courseId = $request->get('courseId'); $teacherId = $request->get('teacherId'); $translator = $this->get("translator"); if( isset($gradeId) && isset($periodId) && isset($courseId) && isset($teacherId)) { $courseClass = new \Tecnotek\ExpedienteBundle\Entity\CourseClass(); $em = $this->getDoctrine()->getEntityManager(); $teacher = $em->getRepository("TecnotekExpedienteBundle:User")->find($teacherId); $courseClass->setPeriod($em->getRepository("TecnotekExpedienteBundle:Period")->find($periodId)); $courseClass->setGrade($em->getRepository("TecnotekExpedienteBundle:Grade")->find($gradeId)); $courseClass->setTeacher($teacher); $courseClass->setCourse($em->getRepository("TecnotekExpedienteBundle:Course")->find($courseId)); $em->persist($courseClass); //Get groups of period-grade to assigned teacher $dql = "SELECT g FROM TecnotekExpedienteBundle:Group g WHERE g.period = " . $periodId . " AND g.grade = " . $gradeId; $query = $em->createQuery($dql); $groups = $query->getResult(); foreach( $groups as $group ) { $assignedTeacher = new \Tecnotek\ExpedienteBundle\Entity\AssignedTeacher(); $assignedTeacher->setCourseClass($courseClass); $assignedTeacher->setGroup($group); $assignedTeacher->setTeacher($teacher); $em->persist($assignedTeacher); } $em->flush(); return new Response(json_encode(array('error' => false, 'courseClass' => $courseClass->getId()))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadAvailableCoursesAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadAvailableCoursesGroupsAction(){ //2016 - 4 $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); //$gradeId = $request->get('gradeId'); $translator = $this->get("translator"); if(isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); //Get Courses $sql = "SELECT c.id, c.name" . " FROM tek_courses c" //. " WHERE c.id not in (select cc.course_id from tek_course_class cc where cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . ")" . " ORDER BY c.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadAvailableCoursesGroupsAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadAvailableCourseClassAction(){ //2016 -4 $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $groupId = $request->get('groupId'); $keywords = preg_split("/[\s-]+/", $groupId); $groupId = $keywords[0]; $gradeId = $keywords[1]; $translator = $this->get("translator"); if( isset($gradeId) && isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); //Get Courses $sql = "SELECT cc.id as courseclass, c.id as course, c.name as name" . " FROM tek_courses c, tek_course_class cc" . " WHERE cc.course_id = c.id and cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . " " . " ORDER BY c.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadAvailableCourseClassAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadCoursesExtraPointsAction(){ //2016 -5 $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); /*$keywords = preg_split("/[\s-]+/", $groupId); $groupId = $keywords[0]; $gradeId = $keywords[1];*/ $translator = $this->get("translator"); if( isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); //Get Courses $sql = "SELECT c.id, c.name as name" . " FROM tek_courses c" //. " WHERE cc.course_id = c.id and cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . " " . " ORDER BY c.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadAvailableCourseClassAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadCoursesByTeacherAction(){ //2016 - 4 $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $teacherId = $request->get('teacherId'); $translator = $this->get("translator"); if( isset($periodId) && isset($teacherId)) { $em = $this->getDoctrine()->getEntityManager(); /* $dql = "SELECT a FROM TecnotekExpedienteBundle:AssignedTeacher a WHERE a.period = $periodId AND a.user = $teacherId"; $query = $em->createQuery($dql); $entries = $query->getResult(); */ $stmt = $this->getDoctrine()->getEntityManager() ->getConnection() ->prepare('SELECT t.id as id, t.group_id, c.id as course, c.name as name, cc.id as courseclass, concat(g.grade_id,"-",g.name) as groupname FROM `tek_assigned_teachers` t, tek_courses c, tek_course_class cc, tek_groups g where cc.course_id = c.id and t.course_class_id = cc.id and g.id = t.group_id and cc.period_id = "'.$periodId.'" and t.user_id = "'.$teacherId.'"'); $stmt->execute(); $entity = $stmt->fetchAll(); $colors = array( "one" => "#38255c", "two" => "#04D0E6" ); $html = ""; $groupOptions = ""; foreach( $entity as $entry ){ $html .= '<div id="courseTeacherRows_' . $entry['id'] . '" class="row userRow tableRowOdd">'; $html .= ' <div id="entryNameField_' . $entry['courseclass'] . '" name="entryNameField_' . $entry['courseclass'] . '" class="option_width" style="float: left; width: 150px;">' . $entry['name'] . '</div>'; $html .= ' <div id="entryCodeField_' . $entry['group_id'] . '" name="entryCodeField_' . $entry['group_id'] . '" class="option_width" style="float: left; width: 100px;">' . $entry['groupname'] . '</div>'; $html .= ' <div class="right imageButton deleteButton deleteTeacherAssigned" style="height: 16px;" title="Eliminar" rel="' . $entry['id'] . '"></div>'; $html .= ' <div class="clear"></div>'; $html .= '</div>'; } $dql = "SELECT g FROM TecnotekExpedienteBundle:Group g WHERE g.period = $periodId"; $query = $em->createQuery($dql); $results = $query->getResult(); $courseClassId = 0; $groupOptions .= '<option value="0"></option>'; foreach( $results as $result ){ $groupOptions .= '<option value="' . $result->getId() . '-' . $result->getGrade()->getId() . '">'. $result->getGrade() . '-'. $result->getName() . '</option>'; } return new Response(json_encode(array('error' => false, 'groupOptions' => $groupOptions, 'entriesHtml' => $html))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadCoursesByTeacherAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function removeTeacherAssignedAction(){ /// 2016 - 4 $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $teacherAssignedId = $request->get('teacherAssignedId'); $translator = $this->get("translator"); if( isset($teacherAssignedId) ) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository("TecnotekExpedienteBundle:AssignedTeacher")->find( $teacherAssignedId ); if ( isset($entity) ) { $em->remove($entity); $em->flush(); } return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::removeTeacherAssignedAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function createTeacherAssignedAction(){ //2016 - 4 temp $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $teacherId = $request->get('teacherId'); $courseClassId = $request->get('courseClassId'); $groupId = $request->get('groupId'); $keywords = preg_split("/[\s-]+/", $groupId); $groupId = $keywords[0]; $gradeId = $keywords[1]; $translator = $this->get("translator"); if( isset($courseClassId) && isset($groupId) && isset($teacherId)) { $em = $this->getDoctrine()->getEntityManager(); $assignedTeacher = new AssignedTeacher(); $assignedTeacher->setCourseClass($em->getRepository("TecnotekExpedienteBundle:CourseClass")->find($courseClassId)); $assignedTeacher->setGroup($em->getRepository("TecnotekExpedienteBundle:Group")->find($groupId)); $assignedTeacher->setTeacher($em->getRepository("TecnotekExpedienteBundle:User")->find($teacherId)); $em->persist($assignedTeacher); $em->flush(); return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::createTeacherAssignedAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } /**/ public function getPaginationPage($dql, $currentPage, $rowsPerPage){ if(isset($currentPage) == false || $currentPage <= 1){ return 1; } else { $em = $this->getDoctrine()->getEntityManager(); $query = $em->createQuery($dql); $total = $query->getSingleScalarResult(); //Check if current page has Results if( $total > (($currentPage - 1) * $rowsPerPage)){//the page has results return $currentPage; } else { $x = intval($total / $rowsPerPage); if($x == 0){ return 1; } else { if( $total % ($x * $rowsPerPage) > 0){ return $x+1; } else { return $x; } } } } } public function changeUserPasswordAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $newPassword = $request->get('newPassword'); $confirmPassword = $request->get('confirmPassword'); $userId = $request->get('userId'); $em = $this->getDoctrine()->getEntityManager(); $user = $em->getRepository("TecnotekExpedienteBundle:User")->find($userId); $translator = $this->get("translator"); if ( isset($user) ) { $defaultController = new DefaultController(); $error = $defaultController->validateUserPassword($newPassword, $confirmPassword, $translator); if ( isset($error) ) { return new Response(json_encode(array('error' => true, 'message' => $error))); } else { $user->setPassword($newPassword); $em->persist($user); $em->flush(); return new Response(json_encode(array('error' => false, 'message' =>$translator->trans("messages.confirmation.password.change")))); } } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.entity.not.found")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::changeUserPasswordAction [' . $info . "]"); return new Response($info); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function enterQualificationsAction(){ $logger = $this->get("logger"); $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT p FROM TecnotekExpedienteBundle:Period p ORDER BY p.year"; $query = $em->createQuery($dql); $periods = $query->getResult(); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Qualification/index.html.twig', array('periods' => $periods, 'menuIndex' => 5)); } public function enterQualificationssssAction(){ $logger = $this->get("logger"); $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT e FROM TecnotekExpedienteBundle:CourseEntry e WHERE e.parent IS NULL ORDER BY e.sortOrder"; $query = $em->createQuery($dql); $logger->err("-----> SQL: " . $query->getSQL()); $entries = $query->getResult(); $logger->err("-----> ENTRIES: " . sizeof($entries)); $temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry(); $html = '<div class="itemPromedioPeriodo itemHeader" style="margin-left: 0px; color: #fff;">Promedio Trimestral</div>'; /* <div class="itemHeader itemNota" style="margin-left: 125px;">Tarea 2</div> <div class="itemHeader itemPromedio" style="margin-left:150px;">Promedio Tareas </div> <div class="itemHeader itemPorcentage" style="margin-left: 175px;">10 % Tarea</div> <div class="itemHeaderCode itemNota" style="margin-left: 0px;"></div> */ $marginLeft = 34; $marginLeftCode = 62; $htmlCodes = '<div class="itemPromedioPeriodo itemHeaderCode" style="color: #fff;">SCIE</div>'; $jumpRight = 34; $width = 32; $html3 = '<div class="itemHeader2 itemPromedioPeriodo" style="width: 32px; color: #fff;">TRIM</div>'; $studentRow = ""; $studentsHeader = ''; $colors = array( "one" => "#38255c", "two" => "#04D0E6" ); foreach( $entries as $entry ) { $temp = $entry; $childrens = $temp->getChildrens(); $size = sizeof($childrens); $logger->err("-----> Childrens of " . $temp->getName() . ": " . sizeof($childrens)); if($size == 0){//No child $studentRow .= '<input type="text" class="textField itemNota" tipo="1" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >'; $htmlCodes .= '<div class="itemHeaderCode itemNota"></div>'; $html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>'; $htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>'; $html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * 2) + 2) . 'px">' . $temp->getName() . '</div>'; } else { if($size == 1){//one child foreach ( $childrens as $child){ $htmlCodes .= '<div class="itemHeaderCode itemNota"></div>'; $html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } $htmlCodes .= '<div class="itemHeaderCode itemPorcentage"></div>'; $html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } else {//two or more foreach ( $childrens as $child){ //$studentRow .= '<input type="text" class="textField itemNota">'; $studentRow .= '<input type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >'; $htmlCodes .= '<div class="itemHeaderCode itemNota">' . $child->getCode() . '</div>'; $html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } $studentRow .= '<div class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</div>'; $htmlCodes .= '<div class="itemHeaderCode itemPromedio"></div>'; $html .= '<div class="itemHeader itemPromedio" style="margin-left:' . $marginLeft . 'px;">Promedio ' . $temp->getName() . ' </div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; //$studentRow .= '<div class="itemHeaderCode itemPorcentage">-</div>'; $studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>'; $htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>'; $html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * ($size + 2)) + (($size + 1) * 2)) . 'px">' . $temp->getName() . '</div>'; } } /*$assignedTeacher = new \Tecnotek\ExpedienteBundle\Entity\AssignedTeacher(); $assignedTeacher->setCourseClass($courseClass); $assignedTeacher->setGroup($group); $assignedTeacher->setTeacher($teacher); $em->persist($assignedTeacher);*/ } $html = $htmlCodes . '<div class="clear"></div>' . '<div style="position: relative; height: 152px; margin-left: -59px;">' . $html . '</div>' . '<div class="clear"></div>' . $html3; $students = $em->getRepository("TecnotekExpedienteBundle:Student")->findAll(); foreach($students as $student){ $studentsHeader .= '<div class="itemCarne">' . $student->getCarne() . '</div><div class="itemEstudiante">' . $student . '</div><div class="clear"></div>'; $row = str_replace("stdId", $student->getId(), $studentRow); $html .= '<div class="clear"></div><div id="total_trim_' . $student->getId() . '" class="itemHeaderCode itemPromedioPeriodo"style="color: #fff;">-</div>' . $row; } return $this->render('TecnotekExpedienteBundle:SuperAdmin:Qualification/index.html.twig', array('table' => $html, 'studentsHeader' => $studentsHeader, 'menuIndex' => 5)); } public function loadEntriesByCourseAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $gradeId = $request->get('gradeId'); $courseId = $request->get('courseId'); $translator = $this->get("translator"); if( isset($gradeId) && isset($periodId) && isset($courseId)) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT e FROM TecnotekExpedienteBundle:CourseEntry e, TecnotekExpedienteBundle:CourseClass cc WHERE e.parent IS NULL AND e.courseClass = cc AND cc.period = $periodId AND cc.grade = $gradeId And cc.course = $courseId ORDER BY e.sortOrder"; $query = $em->createQuery($dql); $entries = $query->getResult(); $colors = array( "one" => "#38255c", "two" => "#04D0E6" ); $html = ""; $entriesOptions = ""; $temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry(); $dql = "SELECT cc FROM TecnotekExpedienteBundle:CourseClass cc WHERE cc.period = $periodId AND cc.grade = $gradeId And cc.course = $courseId"; $query = $em->createQuery($dql); $results = $query->getResult(); $courseClassId = 0; foreach( $results as $result ){ $courseClassId = $result->getId(); } foreach( $entries as $entry ){ $temp = $entry; $courseClassId = $temp->getCourseClass()->getId(); $childrens = $temp->getChildrens(); $size = sizeof($childrens); $entriesOptions .= '<option value="' . $entry->getId() . '">' . $entry->getName() . '</option>'; $html .= '<div id="entryRow_' . $entry->getId() . '" class="row userRow tableRowOdd">'; $html .= ' <div id="entryNameField_' . $entry->getId() . '" name="entryNameField_' . $entry->getId() . '" class="option_width" style="float: left; width: 150px;">' . $entry->getName() . '</div>'; $html .= ' <div id="entryCodeField_' . $entry->getId() . '" name="entryCodeField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getCode() . '</div>'; $html .= ' <div id="entryPercentageField_' . $entry->getId() . '" name="entryPercentageField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getPercentage() . '</div>'; $html .= ' <div id="entryMaxValueField_' . $entry->getId() . '" name="entryMaxValueField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getMaxValue() . '</div>'; $html .= ' <div id="entryOrderField_' . $entry->getId() . '" name="entryOrderField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getSortOrder() . '</div>'; $html .= ' <div id="entryParentField_' . $entry->getId() . '" name="entryParentField_' . $entry->getId() . '" class="option_width" style="float: left; width: 150px;">' . $entry->getParent() . '</div>'; $html .= ' <div class="right imageButton deleteButton deleteEntry" style="height: 16px;" title="Eliminar" rel="' . $entry->getId() . '"></div>'; $html .= ' <div class="right imageButton editButton editEntry" title="Editar" rel="' . $entry->getId() . '" entryParent="0"></div>'; $html .= ' <div class="clear"></div>'; $html .= '</div>'; foreach ( $childrens as $child){ $html .= '<div id="entryRow_' . $child->getId() . '" class="row userRow tableRowOdd">'; $html .= ' <div id="entryNameField_' . $child->getId() . '" name="entryNameField_' . $child->getId() . '" class="option_width" style="float: left; width: 150px;">' . $child->getName() . '</div>'; $html .= ' <div id="entryCodeField_' . $child->getId() . '" name="entryCodeField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getCode() . '</div>'; $html .= ' <div id="entryPercentageField_' . $child->getId() . '" name="entryPercentageField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getPercentage() . '</div>'; $html .= ' <div id="entryMaxValueField_' . $child->getId() . '" name="entryMaxValueField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getMaxValue() . '</div>'; $html .= ' <div id="entryOrderField_' . $child->getId() . '" name="entryOrderField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getSortOrder() . '</div>'; $html .= ' <div id="entryParentField_' . $child->getId() . '" name="entryParentField_' . $child->getId() . '" class="option_width" style="float: left; width: 150px;">' . $child->getParent() . '</div>'; $html .= ' <div class="right imageButton deleteButton deleteEntry" style="height: 16px;" title="Eliminar" rel="' . $child->getId() . '"></div>'; $html .= ' <div class="right imageButton editButton editEntry" title="Editar" rel="' . $child->getId() . '" entryParent="' . $entry->getId() . '"></div>'; $html .= ' <div class="clear"></div>'; $html .= '</div>'; } /*if($size == 0){//No child $studentRow .= '<input type="text" class="textField itemNota" tipo="1" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >'; $htmlCodes .= '<div class="itemHeaderCode itemNota"></div>'; $html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>'; $htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>'; $html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * 2) + 2) . 'px">' . $temp->getName() . '</div>'; } else { if($size == 1){//one child foreach ( $childrens as $child){ $htmlCodes .= '<div class="itemHeaderCode itemNota"></div>'; $html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } $htmlCodes .= '<div class="itemHeaderCode itemPorcentage"></div>'; $html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } else {//two or more foreach ( $childrens as $child){ //$studentRow .= '<input type="text" class="textField itemNota">'; $studentRow .= '<input type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >'; $htmlCodes .= '<div class="itemHeaderCode itemNota">' . $child->getCode() . '</div>'; $html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } $studentRow .= '<div class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</div>'; $htmlCodes .= '<div class="itemHeaderCode itemPromedio"></div>'; $html .= '<div class="itemHeader itemPromedio" style="margin-left:' . $marginLeft . 'px;">Promedio ' . $temp->getName() . ' </div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; //$studentRow .= '<div class="itemHeaderCode itemPorcentage">-</div>'; $studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>'; $htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>'; $html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * ($size + 2)) + (($size + 1) * 2)) . 'px">' . $temp->getName() . '</div>'; } }*/ } return new Response(json_encode(array('error' => false, 'entries' => $entriesOptions, 'entriesHtml' => $html, 'courseClassId' => $courseClassId))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::loadEntriesByCourseAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function createEntryAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $parentId = $request->get('parentId'); $name = $request->get('name'); $code = $request->get('code'); $maxValue = $request->get('maxValue'); $percentage = $request->get('percentage'); $sortOrder = $request->get('sortOrder'); $courseClassId = $request->get('courseClassId'); $entryId = $request->get('entryId'); $translator = $this->get("translator"); if( isset($parentId) && isset($name) && isset($code) && isset($maxValue) && isset($percentage) && isset($sortOrder) && isset($courseClassId) && isset($entryId)) { $em = $this->getDoctrine()->getEntityManager(); if($entryId == 0){//Is new $courseEntry = new CourseEntry(); $courseEntry->setCourseClass($em->getRepository("TecnotekExpedienteBundle:CourseClass")->find($courseClassId)); } else {//Is editing $courseEntry = $em->getRepository("TecnotekExpedienteBundle:CourseEntry")->find($entryId); } $courseEntry->setName($name); $courseEntry->setCode($code); $courseEntry->setMaxValue($maxValue); $courseEntry->setPercentage($percentage); $courseEntry->setSortOrder($sortOrder); if($parentId == 0){ $courseEntry->removeParent(); }else { $parent = $em->getRepository("TecnotekExpedienteBundle:CourseEntry")->find($parentId); if(isset($parent)) $courseEntry->setParent($parent); } $em->persist($courseEntry); $em->flush(); return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::createEntryAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } /******************************* Funciones para la administracion de las calificaciones *******************************/ public function loadLevelsOfPeriodAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $translator = $this->get("translator"); if( isset($periodId) ) { $em = $this->getDoctrine()->getEntityManager(); //Get Groups $sql = "SELECT grade.id as 'id', grade.name as 'name' FROM tek_groups g, tek_grades grade WHERE g.period_id = " . $periodId . " AND g.grade_id = grade.id GROUP BY grade.id ORDER BY grade.id, g.name;"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $levels = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'levels' => $levels))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadGroupsOfPeriodAndLevelAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $levelId = $request->get('levelId'); $translator = $this->get("translator"); if( isset($periodId) && isset($levelId) ) { $em = $this->getDoctrine()->getEntityManager(); //Get Groups $sql = "SELECT CONCAT(g.id,'-',grade.id) as 'id', CONCAT(grade.name, ' :: ', g.name) as 'name'" . " FROM tek_groups g, tek_grades grade" . " WHERE g.period_id = " . $periodId . " AND g.grade_id = grade.id"; if($levelId != 0){ $sql .= " AND grade.id = " . $levelId; } $sql .+ " GROUP BY g.id" . " ORDER BY grade.id, g.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $groups = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'groups' => $groups))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadGroupsOfPeriodAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $translator = $this->get("translator"); if( isset($periodId) ) { $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('security.context')->getToken()->getUser(); //Get Groups $sql = "SELECT CONCAT(g.id,'-',grade.id) as 'id', CONCAT(grade.name, ' :: ', g.name) as 'name'" . " FROM tek_groups g, tek_grades grade" . " WHERE g.period_id = " . $periodId . " AND g.institution_id in (" . $user->getInstitutionsIdsStr() . ")" . " AND g.grade_id = grade.id" . " GROUP BY g.id" . " ORDER BY grade.id, g.name"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $groups = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'groups' => $groups))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadCourseOfGroupByTeacherAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $keywords = preg_split("/[\s-]+/", $request->get('groupId')); $groupId = $keywords[0]; $translator = $this->get("translator"); if( isset($groupId) ) { $em = $this->getDoctrine()->getEntityManager(); //Get Courses $sql = "SELECT course.id, course.name " . " FROM tek_assigned_teachers tat, tek_course_class tcc, tek_courses course " . " WHERE tat.group_id = " . $groupId . " AND tat.course_class_id = tcc.id AND tcc.course_id = course.id" . " ORDER BY course.name "; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadPrintableGroupQualificationsAction(){ $logger = $this->get('logger'); $translator = $this->get("translator"); try { $request = $this->get('request'); $periodId = $request->get('periodId'); $groupId = $request->get('groupId'); $courseId = $request->get('courseId'); if( !isset($courseId) || !isset($groupId) || !isset($periodId)) { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } $keywords = preg_split("/[\s-]+/", $groupId); $groupId = $keywords[0]; $gradeId = $keywords[1]; if( isset($courseId) && isset($groupId) && isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); $group = $em->getRepository("TecnotekExpedienteBundle:Group")->find( $groupId ); $grade = $group->getGrade(); $course = $em->getRepository("TecnotekExpedienteBundle:Course")->find( $courseId ); $title = "Calificaciones del grupo: " . $group->getGrade() . "-" . $group . " en la materia: " . $course. " en el Periodo: " . $periodId; $dql = "SELECT ce FROM TecnotekExpedienteBundle:CourseEntry ce " . " JOIN ce.courseClass cc" . " WHERE ce.parent IS NULL AND cc.period = " . $periodId . " AND cc.grade = " . $gradeId . " AND cc.course = " . $courseId . " ORDER BY ce.sortOrder"; $query = $em->createQuery($dql); $entries = $query->getResult(); $temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry(); $html = '<tr style="height: 75px; line-height: 0px;"><td class="celesteOscuro" style="min-width: 75px; font-size: 12px; height: 75px;">Carne</td>'; $html .= '<td class="celesteClaro bold" style="min-width: 300px; font-size: 12px; height: 75px;">Estudiante</td>'; $html .= '<td class="azul" style="vertical-align: bottom; padding: 1.5625em 0.625em; height: 75px;"><div class="verticalText" style="color: #000;">Promedio</div></td>'; $marginLeft = 48; $marginLeftCode = 62; $htmlCodes = '<tr style="height: 25px;"><td class="celesteOscuro" style="width: 75px; font-size: 10px;"></td>'; $htmlCodes .= '<td class="celesteClaro bold" style="width: 300px; font-size: 8px;"></td>'; $htmlCodes .= '<td class="azul" style="color: #000;"></td>'; $jumpRight = 46; $width = 44; $html3 = '<tr style="height: 25px; line-height: 0px;" class="noPrint"><td class="celesteOscuro bold headcolcarne" style="min-width: 75px; font-size: 12px;">Carne</td>'; $html3 .= '<td class="celesteClaro bold headcolnombre" style="min-width: 300px; font-size: 12px;">Estudiante</td>'; $html3 .= '<td class="azul headcoltrim" style="color: #000;">TRIM1111</td>'; $studentRow = ''; $studentsHeader = ''; $colors = array( "one" => "#38255c", "two" => "#04D0E6" ); $dql = "SELECT stdy FROM TecnotekExpedienteBundle:Student std, TecnotekExpedienteBundle:StudentYear stdy " . " WHERE stdy.student = std AND stdy.group = " . $groupId . " AND stdy.period = " . $periodId . " ORDER BY std.lastname, std.firstname"; $query = $em->createQuery($dql); $students = $query->getResult(); $studentsCount = sizeof($students); $rowIndex = 1; $colsCounter = 1; $specialCounter = 1; foreach( $entries as $entry ) { $temp = $entry; $childrens = $temp->getChildrens(); $size = sizeof($childrens); if($size == 0){//No child //Find SubEntries $dql = "SELECT ce FROM TecnotekExpedienteBundle:SubCourseEntry ce " . " WHERE ce.parent = " . $temp->getId() . " AND ce.group = " . $groupId . " ORDER BY ce.sortOrder"; $query = $em->createQuery($dql); $subentries = $query->getResult(); $size = sizeof($subentries); if($size > 1){ foreach( $subentries as $subentry ) { //$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>'; $studentRow .= '<td class="celesteClaro noPrint"><div><input disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>'; $colsCounter++; $htmlCodes .= '<td class="celesteClaro noPrint"></td>'; $specialCounter++; $html .= '<td class="celesteClaro noPrint"><div class="verticalText">' . $subentry->getCode() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } //$studentRow .= '<td class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>'; $studentRow .= '<td class="celesteOscuro noPrint" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>'; $htmlCodes .= '<td class="celesteOscuro noPrint"></td>'; $specialCounter++; $html .= '<td class="celesteOscuro noPrint"><div class="verticalText">Promedio ' . $temp->getCode() . ' </div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; //$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>'; $studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>'; $htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>'; $specialCounter++; $html .= '<td class="morado" style="padding: 1.5625em 0.625em; vertical-align: bottom;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getCode() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; // $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * (sizeof($subentries)+1)) + ((sizeof($subentries)) * 2) ) . 'px">' . $temp->getCode() . '</div>'; $html3 .= '<td class="celesteClaro noPrint" colspan="' . (sizeof($subentries)+2) . '">' . $temp->getCode() . '</td>'; } else { if($size == 1){ foreach( $subentries as $subentry ) { //$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>'; $studentRow .= '<td class="celesteClaro noPrint"><div style="height: 15px;"><input disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>'; $colsCounter++; $htmlCodes .= '<td class="celesteClaro noPrint"></td>'; $specialCounter++; $html .= '<td class="celesteClaro noPrint"><div class="verticalText">' . $subentry->getCode() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } //$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>'; $studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>'; $htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>'; $specialCounter++; $html .= '<td class="morado" style="padding: 1.5625em 0.625em; vertical-align: bottom;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getCode() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<td class="celesteClaro noPrint" colspan="' . (sizeof($subentries)+1) . '">' . $temp->getName() . '</td>'; } } } else { } } $htmlCodes .= "</tr>"; $html .= "</tr>"; $html3 .= "</tr>"; $html = '<table class="tableQualifications" style="border-spacing: 0px; border-collapse: collapse;">' . $htmlCodes . $html; $studentRowIndex = 0; foreach($students as $stdy){ $html .= '<tr style="height: 25px; line-height: 0px;">'; $studentRowIndex++; $html .= '<td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;">' . $stdy->getStudent()->getCarne() . '</td>'; $html .= '<td class="celesteClaro bold headcolnombre" style="width: 300px; font-size: 12px;">' . $stdy->getStudent() . '</td>'; $row = str_replace("stdId", $stdy->getStudent()->getId(), $studentRow); $row = str_replace("stdyIdd", $stdy->getId(), $row); //tabIndexColXx for ($i = 1; $i <= $colsCounter; $i++) { $indexVar = "tabIndexCol" . $i . "x"; $row = str_replace($indexVar, "" . ($studentRowIndex + (($i - 1) * $studentsCount)), $row); } $dql = "SELECT qua FROM TecnotekExpedienteBundle:StudentQualification qua" . " WHERE qua.studentYear = " . $stdy->getId(); $query = $em->createQuery($dql); $qualifications = $query->getResult(); foreach($qualifications as $qualification){ $row = str_replace("val_" . $stdy->getStudent()->getId() . "_" . $qualification->getSubCourseEntry()->getId() . "_", $qualification->getQualification(), $row); } $html .= '<td id="total_trim_' . $stdy->getStudent()->getId() . '" class="azul headcoltrim" style="color: #000;">-</td>' . $row . "</tr>"; } $html .= "</table>"; return $this->render('TecnotekExpedienteBundle:SuperAdmin:Qualification/courseGroupQualification.html.twig', array('table' => $html, 'studentsCounter' => $studentsCount, "codesCounter" => $specialCounter, 'menuIndex' => 5, 'title' => $title, "notaMin" => $grade->getNotaMin())); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Teacher::loadEntriesByCourseAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } } public function loadGroupQualificationsAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $periodId = $request->get('periodId'); $groupId = $request->get('groupId'); $keywords = preg_split("/[\s-]+/", $groupId); $groupId = $keywords[0]; $gradeId = $keywords[1]; $courseId = $request->get('courseId'); $translator = $this->get("translator"); if( isset($courseId) && isset($groupId) && isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT ce FROM TecnotekExpedienteBundle:CourseEntry ce " . " JOIN ce.courseClass cc" . " WHERE ce.parent IS NULL AND cc.period = " . $periodId . " AND cc.grade = " . $gradeId . " AND cc.course = " . $courseId . " ORDER BY ce.sortOrder"; $query = $em->createQuery($dql); $entries = $query->getResult(); $temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry(); $html = '<tr style="height: 175px; line-height: 0px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px; height: 175px;"></td>'; $html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px; height: 175px;"></td>'; $html .= '<td class="azul headcoltrim" style="vertical-align: bottom; padding: 0.5625em 0.625em; height: 175px; line-height: 220px;"><div class="verticalText" style="color: #fff;">Promedio Trimestral</div></td>'; $marginLeft = 48; $marginLeftCode = 62; $htmlCodes = '<tr style="height: 30px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;"></td>'; $htmlCodes .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px;"></td>'; $htmlCodes .= '<td class="azul headcoltrim" style="color: #fff;">SCIE</td>'; $jumpRight = 46; $width = 44; $html3 = '<tr style="height: 30px; line-height: 0px;" class="noPrint"><td class="celesteOscuro bold headcolcarne" style="width: 75px; font-size: 12px;">Carne</td>'; $html3 .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 12px;">Estudiante</td>'; $html3 .= '<td class="azul headcoltrim" style="color: #fff;">TRIM</td>'; $studentRow = ''; $studentsHeader = ''; $colors = array( "one" => "#38255c", "two" => "#04D0E6" ); $dql = "SELECT stdy FROM TecnotekExpedienteBundle:Student std, TecnotekExpedienteBundle:StudentYear stdy " . " WHERE stdy.student = std AND stdy.group = " . $groupId . " AND stdy.period = " . $periodId . " ORDER BY std.lastname, std.firstname"; $query = $em->createQuery($dql); $students = $query->getResult(); $studentsCount = sizeof($students); $rowIndex = 1; $colsCounter = 1; $specialCounter = 1; foreach( $entries as $entry ) { $temp = $entry; $childrens = $temp->getChildrens(); $size = sizeof($childrens); if($size == 0){//No child //Find SubEntries $dql = "SELECT ce FROM TecnotekExpedienteBundle:SubCourseEntry ce " . " WHERE ce.parent = " . $temp->getId() . " AND ce.group = " . $groupId . " ORDER BY ce.sortOrder"; $query = $em->createQuery($dql); $subentries = $query->getResult(); $size = sizeof($subentries); if($size > 1){ foreach( $subentries as $subentry ) { //$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>'; $studentRow .= '<td class="celesteClaro"><div><input style="background-color: #A4D2FD;" disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></input></div></td>'; $colsCounter++; $htmlCodes .= '<td class="celesteClaro"></td>'; $specialCounter++; $html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } //$studentRow .= '<td class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>'; $studentRow .= '<td class="celesteOscuro" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>'; $htmlCodes .= '<td class="celesteOscuro"></td>'; $specialCounter++; $html .= '<td class="celesteOscuro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">Promedio ' . $temp->getName() . ' </div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; //$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>'; $studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>'; $htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>'; $specialCounter++; $html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; // $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * (sizeof($subentries)+1)) + ((sizeof($subentries)) * 2) ) . 'px">' . $temp->getName() . '</div>'; $html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+2) . '">' . $temp->getName() . '</td>'; } else { if($size == 1){ foreach( $subentries as $subentry ) { //$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>'; $studentRow .= '<td class="celesteClaro"><div><input style="background-color: #A4D2FD;" disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></input></div></td>'; $colsCounter++; $htmlCodes .= '<td class="celesteClaro"></td>'; $specialCounter++; $html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; } //$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>'; $studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>'; $htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>'; $specialCounter++; $html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+1) . '">' . $temp->getName() . '</td>'; } } } else { } } $htmlCodes .= "</tr>"; $html .= "</tr>"; $html3 .= "</tr>"; $html = '<table class="tableQualifications">' . $htmlCodes . $html . $html3; $studentRowIndex = 0; foreach($students as $stdy){ $html .= '<tr style="height: 30px; line-height: 0px;">'; $studentRowIndex++; $html .= '<td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;">' . $stdy->getStudent()->getCarne() . '</td>'; $html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 12px;">' . $stdy->getStudent() . '</td>'; $row = str_replace("stdId", $stdy->getStudent()->getId(), $studentRow); $row = str_replace("stdyIdd", $stdy->getId(), $row); //tabIndexColXx for ($i = 1; $i <= $colsCounter; $i++) { $indexVar = "tabIndexCol" . $i . "x"; $row = str_replace($indexVar, "" . ($studentRowIndex + (($i - 1) * $studentsCount)), $row); } $dql = "SELECT qua FROM TecnotekExpedienteBundle:StudentQualification qua" . " WHERE qua.studentYear = " . $stdy->getId(); $query = $em->createQuery($dql); $qualifications = $query->getResult(); foreach($qualifications as $qualification){ $row = str_replace("val_" . $stdy->getStudent()->getId() . "_" . $qualification->getSubCourseEntry()->getId() . "_", "" . $qualification->getQualification(), $row); } $html .= '<td id="total_trim_' . $stdy->getStudent()->getId() . '" class="azul headcoltrim" style="color: #fff;">-</td>' . $row . "</tr>"; } $html .= "</table>"; return new Response(json_encode(array('error' => false, 'html' => $html, "studentsCounter" => $studentsCount, "codesCounter" => $specialCounter))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Teacher::loadEntriesByCourseAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function saveStudentQualificationAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $subentryId = $request->get('subentryId'); $studentYearId = $request->get('studentYearId'); $qualification = $request->get('qualification'); $translator = $this->get("translator"); $logger->err('--> ' . $subentryId . " :: " . $studentYearId . " :: " . $qualification); if( !isset($qualification) || $qualification == ""){ $qualification = -1; } if( isset($subentryId) || isset($studentYearId) ) { $em = $this->getDoctrine()->getEntityManager(); $studentQ = $em->getRepository("TecnotekExpedienteBundle:StudentQualification")->findOneBy(array('subCourseEntry' => $subentryId, 'studentYear' => $studentYearId)); if ( isset($studentQ) ) { $studentQ->setQualification($qualification); } else { $studentQ = new StudentQualification(); $studentQ->setSubCourseEntry($em->getRepository("TecnotekExpedienteBundle:SubCourseEntry")->find( $subentryId )); $studentQ->setStudentYear($em->getRepository("TecnotekExpedienteBundle:StudentYear")->find( $studentYearId )); $studentQ->setQualification($qualification); } $em->persist($studentQ); $em->flush(); return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('SuperAdmin::saveStudentQualificationAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function generateExcelAction(){ $excelService = $this->get('export.excel')->setNameOfSheet("Notas"); //$this->get('export.excel')->createSheet(); $filepath = "export/excel/groupNotes"; $request = $this->get('request')->request; //$periodId = $request->get('periodId'); $periodId = 1; //$groupId = $request->get('groupId'); $groupId = "1-1"; $keywords = preg_split("/[\s-]+/", $groupId); $groupId = $keywords[0]; $gradeId = $keywords[1]; //$courseId = $request->get('courseId'); $courseId = "42"; $translator = $this->get("translator"); if( isset($courseId) && isset($groupId) && isset($periodId)) { $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT ce FROM TecnotekExpedienteBundle:CourseEntry ce " . " JOIN ce.courseClass cc" . " WHERE ce.parent IS NULL AND cc.period = " . $periodId . " AND cc.grade = " . $gradeId . " AND cc.course = " . $courseId . " ORDER BY ce.sortOrder"; $query = $em->createQuery($dql); $entries = $query->getResult(); $temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry(); //$html = '<tr style="height: 175px; line-height: 0px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px; height: 175px;"></td>'; //$html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px; height: 175px;"></td>'; $excelService->writeCellByPositionWithOptions(2,2,"Promedio Trimestral", array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => '2b34ee', 'color' => 'ffffff', 'bold' => true)); //$html .= '<td class="azul headcoltrim" style="vertical-align: bottom; padding: 0.5625em 0.625em; height: 175px; line-height: 220px;"><div class="verticalText" style="color: #fff;">Promedio Trimestral</div></td>'; $marginLeft = 48; $marginLeftCode = 62; //$htmlCodes = '<tr style="height: 30px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;"></td>'; //$htmlCodes .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px;"></td>'; //$htmlCodes .= '<td class="azul headcoltrim" style="color: #fff;">SCIE</td>'; $excelService->writeCellByPositionWithOptions(1,2,"SCIE", array('height' => 15, 'width' => 5, 'backgroundColor' => '2b34ee', 'color' => 'ffffff', 'bold' => true)); $jumpRight = 46; $width = 44; $excelService->writeCellByPositionWithOptions(1,0,"", array('height' => 15, 'width' => 5, 'backgroundColor' => '82c0fd', 'bold' => true)); $excelService->writeCellByPositionWithOptions(1,1,"", array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD', 'bold' => true)); $excelService->writeCellByPositionWithOptions(2,0,"", array('height' => 195, 'width' => 5, 'backgroundColor' => '82c0fd', 'bold' => true)); $excelService->writeCellByPositionWithOptions(2,1,"", array('height' => 195, 'width' => 5, 'backgroundColor' => 'A4D2FD', 'bold' => true)); $excelService->writeCellByPositionWithOptions(3,0,"Carne", array('height' => 15, 'width' => 5, 'backgroundColor' => '82c0fd', 'bold' => true)); $excelService->writeCellByPositionWithOptions(3,1,"Estudiante", array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD', 'bold' => true)); $excelService->writeCellByPositionWithOptions(3,2,"TRIM", array('height' => 15, 'width' => 5, 'backgroundColor' => '2b34ee', 'color' => 'ffffff', 'bold' => true)); //$html3 = '<tr style="height: 30px; line-height: 0px;" class="noPrint"><td class="celesteOscuro bold headcolcarne" style="width: 75px; font-size: 12px;">Carne</td>'; //$html3 .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 12px;">Estudiante</td>'; //$html3 .= '<td class="azul headcoltrim" style="color: #fff;">TRIM</td>'; $studentRow = ''; $studentsHeader = ''; $colors = array( "one" => "#38255c", "two" => "#04D0E6" ); $dql = "SELECT stdy FROM TecnotekExpedienteBundle:Student std, TecnotekExpedienteBundle:StudentYear stdy " . " WHERE stdy.student = std AND stdy.group = " . $groupId . " AND stdy.period = " . $periodId . " ORDER BY std.lastname, std.firstname"; $query = $em->createQuery($dql); $students = $query->getResult(); $studentsCount = sizeof($students); $rowIndex = 1; $colsCounter = 1; $specialCounter = 1; $colsIndex = 3; foreach( $entries as $entry ) { $temp = $entry; $childrens = $temp->getChildrens(); $size = sizeof($childrens); if($size == 0){//No child //Find SubEntries $dql = "SELECT ce FROM TecnotekExpedienteBundle:SubCourseEntry ce " . " WHERE ce.parent = " . $temp->getId() . " AND ce.group = " . $groupId . " ORDER BY ce.sortOrder"; $query = $em->createQuery($dql); $subentries = $query->getResult(); $size = sizeof($subentries); if($size > 1){ foreach( $subentries as $subentry ) { $excelService->writeCellByPositionWithOptions(1,$colsIndex,"", array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD')); $excelService->writeCellByPositionWithOptions(2,$colsIndex,$subentry->getName(), array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'A4D2FD')); $colsIndex += 1; //$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>'; /*$studentRow .= '<td class="celesteClaro"><div><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>'; $colsCounter++; $htmlCodes .= '<td class="celesteClaro"></td>'; $specialCounter++; $html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>';*/ $marginLeft += $jumpRight; $marginLeftCode += 25; } $excelService->writeCellByPositionWithOptions(1,$colsIndex,"", array('height' => 15, 'width' => 5, 'backgroundColor' => '5F96E7')); $excelService->writeCellByPositionWithOptions(2,$colsIndex,'Promedio ' . $temp->getName(), array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => '5F96E7')); $colsIndex += 1; //$studentRow .= '<td class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>'; /*$studentRow .= '<td class="celesteOscuro" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>'; $htmlCodes .= '<td class="celesteOscuro"></td>'; $specialCounter++; $html .= '<td class="celesteOscuro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">Promedio ' . $temp->getName() . ' </div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25;*/ //$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>'; /*$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>'; $htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>'; $specialCounter++; $html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; // $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * (sizeof($subentries)+1)) + ((sizeof($subentries)) * 2) ) . 'px">' . $temp->getName() . '</div>'; $html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+2) . '">' . $temp->getName() . '</td>';*/ $excelService->writeCellByPositionWithOptions(1,$colsIndex,$temp->getCode(), array('height' => 15, 'width' => 5, 'backgroundColor' => 'B698EE')); $excelService->writeCellByPositionWithOptions(2,$colsIndex,$temp->getPercentage() . '% ' . $temp->getName(), array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'B698EE')); $colsIndex += 1; } else { if($size == 1){ foreach( $subentries as $subentry ) { //$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>'; /*$studentRow .= '<td class="celesteClaro"><div><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>'; $colsCounter++; $htmlCodes .= '<td class="celesteClaro"></td>'; $specialCounter++; $html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25;*/ $excelService->writeCellByPositionWithOptions(1,$colsIndex,"", array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD')); $excelService->writeCellByPositionWithOptions(2,$colsIndex,$temp->getPercentage() . '% ' . $temp->getName(), array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'A4D2FD')); $colsIndex += 1; } //$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>'; /*$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>'; $htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>'; $specialCounter++; $html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>'; $marginLeft += $jumpRight; $marginLeftCode += 25; $html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+1) . '">' . $temp->getName() . '</td>';*/ $excelService->writeCellByPositionWithOptions(1,$colsIndex,$temp->getCode(), array('height' => 15, 'width' => 5, 'backgroundColor' => 'B698EE')); $excelService->writeCellByPositionWithOptions(2,$colsIndex,$temp->getPercentage() . '% ' . $temp->getName(), array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'B698EE')); $colsIndex += 1; } } } else { } } /* $htmlCodes .= "</tr>"; $html .= "</tr>"; $html3 .= "</tr>"; $html = '<table class="tableQualifications">' . $htmlCodes . $html . $html3;*/ $studentRowIndex = 4; foreach($students as $stdy){ //$html .= '<tr style="height: 30px; line-height: 0px;">'; $excelService->writeCellByPositionWithOptions($studentRowIndex,0,$stdy->getStudent()->getCarne(), array('height' => 15, 'width' => 10, 'backgroundColor' => '82c0fd')); $excelService->writeCellByPositionWithOptions($studentRowIndex,1,$stdy->getStudent(), array('height' => 15, 'width' => 40, 'backgroundColor' => 'A4D2FD')); $studentRowIndex++; /*$html .= '<td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;">' . $stdy->getStudent()->getCarne() . '</td>'; $html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px;">' . $stdy->getStudent() . '</td>'; $row = str_replace("stdId", $stdy->getStudent()->getId(), $studentRow); $row = str_replace("stdyIdd", $stdy->getId(), $row); //tabIndexColXx for ($i = 1; $i <= $colsCounter; $i++) { $indexVar = "tabIndexCol" . $i . "x"; $row = str_replace($indexVar, "" . ($studentRowIndex + (($i - 1) * $studentsCount)), $row); } $dql = "SELECT qua FROM TecnotekExpedienteBundle:StudentQualification qua" . " WHERE qua.studentYear = " . $stdy->getId(); $query = $em->createQuery($dql); $qualifications = $query->getResult(); foreach($qualifications as $qualification){ $row = str_replace("val_" . $stdy->getStudent()->getId() . "_" . $qualification->getSubCourseEntry()->getId() . "_", "" . $qualification->getQualification(), $row); } $html .= '<td id="total_trim_' . $stdy->getStudent()->getId() . '" class="azul headcoltrim" style="color: #fff;">-</td>' . $row . "</tr>";*/ } $excelService->applyBorderByRange(0, 1, $colsIndex - 1, $studentRowIndex - 1); //$html .= "</table>"; } /*$excelService->writeCellByPosition(1,1,"probando 1"); $excelService->writeCellByPosition(1,2,"probando 2"); $excelService->writeCellByPosition(2,1,"probando 3");*/ //$excelService->writeCellByPosition(row,col,""); $excelService->writeExport($filepath); /*$response = new Response(); $response->setContent("<html><body>OK!!!</body></html>"); $response->setStatusCode(200); /*$response->headers->add('Content-Type', 'text/vnd.ms-excel; charset=utf-8'); $response->headers->add('Content-Disposition', 'attachment;filename=stdream2.xls');*/ //return $response; return new Response(json_encode(array('error' => false))); //create the response /*$response = $excelService->getResponse(); $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment;filename=stdream2.xls'); // If you are using a https connection, you have to set those two headers for compatibility with IE <9 $response->headers->set('Pragma', 'public'); $response->headers->set('Cache-Control', 'maxage=1'); return $response;*/ } public function loadGroupsOfYearAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $year = $request->get('year'); $loadOnlyBachelors = $request->get('loadOnlyBachelors'); if ( !isset($loadOnlyBachelors) ) { $loadOnlyBachelors = false; } else { $loadOnlyBachelors = ($loadOnlyBachelors == "true"); } $translator = $this->get("translator"); if( isset($year) ) { $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('security.context')->getToken()->getUser(); //Get Groups $sqlOnlyBachelors = $loadOnlyBachelors? " AND grade.number = 11 ":""; $sql = "SELECT CONCAT(g.id,'-',grade.id) as 'id', CONCAT(grade.name, ' :: ', g.name) as 'name'" . " FROM tek_groups g, tek_periods p, tek_grades grade" . " WHERE p.orderInYear = 3 AND g.period_id = p.id AND p.year = " . $year . " AND g.grade_id = grade.id" . "" . $sqlOnlyBachelors . " AND g.institution_id in (" . $user->getInstitutionsIdsStr() . ")" . " GROUP BY CONCAT(grade.name, ' :: ', g.name)" . " ORDER BY g.id"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $groups = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'groups' => $groups))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfYearAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function loadCoursesOfGroupAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $keywords = preg_split("/[\s-]+/", $request->get('groupId')); $groupId = $keywords[0]; $translator = $this->get("translator"); if( isset($groupId) ) { $em = $this->getDoctrine()->getEntityManager(); //Get Courses $sql = "SELECT course.id, course.name " . " FROM tek_assigned_teachers tat, tek_course_class tcc, tek_courses course " . " WHERE tat.group_id = " . $groupId . " AND tat.course_class_id = tcc.id AND tcc.course_id = course.id" . " GROUP BY course.id" . " ORDER BY course.name "; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); $courses = $stmt->fetchAll(); return new Response(json_encode(array('error' => false, 'courses' => $courses))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } public function questionnairesAction(){ $em = $this->getDoctrine()->getEntityManager(); $dql = "SELECT q FROM TecnotekExpedienteBundle:Questionnaire q"; $query = $em->createQuery($dql); $questionnaires = $query->getResult(); $groups = $em->getRepository('TecnotekExpedienteBundle:QuestionnaireGroup')->findAll(); $institutions = $em->getRepository('TecnotekExpedienteBundle:Institution')->findAll(); return $this->render('TecnotekExpedienteBundle:SuperAdmin:Questionnaires/list.html.twig', array( 'questionnaires' => $questionnaires, 'groups' => $groups, 'institutions' => $institutions )); } public function saveQuestionnaireConfigAction(){ $logger = $this->get('logger'); if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one? { try { $request = $this->get('request')->request; $questionnaireId = $request->get('q'); $field = $request->get('field'); $val = $request->get('val'); $translator = $this->get("translator"); if( isset($questionnaireId) && isset($field) && isset($val) ) { $em = $this->getDoctrine()->getEntityManager(); $q = new \Tecnotek\ExpedienteBundle\Entity\Questionnaire(); $q = $em->getRepository('TecnotekExpedienteBundle:Questionnaire')->find($questionnaireId); switch($field){ case 'group': $qGroup = $em->getRepository('TecnotekExpedienteBundle:QuestionnaireGroup')->find($val); $q->setGroup($qGroup); break; case 'teacher': $q->setEnabledForTeacher($val == 1); break; case 'institution': $values = preg_split("/[\s-]+/", $val); $institution = $em->getRepository('TecnotekExpedienteBundle:Institution')->find($values[0]); if($values[1] == 0){ $q->getInstitutions()->removeElement($institution); } else { $q->getInstitutions()->add($institution); } break; default: break; } $em->persist($q); $em->flush(); return new Response(json_encode(array('error' => false))); } else { return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing")))); } } catch (Exception $e) { $info = toString($e); $logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]"); return new Response(json_encode(array('error' => true, 'message' => $info))); } }// endif this is an ajax request else { return new Response("<b>Not an ajax call!!!" . "</b>"); } } }
selimcr/Tecnotek_Expediente
src/Tecnotek/ExpedienteBundle/Controller/SuperAdminController.php
PHP
mit
153,919
/** * create edit language file link */ export default (lang) => { return `https://github.com/electerm/electerm-locales/edit/master/locales/${lang}.js` }
electerm/electerm
src/client/common/create-lang-edit-link.js
JavaScript
mit
159
using System.Security.Cryptography.X509Certificates; using Xunit; namespace OpenGost.Security.Cryptography.X509Certificates { public class GostECDsaCertificateExtensionsTests : CryptoConfigRequiredTest { [Theory] [InlineData("GostECDsa256")] [InlineData("GostECDsa512")] public void GetPublicKeyFromX509Certificate2(string certificateName) { var certificate = new X509Certificate2( ResourceUtils.GetBinaryResource( $"OpenGost.Security.Cryptography.Tests.Resources.{certificateName}.cer")); using (var publicKey = certificate.GetECDsaPublicKey()) { Assert.NotNull(publicKey); } } } }
sergezhigunov/gost
tests/OpenGost.Security.Cryptography.Tests/X509Certificates/GostECDsaCertificateExtensionsTests.cs
C#
mit
748
""" The MIT License (MIT) Copyright (c) 2016 Louis-Philippe Querel l_querel@encs.concordia.ca Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from utility.abstract_override import AbstractOverride class JdkOverride(AbstractOverride): def _get_override_format(self): return 'JAVA_HOME="%s"' def _get_default_format(self): return '' def __init__(self, *args): AbstractOverride.__init__(self, *args) self.name = "JDK"
louisq/staticguru
utility/jdk_override.py
Python
mit
1,445
/* Módulo: Financeiro Função: Relatório Recebimento por Cliente Autor.: Jackson Patrick Werka Data..: 01/07/2012 © Copyright 2012-2012 SoftGreen - All Rights Reserved */ //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "uFin3015.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" //--------------------------------------------------------------------------- __fastcall TFin3015::TFin3015(TComponent* Owner) : TfrmRelatBase01(Owner) { } //---------------------------------------------------------------------------
jpwerka/SistemaSFG
Financeiro/uFin3015.cpp
C++
mit
669
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;bitcoinlite&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The bitcoinlite developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Este é um programa experimental. Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php. Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young (eay@cryptsoft.com) e software UPnP escrito por Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Clique duas vezes para editar o endereço ou o rótulo</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Criar um novo endereço</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copie o endereço selecionado para a área de transferência</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your bitcoinlite addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar Endereço</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a bitcoinlite address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Apagar o endereço selecionado da lista</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified bitcoinlite address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>E&amp;liminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;Rótulo</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgulas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(sem rótulo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Diálogo de Frase-Passe</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Escreva a frase de segurança</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova frase de segurança</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita a nova frase de segurança</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Escreva a nova frase de seguraça da sua carteira. &lt;br/&gt; Por favor, use uma frase de &lt;b&gt;10 ou mais caracteres aleatórios,&lt;/b&gt; ou &lt;b&gt;oito ou mais palavras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Encriptar carteira</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desencriptar carteira</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Alterar frase de segurança</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar encriptação da carteira</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Tem a certeza que deseja encriptar a carteira?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Atenção: A tecla Caps Lock está activa!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Carteira encriptada</translation> </message> <message> <location line="-58"/> <source>bitcoinlite will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>A encriptação da carteira falhou</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>As frases de segurança fornecidas não coincidem.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>O desbloqueio da carteira falhou</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>A desencriptação da carteira falhou</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>A frase de segurança da carteira foi alterada com êxito.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+280"/> <source>Sign &amp;message...</source> <translation>Assinar &amp;mensagem...</translation> </message> <message> <location line="+242"/> <source>Synchronizing with network...</source> <translation>Sincronizando com a rede...</translation> </message> <message> <location line="-308"/> <source>&amp;Overview</source> <translation>Visã&amp;o geral</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar visão geral da carteira</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transações</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Navegar pelo histórico de transações</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>Fec&amp;har</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sair da aplicação</translation> </message> <message> <location line="+4"/> <source>Show information about bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar informação sobre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opções...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>E&amp;ncriptar Carteira...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Guardar Carteira...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Mudar &amp;Palavra-passe...</translation> </message> <message numerus="yes"> <location line="+250"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-247"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Send coins to a bitcoinlite address</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Modify configuration options for bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Faça uma cópia de segurança da carteira para outra localização</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Janela de &amp;depuração</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de diagnóstico e depuração</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensagem...</translation> </message> <message> <location line="-200"/> <source>bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+178"/> <source>&amp;About bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar / Ocultar</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>&amp;File</source> <translation>&amp;Ficheiro</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>Con&amp;figurações</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>A&amp;juda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra de separadores</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>bitcoinlite client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to bitcoinlite network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-284"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+288"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Atualizado</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Recuperando...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transação enviada</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transação recebida</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantia: %2 Tipo: %3 Endereço: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid bitcoinlite address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;desbloqueada&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;bloqueada&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. bitcoinlite can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Alerta da Rede</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Quantidade:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioridade:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Taxa:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Saída Baixa:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>não</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Depois de taxas:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Troco:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(des)seleccionar todos</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Modo de árvore</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Modo lista</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Confirmados</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Prioridade</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copiar ID da Transação</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Copiar quantidade</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Taxa de cópia</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Taxa depois de cópia</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Prioridade de Cópia</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copiar output baixo</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copiar alteração</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>o maior</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>alto</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>médio-alto</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>médio</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>baixo-médio</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>baixo</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>O mais baixo</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>sim</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(Sem rótulo)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>Alteração de %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(Alteração)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Endereço</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Rótulo</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>E&amp;ndereço</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Novo endereço de entrada</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Novo endereço de saída</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar endereço de entrada</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar endereço de saída</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>O endereço introduzido &quot;%1&quot; já se encontra no livro de endereços.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid bitcoinlite address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossível desbloquear carteira.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Falha ao gerar nova chave.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>bitcoinlite-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opções</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pagar &amp;taxa de transação</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start bitcoinlite after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start bitcoinlite on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Rede</translation> </message> <message> <location line="+6"/> <source>Automatically open the bitcoinlite client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear porta usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the bitcoinlite network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP do proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta do proxy (p.ex. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versão SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versão do proxy SOCKS (p.ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Janela</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar para a bandeja e não para a barra de ferramentas</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao fechar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Vis&amp;ualização</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Linguagem da interface de utilizador:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting bitcoinlite.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade a usar em quantias:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation> </message> <message> <location line="+9"/> <source>Whether to show bitcoinlite addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Mostrar en&amp;dereços na lista de transações</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation>Escolha para mostrar funcionalidades de controlo &quot;coin&quot; ou não.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>padrão</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting bitcoinlite.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>O endereço de proxy introduzido é inválido. </translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the bitcoinlite network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>O seu saldo disponível para gastar</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Imaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>O saldo minado ainda não maturou</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Total:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>O seu saldo total actual</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transações recentes&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>fora de sincronia</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome do Cliente</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versão do Cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informação</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Usando versão OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo de início</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rede</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de ligações</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Cadeia de blocos</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Número actual de blocos</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Total estimado de blocos</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tempo do último bloco</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the bitcoinlite-Qt help message to get a list with possible bitcoinlite command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data de construção</translation> </message> <message> <location line="-104"/> <source>bitcoinlite - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>bitcoinlite Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Ficheiro de registo de depuração</translation> </message> <message> <location line="+7"/> <source>Open the bitcoinlite debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Limpar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the bitcoinlite RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use as setas para cima e para baixo para navegar no histórico e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar o ecrã.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Digite &lt;b&gt;help&lt;/b&gt; para visualizar os comandos disponíveis.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Funcionalidades de Coin Controlo:</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Entradas</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>Selecção automática</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Fundos insuficientes!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Quantidade:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioridade:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Taxa:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Output Baixo:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Depois de taxas:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Enviar para múltiplos destinatários de uma vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adicionar &amp;Destinatário</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Limpar Tudo</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 BC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirme ação de envio</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a bitcoinlite address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Copiar quantidade</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Taxa de cópia</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Taxa depois de cópia</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Prioridade de Cópia</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copiar output baixo</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copiar alteração</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirme envio de moedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>O endereço de destino não é válido, por favor verifique.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>A quantia a pagar deverá ser maior que 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>A quantia excede o seu saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid bitcoinlite address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(Sem rótulo)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Qu&amp;antia:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Pagar A:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>Rótu&amp;lo:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Cole endereço da área de transferência</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a bitcoinlite address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Assinaturas - Assinar / Verificar uma Mensagem</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>A&amp;ssinar Mensagem</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Cole endereço da área de transferência</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Escreva aqui a mensagem que deseja assinar</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a assinatura actual para a área de transferência</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this bitcoinlite address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Repôr todos os campos de assinatura de mensagem</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpar &amp;Tudo</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified bitcoinlite address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Repôr todos os campos de verificação de mensagem</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a bitcoinlite address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clique &quot;Assinar mensagem&quot; para gerar a assinatura</translation> </message> <message> <location line="+3"/> <source>Enter bitcoinlite signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>O endereço introduzido é inválido. </translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Por favor verifique o endereço e tente de novo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>O endereço introduzido não refere a chave alguma.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>O desbloqueio da carteira foi cancelado.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>A chave privada para o endereço introduzido não está disponível.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Assinatura de mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensagem assinada.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>A assinatura não pôde ser descodificada.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Por favor verifique a assinatura e tente de novo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>A assinatura não condiz com o conteúdo da mensagem.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificação da mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensagem verificada.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/desligado</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/não confirmada</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmações</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Origem</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gerado</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>endereço próprio</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>rótulo</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>não aceite</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Taxa de transação</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Valor líquido</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensagem</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentário</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID da Transação</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informação de depuração</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transação</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadeiro</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, ainda não foi transmitida com sucesso</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>desconhecido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalhes da transação</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Esta janela mostra uma descrição detalhada da transação</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmada (%1 confirmações)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gerado mas não aceite</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Recebido com</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recebido de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento ao próprio</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minadas</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e hora a que esta transação foi recebida.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transação.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Endereço de destino da transação.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantia retirada ou adicionada ao saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Todas</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoje</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mês</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mês passado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este ano</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Período...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recebida com</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviada para</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Para si</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minadas</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Outras</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Escreva endereço ou rótulo a procurar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantia mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar ID da Transação</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar rótulo</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalhes da transação</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgula (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Período:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>até</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>bitcoinlite version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or bitcoinlited</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Listar comandos</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Obter ajuda para um comando</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Opções:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: bitcoinlite.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: bitcoinlited.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Especifique ficheiro de carteira (dentro da pasta de dados)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar pasta de dados</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 28756)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manter no máximo &lt;n&gt; ligações a outros nós da rede (por defeito: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Especifique o seu endereço público</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 28755)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceitar comandos da consola e JSON-RPC</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Correr o processo como um daemon e aceitar comandos</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Utilizar a rede de testes - testnet</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong bitcoinlite will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Opções de criação de bloco:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Apenas ligar ao(s) nó(s) especificado(s)</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Armazenamento intermédio de recepção por ligação, &lt;n&gt;*1000 bytes (por defeito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Armazenamento intermédio de envio por ligação, &lt;n&gt;*1000 bytes (por defeito: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Apenas ligar a nós na rede &lt;net&gt; (IPv4, IPv6 ou Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Opções SSL: (ver a Wiki Bitcoin para instruções de configuração SSL)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Nome de utilizador para ligações JSON-RPC</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupta, recuperação falhou</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Palavra-passe para ligações JSON-RPC</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinliterpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;bitcoinlite Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir ligações JSON-RPC do endereço IP especificado</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comandos para o nó a correr em &lt;ip&gt; (por defeito: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Atualize a carteira para o formato mais recente</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Definir o tamanho da memória de chaves para &lt;n&gt; (por defeito: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para ligações JSON-RPC</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chave privada do servidor (por defeito: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Esta mensagem de ajuda</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. bitcoinlite is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Carregar endereços...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erro ao carregar wallet.dat: Carteira danificada</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of bitcoinlite</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart bitcoinlite to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Erro ao carregar wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Endereço -proxy inválido: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rede desconhecida especificada em -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versão desconhecida de proxy -socks requisitada: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -bind: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Quantia inválida</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Fundos insuficientes</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Carregar índice de blocos...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. bitcoinlite is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Carregar carteira...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Impossível mudar a carteira para uma versão anterior</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Impossível escrever endereço por defeito</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Reexaminando...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Carregamento completo</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Para usar a opção %s</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Deverá definir rpcpassword=&lt;password&gt; no ficheiro de configuração: %s Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation> </message> </context> </TS>
bitcoinlitedev/bitcoinlite-master
src/qt/locale/bitcoin_pt_PT.ts
TypeScript
mit
119,136
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("16-SubsetWithSumS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("16-SubsetWithSumS")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [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("0bbfe77c-7409-4639-bf56-3c9ee7025042")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
svetlai/TelerikAcademy
Programming-with-C#/C#-Part-2/01-Arrays/16-SubsetWithSumS/Properties/AssemblyInfo.cs
C#
mit
1,410
<?php namespace Brainwave\Database; /** * Narrowspark - a PHP 5 framework * * @author Daniel Bannert <info@anolilab.de> * @copyright 2014 Daniel Bannert * @link http://www.narrowspark.de * @license http://www.narrowspark.com/license * @version 0.9.3-dev * @package Narrowspark/framework * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Narrowspark is an open source PHP 5 framework, based on the Slim framework. * */ use \Pimple\Container; use \Brainwave\Support\Arr; use \Brainwave\Database\Connection\ConnectionFactory; use \Brainwave\Database\Connection\Interfaces\ConnectionInterface; use \Brainwave\Database\Connection\Interfaces\ConnectionResolverInterface; /** * DatabaseManager * * @package Narrowspark/Database * @author Daniel Bannert * @since 0.9.2-dev * */ class DatabaseManager implements ConnectionResolverInterface { /** * The application instance. * * @var \Pimple\Container */ protected $app; /** * The database connection factory instance. * * @var \Brainwave\Database\Connection\ConnectionFactory */ protected $factory; /** * The active connection instances. * * @var array */ protected $connections = []; /** * The custom connection resolvers. * * @var array */ protected $extensions = []; /** * Create a new database manager instance. * * @param \Pimple\Container $app * @param \Brainwave\Database\Connection\ConnectionFactory $factory * @return void */ public function __construct(Container $app, ConnectionFactory $factory) { $this->app = $app; $this->factory = $factory; } /** * Get a database connection instance. * * @param string $name * @return \Brainwave\Database\Connection\Connection */ public function connection($name = null) { // If we haven't created this connection, we'll create it based on the config // provided in the application. Once we've created the connections we will // set the "fetch mode" for PDO which determines the query return types. if (!isset($this->connections[$name])) { $connection = $this->makeConnection($name); $this->connections[$name] = $this->prepare($connection); } return $this->connections[$name]; } /** * Disconnect from the given database and remove from local cache. * * @param string $name * @return void */ public function purge($name = null) { $this->disconnect($name); unset($this->connections[$name]); } /** * Disconnect from the given database. * * @param string $name * @return void */ public function disconnect($name = null) { if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) { $this->connections[$name]->disconnect(); } } /** * Reconnect to the given database. * * @param string $name * @return \Brainwave\Database\Connection\Connection */ public function reconnect($name = null) { $this->disconnect($name = $name ?: $this->getDefaultConnection()); if (!isset($this->connections[$name])) { return $this->connection($name); } else { return $this->refreshPdoConnections($name); } } /** * Refresh the PDO connections on a given connection. * * @param string $name * @return \Brainwave\Database\Connection\Connection */ protected function refreshPdoConnections($name) { $fresh = $this->makeConnection($name); return $this->connections[$name]->setPdo($fresh->getPdo()); } /** * Make the database connection instance. * * @param string $name * @return \Brainwave\Database\Connection\Connection */ protected function makeConnection($name) { $config = $this->getConfig($name); // First we will check by the connection name to see if an extension has been // registered specifically for that connection. If it has we will call the // Closure and pass it the config allowing it to resolve the connection. if (isset($this->extensions[$name])) { return call_user_func($this->extensions[$name], $config, $name); } $driver = $config['driver']; // Next we will check to see if an extension has been registered for a driver // and will call the Closure if so, which allows us to have a more generic // resolver for the drivers themselves which applies to all connections. if (isset($this->extensions[$driver])) { return call_user_func($this->extensions[$driver], $config, $name); } return $this->factory->make($config, $name); } /** * Prepare the database connection instance. * * @param \Brainwave\Database\Connection\Interfaces\ConnectionInterface $connection * @return \Brainwave\Database\Connection\Connection */ protected function prepare(ConnectionInterface $connection) { $connection->setFetchMode($this->app['settings']['database::fetch']); // The database connection can also utilize a cache manager instance when cache // functionality is used on queries, which provides an expressive interface // to caching both fluent queries and Eloquent queries that are executed. $app = $this->app; $connection->setCacheManager(function () use ($app) { return $app['cache']; }); // Here we'll set a reconnector callback. This reconnector can be any callable // so we will set a Closure to reconnect from this manager with the name of // the connection, which will allow us to reconnect from the connections. $connection->setReconnector(function (ConnectionInterface $connection) { $this->reconnect($connection->getName()); }); return $connection; } /** * Get the configuration for a connection. * * @param string $name * @return array * * @throws \InvalidArgumentException */ protected function getConfig($name) { $name = $name ?: $this->getDefaultConnection(); // To get the database connection configuration, we will just pull each of the // connection configurations and get the configurations for the given name. // If the configuration doesn't exist, we'll throw an exception and bail. $connections = $this->app['settings']['database::connections']; if (is_null($config = Arr::arrayGet($connections, $name))) { throw new \InvalidArgumentException("Database [$name] not configured."); } return $config; } /** * Get the default connection name. * * @return string */ public function getDefaultConnection() { return $this->app['settings']['database::default']; } /** * Set the default connection name. * * @param string $name * @return void */ public function setDefaultConnection($name) { $this->app['settings']['database::default'] = $name; } /** * Register an extension connection resolver. * * @param string $name * @param callable $resolver * @return void */ public function extend($name, callable $resolver) { $this->extensions[$name] = $resolver; } /** * Return all of the created connections. * * @return array */ public function getConnections() { return $this->connections; } /** * Dynamically pass methods to the default connection. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { return call_user_func_array(array($this->connection(), $method), $parameters); } }
ovr/framework-2
src/Brainwave/Database/DatabaseManager.php
PHP
mit
8,220
# -*- coding: utf-8 -*- """ Created on Thu Sep 21 16:29:34 2017 @author: ishort """ import math """ procedure to generate Gaussian of unit area when passed a FWHM""" #IDL: PRO GAUSS2,FWHM,LENGTH,NGAUS def gauss2(fwhm, length): #length=length*1l & FWHM=FWHM*1l #NGAUS=FLTARR(LENGTH) ngaus = [0.0 for i in range(length)] #This expression for CHAR comes from requiring f(x=0.5*FWHM)=0.5*f(x=0): #CHAR=-1d0*ALOG(0.5d0)/(0.5d0*0.5d0*FWHM*FWHM) char = -1.0 * math.log(0.5) / (0.5*0.5*fwhm*fwhm) #This expression for AMP (amplitude) comes from requiring that the #area under the gaussian is unity: #AMP=SQRT(CHAR/PI) amp = math.sqrt(char/math.pi) #FOR CNT=0l,(LENGTH-1) DO BEGIN # X=(CNT-LENGTH/2)*1.d0 # NGAUS(CNT)=AMP*EXP(-CHAR*X^2) #ENDFOR for cnt in range(length): x = 1.0 * (cnt - length/2) ngaus[cnt] = amp * math.exp(-1.0*char*x*x) return ngaus
sevenian3/ChromaStarPy
Gauss2.py
Python
mit
996
/** * @author Ultimo <von.ultimo@gmail.com> * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version 0.1 (25-06-2017) * * Hier schreiben wir die JavaScript Funktionen. * */ src="jquery-3.2.1.min"; $(document).ready(function(){ $("td:contains('-')").filter(":contains('€')").addClass('neg'); $(".betrag").filter(":contains('-')").addClass('neg'); }); function goBack() { window.history.back(); }
vonUltimo/kasse
js/lib.js
JavaScript
mit
446
AMD::Engine.routes.draw do get '/amd/:asset', to: 'assets#finder' end
Yellowen/amd
config/routes.rb
Ruby
mit
72
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("Console-Input-Output")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Console-Input-Output")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [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("863d8aa0-f168-49fe-b8d2-ceffdd496f75")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bstaykov/Telerik-CSharp-Part-1
Console-Input-Output/Console-Input-Output/Properties/AssemblyInfo.cs
C#
mit
1,416
var compare = require('typewiselite') var search = require('binary-search') function compareKeys (a, b) { return compare(a.key, b.key) } module.exports = function (_compare) { var ary = [], kv _compare = _compare || compare function cmp (a, b) { return _compare(a.key, b.key) } return kv = { getIndex: function (key) { return search(ary, {key: key}, cmp, 0, ary.length - 1) }, get: function (key) { var i = this.getIndex(key) return i >= 0 ? ary[i].value : undefined }, has: function (key) { return this.getIndex(key) >= 0 }, //update a key set: function (key, value) { return kv.add({key: key, value: value}) }, add: function (o) { var i = search(ary, o, cmp) //overwrite a key, or insert a key if(i < 0) ary.splice(~i, 0, o) else ary[i] = o return i }, toJSON: function () { return ary.slice() }, store: ary } } module.exports.search = search module.exports.compareKeys = compareKeys
dominictarr/binary-map
index.js
JavaScript
mit
1,040
namespace Grauenwolf.TravellerTools.Names { public class RandomPerson { /// <summary> /// Initializes a new instance of the <see cref="RandomName"/> class. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> internal RandomPerson(Result user) { FirstName = user.name.first.Substring(0, 1).ToUpper() + user.name.first.Substring(1); LastName = user.name.last.Substring(0, 1).ToUpper() + user.name.last.Substring(1); Gender = user.gender == "female" ? "F" : "M"; } internal RandomPerson(string first, string last, string gender) { LastName = last.Substring(0, 1).ToUpper() + last.Substring(1); ; FirstName = first.Substring(0, 1).ToUpper() + first.Substring(1); ; Gender = gender; } public string FirstName { get; set; } public string LastName { get; set; } public string Gender { get; set; } public string FullName { get { return FirstName + " " + LastName; } } } }
Grauenwolf/TravellerTools
TravellerTools/Grauenwolf.TravellerTools.Services/Names/RandomPerson.cs
C#
mit
1,109
define( [ 'jquery', 'angular', 'json!nuke/data/dummy_model.json', 'json!nuke/data/dummy_layout.json', 'text!nuke/demo.html' ], function( $, ng, dummyModel, dummyLayout, htmlDemoTemplate ) { 'use strict'; var module = ng.module( 'NukeDemoApp', [ 'nbe' ] ) .run( [ '$templateCache', function( $templateCache ) { $templateCache.put( 'lib/demo.html', htmlDemoTemplate ); } ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// function NukeDemoController( $scope, $timeout ) { $scope.model = dummyModel; $scope.layout = dummyLayout; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// module.controller( 'NukeDemoController', [ '$scope', '$timeout', NukeDemoController ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// return module; } );
x1B/nbe
examples/nuke/lib/NukeDemoController.js
JavaScript
mit
998
module Editor::Controllers::Document class Export include Editor::Action include ::Noteshare::Core::Document expose :document, :active_item def call(params) @active_item = 'editor' @document = DocumentRepository.find params[:id] ContentManager.new(@document).export redirect_to "/document/#{params[:id]}" end end end
jxxcarlson/noteshare
apps/editor/controllers/document/export.rb
Ruby
mit
368
using UnityEngine; using System.Collections; public class Menu : MonoBehaviour { public GUIStyle exit; public GUIStyle play; // Use this for initialization void Start () { Screen.showCursor = true; } // Update is called once per frame void Update () { } void OnGUI() { if (GUI.Button(new Rect(Screen.width/3,Screen.height/3*2, 250, 150), "", play)) Application.LoadLevel(1); if (GUI.Button(new Rect(Screen.width/3*2,Screen.height/3*2, 250,150), "", exit)) Application.Quit(); } }
lazokin/FollowZeus
Assets/Scripts/Menu.cs
C#
mit
516
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.IO; namespace VSCodeDebug { // ---- Types ------------------------------------------------------------------------- public class Message { public int id { get; } public string format { get; } public dynamic variables { get; } public dynamic showUser { get; } public dynamic sendTelemetry { get; } public Message(int id, string format, dynamic variables = null, bool user = true, bool telemetry = false) { this.id = id; this.format = format; this.variables = variables; this.showUser = user; this.sendTelemetry = telemetry; } } public class StackFrame { public int id { get; } public Source source { get; } public int line { get; } public int column { get; } public string name { get; } public string presentationHint { get; } public StackFrame(int id, string name, Source source, int line, int column, string hint) { this.id = id; this.name = name; this.source = source; // These should NEVER be negative this.line = Math.Max(0, line); this.column = Math.Max(0, column); this.presentationHint = hint; } } public class Scope { public string name { get; } public int variablesReference { get; } public bool expensive { get; } public Scope(string name, int variablesReference, bool expensive = false) { this.name = name; this.variablesReference = variablesReference; this.expensive = expensive; } } public class Variable { public string name { get; } public string value { get; } public string type { get; } public int variablesReference { get; } public Variable(string name, string value, string type, int variablesReference = 0) { this.name = name; this.value = value; this.type = type; this.variablesReference = variablesReference; } } public class Thread { public int id { get; } public string name { get; } public Thread(int id, string name) { this.id = id; if (name == null || name.Length == 0) { this.name = string.Format("Thread #{0}", id); } else { this.name = name; } } } public class Source { public string name { get; } public string path { get; } public int sourceReference { get; } public string presentationHint { get; } public Source(string name, string path, int sourceReference, string hint) { this.name = name; this.path = path; this.sourceReference = sourceReference; this.presentationHint = hint; } } public class Breakpoint { public bool verified { get; } public int line { get; } public Breakpoint(bool verified, int line) { this.verified = verified; this.line = line; } } // ---- Events ------------------------------------------------------------------------- public class InitializedEvent : Event { public InitializedEvent() : base("initialized") { } } public class StoppedEvent : Event { public StoppedEvent(int tid, string reasn, string txt = null) : base("stopped", new { threadId = tid, reason = reasn, text = txt }) { } } public class ExitedEvent : Event { public ExitedEvent(int exCode) : base("exited", new { exitCode = exCode } ) { } } public class TerminatedEvent : Event { public TerminatedEvent() : base("terminated") { } } public class ThreadEvent : Event { public ThreadEvent(string reasn, int tid) : base("thread", new { reason = reasn, threadId = tid }) { } } public class OutputEvent : Event { public OutputEvent(string cat, string outpt) : base("output", new { category = cat, output = outpt }) { } } // ---- Response ------------------------------------------------------------------------- public class Capabilities : ResponseBody { public bool supportsConfigurationDoneRequest; public bool supportsFunctionBreakpoints; public bool supportsConditionalBreakpoints; public bool supportsEvaluateForHovers; public dynamic[] exceptionBreakpointFilters; } public class ErrorResponseBody : ResponseBody { public Message error { get; } public ErrorResponseBody(Message error) { this.error = error; } } public class StackTraceResponseBody : ResponseBody { public StackFrame[] stackFrames { get; } public int totalFrames { get; } public StackTraceResponseBody(List<StackFrame> frames, int total) { stackFrames = frames.ToArray<StackFrame>(); totalFrames = total; } } public class ScopesResponseBody : ResponseBody { public Scope[] scopes { get; } public ScopesResponseBody(List<Scope> scps) { scopes = scps.ToArray<Scope>(); } } public class VariablesResponseBody : ResponseBody { public Variable[] variables { get; } public VariablesResponseBody(List<Variable> vars) { variables = vars.ToArray<Variable>(); } } public class ThreadsResponseBody : ResponseBody { public Thread[] threads { get; } public ThreadsResponseBody(List<Thread> ths) { threads = ths.ToArray<Thread>(); } } public class EvaluateResponseBody : ResponseBody { public string result { get; } public int variablesReference { get; } public EvaluateResponseBody(string value, int reff = 0) { result = value; variablesReference = reff; } } public class SetBreakpointsResponseBody : ResponseBody { public Breakpoint[] breakpoints { get; } public SetBreakpointsResponseBody(List<Breakpoint> bpts = null) { if (bpts == null) breakpoints = new Breakpoint[0]; else breakpoints = bpts.ToArray<Breakpoint>(); } } // ---- The Session -------------------------------------------------------- public abstract class DebugSession : ProtocolServer { private bool _clientLinesStartAt1 = true; private bool _clientPathsAreURI = true; public DebugSession() { } public void SendResponse(Response response, dynamic body = null) { if (body != null) { response.SetBody(body); } SendMessage(response); } public void SendErrorResponse(Response response, int id, string format, dynamic arguments = null, bool user = true, bool telemetry = false) { var msg = new Message(id, format, arguments, user, telemetry); var message = Utilities.ExpandVariables(msg.format, msg.variables); response.SetErrorBody(message, new ErrorResponseBody(msg)); SendMessage(response); } protected override void DispatchRequest(string command, dynamic args, Response response) { if (args == null) { args = new { }; } try { switch (command) { case "initialize": if (args.linesStartAt1 != null) { _clientLinesStartAt1 = (bool)args.linesStartAt1; } var pathFormat = (string)args.pathFormat; if (pathFormat != null) { switch (pathFormat) { case "uri": _clientPathsAreURI = true; break; case "path": _clientPathsAreURI = false; break; default: SendErrorResponse(response, 1015, "initialize: bad value '{_format}' for pathFormat", new { _format = pathFormat }); return; } } Initialize(response, args); break; case "launch": Launch(response, args); break; case "attach": Attach(response, args); break; case "disconnect": Disconnect(response, args); break; case "next": Next(response, args); break; case "continue": Continue(response, args); break; case "stepIn": StepIn(response, args); break; case "stepOut": StepOut(response, args); break; case "pause": Pause(response, args); break; case "stackTrace": StackTrace(response, args); break; case "scopes": Scopes(response, args); break; case "variables": Variables(response, args); break; case "source": Source(response, args); break; case "threads": Threads(response, args); break; case "setBreakpoints": SetBreakpoints(response, args); break; case "setFunctionBreakpoints": SetFunctionBreakpoints(response, args); break; case "setExceptionBreakpoints": SetExceptionBreakpoints(response, args); break; case "evaluate": Evaluate(response, args); break; default: SendErrorResponse(response, 1014, "unrecognized request: {_request}", new { _request = command }); break; } } catch (Exception e) { SendErrorResponse(response, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message }); } if (command == "disconnect") { Stop(); } } public abstract void Initialize(Response response, dynamic args); public abstract void Launch(Response response, dynamic arguments); public abstract void Attach(Response response, dynamic arguments); public abstract void Disconnect(Response response, dynamic arguments); public virtual void SetFunctionBreakpoints(Response response, dynamic arguments) { } public virtual void SetExceptionBreakpoints(Response response, dynamic arguments) { } public abstract void SetBreakpoints(Response response, dynamic arguments); public abstract void Continue(Response response, dynamic arguments); public abstract void Next(Response response, dynamic arguments); public abstract void StepIn(Response response, dynamic arguments); public abstract void StepOut(Response response, dynamic arguments); public abstract void Pause(Response response, dynamic arguments); public abstract void StackTrace(Response response, dynamic arguments); public abstract void Scopes(Response response, dynamic arguments); public abstract void Variables(Response response, dynamic arguments); public abstract void Source(Response response, dynamic arguments); public abstract void Threads(Response response, dynamic arguments); public abstract void Evaluate(Response response, dynamic arguments); // protected protected int ConvertDebuggerLineToClient(int line) { return _clientLinesStartAt1 ? line : line - 1; } protected int ConvertClientLineToDebugger(int line) { return _clientLinesStartAt1 ? line : line + 1; } protected string ConvertDebuggerPathToClient(string path) { if (_clientPathsAreURI) { try { var uri = new System.Uri(path); return uri.AbsoluteUri; } catch { return null; } } else { return path; } } protected string ConvertClientPathToDebugger(string clientPath) { if (clientPath == null) { return null; } if (_clientPathsAreURI) { if (Uri.IsWellFormedUriString(clientPath, UriKind.Absolute)) { Uri uri = new Uri(clientPath); return uri.LocalPath; } Program.Log("path not well formed: '{0}'", clientPath); return null; } else { return clientPath; } } } }
Microsoft/vscode-mono-debug
src/DebugSession.cs
C#
mit
11,204