repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
starzeng/kityminder
spec/import.js
/** * Created by dongyancen on 13-12-27. */ ///import core/kityminder; ///import core/utils; ///import core/command; ///import core/node; ///import core/module; ///import core/event; ///import core/minder; ///import core/minder.data.compatibility; ///import core/minder.data; ///import core/minder.event; ///import core/minder.module; ///import core/minder.command; ///import core/minder.node; ///import core/minder.select; ///import core/keymap; ///import core/minder.lang; ///import core/minder.defaultoptions; ///import core/minder.preference; ///import core/browser; ///import core/layout; ///import core/connect; ///import core/render; ///import core/theme; ///import core/template; ///import layout/default; ///import layout/default.connect; ///import layout/bottom; ///import layout/filetree; ///import theme/default; ///import theme/snow; ///import theme/fresh; ///import template/structure; ///import module/node; ///import module/text; ///import module/expand; ///import module/outline; ///import module/geometry; ///import module/history; ///import module/progress; ///import module/priority; ///import module/image; ///import module/resource; ///import module/view; ///import module/dragtree; ///import module/keyboard; ///import module/select; ///import module/history; ///import module/editor; ///import module/editor.keyboard; ///import module/editor.range; ///import module/editor.receiver; ///import module/editor.selection; ///import module/basestyle; ///import module/font; ///import module/zoom; ///import module/hyperlink; ///import module/arrange; ///import module/paste; ///import module/style; ///import protocal/xmind; ///import protocal/freemind; ///import protocal/mindmanager; ///import protocal/plain; ///import protocal/json; ///import protocal/png; ///import protocal/svg; ///import ui/ui; ///import ui/eve; ///import ui/fuix; ///import ui/fiox; ///import ui/doc; ///import ui/widget/commandbutton; ///import ui/widget/commandbuttonset; ///import ui/widget/commandinputmenu; ///import ui/widget/friendlytimespan; ///import ui/widget/locallist; ///import ui/widget/netdiskfinder; ///import ui/widget/menutab; ///import ui/menu/menu; ///import ui/menu/header; ///import ui/menu/default; ///import ui/menu/new/new; ///import ui/menu/open/open; ///import ui/menu/open/recent; ///import ui/menu/open/netdisk; ///import ui/menu/open/local; ///import ui/menu/open/draft; ///import ui/menu/save/save; ///import ui/menu/save/netdisk; ///import ui/menu/save/download; ///import ui/menu/share/share; ///import ui/topbar/history; ///import ui/topbar/user; ///import ui/topbar/search; ///import ui/topbar/title; ///import ui/ribbon/tabs; ///import ui/ribbon/idea/insert; ///import ui/ribbon/idea/arrange; ///import ui/ribbon/idea/operation; ///import ui/ribbon/idea/attachment; ///import ui/ribbon/idea/link; ///import ui/ribbon/idea/image; ///import ui/ribbon/idea/priority; ///import ui/ribbon/idea/progress; ///import ui/ribbon/idea/resource; ///import ui/ribbon/appearence/template; ///import ui/ribbon/appearence/theme; ///import ui/ribbon/appearence/layout; ///import ui/ribbon/appearence/style; ///import ui/ribbon/appearence/font; ///import ui/ribbon/appearence/color; ///import ui/ribbon/view/level;
HelixOS/cts
tests/tests/graphics/src/android/graphics/drawable/cts/ColorDrawableTest.java
/* * Copyright (C) 2008 The Android Open Source Project * * 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 android.graphics.drawable.cts; import android.content.res.ColorStateList; import android.content.res.XmlResourceParser; import android.graphics.Color; import android.graphics.PixelFormat; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.ColorDrawable; import android.test.AndroidTestCase; import android.util.AttributeSet; import android.util.Xml; import com.android.cts.graphics.R; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; public class ColorDrawableTest extends AndroidTestCase { public void testConstructors() { new ColorDrawable(); new ColorDrawable(0); new ColorDrawable(1); } public void testDraw() { } public void testAccessAlpha() { ColorDrawable colorDrawable = new ColorDrawable(); assertEquals(0, colorDrawable.getAlpha()); colorDrawable.setAlpha(128); assertEquals(0, colorDrawable.getAlpha()); colorDrawable = new ColorDrawable(1 << 24); assertEquals(1, colorDrawable.getAlpha()); colorDrawable.setAlpha(128); assertEquals(0, colorDrawable.getAlpha()); colorDrawable.setAlpha(255); assertEquals(1, colorDrawable.getAlpha()); } public void testGetChangingConfigurations() { final ColorDrawable colorDrawable = new ColorDrawable(); assertEquals(0, colorDrawable.getChangingConfigurations()); colorDrawable.setChangingConfigurations(1); assertEquals(1, colorDrawable.getChangingConfigurations()); colorDrawable.setChangingConfigurations(Integer.MIN_VALUE); assertEquals(Integer.MIN_VALUE, colorDrawable.getChangingConfigurations()); colorDrawable.setChangingConfigurations(Integer.MAX_VALUE); assertEquals(Integer.MAX_VALUE, colorDrawable.getChangingConfigurations()); } public void testGetConstantState() { final ColorDrawable colorDrawable = new ColorDrawable(); assertNotNull(colorDrawable.getConstantState()); assertEquals(colorDrawable.getChangingConfigurations(), colorDrawable.getConstantState().getChangingConfigurations()); } public void testGetOpacity() { ColorDrawable colorDrawable = new ColorDrawable(); assertEquals(PixelFormat.TRANSPARENT, colorDrawable.getOpacity()); colorDrawable = new ColorDrawable(255 << 24); assertEquals(PixelFormat.OPAQUE, colorDrawable.getOpacity()); colorDrawable = new ColorDrawable(1 << 24); assertEquals(PixelFormat.TRANSLUCENT, colorDrawable.getOpacity()); } public void testInflate() throws XmlPullParserException, IOException { int eventType = -1; final ColorDrawable colorDrawable = new ColorDrawable(); final XmlPullParser parser = mContext.getResources().getXml(R.drawable.colordrawable_test); // start to parse XML document while (eventType != XmlResourceParser.START_TAG && eventType != XmlResourceParser.END_DOCUMENT) { try { eventType = parser.next(); } catch (XmlPullParserException e) { fail(e.getMessage()); } catch (IOException e) { fail(e.getMessage()); } } if (eventType == XmlResourceParser.START_TAG) { final AttributeSet attrs = Xml.asAttributeSet(parser); colorDrawable.inflate(mContext.getResources(), parser, attrs); // set the alpha to 2 in colordrawable_test.xml assertEquals(2, colorDrawable.getAlpha()); } else { fail("XML parser didn't find the start element of the specified xml file."); } } public void testSetColorFilter() { final ColorDrawable d = new ColorDrawable(Color.WHITE); assertEquals(Color.WHITE, DrawableTestingUtils.getPixel(d, 0, 0)); d.setColorFilter(Color.BLACK, Mode.SRC_OVER); assertEquals(Color.BLACK, DrawableTestingUtils.getPixel(d, 0, 0)); } public void testSetTint() { final ColorDrawable d = new ColorDrawable(Color.WHITE); assertEquals(Color.WHITE, DrawableTestingUtils.getPixel(d, 0, 0)); d.setTint(Color.BLACK); d.setTintMode(Mode.SRC_OVER); assertEquals(Color.BLACK, DrawableTestingUtils.getPixel(d, 0, 0)); } }
MRgzhen/yanyu-fast
yanyu-swagger/src/main/java/com/github/mrgzhen/swagger/constant/SwaggerConstant.java
package com.github.mrgzhen.swagger.constant; /** * @author yanyu */ public interface SwaggerConstant { String[] SWAGGER_IGNORING_URL = new String[]{"/v2/api-docs", //swagger api json "/swagger-resources/configuration/ui",//用来获取支持的动作 "/swagger-resources/**",//用来获取api-docs的URI "/swagger-resources/configuration/security",//安全选项 "/webjars/**", "/swagger-ui.html"}; }
JoelLefkowitz/yummy-cereal
tests/unit_tests/utils/test_annotations.py
<gh_stars>1-10 from dataclasses import dataclass from typing import Dict, List from yummy_cereal.utils.annotations import ( cls_is_annotated, field_is_generic_dict, field_is_generic_list, get_cls_annotations, ) @dataclass class AnnotatedClass: name: str names_list: List[str] names_dict: Dict[str, str] class BlankClass: pass def test_cls_is_annotated() -> None: assert cls_is_annotated(AnnotatedClass) assert not cls_is_annotated(BlankClass) def test_get_cls_annotations() -> None: assert get_cls_annotations(AnnotatedClass) == { "name": str, "names_list": List[str], "names_dict": Dict[str, str], } assert get_cls_annotations(BlankClass) == {} def test_is_generic_list() -> None: assert field_is_generic_list(AnnotatedClass, "names_list") assert not field_is_generic_list(AnnotatedClass, "name") assert not field_is_generic_list(AnnotatedClass, "names_dict") def test_is_generic_dict() -> None: assert field_is_generic_dict(AnnotatedClass, "names_dict") assert not field_is_generic_dict(AnnotatedClass, "name") assert not field_is_generic_dict(AnnotatedClass, "names_list")
Devyani606/chatwoot
spec/jobs/inboxes/fetch_imap_email_inboxes_job_spec.rb
<reponame>Devyani606/chatwoot require 'rails_helper' RSpec.describe Inboxes::FetchImapEmailInboxesJob, type: :job do let(:account) { create(:account) } let(:imap_email_channel) do create(:channel_email, imap_enabled: true, imap_address: 'imap.gmail.com', imap_port: 993, imap_email: '<EMAIL>', imap_password: 'password', account: account) end let(:email_inbox) { create(:inbox, channel: imap_email_channel, account: account) } it 'enqueues the job' do expect { described_class.perform_later }.to have_enqueued_job(described_class) .on_queue('low') end context 'when called' do it 'fetch all the email channels' do imap_email_inboxes = double allow(imap_email_inboxes).to receive(:all).and_return([email_inbox]) allow(Inbox).to receive(:where).and_return(imap_email_inboxes) expect(Inboxes::FetchImapEmailsJob).to receive(:perform_later).with(imap_email_channel).once described_class.perform_now end end end
intelie/tinymap
src/test/java/net/intelie/tinymap/support/SetAsserts.java
<reponame>intelie/tinymap package net.intelie.tinymap.support; import net.intelie.tinymap.base.IndexedSet; import java.io.IOException; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SetAsserts { public static void assertSet(Set<String> expected, IndexedSet<String> actual, int removeFrom, int removeTo) throws Exception { assertSizes(expected, actual); assertElements(expected, actual, removeFrom, removeTo); assertElementsInverse(expected, actual, removeFrom, removeTo); assertInvalidIndex(actual, -1); assertInvalidIndex(actual, actual.rawSize()); assertForEach(expected, actual); assertThat(actual.contains("bbb")).isFalse(); assertThat(actual.getIndex("bbb")).isLessThan(0); assertCommonProperties(expected, actual); assertSerialization(actual); } private static void assertSerialization(IndexedSet<String> actual) throws IOException, ClassNotFoundException { byte[] serialized = SerializationHelper.testSerialize(actual); // byte[] serializedExpected = SerializationHelper.testSerialize(expected); // if (expected.size() > 10 && removeTo - removeFrom == 0) // assertThat(serialized.length).isLessThan(2 * serializedExpected.length); Set<String> deserialized = SerializationHelper.testDeserialize(serialized); assertThat(deserialized).isEqualTo(actual); } private static void assertCommonProperties(Set<String> expected, IndexedSet<String> actual) { assertThat(actual.isEmpty()).isEqualTo(expected.isEmpty()); assertThat(expected).isEqualTo(actual); assertThat(actual.toString()).isEqualTo(expected.toString()); assertThat(actual).isEqualTo(expected); assertThat(actual.hashCode()).isEqualTo(expected.hashCode()); HashSet<String> unordered = new HashSet<>(expected); assertThat(actual).isEqualTo(unordered); assertThat(actual.hashCode()).isEqualTo(unordered.hashCode()); unordered.remove("aaa0"); unordered.add("bbb0"); assertThat(actual).isNotEqualTo(unordered); assertThat(actual.hashCode()).isNotEqualTo(unordered.hashCode()); } private static void assertForEach(Set<String> expected, IndexedSet<String> actual) { Iterator<String> expectedIterator = expected.iterator(); actual.forEach(obj -> { assertThat(expectedIterator.hasNext()); String expectedEntry = expectedIterator.next(); assertThat(obj).isEqualTo(expectedEntry); }); } private static void assertInvalidIndex(IndexedSet<String> actual, int index) { assertThatThrownBy(() -> actual.getEntryAt(index)).isInstanceOfAny(UnsupportedOperationException.class, IndexOutOfBoundsException.class); assertThatThrownBy(() -> actual.removeAt(index)).isInstanceOfAny(UnsupportedOperationException.class, IndexOutOfBoundsException.class); } private static void assertElements(Set<String> expected, IndexedSet<String> actual, int removeFrom, int removeTo) { Iterator<String> keysIterator = actual.iterator(); int index = 0; for (String entry : expected) { if (index == removeFrom) index = removeTo; assertThat(actual.getIndex(entry)).isEqualTo(index); assertThat(actual.getEntryAt(index)).isEqualTo(entry); assertThat(keysIterator.hasNext()).isTrue(); assertThat(keysIterator.next()).isEqualTo(entry); index++; } assertThat(keysIterator.hasNext()).isFalse(); } private static void assertElementsInverse(Set<?> expectedSet, IndexedSet<?> actual, int removeFrom, int removeTo) { ListIterator<?> keysIterator = actual.iterator(actual.rawSize()); ListIterator<?> revIterator = new ArrayList<>(expectedSet).listIterator(actual.size()); while (keysIterator.hasNext()) keysIterator.next(); while (revIterator.hasNext()) revIterator.next(); assertThat(keysIterator.nextIndex()).isEqualTo(translateIndex(revIterator.nextIndex(), removeFrom, removeTo)); assertThat(keysIterator.previousIndex()).isEqualTo(translateIndex(revIterator.previousIndex(), removeFrom, removeTo)); int index = expectedSet.size() - 1; while (revIterator.hasPrevious()) { Object entry = revIterator.previous(); assertThat(actual.getIndex(entry)).isEqualTo(translateIndex(index, removeFrom, removeTo)); assertThat(actual.getEntryAt(translateIndex(index, removeFrom, removeTo))).isEqualTo(entry); assertThat(keysIterator.hasPrevious()).isTrue(); assertThat(keysIterator.previous()).isEqualTo(entry); assertThat(keysIterator.nextIndex()).isEqualTo(translateIndex(revIterator.nextIndex(), removeFrom, removeTo)); assertThat(keysIterator.previousIndex()).isEqualTo(translateIndex(revIterator.previousIndex(), removeFrom, removeTo)); index--; } assertThat(keysIterator.hasPrevious()).isFalse(); assertThatThrownBy(() -> keysIterator.previous()).isInstanceOf(NoSuchElementException.class); } private static void assertSizes(Set<String> expected, IndexedSet<String> actual) { assertThat(actual.size()).isEqualTo(expected.size()); } private static int translateIndex(int index, int removeFrom, int removeTo) { if (index >= removeFrom) index += (removeTo - removeFrom); return index; } }
Wassaf-Shahzad/micromasters
static/js/entry/style_public.js
<reponame>Wassaf-Shahzad/micromasters<gh_stars>10-100 __webpack_public_path__ = `${SETTINGS.public_path}` // eslint-disable-line no-undef, camelcase // jquery imported here since style_public.js is loaded before public.js import $ from "jquery" window.jQuery = $ window.$ = $ import "../../scss/public_style/web-icons.css" import "../../scss/public_style/bootstrap-extend.css" import "rrssb/css/rrssb.css"
PedroMoreira87/java
src/geek_exercicios/secao05/E13.java
<gh_stars>0 package secao05; import java.util.Scanner; public class E13 { public static void main(String[] Args){ int num; Scanner scan = new Scanner(System.in); System.out.println("Digite um número inteiro positivo par: "); num = scan.nextInt(); if (num > 0 & num % 2 == 0){ for(int i = 0; i < num + 1; i++){ if (i < num & i % 2 == 0){ System.out.print(i + ", "); }if(i == num & i % 2 == 0){ System.out.print(i); } } }else{ System.out.println("Favor digitar um número inteiro positivo par"); } } }
npocmaka/Windows-Server-2003
net/tcpip/winsock/wshtcpip.c
<gh_stars>10-100 /*++ Copyright (c) 1992 Microsoft Corporation Module Name: WshTcpip.c Abstract: This module contains necessary routines for the TCP/IP Windows Sockets Helper DLL. This DLL provides the transport-specific support necessary for the Windows Sockets DLL to use TCP/IP as a transport. Author: <NAME> (davidtr) 19-Jul-1992 Revision History: <NAME> (keithmo) 02-May-1996 Added WinSock 2 support. <NAME> (dthaler) 17-Jan-2000 Added IGMPv3 support. --*/ #define UNICODE #include <nt.h> #include <ntrtl.h> #include <nturtl.h> #include <winsock2.h> #include <windows.h> #include <stdio.h> #include <ctype.h> #include <wchar.h> #include <tdi.h> #include <ws2tcpip.h> #include <wsahelp.h> #include <ipexport.h> #include <tdistat.h> #include <tdiinfo.h> #include <llinfo.h> #include <ipinfo.h> #include <ntddtcp.h> typedef unsigned long ulong; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned char uchar; #define TL_INSTANCE 0 // private socket options to be accessed via WSAIoctl #include <mstcpip.h> #include <ntddtcp.h> #define NT // temporarily needed by tdiinfo.h... #include <ipexport.h> #include <tdiinfo.h> #include <tcpinfo.h> #include <ipinfo.h> #include <basetyps.h> #include <nspapi.h> #include <nspapip.h> #include <afd.h> #define TCP_NAME L"TCP/IP" #define UDP_NAME L"UDP/IP" #define IS_DGRAM_SOCK(type) (((type) == SOCK_DGRAM) || ((type) == SOCK_RAW)) // // Define valid flags for WSHOpenSocket2(). // #define VALID_TCP_FLAGS (WSA_FLAG_OVERLAPPED) #define VALID_UDP_FLAGS (WSA_FLAG_OVERLAPPED | \ WSA_FLAG_MULTIPOINT_C_LEAF | \ WSA_FLAG_MULTIPOINT_D_LEAF) // // Buffer management constants for GetTcpipInterfaceList(). // #define MAX_FAST_ENTITY_BUFFER ( sizeof(TDIEntityID) * 10 ) #define MAX_FAST_ADDRESS_BUFFER ( sizeof(IPAddrEntry) * 4 ) // // Structure and variables to define the triples supported by TCP/IP. The // first entry of each array is considered the canonical triple for // that socket type; the other entries are synonyms for the first. // typedef struct _MAPPING_TRIPLE { INT AddressFamily; INT SocketType; INT Protocol; } MAPPING_TRIPLE, *PMAPPING_TRIPLE; MAPPING_TRIPLE TcpMappingTriples[] = { AF_INET, SOCK_STREAM, IPPROTO_TCP, AF_INET, SOCK_STREAM, 0, AF_INET, 0, IPPROTO_TCP, AF_UNSPEC, 0, IPPROTO_TCP, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP }; MAPPING_TRIPLE UdpMappingTriples[] = { AF_INET, SOCK_DGRAM, IPPROTO_UDP, AF_INET, SOCK_DGRAM, 0, AF_INET, 0, IPPROTO_UDP, AF_UNSPEC, 0, IPPROTO_UDP, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP }; MAPPING_TRIPLE RawMappingTriples[] = { AF_INET, SOCK_RAW, 0 }; // // Winsock 2 WSAPROTOCOL_INFO structures for all supported protocols. // #define WINSOCK_SPI_VERSION 2 #define UDP_MESSAGE_SIZE (65535-68) WSAPROTOCOL_INFOW Winsock2Protocols[] = { // // TCP // { XP1_GUARANTEED_DELIVERY // dwServiceFlags1 | XP1_GUARANTEED_ORDER | XP1_GRACEFUL_CLOSE | XP1_EXPEDITED_DATA | XP1_IFS_HANDLES, 0, // dwServiceFlags2 0, // dwServiceFlags3 0, // dwServiceFlags4 PFL_MATCHES_PROTOCOL_ZERO, // dwProviderFlags { // gProviderId 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } }, 0, // dwCatalogEntryId { // ProtocolChain BASE_PROTOCOL, // ChainLen { 0, 0, 0, 0, 0, 0, 0 } // ChainEntries }, WINSOCK_SPI_VERSION, // iVersion AF_INET, // iAddressFamily sizeof(SOCKADDR_IN), // iMaxSockAddr sizeof(SOCKADDR_IN), // iMinSockAddr SOCK_STREAM, // iSocketType IPPROTO_TCP, // iProtocol 0, // iProtocolMaxOffset BIGENDIAN, // iNetworkByteOrder SECURITY_PROTOCOL_NONE, // iSecurityScheme 0, // dwMessageSize 0, // dwProviderReserved L"MSAFD Tcpip [TCP/IP]" // szProtocol }, // // UDP // { XP1_CONNECTIONLESS // dwServiceFlags1 | XP1_MESSAGE_ORIENTED | XP1_SUPPORT_BROADCAST | XP1_SUPPORT_MULTIPOINT | XP1_IFS_HANDLES, 0, // dwServiceFlags2 0, // dwServiceFlags3 0, // dwServiceFlags4 PFL_MATCHES_PROTOCOL_ZERO, // dwProviderFlags { // gProviderId 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } }, 0, // dwCatalogEntryId { // ProtocolChain BASE_PROTOCOL, // ChainLen { 0, 0, 0, 0, 0, 0, 0 } // ChainEntries }, WINSOCK_SPI_VERSION, // iVersion AF_INET, // iAddressFamily sizeof(SOCKADDR_IN), // iMaxSockAddr sizeof(SOCKADDR_IN), // iMinSockAddr SOCK_DGRAM, // iSocketType IPPROTO_UDP, // iProtocol 0, // iProtocolMaxOffset BIGENDIAN, // iNetworkByteOrder SECURITY_PROTOCOL_NONE, // iSecurityScheme UDP_MESSAGE_SIZE, // dwMessageSize 0, // dwProviderReserved L"MSAFD Tcpip [UDP/IP]" // szProtocol }, // // RAW // { XP1_CONNECTIONLESS // dwServiceFlags1 | XP1_MESSAGE_ORIENTED | XP1_SUPPORT_BROADCAST | XP1_SUPPORT_MULTIPOINT | XP1_IFS_HANDLES, 0, // dwServiceFlags2 0, // dwServiceFlags3 0, // dwServiceFlags4 PFL_MATCHES_PROTOCOL_ZERO // dwProviderFlags | PFL_HIDDEN, { // gProviderId 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } }, 0, // dwCatalogEntryId { // ProtocolChain BASE_PROTOCOL, // ChainLen { 0, 0, 0, 0, 0, 0, 0 } // ChainEntries }, WINSOCK_SPI_VERSION, // iVersion AF_INET, // iAddressFamily sizeof(SOCKADDR_IN), // iMaxSockAddr sizeof(SOCKADDR_IN), // iMinSockAddr SOCK_RAW, // iSocketType 0, // iProtocol 255, // iProtocolMaxOffset BIGENDIAN, // iNetworkByteOrder SECURITY_PROTOCOL_NONE, // iSecurityScheme UDP_MESSAGE_SIZE, // dwMessageSize 0, // dwProviderReserved L"MSAFD Tcpip [RAW/IP]" // szProtocol } }; #define NUM_WINSOCK2_PROTOCOLS \ ( sizeof(Winsock2Protocols) / sizeof(Winsock2Protocols[0]) ) // // The GUID identifying this provider. // GUID TcpipProviderGuid = { /* e70f1aa0-ab8b-11cf-8ca3-00805f48a192 */ 0xe70f1aa0, 0xab8b, 0x11cf, {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92} }; // // Forward declarations of internal routines. // VOID CompleteTdiActionApc ( IN PVOID ApcContext, IN PIO_STATUS_BLOCK IoStatusBlock ); INT GetTdiInformation ( IN HANDLE TdiConnectionObjectHandle, IN ULONG Entity, IN ULONG Class, IN ULONG Type, IN ULONG Id, IN PVOID Value, IN ULONG InValueLength, IN ULONG OutValueLength ); INT SetTdiInformation ( IN HANDLE TdiConnectionObjectHandle, IN ULONG Entity, IN ULONG Class, IN ULONG Type, IN ULONG Id, IN PVOID Value, IN ULONG ValueLength, IN BOOLEAN WaitForCompletion ); BOOLEAN IsTripleInList ( IN PMAPPING_TRIPLE List, IN ULONG ListLength, IN INT AddressFamily, IN INT SocketType, IN INT Protocol ); NTSTATUS GetTcpipInterfaceList( IN LPVOID OutputBuffer, IN DWORD OutputBufferLength, OUT LPDWORD NumberOfBytesReturned ); INT NtStatusToSocketError ( IN NTSTATUS Status ); // // The socket context structure for this DLL. Each open TCP/IP socket // will have one of these context structures, which is used to maintain // information about the socket. // typedef struct _WSHTCPIP_SOCKET_CONTEXT { INT AddressFamily; INT SocketType; INT Protocol; INT ReceiveBufferSize; DWORD Flags; INT MulticastTtl; ULONG MulticastInterface; struct tcp_keepalive KeepAliveVals; IN_ADDR MultipointTarget; INT HdrInclude; BOOLEAN UcastIf; BOOLEAN MulticastLoopback; BOOLEAN KeepAlive; BOOLEAN DontRoute; BOOLEAN NoDelay; BOOLEAN BsdUrgent; BOOLEAN MultipointLeaf; BOOLEAN UdpNoChecksum; BOOLEAN ReceiveBroadcast; BOOLEAN HdrIncludeSet; BOOLEAN LimitBroadcasts; UCHAR IpPktInfo; UCHAR IpTtl; UCHAR IpTos; UCHAR IpDontFragment; UCHAR IpOptionsLength; UCHAR IpOptions[MAX_OPT_SIZE]; } WSHTCPIP_SOCKET_CONTEXT, *PWSHTCPIP_SOCKET_CONTEXT; #define DEFAULT_RECEIVE_BUFFER_SIZE 8192 #define DEFAULT_MULTICAST_TTL 1 #define DEFAULT_MULTICAST_INTERFACE INADDR_ANY #define DEFAULT_MULTICAST_LOOPBACK TRUE #define DEFAULT_RECEIVE_BROADCAST TRUE #define DEFAULT_UCAST_IF FALSE // // #define DEFAULT_IP_TTL 32 #define DEFAULT_IP_TOS 0 BOOLEAN DllInitialize ( IN PVOID DllHandle, IN ULONG Reason, IN PVOID Context OPTIONAL ) { switch ( Reason ) { case DLL_PROCESS_ATTACH: // // We don't need to receive thread attach and detach // notifications, so disable them to help application // performance. // DisableThreadLibraryCalls( DllHandle ); return TRUE; case DLL_THREAD_ATTACH: break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_DETACH: break; } return TRUE; } // SockInitialize INT WSHGetSockaddrType ( IN PSOCKADDR Sockaddr, IN DWORD SockaddrLength, OUT PSOCKADDR_INFO SockaddrInfo ) /*++ Routine Description: This routine parses a sockaddr to determine the type of the machine address and endpoint address portions of the sockaddr. This is called by the winsock DLL whenever it needs to interpret a sockaddr. Arguments: Sockaddr - a pointer to the sockaddr structure to evaluate. SockaddrLength - the number of bytes in the sockaddr structure. SockaddrInfo - a pointer to a structure that will receive information about the specified sockaddr. Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { UNALIGNED SOCKADDR_IN *sockaddr = (PSOCKADDR_IN)Sockaddr; ULONG i; // // Make sure that the length is correct. // if ( SockaddrLength < sizeof(SOCKADDR_IN) ) { return WSAEFAULT; } // // Make sure that the address family is correct. // if ( sockaddr->sin_family != AF_INET ) { return WSAEAFNOSUPPORT; } // // The address passed the tests, looks like a good address. // Determine the type of the address portion of the sockaddr. // if ( sockaddr->sin_addr.s_addr == INADDR_ANY ) { ASSERT (htonl(INADDR_ANY)==INADDR_ANY); SockaddrInfo->AddressInfo = SockaddrAddressInfoWildcard; } else if ( sockaddr->sin_addr.s_addr == INADDR_BROADCAST ) { ASSERT (htonl(INADDR_BROADCAST)==INADDR_BROADCAST); SockaddrInfo->AddressInfo = SockaddrAddressInfoBroadcast; } else if ( sockaddr->sin_addr.s_addr == htonl(INADDR_LOOPBACK) ) { SockaddrInfo->AddressInfo = SockaddrAddressInfoLoopback; } else { SockaddrInfo->AddressInfo = SockaddrAddressInfoNormal; } // // Determine the type of the port (endpoint) in the sockaddr. // if ( sockaddr->sin_port == 0 ) { SockaddrInfo->EndpointInfo = SockaddrEndpointInfoWildcard; } else if ( ntohs( sockaddr->sin_port ) < 1025 ) { SockaddrInfo->EndpointInfo = SockaddrEndpointInfoReserved; } else { SockaddrInfo->EndpointInfo = SockaddrEndpointInfoNormal; } // // Zero out the sin_zero part of the address. We silently allow // nonzero values in this field. // for ( i = 0; i < sizeof(sockaddr->sin_zero); i++ ) { sockaddr->sin_zero[i] = 0; } return NO_ERROR; } // WSHGetSockaddrType INT WSHGetSocketInformation ( IN PVOID HelperDllSocketContext, IN SOCKET SocketHandle, IN HANDLE TdiAddressObjectHandle, IN HANDLE TdiConnectionObjectHandle, IN INT Level, IN INT OptionName, OUT PCHAR OptionValue, OUT PINT OptionLength ) /*++ Routine Description: This routine retrieves information about a socket for those socket options supported in this helper DLL. The options supported here are SO_KEEPALIVE, SO_DONTROUTE, and TCP_EXPEDITED_1122. This routine is called by the winsock DLL when a level/option name combination is passed to getsockopt() that the winsock DLL does not understand. Arguments: HelperDllSocketContext - the context pointer returned from WSHOpenSocket(). SocketHandle - the handle of the socket for which we're getting information. TdiAddressObjectHandle - the TDI address object of the socket, if any. If the socket is not yet bound to an address, then it does not have a TDI address object and this parameter will be NULL. TdiConnectionObjectHandle - the TDI connection object of the socket, if any. If the socket is not yet connected, then it does not have a TDI connection object and this parameter will be NULL. Level - the level parameter passed to getsockopt(). OptionName - the optname parameter passed to getsockopt(). OptionValue - the optval parameter passed to getsockopt(). OptionLength - the optlen parameter passed to getsockopt(). Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { PWSHTCPIP_SOCKET_CONTEXT context = HelperDllSocketContext; UNREFERENCED_PARAMETER( SocketHandle ); UNREFERENCED_PARAMETER( TdiAddressObjectHandle ); UNREFERENCED_PARAMETER( TdiConnectionObjectHandle ); // // Check if this is an internal request for context information. // if ( Level == SOL_INTERNAL && OptionName == SO_CONTEXT ) { // // The Windows Sockets DLL is requesting context information // from us. If an output buffer was not supplied, the Windows // Sockets DLL is just requesting the size of our context // information. // if ( OptionValue != NULL ) { // // Make sure that the buffer is sufficient to hold all the // context information. // if ( *OptionLength < sizeof(*context) ) { return WSAEFAULT; } // // Copy in the context information. // RtlCopyMemory( OptionValue, context, sizeof(*context) ); } *OptionLength = sizeof(*context); return NO_ERROR; } // // The only other levels we support here are SOL_SOCKET, // IPPROTO_TCP, IPPROTO_UDP, and IPPROTO_IP. // if ( Level != SOL_SOCKET && Level != IPPROTO_TCP && Level != IPPROTO_UDP && Level != IPPROTO_IP ) { return WSAEINVAL; } // // Make sure that the output buffer is sufficiently large. // if ( *OptionLength < sizeof(char)) { return WSAEFAULT; } __try { RtlZeroMemory( OptionValue, *OptionLength ); } __except (EXCEPTION_EXECUTE_HANDLER) { return WSAEFAULT; } // // Handle TCP-level options. // if ( Level == IPPROTO_TCP ) { if ( IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } switch ( OptionName ) { case TCP_NODELAY: *OptionValue = context->NoDelay; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); break; case TCP_EXPEDITED_1122: *OptionValue = !context->BsdUrgent; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); break; default: return WSAEINVAL; } return NO_ERROR; } // // Handle UDP-level options. // if ( Level == IPPROTO_UDP ) { switch ( OptionName ) { case UDP_NOCHECKSUM : // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } *OptionValue = context->UdpNoChecksum; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); break; break; default : return WSAEINVAL; } return NO_ERROR; } // // Handle IP-level options. // if ( Level == IPPROTO_IP ) { // // Act based on the specific option. // switch ( OptionName ) { case IP_TTL: *OptionValue = (char) context->IpTtl; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); return NO_ERROR; case IP_TOS: *OptionValue = (char) context->IpTos; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); return NO_ERROR; case IP_DONTFRAGMENT: *OptionValue = (char) context->IpDontFragment; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); return NO_ERROR; case IP_OPTIONS: if ( *OptionLength < context->IpOptionsLength ) { return WSAEFAULT; } if (context->IpOptionsLength>0) { RtlMoveMemory( OptionValue, context->IpOptions, context->IpOptionsLength ); } *OptionLength = context->IpOptionsLength; return NO_ERROR; default: // // No match, fall through. // break; } // // The following IP options are only valid on datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // Act based on the specific option. // switch ( OptionName ) { case IP_MULTICAST_TTL: *OptionValue = (char)context->MulticastTtl; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); return NO_ERROR; case IP_MULTICAST_IF: *(int *)OptionValue = context->MulticastInterface; *OptionLength = sizeof(int); return NO_ERROR; case IP_MULTICAST_LOOP: *OptionValue = context->MulticastLoopback; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); return NO_ERROR; case IP_HDRINCL: // User hdr include option // // if (*OptionLength<sizeof (int)) return WSAEFAULT; if (context->HdrIncludeSet == TRUE) { *((PINT)OptionValue) = context->HdrInclude; } else { *((PINT)OptionValue) = 0; } *OptionLength = sizeof(int); return NO_ERROR; case IP_PKTINFO: *OptionValue = (char) context->IpPktInfo; *OptionLength = *OptionLength < sizeof (int) ? sizeof (char) : sizeof(int); return NO_ERROR; case IP_RECEIVE_BROADCAST: if (*OptionLength < sizeof(int)) return WSAEFAULT; *((PINT)OptionValue) = context->ReceiveBroadcast; *OptionLength = sizeof(int); return NO_ERROR; default: return WSAENOPROTOOPT; } } // // Handle socket-level options. // switch ( OptionName ) { case SO_KEEPALIVE: if ( IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } *OptionValue = context->KeepAlive; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); break; case SO_DONTROUTE: *OptionValue = context->DontRoute; *OptionLength = *OptionLength<sizeof (int) ? sizeof (char) : sizeof(int); break; default: return WSAENOPROTOOPT; } return NO_ERROR; } // WSHGetSocketInformation INT WSHGetWildcardSockaddr ( IN PVOID HelperDllSocketContext, OUT PSOCKADDR Sockaddr, OUT PINT SockaddrLength ) /*++ Routine Description: This routine returns a wildcard socket address. A wildcard address is one which will bind the socket to an endpoint of the transport's choosing. For TCP/IP, a wildcard address has IP address == 0.0.0.0 and port = 0. Arguments: HelperDllSocketContext - the context pointer returned from WSHOpenSocket() for the socket for which we need a wildcard address. Sockaddr - points to a buffer which will receive the wildcard socket address. SockaddrLength - receives the length of the wioldcard sockaddr. Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { if ( *SockaddrLength < sizeof(SOCKADDR_IN) ) { return WSAEFAULT; } *SockaddrLength = sizeof(SOCKADDR_IN); // // Just zero out the address and set the family to AF_INET--this is // a wildcard address for TCP/IP. // RtlZeroMemory( Sockaddr, sizeof(SOCKADDR_IN) ); Sockaddr->sa_family = AF_INET; return NO_ERROR; } // WSAGetWildcardSockaddr DWORD WSHGetWinsockMapping ( OUT PWINSOCK_MAPPING Mapping, IN DWORD MappingLength ) /*++ Routine Description: Returns the list of address family/socket type/protocol triples supported by this helper DLL. Arguments: Mapping - receives a pointer to a WINSOCK_MAPPING structure that describes the triples supported here. MappingLength - the length, in bytes, of the passed-in Mapping buffer. Return Value: DWORD - the length, in bytes, of a WINSOCK_MAPPING structure for this helper DLL. If the passed-in buffer is too small, the return value will indicate the size of a buffer needed to contain the WINSOCK_MAPPING structure. --*/ { DWORD mappingLength; mappingLength = sizeof(WINSOCK_MAPPING) - sizeof(MAPPING_TRIPLE) + sizeof(TcpMappingTriples) + sizeof(UdpMappingTriples) + sizeof(RawMappingTriples); // // If the passed-in buffer is too small, return the length needed // now without writing to the buffer. The caller should allocate // enough memory and call this routine again. // if ( mappingLength > MappingLength ) { return mappingLength; } // // Fill in the output mapping buffer with the list of triples // supported in this helper DLL. // Mapping->Rows = sizeof(TcpMappingTriples) / sizeof(TcpMappingTriples[0]) + sizeof(UdpMappingTriples) / sizeof(UdpMappingTriples[0]) + sizeof(RawMappingTriples) / sizeof(RawMappingTriples[0]); Mapping->Columns = sizeof(MAPPING_TRIPLE) / sizeof(DWORD); RtlMoveMemory( Mapping->Mapping, TcpMappingTriples, sizeof(TcpMappingTriples) ); RtlMoveMemory( (PCHAR)Mapping->Mapping + sizeof(TcpMappingTriples), UdpMappingTriples, sizeof(UdpMappingTriples) ); RtlMoveMemory( (PCHAR)Mapping->Mapping + sizeof(TcpMappingTriples) + sizeof(UdpMappingTriples), RawMappingTriples, sizeof(RawMappingTriples) ); // // Return the number of bytes we wrote. // return mappingLength; } // WSHGetWinsockMapping INT WSHOpenSocket ( IN OUT PINT AddressFamily, IN OUT PINT SocketType, IN OUT PINT Protocol, OUT PUNICODE_STRING TransportDeviceName, OUT PVOID *HelperDllSocketContext, OUT PDWORD NotificationEvents ) { return WSHOpenSocket2( AddressFamily, SocketType, Protocol, 0, // Group 0, // Flags TransportDeviceName, HelperDllSocketContext, NotificationEvents ); } // WSHOpenSocket INT WSHOpenSocket2 ( IN OUT PINT AddressFamily, IN OUT PINT SocketType, IN OUT PINT Protocol, IN GROUP Group, IN DWORD Flags, OUT PUNICODE_STRING TransportDeviceName, OUT PVOID *HelperDllSocketContext, OUT PDWORD NotificationEvents ) /*++ Routine Description: Does the necessary work for this helper DLL to open a socket and is called by the winsock DLL in the socket() routine. This routine verifies that the specified triple is valid, determines the NT device name of the TDI provider that will support that triple, allocates space to hold the socket's context block, and canonicalizes the triple. Arguments: AddressFamily - on input, the address family specified in the socket() call. On output, the canonicalized value for the address family. SocketType - on input, the socket type specified in the socket() call. On output, the canonicalized value for the socket type. Protocol - on input, the protocol specified in the socket() call. On output, the canonicalized value for the protocol. Group - Identifies the group for the new socket. Flags - Zero or more WSA_FLAG_* flags as passed into WSASocket(). TransportDeviceName - receives the name of the TDI provider that will support the specified triple. HelperDllSocketContext - receives a context pointer that the winsock DLL will return to this helper DLL on future calls involving this socket. NotificationEvents - receives a bitmask of those state transitions this helper DLL should be notified on. Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { PWSHTCPIP_SOCKET_CONTEXT context; BOOLEAN FreeDeviceNameBuffer = FALSE; // // Determine whether this is to be a TCP, UDP, or RAW socket. // if ( IsTripleInList( TcpMappingTriples, sizeof(TcpMappingTriples) / sizeof(TcpMappingTriples[0]), *AddressFamily, *SocketType, *Protocol ) ) { // // It's a TCP socket. Check the flags. // if( ( Flags & ~VALID_TCP_FLAGS ) != 0 ) { return WSAEINVAL; } // // Return the canonical form of a TCP socket triple. // *AddressFamily = TcpMappingTriples[0].AddressFamily; *SocketType = TcpMappingTriples[0].SocketType; *Protocol = TcpMappingTriples[0].Protocol; // // Indicate the name of the TDI device that will service // SOCK_STREAM sockets in the internet address family. // RtlInitUnicodeString( TransportDeviceName, DD_TCP_DEVICE_NAME ); } else if ( IsTripleInList( UdpMappingTriples, sizeof(UdpMappingTriples) / sizeof(UdpMappingTriples[0]), *AddressFamily, *SocketType, *Protocol ) ) { // // It's a UDP socket. Check the flags & group ID. // if( ( Flags & ~VALID_UDP_FLAGS ) != 0 || Group == SG_CONSTRAINED_GROUP ) { return WSAEINVAL; } // // Return the canonical form of a UDP socket triple. // *AddressFamily = UdpMappingTriples[0].AddressFamily; *SocketType = UdpMappingTriples[0].SocketType; *Protocol = UdpMappingTriples[0].Protocol; // // Indicate the name of the TDI device that will service // SOCK_DGRAM sockets in the internet address family. // RtlInitUnicodeString( TransportDeviceName, DD_UDP_DEVICE_NAME ); } else if ( IsTripleInList( RawMappingTriples, sizeof(RawMappingTriples) / sizeof(RawMappingTriples[0]), *AddressFamily, *SocketType, *Protocol ) ) { UNICODE_STRING unicodeString; NTSTATUS status; // // There is no canonicalization to be done for SOCK_RAW. // if (*Protocol < 0 || *Protocol > 255) { return(WSAEINVAL); } // // Indicate the name of the TDI device that will service // SOCK_RAW sockets in the internet address family. // RtlInitUnicodeString(&unicodeString, DD_RAW_IP_DEVICE_NAME); RtlInitUnicodeString(TransportDeviceName, NULL); TransportDeviceName->MaximumLength = unicodeString.Length + (4 * sizeof(WCHAR) + sizeof(UNICODE_NULL)); TransportDeviceName->Buffer = RtlAllocateHeap( RtlProcessHeap( ), 0, TransportDeviceName->MaximumLength ); if (TransportDeviceName->Buffer == NULL) { return(WSAENOBUFS); } FreeDeviceNameBuffer = TRUE; // // Append the device name. // status = RtlAppendUnicodeStringToString( TransportDeviceName, &unicodeString ); ASSERT(NT_SUCCESS(status)); // // Append a separator. // TransportDeviceName->Buffer[TransportDeviceName->Length/sizeof(WCHAR)] = OBJ_NAME_PATH_SEPARATOR; TransportDeviceName->Length += sizeof(WCHAR); TransportDeviceName->Buffer[TransportDeviceName->Length/sizeof(WCHAR)] = UNICODE_NULL; // // Append the protocol number. // unicodeString.Buffer = TransportDeviceName->Buffer + (TransportDeviceName->Length / sizeof(WCHAR)); unicodeString.Length = 0; unicodeString.MaximumLength = TransportDeviceName->MaximumLength - TransportDeviceName->Length; status = RtlIntegerToUnicodeString( (ULONG) *Protocol, 10, &unicodeString ); TransportDeviceName->Length += unicodeString.Length; ASSERT(NT_SUCCESS(status)); } else { // // This should never happen if the registry information about this // helper DLL is correct. If somehow this did happen, just return // an error. // return WSAEINVAL; } // // Allocate context for this socket. The Windows Sockets DLL will // return this value to us when it asks us to get/set socket options. // context = RtlAllocateHeap( RtlProcessHeap( ), 0, sizeof(*context) ); if ( context == NULL ) { if ( FreeDeviceNameBuffer ) { RtlFreeHeap( RtlProcessHeap( ), 0, TransportDeviceName->Buffer ); } TransportDeviceName->Buffer = NULL; return WSAENOBUFS; } // // Initialize the context for the socket. // context->AddressFamily = *AddressFamily; context->SocketType = *SocketType; context->Protocol = *Protocol; context->ReceiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE; context->Flags = Flags; context->MulticastTtl = DEFAULT_MULTICAST_TTL; context->MulticastInterface = DEFAULT_MULTICAST_INTERFACE; context->MulticastLoopback = DEFAULT_MULTICAST_LOOPBACK; context->KeepAlive = FALSE; context->DontRoute = FALSE; context->NoDelay = FALSE; context->BsdUrgent = TRUE; context->IpDontFragment = FALSE; context->IpTtl = DEFAULT_IP_TTL; context->IpTos = DEFAULT_IP_TOS; context->IpOptionsLength = 0; context->MultipointLeaf = FALSE; context->UdpNoChecksum = FALSE; context->ReceiveBroadcast = DEFAULT_RECEIVE_BROADCAST; context->HdrIncludeSet = FALSE; context->KeepAliveVals.onoff = FALSE; context->UcastIf = DEFAULT_UCAST_IF; context->LimitBroadcasts = FALSE; context->IpPktInfo = FALSE; // // Tell the Windows Sockets DLL which state transitions we're // interested in being notified of. The only times we need to be // called is after a connect has completed so that we can turn on // the sending of keepalives if SO_KEEPALIVE was set before the // socket was connected, when the socket is closed so that we can // free context information, and when a connect fails so that we // can, if appropriate, dial in to the network that will support the // connect attempt. // if (*SocketType == SOCK_STREAM) { *NotificationEvents = WSH_NOTIFY_CONNECT | WSH_NOTIFY_CLOSE | WSH_NOTIFY_CONNECT_ERROR; } else { // *SocketType == SOCK_DGRAM || *SocketType == SOCK_RAW *NotificationEvents = WSH_NOTIFY_CONNECT | WSH_NOTIFY_CLOSE | WSH_NOTIFY_CONNECT_ERROR | WSH_NOTIFY_BIND; } // // Everything worked, return success. // *HelperDllSocketContext = context; return NO_ERROR; } // WSHOpenSocket INT WSHNotify ( IN PVOID HelperDllSocketContext, IN SOCKET SocketHandle, IN HANDLE TdiAddressObjectHandle, IN HANDLE TdiConnectionObjectHandle, IN DWORD NotifyEvent ) /*++ Routine Description: This routine is called by the winsock DLL after a state transition of the socket. Only state transitions returned in the NotificationEvents parameter of WSHOpenSocket() are notified here. This routine allows a winsock helper DLL to track the state of socket and perform necessary actions corresponding to state transitions. Arguments: HelperDllSocketContext - the context pointer given to the winsock DLL by WSHOpenSocket(). SocketHandle - the handle for the socket. TdiAddressObjectHandle - the TDI address object of the socket, if any. If the socket is not yet bound to an address, then it does not have a TDI address object and this parameter will be NULL. TdiConnectionObjectHandle - the TDI connection object of the socket, if any. If the socket is not yet connected, then it does not have a TDI connection object and this parameter will be NULL. NotifyEvent - indicates the state transition for which we're being called. Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { PWSHTCPIP_SOCKET_CONTEXT context = HelperDllSocketContext; INT err; // // We should only be called after a connect() completes or when the // socket is being closed. // if ( NotifyEvent == WSH_NOTIFY_CONNECT ) { ULONG true = TRUE; ULONG false = FALSE; // // If a connection-object option was set on the socket before // it was connected, set the option for real now. // if ( context->KeepAlive ) { err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE, &true, sizeof(true), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->KeepAliveVals.onoff ) { err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE_VALS, &context->KeepAliveVals, sizeof(struct tcp_keepalive), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->NoDelay ) { err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_NODELAY, &true, sizeof(true), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( !context->BsdUrgent ) { err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_BSDURGENT, &false, sizeof(false), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->IpTos != DEFAULT_IP_TOS ) { int value = (int) context->IpTos; err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_TOS, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } } else if ( NotifyEvent == WSH_NOTIFY_CLOSE ) { // // If this is a multipoint leaf, then remove the multipoint target // from the session. // if( context->MultipointLeaf && TdiAddressObjectHandle != NULL ) { struct ip_mreq req; req.imr_multiaddr = context->MultipointTarget; req.imr_interface.s_addr = 0; SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_DEL_MCAST, &req, sizeof(req), TRUE ); } // // Free the socket context. // RtlFreeHeap( RtlProcessHeap( ), 0, context ); } else if ( NotifyEvent == WSH_NOTIFY_CONNECT_ERROR ) { // // Return WSATRY_AGAIN to get wsock32 to attempt the connect // again. Any other return code is ignored. // } else if ( NotifyEvent == WSH_NOTIFY_BIND ) { ULONG true = TRUE; if( context->UdpNoChecksum ) { ULONG flag = FALSE; err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_XSUM, &flag, sizeof(flag), TRUE ); if( err != NO_ERROR ) { return err; } } if ( context->IpTtl != DEFAULT_IP_TTL ) { int value = (int) context->IpTtl; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_TTL, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->IpTos != DEFAULT_IP_TOS ) { int value = (int) context->IpTos; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_TOS, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->MulticastTtl != DEFAULT_MULTICAST_TTL ) { int value = (int) context->MulticastTtl; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCASTTTL, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->MulticastInterface != DEFAULT_MULTICAST_INTERFACE ) { int value = (int) context->MulticastInterface; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCASTIF, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->MulticastLoopback != DEFAULT_MULTICAST_LOOPBACK ) { int value = (int) context->MulticastLoopback; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCASTLOOP, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->HdrIncludeSet ) { err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_HDRINCL, &context->HdrInclude, sizeof (context->HdrInclude), TRUE ); if ( err != NO_ERROR ) { return err; } } if (context->IpOptionsLength > 0 ) { err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IPOPTIONS, context->IpOptions, context->IpOptionsLength, TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->UcastIf != DEFAULT_UCAST_IF ) { int value = (int) context->UcastIf; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_UCASTIF, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->IpDontFragment ) { err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_DONTFRAGMENT, &true, sizeof(true), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->ReceiveBroadcast != DEFAULT_RECEIVE_BROADCAST ) { int value = (int) context->ReceiveBroadcast; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_BROADCAST, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->LimitBroadcasts ) { err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_LIMIT_BCASTS, &true, sizeof(true), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->IpPktInfo ) { err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_PKTINFO, &true, sizeof (TRUE), TRUE ); if ( err != NO_ERROR ) { return err; } } if ( context->ReceiveBufferSize != DEFAULT_RECEIVE_BUFFER_SIZE ) { int value = (int) context->ReceiveBufferSize; err = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_WINDOW, &value, sizeof(int), TRUE ); if ( err != NO_ERROR ) { return err; } } } else { return WSAEINVAL; } return NO_ERROR; } // WSHNotify INT WSHSetSocketInformation ( IN PVOID HelperDllSocketContext, IN SOCKET SocketHandle, IN HANDLE TdiAddressObjectHandle, IN HANDLE TdiConnectionObjectHandle, IN INT Level, IN INT OptionName, IN PCHAR OptionValue, IN INT OptionLength ) /*++ Routine Description: This routine sets information about a socket for those socket options supported in this helper DLL. The options supported here are SO_KEEPALIVE, SO_DONTROUTE, and TCP_EXPEDITED_1122. This routine is called by the winsock DLL when a level/option name combination is passed to setsockopt() that the winsock DLL does not understand. Arguments: HelperDllSocketContext - the context pointer returned from WSHOpenSocket(). SocketHandle - the handle of the socket for which we're getting information. TdiAddressObjectHandle - the TDI address object of the socket, if any. If the socket is not yet bound to an address, then it does not have a TDI address object and this parameter will be NULL. TdiConnectionObjectHandle - the TDI connection object of the socket, if any. If the socket is not yet connected, then it does not have a TDI connection object and this parameter will be NULL. Level - the level parameter passed to setsockopt(). OptionName - the optname parameter passed to setsockopt(). OptionValue - the optval parameter passed to setsockopt(). OptionLength - the optlen parameter passed to setsockopt(). Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { PWSHTCPIP_SOCKET_CONTEXT context = HelperDllSocketContext; INT error; INT optionValue; // // Check if this is an internal request for context information. // if ( Level == SOL_INTERNAL && OptionName == SO_CONTEXT ) { // // The Windows Sockets DLL is requesting that we set context // information for a new socket. If the new socket was // accept()'ed, then we have already been notified of the socket // and HelperDllSocketContext will be valid. If the new socket // was inherited or duped into this process, then this is our // first notification of the socket and HelperDllSocketContext // will be equal to NULL. // // Insure that the context information being passed to us is // sufficiently large. // if ( OptionLength < sizeof(*context) || ( OptionValue == NULL)) { return WSAEINVAL; } if ( HelperDllSocketContext == NULL ) { // // This is our notification that a socket handle was // inherited or duped into this process. Allocate a context // structure for the new socket. // context = RtlAllocateHeap( RtlProcessHeap( ), 0, sizeof(*context) ); if ( context == NULL ) { return WSAENOBUFS; } // // Copy over information into the context block. // RtlCopyMemory( context, OptionValue, sizeof(*context) ); // // Tell the Windows Sockets DLL where our context information is // stored so that it can return the context pointer in future // calls. // *(PWSHTCPIP_SOCKET_CONTEXT *)OptionValue = context; return NO_ERROR; } else { PWSHTCPIP_SOCKET_CONTEXT parentContext; INT one = 1; INT zero = 0; // // The socket was accept()'ed and it needs to have the same // properties as it's parent. The OptionValue buffer // contains the context information of this socket's parent. // parentContext = (PWSHTCPIP_SOCKET_CONTEXT)OptionValue; ASSERT( context->AddressFamily == parentContext->AddressFamily ); ASSERT( context->SocketType == parentContext->SocketType ); ASSERT( context->Protocol == parentContext->Protocol ); // // Turn on in the child any options that have been set in // the parent. First restore the child context to default context. // Ignore all the changes made by APP before acceptex complete. // context->KeepAlive = FALSE; if ( parentContext->KeepAlive ) { error = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, SOL_SOCKET, SO_KEEPALIVE, (PCHAR)&one, sizeof(one) ); if ( error != NO_ERROR ) { return error; } } context->KeepAliveVals.onoff = FALSE; if ( parentContext->KeepAliveVals.onoff ) { struct tcp_keepalive *optionval; // // Atempt to turn on or off keepalive sending, as necessary. // optionval = (struct tcp_keepalive *)&parentContext->KeepAliveVals; if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE_VALS, optionval, sizeof(struct tcp_keepalive), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that keepalives are enabled for this socket. // context->KeepAliveVals.onoff = TRUE; context->KeepAliveVals.keepalivetime = optionval->keepalivetime; context->KeepAliveVals.keepaliveinterval = optionval->keepaliveinterval; } context->DontRoute = FALSE; if ( parentContext->DontRoute ) { error = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, SOL_SOCKET, SO_DONTROUTE, (PCHAR)&one, sizeof(one) ); if ( error != NO_ERROR ) { return error; } } context->NoDelay = FALSE; if ( parentContext->NoDelay ) { error = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_TCP, TCP_NODELAY, (PCHAR)&one, sizeof(one) ); if ( error != NO_ERROR ) { return error; } } context->ReceiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE; if ( parentContext->ReceiveBufferSize != DEFAULT_RECEIVE_BUFFER_SIZE ) { error = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, SOL_SOCKET, SO_RCVBUF, (PCHAR)&parentContext->ReceiveBufferSize, sizeof(parentContext->ReceiveBufferSize) ); if ( error != NO_ERROR ) { return error; } } context->BsdUrgent = TRUE; if ( !parentContext->BsdUrgent ) { error = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_TCP, TCP_EXPEDITED_1122, (PCHAR)&one, sizeof(one) ); if ( error != NO_ERROR ) { return error; } } context->IpTos = DEFAULT_IP_TOS; if ( parentContext->IpTos != DEFAULT_IP_TOS ) { int value = (int) parentContext->IpTos; error = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_IP, IP_TOS, (PCHAR)&value, sizeof(value) ); if ( error != NO_ERROR ) { return error; } } return NO_ERROR; } } // // The only other levels we support here are SOL_SOCKET, // IPPROTO_TCP, IPPROTO_UDP, and IPPROTO_IP. // if ( Level != SOL_SOCKET && Level != IPPROTO_TCP && Level != IPPROTO_UDP && Level != IPPROTO_IP ) { return WSAEINVAL; } // // Make sure that the option length is sufficient. // if ( OptionLength < sizeof(char) || (OptionValue == NULL) ) { return WSAEFAULT; } if ( OptionLength >= sizeof (int)) { optionValue = *((INT UNALIGNED *)OptionValue); } else { optionValue = (UCHAR)*OptionValue; } // // Handle TCP-level options. // if ( Level == IPPROTO_TCP && OptionName == TCP_NODELAY ) { if ( IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // Atempt to turn on or off Nagle's algorithm, as necessary. // if ( !context->NoDelay && optionValue != 0 ) { optionValue = TRUE; // // NoDelay is currently off and the application wants to // turn it on. If the TDI connection object handle is NULL, // then the socket is not yet connected. In this case we'll // just remember that the no delay option was set and // actually turn them on in WSHNotify() after a connect() // has completed on the socket. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_NODELAY, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that no delay is enabled for this socket. // context->NoDelay = TRUE; } else if ( context->NoDelay && optionValue == 0 ) { // // No delay is currently enabled and the application wants // to turn it off. If the TDI connection object is NULL, // the socket is not yet connected. In this case we'll just // remember that nodelay is disabled. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_NODELAY, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that no delay is disabled for this socket. // context->NoDelay = FALSE; } return NO_ERROR; } if ( Level == IPPROTO_TCP && OptionName == TCP_EXPEDITED_1122 ) { if ( IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // Atempt to turn on or off BSD-style urgent data semantics as // necessary. // if ( !context->BsdUrgent && optionValue == 0 ) { optionValue = TRUE; // // BsdUrgent is currently off and the application wants to // turn it on. If the TDI connection object handle is NULL, // then the socket is not yet connected. In this case we'll // just remember that the no delay option was set and // actually turn them on in WSHNotify() after a connect() // has completed on the socket. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_BSDURGENT, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that BSD urgent is enabled for this socket. // context->BsdUrgent = TRUE; } else if ( context->BsdUrgent && optionValue != 0 ) { // // No delay is currently enabled and the application wants // to turn it off. If the TDI connection object is NULL, // the socket is not yet connected. In this case we'll just // remember that BsdUrgent is disabled. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_BSDURGENT, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that BSD urgent is disabled for this socket. // context->BsdUrgent = FALSE; } return NO_ERROR; } // // Handle UDP-level options. // if ( Level == IPPROTO_UDP ) { switch ( OptionName ) { case UDP_NOCHECKSUM : // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } if( TdiAddressObjectHandle != NULL ) { ULONG flag; // // Note that the incoming flag is TRUE if XSUM should // be *disabled*, but the flag we pass to TDI is TRUE // if it should be *enabled*, so we must negate the flag. // flag = (ULONG)!optionValue; error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_XSUM, &flag, sizeof(flag), TRUE ); if( error != NO_ERROR ) { return error; } } context->UdpNoChecksum = !!optionValue; break; default : return WSAEINVAL; } return NO_ERROR; } // // Handle IP-level options. // if ( Level == IPPROTO_IP ) { // // Act based on the specific option. // switch ( OptionName ) { case IP_TTL: // // An attempt to change the unicast TTL sent on // this socket. It is illegal to set this to a value // greater than 255. // if ( optionValue > 255 || optionValue < 0 ) { return WSAEINVAL; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_TTL, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->IpTtl = (uchar) optionValue; return NO_ERROR; case IP_TOS: // // An attempt to change the Type Of Service of packets sent on // this socket. It is illegal to set this to a value // greater than 255. // if ( optionValue > 255 || optionValue < 0 ) { return WSAEINVAL; } // // If we have a TDI address or connectionobject, // set this option to it. If we don't have a TDI // object then we'll have to wait until after the socket // is bound or connected. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_TOS, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } else if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_TOS, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->IpTos = (uchar) optionValue; return NO_ERROR; case IP_MULTICAST_TTL: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // An attempt to change the TTL on multicasts sent on // this socket. It is illegal to set this to a value // greater than 255. // if ( optionValue > 255 || optionValue < 0 ) { return WSAEINVAL; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCASTTTL, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->MulticastTtl = optionValue; return NO_ERROR; case IP_MULTICAST_IF: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCASTIF, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->MulticastInterface = optionValue; return NO_ERROR; case IP_MULTICAST_LOOP: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCASTLOOP, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->MulticastLoopback = optionValue ? TRUE : FALSE; return NO_ERROR; case IP_ADD_MEMBERSHIP: case IP_DROP_MEMBERSHIP: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // Make sure that the option buffer is large enough. // if ( OptionLength < sizeof(struct ip_mreq) ) { return WSAEFAULT; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, OptionName == IP_ADD_MEMBERSHIP ? AO_OPTION_ADD_MCAST : AO_OPTION_DEL_MCAST, OptionValue, OptionLength, TRUE ); if ( error != NO_ERROR ) { return error; } } else { return WSAEINVAL; } return NO_ERROR; case IP_BLOCK_SOURCE: case IP_UNBLOCK_SOURCE: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // Make sure that the option buffer is large enough. // if ( OptionLength < sizeof(struct ip_mreq_source) ) { return WSAEFAULT; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, OptionName == IP_BLOCK_SOURCE ? AO_OPTION_BLOCK_MCAST_SRC : AO_OPTION_UNBLOCK_MCAST_SRC, OptionValue, OptionLength, TRUE ); if ( error != NO_ERROR ) { return error; } } else { return WSAEINVAL; } return NO_ERROR; case IP_ADD_SOURCE_MEMBERSHIP: case IP_DROP_SOURCE_MEMBERSHIP: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } // // Make sure that the option buffer is large enough. // if ( OptionLength < sizeof(struct ip_mreq_source) ) { return WSAEFAULT; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, OptionName == IP_ADD_SOURCE_MEMBERSHIP ? AO_OPTION_ADD_MCAST_SRC : AO_OPTION_DEL_MCAST_SRC, OptionValue, OptionLength, TRUE ); if ( error != NO_ERROR ) { return error; } } else { return WSAEINVAL; } return NO_ERROR; case IP_HDRINCL: // User hdr include option // // if ( OptionLength != 4) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_HDRINCL, &optionValue, OptionLength, TRUE ); if ( error != NO_ERROR ) { return error; } } context->HdrIncludeSet = TRUE; context->HdrInclude = optionValue; return NO_ERROR; case IP_PKTINFO: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_PKTINFO, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->IpPktInfo = optionValue ? TRUE : FALSE; return NO_ERROR; case IP_RECEIVE_BROADCAST: // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } if ( OptionLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_BROADCAST, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->ReceiveBroadcast = optionValue ? TRUE : FALSE; return NO_ERROR; default: // // No match, fall through. // break; } if ( OptionName == IP_OPTIONS ) { // // Setting IP options. // if (OptionLength < 0 || OptionLength > MAX_OPT_SIZE || ( OptionValue == NULL) ) { return WSAEINVAL; } // // Try to set these options. If the TDI address object handle // is NULL, then the socket is not yet bound. In this case we'll // just remember options and actually set them in WSHNotify() // after a bind has completed on the socket. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IPOPTIONS, OptionValue, OptionLength, TRUE ); if ( error != NO_ERROR ) { return error; } } // // They were successfully set. Copy them. // RtlMoveMemory(context->IpOptions, OptionValue, OptionLength); context->IpOptionsLength = (UCHAR)OptionLength; return NO_ERROR; } if ( OptionName == IP_DONTFRAGMENT ) { // // Attempt to turn on or off the DF bit in the IP header. // if ( !context->IpDontFragment && optionValue != 0 ) { optionValue = TRUE; // // DF is currently off and the application wants to // turn it on. If the TDI address object handle is NULL, // then the socket is not yet bound. In this case we'll // just remember that the header inclusion option was set and // actually turn it on in WSHNotify() after a bind // has completed on the socket. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_DONTFRAGMENT, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that header inclusion is enabled for this socket. // context->IpDontFragment = TRUE; } else if ( context->IpDontFragment && optionValue == 0 ) { // // The DF flag is currently set and the application wants // to turn it off. If the TDI address object is NULL, // the socket is not yet bound. In this case we'll just // remember that the flag is turned off. // if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_DONTFRAGMENT, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that DF flag is not set for this socket. // context->IpDontFragment = FALSE; } return NO_ERROR; } // // We don't support this option. // return WSAENOPROTOOPT; } // // Handle socket-level options. // switch ( OptionName ) { case SO_KEEPALIVE: // // Atempt to turn on or off keepalive sending, as necessary. // if ( IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } if ( !context->KeepAlive && optionValue != 0 ) { optionValue = TRUE; // // Keepalives are currently off and the application wants to // turn them on. If the TDI connection object handle is // NULL, then the socket is not yet connected. In this case // we'll just remember that the keepalive option was set and // actually turn them on in WSHNotify() after a connect() // has completed on the socket. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that keepalives are enabled for this socket. // context->KeepAlive = TRUE; } else if ( context->KeepAlive && optionValue == 0 ) { // // Keepalives are currently enabled and the application // wants to turn them off. If the TDI connection object is // NULL, the socket is not yet connected. In this case // we'll just remember that keepalives are disabled. // if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } // // Remember that keepalives are disabled for this socket. // context->KeepAlive = FALSE; } break; case SO_DONTROUTE: // // We don't really support SO_DONTROUTE. Just remember that the // option was set or unset. // if ( optionValue != 0 ) { context->DontRoute = TRUE; } else if ( optionValue == 0 ) { context->DontRoute = FALSE; } break; case SO_RCVBUF: // // If the receive buffer size is being changed, tell TCP about // it. Do nothing if this is a datagram. // if ( context->ReceiveBufferSize == optionValue || IS_DGRAM_SOCK(context->SocketType) ) { break; } if ( TdiConnectionObjectHandle != NULL ) { error = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_WINDOW, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } else if ( TdiAddressObjectHandle != NULL ) { error = SetTdiInformation( TdiAddressObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_WINDOW, &optionValue, sizeof(optionValue), TRUE ); if ( error != NO_ERROR ) { return error; } } context->ReceiveBufferSize = optionValue; break; default: return WSAENOPROTOOPT; } return NO_ERROR; } // WSHSetSocketInformation INT WSHEnumProtocols ( IN LPINT lpiProtocols, IN LPWSTR lpTransportKeyName, IN OUT LPVOID lpProtocolBuffer, IN OUT LPDWORD lpdwBufferLength ) /*++ Routine Description: Enumerates the protocols supported by this helper. Arguments: lpiProtocols - Pointer to a NULL-terminated array of protocol identifiers. Only protocols specified in this array will be returned by this function. If this pointer is NULL, all protocols are returned. lpTransportKeyName - lpProtocolBuffer - Pointer to a buffer to fill with PROTOCOL_INFO structures. lpdwBufferLength - Pointer to a variable that, on input, contains the size of lpProtocolBuffer. On output, this value will be updated with the size of the data actually written to the buffer. Return Value: INT - The number of protocols returned if successful, -1 if not. --*/ { DWORD bytesRequired; PPROTOCOL_INFO tcpProtocolInfo; PPROTOCOL_INFO udpProtocolInfo; BOOL useTcp = FALSE; BOOL useUdp = FALSE; DWORD i; lpTransportKeyName; // Avoid compiler warnings. // // Make sure that the caller cares about TCP and/or UDP. // if ( ARGUMENT_PRESENT( lpiProtocols ) ) { for ( i = 0; lpiProtocols[i] != 0; i++ ) { if ( lpiProtocols[i] == IPPROTO_TCP ) { useTcp = TRUE; } if ( lpiProtocols[i] == IPPROTO_UDP ) { useUdp = TRUE; } } } else { useTcp = TRUE; useUdp = TRUE; } if ( !useTcp && !useUdp ) { *lpdwBufferLength = 0; return 0; } // // Make sure that the caller has specified a sufficiently large // buffer. // bytesRequired = (DWORD)((sizeof(PROTOCOL_INFO) * 2) + ( (wcslen( TCP_NAME ) + 1) * sizeof(WCHAR)) + ( (wcslen( UDP_NAME ) + 1) * sizeof(WCHAR))); if ( bytesRequired > *lpdwBufferLength ) { *lpdwBufferLength = bytesRequired; return -1; } // // Fill in TCP info, if requested. // if ( useTcp ) { tcpProtocolInfo = lpProtocolBuffer; tcpProtocolInfo->dwServiceFlags = XP_GUARANTEED_DELIVERY | XP_GUARANTEED_ORDER | XP_GRACEFUL_CLOSE | XP_EXPEDITED_DATA | XP_FRAGMENTATION; tcpProtocolInfo->iAddressFamily = AF_INET; tcpProtocolInfo->iMaxSockAddr = sizeof(SOCKADDR_IN); tcpProtocolInfo->iMinSockAddr = sizeof(SOCKADDR_IN); tcpProtocolInfo->iSocketType = SOCK_STREAM; tcpProtocolInfo->iProtocol = IPPROTO_TCP; tcpProtocolInfo->dwMessageSize = 0; tcpProtocolInfo->lpProtocol = (LPWSTR) ( (PBYTE)lpProtocolBuffer + *lpdwBufferLength - ( (wcslen( TCP_NAME ) + 1) * sizeof(WCHAR) ) ); wcscpy( tcpProtocolInfo->lpProtocol, TCP_NAME ); udpProtocolInfo = tcpProtocolInfo + 1; udpProtocolInfo->lpProtocol = (LPWSTR) ( (PBYTE)tcpProtocolInfo->lpProtocol - ( (wcslen( UDP_NAME ) + 1) * sizeof(WCHAR) ) ); } else { udpProtocolInfo = lpProtocolBuffer; udpProtocolInfo->lpProtocol = (LPWSTR) ( (PBYTE)lpProtocolBuffer + *lpdwBufferLength - ( (wcslen( UDP_NAME ) + 1) * sizeof(WCHAR) ) ); } // // Fill in UDP info, if requested. // if ( useUdp ) { udpProtocolInfo->dwServiceFlags = XP_CONNECTIONLESS | XP_MESSAGE_ORIENTED | XP_SUPPORTS_BROADCAST | XP_SUPPORTS_MULTICAST | XP_FRAGMENTATION; udpProtocolInfo->iAddressFamily = AF_INET; udpProtocolInfo->iMaxSockAddr = sizeof(SOCKADDR_IN); udpProtocolInfo->iMinSockAddr = sizeof(SOCKADDR_IN); udpProtocolInfo->iSocketType = SOCK_DGRAM; udpProtocolInfo->iProtocol = IPPROTO_UDP; udpProtocolInfo->dwMessageSize = UDP_MESSAGE_SIZE; wcscpy( udpProtocolInfo->lpProtocol, UDP_NAME ); } *lpdwBufferLength = bytesRequired; return (useTcp && useUdp) ? 2 : 1; } // WSHEnumProtocols BOOLEAN IsTripleInList ( IN PMAPPING_TRIPLE List, IN ULONG ListLength, IN INT AddressFamily, IN INT SocketType, IN INT Protocol ) /*++ Routine Description: Determines whether the specified triple has an exact match in the list of triples. Arguments: List - a list of triples (address family/socket type/protocol) to search. ListLength - the number of triples in the list. AddressFamily - the address family to look for in the list. SocketType - the socket type to look for in the list. Protocol - the protocol to look for in the list. Return Value: BOOLEAN - TRUE if the triple was found in the list, false if not. --*/ { ULONG i; // // Walk through the list searching for an exact match. // for ( i = 0; i < ListLength; i++ ) { // // If all three elements of the triple match, return indicating // that the triple did exist in the list. // if ( AddressFamily == List[i].AddressFamily && SocketType == List[i].SocketType && ( (Protocol == List[i].Protocol) || (SocketType == SOCK_RAW) ) ) { return TRUE; } } // // The triple was not found in the list. // return FALSE; } // IsTripleInList INT GetTdiInformation ( IN HANDLE TdiConnectionObjectHandle, IN ULONG Entity, IN ULONG Class, IN ULONG Type, IN ULONG Id, IN PVOID Value, IN ULONG InValueLength, IN ULONG OutValueLength ) { NTSTATUS status; TCP_REQUEST_QUERY_INFORMATION_EX tcpRequest; IO_STATUS_BLOCK ioStatusBlock; ASSERT(InValueLength <= CONTEXT_SIZE); // // Initialize the TDI information buffers. // RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); tcpRequest.ID.toi_entity.tei_entity = Entity; tcpRequest.ID.toi_entity.tei_instance = TL_INSTANCE; tcpRequest.ID.toi_class = Class; tcpRequest.ID.toi_type = Type; tcpRequest.ID.toi_id = Id; RtlCopyMemory(tcpRequest.Context, Value, InValueLength); // // Make the actual TDI action call. The Streams TDI mapper will // translate this into a TPI option management request for us and // give it to TCP/IP. // status = NtDeviceIoControlFile( TdiConnectionObjectHandle, NULL, NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), Value, OutValueLength ); if (NT_SUCCESS (status)) { return NO_ERROR; } else { return NtStatusToSocketError (status); } } INT SetTdiInformation ( IN HANDLE TdiConnectionObjectHandle, IN ULONG Entity, IN ULONG Class, IN ULONG Type, IN ULONG Id, IN PVOID Value, IN ULONG ValueLength, IN BOOLEAN WaitForCompletion ) /*++ Routine Description: Performs a TDI action to the TCP/IP driver. A TDI action translates into a streams T_OPTMGMT_REQ. Arguments: TdiConnectionObjectHandle - a TDI connection object on which to perform the TDI action. Entity - value to put in the tei_entity field of the TDIObjectID structure. Class - value to put in the toi_class field of the TDIObjectID structure. Type - value to put in the toi_type field of the TDIObjectID structure. Id - value to put in the toi_id field of the TDIObjectID structure. Value - a pointer to a buffer to set as the information. ValueLength - the length of the buffer. WaitForCompletion - TRUE if we should wait for the TDI action to complete, FALSE if we're at APC level and cannot do a wait. Return Value: INT - NO_ERROR, or a Windows Sockets error code. --*/ { NTSTATUS status; PTCP_REQUEST_SET_INFORMATION_EX setInfoEx; PIO_STATUS_BLOCK ioStatusBlock; PVOID completionApc; PVOID apcContext; CHAR localBuffer[sizeof (IO_STATUS_BLOCK) + sizeof (TCP_REQUEST_SET_INFORMATION_EX) + 32]; if (WaitForCompletion || ValueLength>32) { // // Allocate space to hold the TDI set information buffers and the IO // status block. These cannot be stack variables in case we must // return before the operation is complete. // ioStatusBlock = RtlAllocateHeap( RtlProcessHeap( ), 0, sizeof(*ioStatusBlock) + sizeof(*setInfoEx) + ValueLength ); if ( ioStatusBlock == NULL ) { return WSAENOBUFS; } } else { ioStatusBlock = (PIO_STATUS_BLOCK)&localBuffer; } // // Initialize the TDI information buffers. // setInfoEx = (PTCP_REQUEST_SET_INFORMATION_EX)(ioStatusBlock + 1); setInfoEx->ID.toi_entity.tei_entity = Entity; setInfoEx->ID.toi_entity.tei_instance = TL_INSTANCE; setInfoEx->ID.toi_class = Class; setInfoEx->ID.toi_type = Type; setInfoEx->ID.toi_id = Id; RtlCopyMemory( setInfoEx->Buffer, Value, ValueLength ); setInfoEx->BufferSize = ValueLength; // // If we need to wait for completion of the operation, create an // event to wait on. If we can't wait for completion because we // are being called at APC level, we'll use an APC routine to // free the heap we allocated above. // if ( WaitForCompletion ) { completionApc = NULL; apcContext = NULL; } else { completionApc = CompleteTdiActionApc; apcContext = ioStatusBlock; } // // Make the actual TDI action call. The Streams TDI mapper will // translate this into a TPI option management request for us and // give it to TCP/IP. // ioStatusBlock->Status = STATUS_PENDING; status = NtDeviceIoControlFile( TdiConnectionObjectHandle, NULL, completionApc, apcContext, ioStatusBlock, IOCTL_TCP_WSH_SET_INFORMATION_EX, setInfoEx, sizeof(*setInfoEx) + ValueLength, NULL, 0 ); // // If the call pended and we were supposed to wait for completion, // then wait. // if ( status == STATUS_PENDING && WaitForCompletion ) { #if DBG INT count=0; #endif while (ioStatusBlock->Status==STATUS_PENDING) { LARGE_INTEGER timeout; // // Wait one millisecond // timeout.QuadPart = -1i64*1000i64*10i64; NtDelayExecution (FALSE, &timeout); #if DBG if (count++>10*1000) { DbgPrint ("WSHTCPIP: Waiting for TCP/IP IOCTL completion for more than 10 seconds!!!!\n"); DbgBreakPoint (); } #endif } status = ioStatusBlock->Status; } if ( (ioStatusBlock != (PIO_STATUS_BLOCK)&localBuffer) && (WaitForCompletion || !NT_SUCCESS(status)) ){ RtlFreeHeap( RtlProcessHeap( ), 0, ioStatusBlock ); } if (NT_SUCCESS (status)) { return NO_ERROR; } else { return NtStatusToSocketError (status); } } // SetTdiInformation VOID CompleteTdiActionApc ( IN PVOID ApcContext, IN PIO_STATUS_BLOCK IoStatusBlock ) { // // Just free the heap we allocated to hold the IO status block and // the TDI action buffer. There is nothing we can do if the call // failed. // RtlFreeHeap( RtlProcessHeap( ), 0, ApcContext ); } // CompleteTdiActionApc INT WINAPI WSHJoinLeaf ( IN PVOID HelperDllSocketContext, IN SOCKET SocketHandle, IN HANDLE TdiAddressObjectHandle, IN HANDLE TdiConnectionObjectHandle, IN PVOID LeafHelperDllSocketContext, IN SOCKET LeafSocketHandle, IN PSOCKADDR Sockaddr, IN DWORD SockaddrLength, IN LPWSABUF CallerData, IN LPWSABUF CalleeData, IN LPQOS SocketQOS, IN LPQOS GroupQOS, IN DWORD Flags ) /*++ Routine Description: Performs the protocol-dependent portion of creating a multicast socket. Arguments: The following four parameters correspond to the socket passed into the WSAJoinLeaf() API: HelperDllSocketContext - The context pointer returned from WSHOpenSocket(). SocketHandle - The handle of the socket used to establish the multicast "session". TdiAddressObjectHandle - The TDI address object of the socket, if any. If the socket is not yet bound to an address, then it does not have a TDI address object and this parameter will be NULL. TdiConnectionObjectHandle - The TDI connection object of the socket, if any. If the socket is not yet connected, then it does not have a TDI connection object and this parameter will be NULL. The next two parameters correspond to the newly created socket that identifies the multicast "session": LeafHelperDllSocketContext - The context pointer returned from WSHOpenSocket(). LeafSocketHandle - The handle of the socket that identifies the multicast "session". Sockaddr - The name of the peer to which the socket is to be joined. SockaddrLength - The length of Sockaddr. CallerData - Pointer to user data to be transferred to the peer during multipoint session establishment. CalleeData - Pointer to user data to be transferred back from the peer during multipoint session establishment. SocketQOS - Pointer to the flowspecs for SocketHandle, one in each direction. GroupQOS - Pointer to the flowspecs for the socket group, if any. Flags - Flags to indicate if the socket is acting as sender, receiver, or both. Return Value: INT - 0 if successful, a WinSock error code if not. --*/ { struct ip_mreq req; INT err; BOOL bSet_IP_MULTICAST_IF = FALSE; PWSHTCPIP_SOCKET_CONTEXT context; // // Note: at this time we only support non-rooted control schemes, // and therefore no leaf socket is created // // // Quick sanity checks. // if( HelperDllSocketContext == NULL || SocketHandle == INVALID_SOCKET || TdiAddressObjectHandle == NULL || LeafHelperDllSocketContext != NULL || LeafSocketHandle != INVALID_SOCKET || Sockaddr == NULL || SockaddrLength < sizeof(SOCKADDR_IN) || Sockaddr->sa_family != AF_INET || ( CallerData != NULL && CallerData->len > 0 ) || ( CalleeData != NULL && CalleeData->len > 0 ) || SocketQOS != NULL || GroupQOS != NULL ) { return WSAEINVAL; } context = HelperDllSocketContext; // // The multicast group to join... // req.imr_multiaddr = ((LPSOCKADDR_IN)Sockaddr)->sin_addr; // // Now figure out the local interface. Note that the local interface // specified in IP_ADD_MEMBERSHIP applies to that on which you wish // to receive datagrams, while the local interface specified in // IP_MULTICAST_IF applies to that from which to send multicast // packets. If there is >1 local interface then we want to be // consistent regarding the send/recv interfaces. // if (context->MulticastInterface == DEFAULT_MULTICAST_INTERFACE) { TDI_REQUEST_QUERY_INFORMATION query; char tdiAddressInfo[FIELD_OFFSET (TDI_ADDRESS_INFO, Address) + sizeof (TA_IP_ADDRESS)]; NTSTATUS status; IO_STATUS_BLOCK ioStatusBlock; // // App hasn't set IP_MULTICAST_IF, so retrieve the bound // address and use that for the send & recv interfaces // // RtlZeroMemory (&query, sizeof (query)); query.QueryType = TDI_QUERY_ADDRESS_INFO; status = NtDeviceIoControlFile( TdiAddressObjectHandle, NULL, NULL, NULL, &ioStatusBlock, IOCTL_TDI_QUERY_INFORMATION, &query, sizeof (query), tdiAddressInfo, sizeof(tdiAddressInfo) ); if( NT_SUCCESS(status) ) { PTA_IP_ADDRESS pIpAddress = (PTA_IP_ADDRESS)(tdiAddressInfo+FIELD_OFFSET (TDI_ADDRESS_INFO, Address)); req.imr_interface.s_addr = pIpAddress->Address[0].Address[0].in_addr; if (req.imr_interface.s_addr != DEFAULT_MULTICAST_INTERFACE) { bSet_IP_MULTICAST_IF = TRUE; context->MulticastInterface = req.imr_interface.s_addr; } } else { req.imr_interface.s_addr = DEFAULT_MULTICAST_INTERFACE; } } else { req.imr_interface.s_addr = context->MulticastInterface; } // // If the Flags param indicates that caller is a sender only, // then there's no point in actually joining the group (anyone // can send to a multicast group, but it's only members of the // group who recv the packets). So, just check to see if it // is necessary to set the IP_MULTICAST_IF to remain consistent // ith the bound address. // // Otherwise, caller is a receiver (possibly a sender too), so // we really do want to join the group. // if (Flags == JL_SENDER_ONLY) { if (bSet_IP_MULTICAST_IF) { WSHSetSocketInformation ( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_IP, IP_MULTICAST_IF, (char *) &req.imr_interface.s_addr, sizeof (req.imr_interface.s_addr) ); } err = NO_ERROR; } else { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_ADD_MCAST, &req, sizeof(req), TRUE ); if( err == NO_ERROR ) { // // Record this fact in the leaf socket so we can drop membership // when the leaf socket is closed. // context->MultipointLeaf = TRUE; context->MultipointTarget = req.imr_multiaddr; // // Stay consistent, i.e. send interface should match recv interface // if (bSet_IP_MULTICAST_IF && (Flags != JL_RECEIVER_ONLY)) { WSHSetSocketInformation ( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_IP, IP_MULTICAST_IF, (char *) &req.imr_interface.s_addr, sizeof (req.imr_interface.s_addr) ); } } } return err; } // WSHJoinLeaf INT WINAPI WSHGetBroadcastSockaddr ( IN PVOID HelperDllSocketContext, OUT PSOCKADDR Sockaddr, OUT PINT SockaddrLength ) /*++ Routine Description: This routine returns a broadcast socket address. A broadcast address may be used as a destination for the sendto() API to send a datagram to all interested clients. Arguments: HelperDllSocketContext - the context pointer returned from WSHOpenSocket() for the socket for which we need a broadcast address. Sockaddr - points to a buffer which will receive the broadcast socket address. SockaddrLength - receives the length of the broadcast sockaddr. Return Value: INT - a winsock error code indicating the status of the operation, or NO_ERROR if the operation succeeded. --*/ { LPSOCKADDR_IN addr; if( *SockaddrLength < sizeof(SOCKADDR_IN) || (Sockaddr == NULL) ) { return WSAEFAULT; } *SockaddrLength = sizeof(SOCKADDR_IN); // // Build the broadcast address. // addr = (LPSOCKADDR_IN)Sockaddr; RtlZeroMemory( addr, sizeof(*addr) ); addr->sin_family = AF_INET; ASSERT (htonl(INADDR_BROADCAST)==INADDR_BROADCAST); addr->sin_addr.s_addr = INADDR_BROADCAST; return NO_ERROR; } // WSAGetBroadcastSockaddr INT WINAPI WSHGetWSAProtocolInfo ( IN LPWSTR ProviderName, OUT LPWSAPROTOCOL_INFOW * ProtocolInfo, OUT LPDWORD ProtocolInfoEntries ) /*++ Routine Description: Retrieves a pointer to the WSAPROTOCOL_INFOW structure(s) describing the protocol(s) supported by this helper. Arguments: ProviderName - Contains the name of the provider, such as "TcpIp". ProtocolInfo - Receives a pointer to the WSAPROTOCOL_INFOW array. ProtocolInfoEntries - Receives the number of entries in the array. Return Value: INT - 0 if successful, WinSock error code if not. --*/ { if( ProviderName == NULL || ProtocolInfo == NULL || ProtocolInfoEntries == NULL ) { return WSAEFAULT; } if( _wcsicmp( ProviderName, L"TcpIp" ) == 0 ) { *ProtocolInfo = Winsock2Protocols; *ProtocolInfoEntries = NUM_WINSOCK2_PROTOCOLS; return NO_ERROR; } return WSAEINVAL; } // WSHGetWSAProtocolInfo INT WINAPI WSHAddressToString ( IN LPSOCKADDR Address, IN INT AddressLength, IN LPWSAPROTOCOL_INFOW ProtocolInfo, OUT LPWSTR AddressString, IN OUT LPDWORD AddressStringLength ) /*++ Routine Description: Converts a SOCKADDR to a human-readable form. Arguments: Address - The SOCKADDR to convert. AddressLength - The length of Address. ProtocolInfo - The WSAPROTOCOL_INFOW for a particular provider. AddressString - Receives the formatted address string. AddressStringLength - On input, contains the length of AddressString. On output, contains the number of characters actually written to AddressString. Return Value: INT - 0 if successful, WinSock error code if not. --*/ { LPSOCKADDR_IN addr; INT err = NO_ERROR; NTSTATUS Status; // // Quick sanity checks. // if( AddressLength < sizeof(SOCKADDR_IN)) { return WSAEFAULT; } __try { addr = (LPSOCKADDR_IN)Address; if (addr->sin_family != AF_INET) { return WSAEFAULT; } // // Now calling rtl functions to do the address conversion // Status = RtlIpv4AddressToStringExW(&addr->sin_addr, addr->sin_port, AddressString, AddressStringLength ); if (!NT_SUCCESS(Status)) { err = WSAEFAULT; } } __except (EXCEPTION_EXECUTE_HANDLER) { err = WSAEFAULT; } return err; } // WSHAddressToString INT WINAPI WSHStringToAddress ( IN LPWSTR AddressString, IN DWORD AddressFamily, IN LPWSAPROTOCOL_INFOW ProtocolInfo, OUT LPSOCKADDR Address, IN OUT LPINT AddressLength ) /*++ Routine Description: Fills in a SOCKADDR structure by parsing a human-readable string. Arguments: AddressString - Points to the zero-terminated human-readable string. AddressFamily - The address family to which the string belongs. ProtocolInfo - The WSAPROTOCOL_INFOW for a particular provider. Address - Receives the SOCKADDR structure. AddressLength - On input, contains the length of Address. On output, contains the number of bytes actually written to Address. Return Value: INT - 0 if successful, WinSock error code if not. --*/ { LPWSTR terminator; ULONG ipAddress; USHORT port; LPSOCKADDR_IN addr; NTSTATUS Status; __try { if (*AddressLength < sizeof(SOCKADDR_IN) ) { *AddressLength = sizeof(SOCKADDR_IN); return WSAEFAULT; } if (AddressFamily != AF_INET) { return WSAEINVAL; } addr = (LPSOCKADDR_IN)Address; RtlZeroMemory(addr, sizeof(SOCKADDR_IN)); // // Now calling Rtl routine to do the address conversion // Status = RtlIpv4StringToAddressExW(AddressString, FALSE, &addr->sin_addr, &addr->sin_port ); if (!NT_SUCCESS(Status)) { return WSAEINVAL; } } __except (EXCEPTION_EXECUTE_HANDLER) { return WSAEFAULT; } *AddressLength = sizeof(SOCKADDR_IN); addr->sin_family = AF_INET; return NO_ERROR; } // WSHStringToAddress INT WINAPI WSHGetProviderGuid ( IN LPWSTR ProviderName, OUT LPGUID ProviderGuid ) /*++ Routine Description: Returns the GUID identifying the protocols supported by this helper. Arguments: ProviderName - Contains the name of the provider, such as "TcpIp". ProviderGuid - Points to a buffer that receives the provider's GUID. Return Value: INT - 0 if successful, WinSock error code if not. --*/ { if( ProviderName == NULL || ProviderGuid == NULL ) { return WSAEFAULT; } if( _wcsicmp( ProviderName, L"TcpIp" ) == 0 ) { RtlCopyMemory( ProviderGuid, &TcpipProviderGuid, sizeof(GUID) ); return NO_ERROR; } return WSAEINVAL; } // WSHGetProviderGuid INT WINAPI WSHIoctl ( IN PVOID HelperDllSocketContext, IN SOCKET SocketHandle, IN HANDLE TdiAddressObjectHandle, IN HANDLE TdiConnectionObjectHandle, IN DWORD IoControlCode, IN LPVOID InputBuffer, IN DWORD InputBufferLength, IN LPVOID OutputBuffer, IN DWORD OutputBufferLength, OUT LPDWORD NumberOfBytesReturned, IN LPWSAOVERLAPPED Overlapped, IN LPWSAOVERLAPPED_COMPLETION_ROUTINE CompletionRoutine, OUT LPBOOL NeedsCompletion ) /*++ Routine Description: Performs queries & controls on the socket. This is basically an "escape hatch" for IOCTLs not supported by MSAFD.DLL. Any unknown IOCTLs are routed to the socket's helper DLL for protocol-specific processing. Arguments: HelperDllSocketContext - the context pointer returned from WSHOpenSocket(). SocketHandle - the handle of the socket for which we're controlling. TdiAddressObjectHandle - the TDI address object of the socket, if any. If the socket is not yet bound to an address, then it does not have a TDI address object and this parameter will be NULL. TdiConnectionObjectHandle - the TDI connection object of the socket, if any. If the socket is not yet connected, then it does not have a TDI connection object and this parameter will be NULL. IoControlCode - Control code of the operation to perform. InputBuffer - Address of the input buffer. InputBufferLength - The length of InputBuffer. OutputBuffer - Address of the output buffer. OutputBufferLength - The length of OutputBuffer. NumberOfBytesReturned - Receives the number of bytes actually written to the output buffer. Overlapped - Pointer to a WSAOVERLAPPED structure for overlapped operations. CompletionRoutine - Pointer to a completion routine to call when the operation is completed. NeedsCompletion - WSAIoctl() can be overlapped, with all the gory details that involves, such as setting events, queuing completion routines, and posting to IO completion ports. Since the majority of the IOCTL codes can be completed quickly "in-line", MSAFD.DLL can optionally perform the overlapped completion of the operation. Setting *NeedsCompletion to TRUE (the default) causes MSAFD.DLL to handle all of the IO completion details iff this is an overlapped operation on an overlapped socket. Setting *NeedsCompletion to FALSE tells MSAFD.DLL to take no further action because the helper DLL will perform any necessary IO completion. Note that if a helper performs its own IO completion, the helper is responsible for maintaining the "overlapped" mode of the socket at socket creation time and NOT performing overlapped IO completion on non-overlapped sockets. Return Value: INT - 0 if successful, WinSock error code if not. --*/ { INT err; NTSTATUS status; PWSHTCPIP_SOCKET_CONTEXT context; // // Quick sanity checks. // if( HelperDllSocketContext == NULL || SocketHandle == INVALID_SOCKET || NumberOfBytesReturned == NULL || NeedsCompletion == NULL ) { return WSAEINVAL; } *NeedsCompletion = TRUE; context = (PWSHTCPIP_SOCKET_CONTEXT) HelperDllSocketContext; switch( IoControlCode ) { case SIO_MULTIPOINT_LOOPBACK : if ( !IS_DGRAM_SOCK(context->SocketType) ) { err = WSAENOPROTOOPT; break; } err = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_IP, IP_MULTICAST_LOOP, (PCHAR)InputBuffer, (INT)InputBufferLength ); break; case SIO_MULTICAST_SCOPE : err = WSHSetSocketInformation( HelperDllSocketContext, SocketHandle, TdiAddressObjectHandle, TdiConnectionObjectHandle, IPPROTO_IP, IP_MULTICAST_TTL, (PCHAR)InputBuffer, (INT)InputBufferLength ); break; case SIO_GET_MULTICAST_FILTER : if ( OutputBufferLength < IP_MSFILTER_SIZE(0) || (OutputBuffer == NULL) ) { err = WSAEFAULT; break; } if ( TdiAddressObjectHandle == NULL ) { err = WSAEINVAL; break; } if ( !IS_DGRAM_SOCK(context->SocketType) ) { err = WSAENOPROTOOPT; break; } err = GetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCAST_FILTER, OutputBuffer, FIELD_OFFSET(UDPMCastFilter, umf_fmode), OutputBufferLength ); break; case SIO_SET_MULTICAST_FILTER : { PWSHTCPIP_SOCKET_CONTEXT context = HelperDllSocketContext; // // This option is only valid for datagram sockets. // if ( !IS_DGRAM_SOCK(context->SocketType) ) { err = WSAENOPROTOOPT; break; } // // Make sure that the option buffer is large enough. // if ( InputBufferLength < IP_MSFILTER_SIZE(0) ) { err = WSAEFAULT; break; } // // If we have a TDI address object, set this option to // the address object. If we don't have a TDI address // object then we'll have to wait until after the socket // is bound. // if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_MCAST_FILTER, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { break; } } err = NO_ERROR; break; } case SIO_GET_INTERFACE_LIST : if ( OutputBuffer == NULL ) { err = WSAEFAULT; break; } status = GetTcpipInterfaceList( OutputBuffer, OutputBufferLength, NumberOfBytesReturned ); if( NT_SUCCESS(status) ) { err = NO_ERROR; } else { err = NtStatusToSocketError (status); } break; case SIO_RCVALL: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( InputBufferLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_RCVALL, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_RCVALL_MCAST: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT) HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( InputBufferLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_RCVALL_MCAST, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_RCVALL_IGMPMCAST: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( InputBufferLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_RCVALL_IGMPMCAST, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_ABSORB_RTRALERT: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( InputBufferLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_ABSORB_RTRALERT, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_UCAST_IF: { uint OptionValue; // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } // this option is valid only if hdr include option is set if ( !(((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->HdrIncludeSet && ((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->HdrInclude) ) { return WSAEINVAL; } if ( InputBufferLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_IP_UCASTIF, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } OptionValue = *((uint UNALIGNED *)InputBuffer); ((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->UcastIf = OptionValue ? TRUE : FALSE; return NO_ERROR; } case SIO_LIMIT_BROADCASTS: { uint OptionValue; // // This option is only valid for UDP sockets. // if ( !IS_DGRAM_SOCK( ((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType )) { return WSAENOPROTOOPT; } if ( InputBufferLength != sizeof(uint)) { return WSAEINVAL; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_LIMIT_BCASTS, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } OptionValue = *((uint UNALIGNED *)InputBuffer); ((PWSHTCPIP_SOCKET_CONTEXT) HelperDllSocketContext)->LimitBroadcasts = OptionValue ? TRUE : FALSE; return NO_ERROR; } case SIO_INDEX_BIND: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_INDEX_BIND, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_INDEX_MCASTIF: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_INDEX_MCASTIF, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_INDEX_ADD_MCAST: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_INDEX_ADD_MCAST, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_INDEX_DEL_MCAST: // // This option is only valid for raw sockets. // if (((PWSHTCPIP_SOCKET_CONTEXT)HelperDllSocketContext)->SocketType != SOCK_RAW) { return WSAENOPROTOOPT; } if ( TdiAddressObjectHandle != NULL ) { err = SetTdiInformation( TdiAddressObjectHandle, CL_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_ADDRESS_OBJECT, AO_OPTION_INDEX_DEL_MCAST, InputBuffer, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } else { return WSAEINVAL; } return NO_ERROR; case SIO_KEEPALIVE_VALS: { struct tcp_keepalive *optionval; PWSHTCPIP_SOCKET_CONTEXT context = HelperDllSocketContext; // // Atempt to turn on or off keepalive sending, as necessary. // if ( IS_DGRAM_SOCK(context->SocketType) ) { return WSAENOPROTOOPT; } if ( InputBufferLength != sizeof(struct tcp_keepalive) ) { return WSAEINVAL; } optionval = (struct tcp_keepalive *)InputBuffer; if (optionval->onoff != 0 ) { // Application wants to turn the keepalive on and also give the // relevant parameters for it. If the TDI connection object handle is // NULL, then the socket is not yet connected. In this case // we'll just remember that the keepalive option was set and // actually turn them on in WSHNotify() after a connect() // has completed on the socket. // if ( TdiConnectionObjectHandle != NULL ) { err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE_VALS, optionval, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } // // Remember that keepalives are enabled for this socket. // context->KeepAliveVals.onoff = TRUE; context->KeepAliveVals.keepalivetime = optionval->keepalivetime; context->KeepAliveVals.keepaliveinterval = optionval->keepaliveinterval; } else if ( optionval->onoff == 0 ) { // // Application wants to turn keepalive off. If the TDI // connection object is NULL, the socket is not yet // connected. In this case we'll just remember that // keepalives are disabled. if ( TdiConnectionObjectHandle != NULL ) { err = SetTdiInformation( TdiConnectionObjectHandle, CO_TL_ENTITY, INFO_CLASS_PROTOCOL, INFO_TYPE_CONNECTION, TCP_SOCKET_KEEPALIVE_VALS, optionval, InputBufferLength, TRUE ); if ( err != NO_ERROR ) { return err; } } // // Remember that keepalives are disabled for this socket. // context->KeepAliveVals.onoff = FALSE; } // break; return NO_ERROR; } default : err = WSAEINVAL; break; } return err; } // WSHIoctl NTSTATUS GetTcpipInterfaceList( IN LPVOID OutputBuffer, IN DWORD OutputBufferLength, OUT LPDWORD NumberOfBytesReturned ) /*++ Routine Description: This routine queries the INTERFACE_INFO array for all supported IP interfaces in the system. This is a helper routine for handling the SIO_GET_INTERFACE_LIST IOCTL. Arguments: OutputBuffer - Points to a buffer that will receive the INTERFACE_INFO array. OutputBufferLength - The length of OutputBuffer. NumberOfBytesReturned - Receives the number of bytes actually written to OutputBuffer. Return Value: NTSTATUS - The completion status. --*/ { OBJECT_ATTRIBUTES objectAttributes; UNICODE_STRING deviceName; NTSTATUS status; IO_STATUS_BLOCK ioStatusBlock; HANDLE deviceHandle; TCP_REQUEST_QUERY_INFORMATION_EX tcpRequest; TDIObjectID objectId; IPSNMPInfo snmpInfo; IPInterfaceInfo * interfaceInfo; IFEntry * ifentry; IPAddrEntry * addressBuffer; IPAddrEntry * addressScan; TDIEntityID * entityBuffer; TDIEntityID * entityScan; ULONG i, j; ULONG entityCount; ULONG entityBufferLength; ULONG entityType; ULONG addressBufferLength; LPINTERFACE_INFO outputInterfaceInfo; DWORD outputBytesRemaining; LPSOCKADDR_IN sockaddr; CHAR fastAddressBuffer[MAX_FAST_ADDRESS_BUFFER]; CHAR fastEntityBuffer[MAX_FAST_ENTITY_BUFFER]; CHAR ifentryBuffer[sizeof(IFEntry) + MAX_IFDESCR_LEN]; CHAR interfaceInfoBuffer[sizeof(IPInterfaceInfo) + MAX_PHYSADDR_SIZE]; // // Setup locals so we know how to cleanup on exit. // deviceHandle = NULL; addressBuffer = NULL; entityBuffer = (PVOID)fastEntityBuffer; entityBufferLength = sizeof(fastEntityBuffer); interfaceInfo = NULL; outputInterfaceInfo = OutputBuffer; outputBytesRemaining = OutputBufferLength; // // Open a handle to the TCP/IP device. // RtlInitUnicodeString( &deviceName, DD_TCP_DEVICE_NAME ); InitializeObjectAttributes( &objectAttributes, &deviceName, OBJ_CASE_INSENSITIVE, NULL, NULL ); status = NtCreateFile( &deviceHandle, SYNCHRONIZE | GENERIC_EXECUTE, &objectAttributes, &ioStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN_IF, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 ); if( !NT_SUCCESS(status) ) { goto exit; } // // Get the entities supported by the TCP device. // RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); tcpRequest.ID.toi_entity.tei_entity = GENERIC_ENTITY; tcpRequest.ID.toi_entity.tei_instance = 0; tcpRequest.ID.toi_class = INFO_CLASS_GENERIC; tcpRequest.ID.toi_type = INFO_TYPE_PROVIDER; tcpRequest.ID.toi_id = ENTITY_LIST_ID; for( ; ; ) { status = NtDeviceIoControlFile( deviceHandle, NULL, // Event NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), entityBuffer, entityBufferLength ); if( NT_SUCCESS(status) ) { break; } if( status != STATUS_BUFFER_TOO_SMALL ) { goto exit; } if( entityBuffer != (PVOID)fastEntityBuffer ) { RtlFreeHeap( RtlProcessHeap(), 0, entityBuffer ); } entityBufferLength += sizeof(TDIEntityID); entityBuffer = RtlAllocateHeap( RtlProcessHeap(), 0, entityBufferLength ); if( entityBuffer == NULL ) { status = STATUS_INSUFFICIENT_RESOURCES; goto exit; } } entityCount = ((ULONG) ioStatusBlock.Information) / sizeof(*entityBuffer); // // Scan the entities looking for IP. // for( i = 0, entityScan = entityBuffer ; i < entityCount ; i++, entityScan++ ) { if( entityScan->tei_entity != CL_NL_ENTITY ) { continue; } RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); objectId.toi_entity = *entityScan; objectId.toi_class = INFO_CLASS_GENERIC; objectId.toi_type = INFO_TYPE_PROVIDER; objectId.toi_id = ENTITY_TYPE_ID; tcpRequest.ID = objectId; status = NtDeviceIoControlFile( deviceHandle, NULL, // Event NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), &entityType, sizeof(entityType) ); if( !NT_SUCCESS(status) ) { goto exit; } if( entityType != CL_NL_IP ) { continue; } // // OK, we found an IP entity. Now lookup its addresses. // Start by querying the number of addresses supported by // this interface. // RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); objectId.toi_class = INFO_CLASS_PROTOCOL; objectId.toi_id = IP_MIB_STATS_ID; tcpRequest.ID = objectId; status = NtDeviceIoControlFile( deviceHandle, NULL, // Event NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), &snmpInfo, sizeof(snmpInfo) ); if( !NT_SUCCESS(status) ) { goto exit; } if( snmpInfo.ipsi_numaddr <= 0 ) { continue; } // // This interface has addresses. Cool. Allocate a temporary // buffer so we can query them. // addressBufferLength = snmpInfo.ipsi_numaddr * sizeof(*addressBuffer); if( addressBufferLength <= sizeof(fastAddressBuffer) ) { addressBuffer = (PVOID)fastAddressBuffer; } else { addressBuffer = RtlAllocateHeap( RtlProcessHeap(), 0, addressBufferLength ); if( addressBuffer == NULL ) { status = STATUS_INSUFFICIENT_RESOURCES; goto exit; } } RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); objectId.toi_id = IP_MIB_ADDRTABLE_ENTRY_ID; tcpRequest.ID = objectId; status = NtDeviceIoControlFile( deviceHandle, NULL, // Event NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), addressBuffer, addressBufferLength ); if( !NT_SUCCESS(status) ) { goto exit; } addressBufferLength = (ULONG)ioStatusBlock.Information; snmpInfo.ipsi_numaddr = addressBufferLength / sizeof(*addressBuffer); // // Try to get the IFEntry info so we can tell if the interface // is "up". // ifentry = (PVOID)ifentryBuffer; RtlZeroMemory( ifentryBuffer, sizeof(ifentryBuffer) ); RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); addressScan = (IPAddrEntry *) addressBuffer; RtlCopyMemory( &tcpRequest.Context, &addressScan->iae_addr, sizeof(addressScan->iae_addr) ); objectId.toi_id = IF_MIB_STATS_ID; tcpRequest.ID = objectId; tcpRequest.ID.toi_entity.tei_entity = IF_ENTITY; status = NtDeviceIoControlFile( deviceHandle, NULL, // Event NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), ifentry, sizeof(ifentryBuffer) ); if( !NT_SUCCESS(status ) ) { ifentry->if_adminstatus = 0; } // // Now scan the list // for( j = 0, addressScan = addressBuffer ; j < snmpInfo.ipsi_numaddr ; j++, addressScan++ ) { // // Skip any entries that don't have IP addresses yet. // if( addressScan->iae_addr == 0 ) { continue; } // // If the output buffer is full, fail the request now. // if( outputBytesRemaining <= sizeof(*outputInterfaceInfo) ) { status = STATUS_BUFFER_TOO_SMALL; goto exit; } // // Setup the output structure. // RtlZeroMemory( outputInterfaceInfo, sizeof(*outputInterfaceInfo) ); outputInterfaceInfo->iiFlags = IFF_MULTICAST; sockaddr = &outputInterfaceInfo->iiAddress.AddressIn; sockaddr->sin_family = AF_INET; sockaddr->sin_addr.s_addr = addressScan->iae_addr; if( sockaddr->sin_addr.s_addr == htonl( INADDR_LOOPBACK ) ) { outputInterfaceInfo->iiFlags |= IFF_LOOPBACK; } sockaddr = &outputInterfaceInfo->iiNetmask.AddressIn; sockaddr->sin_family = AF_INET; sockaddr->sin_addr.s_addr = addressScan->iae_mask; if( addressScan->iae_bcastaddr != 0 ) { outputInterfaceInfo->iiFlags |= IFF_BROADCAST; sockaddr = &outputInterfaceInfo->iiBroadcastAddress.AddressIn; sockaddr->sin_family = AF_INET; ASSERT (htonl(INADDR_BROADCAST)==INADDR_BROADCAST); sockaddr->sin_addr.s_addr = INADDR_BROADCAST; } // // Grrr... // // I know how to enumerate the entities supported by the // driver (those are stored in entityBuffer). // // I know how to find the IP entities in that buffer. // // I know how to enumerate the IP addresses supported // by a given IP entity (those are stored in addressBuffer). // // I also know (but haven't done yet) how to find the IF // entities (interfaces; basically NICs) and determine if // a given IF is "up" or "down". // // What I don't know how to do is associate the addresses // in addressBuffer with specific IF entities. Without // this information, I cannot determine if a given *address* // is "up" or "down", so for now I'll just assume they're // all "up". // // if( ifentry->if_adminstatus == IF_STATUS_UP ) { outputInterfaceInfo->iiFlags |= IFF_UP; } // // Get the IP interface info for this interface so we can // determine if it's "point-to-point". // interfaceInfo = (PVOID)interfaceInfoBuffer; RtlZeroMemory( interfaceInfoBuffer, sizeof(interfaceInfoBuffer) ); RtlZeroMemory( &tcpRequest, sizeof(tcpRequest) ); RtlCopyMemory( &tcpRequest.Context, &addressScan->iae_addr, sizeof(addressScan->iae_addr) ); objectId.toi_id = IP_INTFC_INFO_ID; tcpRequest.ID = objectId; status = NtDeviceIoControlFile( deviceHandle, NULL, // Event NULL, // ApcRoutine NULL, // ApcContext &ioStatusBlock, IOCTL_TCP_QUERY_INFORMATION_EX, &tcpRequest, sizeof(tcpRequest), interfaceInfo, sizeof(interfaceInfoBuffer) ); if( NT_SUCCESS(status) ) { if( interfaceInfo->iii_flags & IP_INTFC_FLAG_P2P ) { outputInterfaceInfo->iiFlags |= IFF_POINTTOPOINT; } } else { // // Print something informative here, then press on. // } // // Advance to the next output structure. // outputInterfaceInfo++; outputBytesRemaining -= sizeof(*outputInterfaceInfo); } // // Free the temporary buffer. // if( addressBuffer != (PVOID)fastAddressBuffer ) { RtlFreeHeap( RtlProcessHeap(), 0, addressBuffer ); } addressBuffer = NULL; } // // Success! // *NumberOfBytesReturned = OutputBufferLength - outputBytesRemaining; status = STATUS_SUCCESS; exit: if( addressBuffer != (PVOID)fastAddressBuffer && addressBuffer != NULL ) { RtlFreeHeap( RtlProcessHeap(), 0, addressBuffer ); } if( entityBuffer != (PVOID)fastEntityBuffer && entityBuffer != NULL ) { RtlFreeHeap( RtlProcessHeap(), 0, entityBuffer ); } if( deviceHandle != NULL ) { NtClose( deviceHandle ); } return status; } // GetTcpipInterfaceList INT NtStatusToSocketError ( IN NTSTATUS Status ) { switch ( Status ) { case STATUS_PENDING: ASSERT (FALSE); return WSASYSCALLFAILURE; case STATUS_INVALID_HANDLE: case STATUS_OBJECT_TYPE_MISMATCH: return WSAENOTSOCK; case STATUS_INSUFFICIENT_RESOURCES: case STATUS_PAGEFILE_QUOTA: case STATUS_COMMITMENT_LIMIT: case STATUS_WORKING_SET_QUOTA: case STATUS_NO_MEMORY: case STATUS_CONFLICTING_ADDRESSES: case STATUS_QUOTA_EXCEEDED: case STATUS_TOO_MANY_PAGING_FILES: case STATUS_REMOTE_RESOURCES: case STATUS_TOO_MANY_ADDRESSES: return WSAENOBUFS; case STATUS_SHARING_VIOLATION: case STATUS_ADDRESS_ALREADY_EXISTS: return WSAEADDRINUSE; case STATUS_LINK_TIMEOUT: case STATUS_IO_TIMEOUT: case STATUS_TIMEOUT: return WSAETIMEDOUT; case STATUS_GRACEFUL_DISCONNECT: return WSAEDISCON; case STATUS_REMOTE_DISCONNECT: case STATUS_CONNECTION_RESET: case STATUS_LINK_FAILED: case STATUS_CONNECTION_DISCONNECTED: case STATUS_PORT_UNREACHABLE: return WSAECONNRESET; case STATUS_LOCAL_DISCONNECT: case STATUS_TRANSACTION_ABORTED: case STATUS_CONNECTION_ABORTED: return WSAECONNABORTED; case STATUS_BAD_NETWORK_PATH: case STATUS_NETWORK_UNREACHABLE: case STATUS_PROTOCOL_UNREACHABLE: return WSAENETUNREACH; case STATUS_HOST_UNREACHABLE: return WSAEHOSTUNREACH; case STATUS_CANCELLED: case STATUS_REQUEST_ABORTED: return WSAEINTR; case STATUS_BUFFER_OVERFLOW: case STATUS_INVALID_BUFFER_SIZE: return WSAEMSGSIZE; case STATUS_BUFFER_TOO_SMALL: case STATUS_ACCESS_VIOLATION: return WSAEFAULT; case STATUS_DEVICE_NOT_READY: case STATUS_REQUEST_NOT_ACCEPTED: return WSAEWOULDBLOCK; case STATUS_INVALID_NETWORK_RESPONSE: case STATUS_NETWORK_BUSY: case STATUS_NO_SUCH_DEVICE: case STATUS_NO_SUCH_FILE: case STATUS_OBJECT_PATH_NOT_FOUND: case STATUS_OBJECT_NAME_NOT_FOUND: case STATUS_UNEXPECTED_NETWORK_ERROR: return WSAENETDOWN; case STATUS_INVALID_CONNECTION: return WSAENOTCONN; case STATUS_REMOTE_NOT_LISTENING: case STATUS_CONNECTION_REFUSED: return WSAECONNREFUSED; case STATUS_PIPE_DISCONNECTED: return WSAESHUTDOWN; case STATUS_INVALID_ADDRESS: case STATUS_INVALID_ADDRESS_COMPONENT: return WSAEADDRNOTAVAIL; case STATUS_NOT_SUPPORTED: case STATUS_NOT_IMPLEMENTED: return WSAEOPNOTSUPP; case STATUS_ACCESS_DENIED: return WSAEACCES; default: if ( NT_SUCCESS(Status) ) { #if DBG DbgPrint ("SockNtStatusToSocketError: success status %lx " "not mapped\n", Status ); #endif return NO_ERROR; } #if DBG DbgPrint ("SockNtStatusToSocketError: unable to map 0x%lX, returning\n", Status ); #endif return WSAENOBUFS; case STATUS_UNSUCCESSFUL: case STATUS_INVALID_PARAMETER: case STATUS_ADDRESS_CLOSED: case STATUS_CONNECTION_INVALID: case STATUS_ADDRESS_ALREADY_ASSOCIATED: case STATUS_ADDRESS_NOT_ASSOCIATED: case STATUS_CONNECTION_ACTIVE: case STATUS_INVALID_DEVICE_STATE: case STATUS_INVALID_DEVICE_REQUEST: return WSAEINVAL; } } // NtStatusToSocketError
yurirocha15/coding_practice
src/leetcode_1675_minimize_deviation_in_array.py
<reponame>yurirocha15/coding_practice # @l2g 1675 python3 # [1675] Minimize Deviation in Array # Difficulty: Hard # https://leetcode.com/problems/minimize-deviation-in-array # # You are given an array nums of n positive integers. # You can perform two types of operations on any element of the array any number of times: # # If the element is even, divide it by 2. # # # For example,if the array is [1,2,3,4],then you can do this operation on the last element, # and the array will be [1,2,3,2]. # # # If the element is odd, multiply it by 2. # # For example,if the array is [1,2,3,4],then you can do this operation on the first element, # and the array will be [2,2,3,4]. # # # # The deviation of the array is the maximum difference between any two elements in the array. # Return the minimum deviation the array can have after performing some number of operations. # # Example 1: # # Input: nums = [1,2,3,4] # Output: 1 # Explanation: You can transform the array to [1,2,3,2],then to [2,2,3,2], # then the deviation will be 3 - 2 = 1. # # Example 2: # # Input: nums = [4,1,5,20,3] # Output: 3 # Explanation: You can transform the array after two operations to [4,2,5,5,3], # then the deviation will be 5 - 2 = 3. # # Example 3: # # Input: nums = [2,10,8] # Output: 3 # # # Constraints: # # n == nums.length # 2 <= n <= 105 # 1 <= nums[i] <= 10^9 # # import heapq from typing import List class Solution: def minimumDeviation(self, nums: List[int]) -> int: nums = [-n << (n & 1) for n in nums] orig_len = len(nums) min_n = -max(nums) heapq.heapify(nums) ret = 10e10 while len(nums) == orig_len: max_n = -heapq.heappop(nums) ret = min(ret, max_n - min_n) if not max_n & 1: max_n >>= 1 min_n = min(min_n, max_n) heapq.heappush(nums, -max_n) return ret if __name__ == "__main__": import os import pytest pytest.main([os.path.join("tests", "test_1675.py")])
jkmishra/prizy
components/camel-cxf/src/main/java/org/apache/camel/component/cxf/WSDLServiceFactoryBean.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf; import java.util.Map; import javax.wsdl.Definition; import javax.wsdl.Service; import javax.xml.namespace.QName; import javax.xml.ws.Provider; import org.apache.camel.RuntimeCamelException; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.endpoint.EndpointException; import org.apache.cxf.endpoint.EndpointImpl; import org.apache.cxf.helpers.CastUtils; import org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean; import org.apache.cxf.service.factory.FactoryBeanListener.Event; import org.apache.cxf.service.invoker.Invoker; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.wsdl.WSDLManager; /** * A service factory bean class that create a service factory without requiring a service class * (SEI). * It will pick the first one service name and first one port/endpoint name in the WSDL, if * there is service name or port/endpoint name setted. * @version */ public class WSDLServiceFactoryBean extends JaxWsServiceFactoryBean { private Definition definition; public WSDLServiceFactoryBean() { setServiceClass(Provider.class); } public void setServiceClass(Class<?> serviceClass) { if (serviceClass != null) { super.setServiceClass(serviceClass); } } protected Definition getDefinition(String url) { if (definition == null) { try { definition = getBus().getExtension(WSDLManager.class).getDefinition(url); } catch (Exception ex) { throw new RuntimeCamelException(ex); } } if (this.getServiceQName(false) == null) { Map<QName, ?> services = CastUtils.cast(definition.getServices()); if (services.size() == 0) { throw new IllegalArgumentException("There is no service in the WSDL" + url); } if (services.size() > 1) { throw new IllegalArgumentException("service name must be specified, there is more than one service in the WSDL" + url); } QName serviceQName = services.keySet().iterator().next(); this.setServiceName(serviceQName); } if (this.getEndpointName(false) == null) { Service service = definition.getService(getServiceQName(false)); Map<String, ?> ports = CastUtils.cast(service.getPorts()); if (ports.size() == 0) { throw new IllegalArgumentException("There is no port/endpoint in the service " + getServiceQName() + "of WSDL" + url); } if (ports.size() > 1) { throw new IllegalArgumentException("Port/endpoint name must be specified, There is more than one port in the service" + service.getQName() + " of the WSDL" + url); } QName endpointQName = new QName(service.getQName().getNamespaceURI(), ports.keySet().iterator().next()); setEndpointName(endpointQName); } return definition; } protected void buildServiceFromWSDL(String url) { getDefinition(url); super.buildServiceFromWSDL(url); } public Endpoint createEndpoint(EndpointInfo ei) throws EndpointException { Endpoint ep = new EndpointImpl(getBus(), getService(), ei); sendEvent(Event.ENDPOINT_CREATED, ei, ep, getServiceClass()); return ep; } @Override protected void initializeWSDLOperations() { // skip this operation that requires service class } @Override protected void checkServiceClassAnnotations(Class<?> sc) { // skip this operation that requires service class } @Override protected Invoker createInvoker() { // Camel specific invoker will be set return null; } }
nnkwrik/fangxianyu
goods-service/src/main/java/io/github/nnkwrik/goodsservice/service/IndexService.java
package io.github.nnkwrik.goodsservice.service; import io.github.nnkwrik.goodsservice.model.po.Category; import io.github.nnkwrik.goodsservice.model.po.Goods; import io.github.nnkwrik.goodsservice.model.vo.CatalogPageVo; import io.github.nnkwrik.goodsservice.model.vo.IndexPageVo; import java.util.List; /** * @author nnkwrik * @date 18/11/16 15:22 */ public interface IndexService { IndexPageVo getIndex(int page, int size); List<Goods> getIndexMore(int page, int size); CatalogPageVo getCatalogIndex(); List<Category> getSubCatalogById(int id); }
ms-courses/JavaScriptAdvance
objects/Objects/defPropWritable.js
<filename>objects/Objects/defPropWritable.js<gh_stars>0 /** * Created by mdylag on 17/03/15. */ var person = {}; Object.defineProperty(person, "name", { writable: false, value: "Nicholas" } ); console.log("Before" ,person.name); person.name="Mirek"; console.log("After", person.name);
openid-certification/-conformance-suite
src/main/java/net/openid/conformance/logging/LogApi.java
package net.openid.conformance.logging; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.gson.Gson; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import net.openid.conformance.CollapsingGsonHttpMessageConverter; import net.openid.conformance.export.HtmlExportRenderer; import net.openid.conformance.export.PlanExportInfo; import net.openid.conformance.export.TestExportInfo; import net.openid.conformance.export.TestHelper; import net.openid.conformance.info.Plan; import net.openid.conformance.info.PublicPlan; import net.openid.conformance.info.PublicTestInfo; import net.openid.conformance.info.TestInfo; import net.openid.conformance.info.TestInfoRepository; import net.openid.conformance.info.TestPlanService; import net.openid.conformance.pagination.PaginationRequest; import net.openid.conformance.pagination.PaginationResponse; import net.openid.conformance.security.AuthenticationFacade; import net.openid.conformance.security.KeyManager; import net.openid.conformance.variant.VariantSelection; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.bson.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.Base64Utils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.security.Signature; import java.security.SignatureException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @Controller @RequestMapping(value = "/api") public class LogApi { @Value("${fintechlabs.base_url:http://localhost:8080}") private String baseUrl; @Value("${fintechlabs.version}") private String version; @Autowired private MongoTemplate mongoTemplate; @Autowired private TestInfoRepository testInfos; @Autowired private AuthenticationFacade authenticationFacade; @Autowired private KeyManager keyManager; @Autowired private HtmlExportRenderer htmlExportRenderer; private Gson gson = CollapsingGsonHttpMessageConverter.getDbObjectCollapsingGson(); @Autowired private TestPlanService planService; @GetMapping(value = "/log", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get all test logs with paging", notes = "Return all published logs when public data is requested, otherwise all test logs if user is admin, or only the user's test logs") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieved successfully") }) public ResponseEntity<Object> getAllTests( @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly, PaginationRequest page) { PaginationResponse<?> response; if (publicOnly) { response = page.getResponse( p -> testInfos.findAllPublic(p), (s, p) -> testInfos.findAllPublicSearch(s, p)); } else if (authenticationFacade.isAdmin()) { response = page.getResponse( p -> testInfos.findAll(p), (s, p) -> testInfos.findAllSearch(s, p)); } else { ImmutableMap<String, String> owner = authenticationFacade.getPrincipal(); response = page.getResponse( p -> testInfos.findAllByOwner(owner, p), (s, p) -> testInfos.findAllByOwnerSearch(owner, s, p)); } return new ResponseEntity<>(response, HttpStatus.OK); } @GetMapping(value = "/log/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get test log of given testId") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieved successfully") }) public ResponseEntity<List<Document>> getLogResults( @ApiParam(value = "Id of test") @PathVariable("id") String id, @ApiParam(value = "Since when test created") @RequestParam(value = "since", required = false) Long since, @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly) { List<Document> results = getTestResults(id, since, publicOnly); return ResponseEntity.ok().body(results); } @GetMapping(value = "/log/export/{id}", produces = "application/zip") @ApiOperation(value = "Export test log by test id") @ApiResponses(value = { @ApiResponse(code = 200, message = "Exported successfully"), @ApiResponse(code = 404, message = "Couldn't find given test Id") }) public ResponseEntity<StreamingResponseBody> export( @ApiParam(value = "Id of test") @PathVariable("id") String id, @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly) { List<Document> results = getTestResults(id, null, publicOnly); Optional<?> testInfo = getTestInfo(publicOnly, id); String testModuleName = null; VariantSelection variant = null; if (!testInfo.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else if (testInfo.get() instanceof TestInfo) { testModuleName = ((TestInfo) testInfo.get()).getTestName(); variant = ((TestInfo) testInfo.get()).getVariant(); } else if (testInfo.get() instanceof PublicTestInfo) { testModuleName = ((PublicTestInfo) testInfo.get()).getTestName(); variant = ((PublicTestInfo) testInfo.get()).getVariant(); } HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=\"test-log-" + (Strings.isNullOrEmpty(testModuleName) ? "" : (testModuleName + "-")) + variantSuffix(variant) + id + ".zip\""); final TestExportInfo export = putTestResultToExport(results, testInfo); StreamingResponseBody responseBody = new StreamingResponseBody() { @Override public void writeTo(OutputStream out) throws IOException { try { ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(out); String jsonFileName = "test-log-" + id + ".json"; String sigFileName = "test-log-" + id + ".sig"; addFilesToZip(archiveOutputStream, jsonFileName, sigFileName, export); archiveOutputStream.close(); } catch (Exception ex) { throw new IOException(ex); } } }; return ResponseEntity.ok().headers(headers).body(responseBody); } @GetMapping(value = "/plan/export/{id}", produces = "application/zip") @ApiOperation(value = "Export all test logs of plan by plan id") @ApiResponses(value = { @ApiResponse(code = 200, message = "Exported successfully"), @ApiResponse(code = 404, message = "Couldn't find given plan Id") }) public ResponseEntity<StreamingResponseBody> exportLogsOfPlan( @ApiParam(value = "Id of plan") @PathVariable("id") String id, @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly) { Object testPlan = publicOnly ? planService.getPublicPlan(id) : planService.getTestPlan(id); String planName = null; VariantSelection variant = null; List<Plan.Module> modules = new ArrayList<>(); if (testPlan == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else if (testPlan instanceof PublicPlan) { planName = ((PublicPlan) testPlan).getPlanName(); variant = ((PublicPlan) testPlan).getVariant(); modules = ((PublicPlan) testPlan).getModules(); } else if (testPlan instanceof Plan) { planName = ((Plan) testPlan).getPlanName(); variant = ((Plan) testPlan).getVariant(); modules = ((Plan) testPlan).getModules(); } List<Map<String, Object>> allLatestLogsExport = new ArrayList<>(); for (Plan.Module module : modules) { String testModuleName = module.getTestModule(); List<String> instances = module.getInstances(); if (instances != null && !instances.isEmpty()) { String testId = instances.get(instances.size() - 1); List<Document> results = getTestResults(testId, null, publicOnly); Optional<?> testInfo = getTestInfo(publicOnly, testId); final TestExportInfo export = putTestResultToExport(results, testInfo); final Map<String, Object> testLogInfoExport = new HashMap<>(); testLogInfoExport.put("testId", testId); testLogInfoExport.put("testModuleName", testModuleName); testLogInfoExport.put("export", export); allLatestLogsExport.add(testLogInfoExport); } } if (allLatestLogsExport.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=\"" + (Strings.isNullOrEmpty(planName) ? "" : (planName + "-")) + variantSuffix(variant) + id + ".zip\""); StreamingResponseBody responseBody = new StreamingResponseBody() { @Override public void writeTo(OutputStream out) throws IOException { try { ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(out); // add all test logs file of a test plan to zip for (Map<String, Object> testLogInfoExport : allLatestLogsExport) { String jsonFileName = "test-log-" + testLogInfoExport.get("testModuleName") + "-" + testLogInfoExport.get("testId") + ".json"; String sigFileName = "test-log-" + testLogInfoExport.get("testModuleName") + "-" + testLogInfoExport.get("testId") + ".sig"; @SuppressWarnings("unchecked") TestExportInfo infoExport = (TestExportInfo) testLogInfoExport.get("export"); addFilesToZip(archiveOutputStream, jsonFileName, sigFileName, infoExport); } archiveOutputStream.close(); } catch (Exception ex) { throw new IOException(ex); } } }; return ResponseEntity.ok().headers(headers).body(responseBody); } protected void addFilesToZip(ZipArchiveOutputStream archiveOutputStream, String jsonFileName, String sigFileName, TestExportInfo export) throws Exception { ZipArchiveEntry testLog = new ZipArchiveEntry(jsonFileName); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyManager.getSigningPrivateKey()); SignatureOutputStream signatureOutputStream = new SignatureOutputStream(archiveOutputStream, signature); String json = gson.toJson(export); testLog.setSize(json.getBytes().length); archiveOutputStream.putArchiveEntry(testLog); signatureOutputStream.write(json.getBytes()); signatureOutputStream.flush(); signatureOutputStream.close(); archiveOutputStream.closeArchiveEntry(); ZipArchiveEntry signatureFile = new ZipArchiveEntry(sigFileName); String encodedSignature = Base64Utils.encodeToUrlSafeString(signature.sign()); signatureFile.setSize(encodedSignature.getBytes().length); archiveOutputStream.putArchiveEntry(signatureFile); archiveOutputStream.write(encodedSignature.getBytes()); archiveOutputStream.closeArchiveEntry(); } protected Optional<?> getTestInfo(boolean publicOnly, String testId) { Optional<?> testInfo = Optional.empty(); if (publicOnly) { testInfo = testInfos.findByIdPublic(testId); } else if (authenticationFacade.isAdmin()) { testInfo = testInfos.findById(testId); } else { ImmutableMap<String, String> owner = authenticationFacade.getPrincipal(); if (owner != null) { testInfo = testInfos.findByIdAndOwner(testId, owner); } } return testInfo; } protected TestExportInfo putTestResultToExport(List<Document> results, Optional<?> testInfo) { TestExportInfo export = new TestExportInfo(baseUrl, authenticationFacade.getPrincipal(), version, testInfo.get(), results); return export; } private List<Document> getTestResults(String id, Long since, boolean isPublic) { boolean summaryOnly; if (isPublic) { // Check publish status of test Optional<PublicTestInfo> testInfo = testInfos.findByIdPublic(id); if (!testInfo.isPresent()) { return Collections.emptyList(); } else { summaryOnly = !testInfo.get().getPublish().equals("everything"); } } else { summaryOnly = false; } Criteria criteria = new Criteria(); criteria.and("testId").is(id); if (!isPublic && !authenticationFacade.isAdmin()) { criteria.and("testOwner").is(authenticationFacade.getPrincipal()); } if (since != null) { criteria.and("time").gt(since); } Query query = new Query(criteria); if (summaryOnly) { query.fields() .include("result") .include("testName") .include("testId") .include("src") .include("time"); } return Lists.newArrayList(mongoTemplate .getCollection(DBEventLog.COLLECTION) .find(query.getQueryObject()) .projection(query.getFieldsObject()) .sort(new Document("time", 1))); } private static String variantSuffix(VariantSelection variant) { if (variant == null) { return ""; } else if (variant.isLegacyVariant()) { return variant.getLegacyVariant() + "-"; } else { return variant.getVariant().values() .stream() .collect(Collectors.joining("-")) + "-"; } } @PostMapping(value = "/plan/{id}/certificationpackage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = "application/zip") @ApiOperation(value = "Prepare certification package for a test plan. Also publishes the plan and marks it as immutable.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Prepared successfully"), @ApiResponse(code = 403, message = "Could not publish plan"), @ApiResponse(code = 404, message = "Could not find a plan with the given id"), @ApiResponse(code = 422, message = "Could not mark the plan as immutable") }) public ResponseEntity<StreamingResponseBody> prepareCertificationPackageForTestPlan( @ApiParam(value = "Id of test plan") @PathVariable("id") String id, @ApiParam(value = "Signed certification of conformance pdf") @RequestParam("certificationOfConformancePdf") MultipartFile certificationOfConformancePdf, @ApiParam(value = "Client data in zip format. Only required for RP tests") @RequestParam("clientSideData") MultipartFile clientSideData ) { if (!planService.publishTestPlan(id, "everything")) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (!planService.changeTestPlanImmutableStatus(id, Boolean.TRUE)) { return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); } return exportPlanAsZip(id, false, true, certificationOfConformancePdf, clientSideData); } @GetMapping(value = "/plan/exporthtml/{id}", produces = "application/zip") @ApiOperation(value = "Export the full results for this plan as both html and json in a zip") @ApiResponses(value = { @ApiResponse(code = 200, message = "Exported successfully"), @ApiResponse(code = 404, message = "Couldn't find given plan Id") }) public ResponseEntity<StreamingResponseBody> exportPlanAsHTML( HttpServletRequest httpRequest, @ApiParam(value = "Id of plan") @PathVariable("id") String id, @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly) { return exportPlanAsZip(id, publicOnly, false, null, null); } protected ResponseEntity<StreamingResponseBody> exportPlanAsZip(String planId, boolean publicOnly, boolean addFolderForHtmlFiles, MultipartFile certificationOfConformancePdf, MultipartFile clientSideData) { Object testPlan = publicOnly ? planService.getPublicPlan(planId) : planService.getTestPlan(planId); String planName = null; VariantSelection variant = null; List<Plan.Module> modules = new ArrayList<>(); if (testPlan == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else if (testPlan instanceof PublicPlan) { planName = ((PublicPlan) testPlan).getPlanName(); variant = ((PublicPlan) testPlan).getVariant(); modules = ((PublicPlan) testPlan).getModules(); } else if (testPlan instanceof Plan) { planName = ((Plan) testPlan).getPlanName(); variant = ((Plan) testPlan).getVariant(); modules = ((Plan) testPlan).getModules(); } //plan summary page PlanExportInfo planExportInfo = new PlanExportInfo(baseUrl, authenticationFacade.getPrincipal(), version, testPlan); for (Plan.Module module : modules) { String testModuleName = module.getTestModule(); List<String> instances = module.getInstances(); if (instances != null && !instances.isEmpty()) { String testId = instances.get(instances.size() - 1); List<Document> results = getTestResults(testId, null, publicOnly); Optional<?> testInfo = getTestInfo(publicOnly, testId); final TestExportInfo export = putTestResultToExport(results, testInfo); PlanExportInfo.TestExportInfoHolder testExportInfoHolder = new PlanExportInfo.TestExportInfoHolder(testId, testModuleName, export); planExportInfo.addTestExportInfoHolder(testExportInfoHolder); } } if (planExportInfo.getTestExportCount()<1) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } String fileDate = DateTimeFormatter.ofPattern("dd-MMM-yyyy").format(LocalDate.now()); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=\"" + (Strings.isNullOrEmpty(planName) ? "" : (planName + "-")) + variantSuffix(variant) + planId + "-" + fileDate + ".zip\""); StreamingResponseBody responseBody = new StreamingResponseBody() { @Override public void writeTo(OutputStream out) throws IOException { try { ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(out); addPlanHTMLToZip(archiveOutputStream, testPlan, planExportInfo, htmlExportRenderer, addFolderForHtmlFiles); // add all test logs file of a test plan to zip for (PlanExportInfo.TestExportInfoHolder testLogInfoExport : planExportInfo.getTestLogExports()) { String htmlFileName = TestHelper.generateHtmlFileName(testLogInfoExport.getTestModuleName(), testLogInfoExport.getTestId()); String sigFileName = TestHelper.generateSigFileName(testLogInfoExport.getTestModuleName(), testLogInfoExport.getTestId()); if(addFolderForHtmlFiles){ htmlFileName = "test-logs/" + htmlFileName; sigFileName = "test-logs/" + sigFileName; } addHTMLFileToZip(archiveOutputStream, htmlFileName, sigFileName, testLogInfoExport.getExport(), htmlExportRenderer); String jsonLogFilename = "test-log-"+testLogInfoExport.getTestModuleName()+"-" + testLogInfoExport.getTestId() + ".json"; String jsonLogSigFilename = "test-log-"+testLogInfoExport.getTestModuleName()+"-" + testLogInfoExport.getTestId() + ".json.sig"; if(addFolderForHtmlFiles){ jsonLogFilename = "test-logs/" + jsonLogFilename; jsonLogSigFilename = "test-logs/" + jsonLogSigFilename; } addFilesToZip(archiveOutputStream, jsonLogFilename, jsonLogSigFilename, testLogInfoExport.getExport()); } if(certificationOfConformancePdf!=null && certificationOfConformancePdf.getSize()>0) { ZipArchiveEntry zipEntry = new ZipArchiveEntry("OpenID-Certification-of-Conformance.pdf"); zipEntry.setSize(certificationOfConformancePdf.getSize()); archiveOutputStream.putArchiveEntry(zipEntry); archiveOutputStream.write(certificationOfConformancePdf.getBytes()); archiveOutputStream.closeArchiveEntry(); } if(clientSideData!=null && clientSideData.getSize()>0) { ZipArchiveEntry zipEntry = new ZipArchiveEntry("client-data/" + clientSideData.getOriginalFilename()); zipEntry.setSize(clientSideData.getSize()); archiveOutputStream.putArchiveEntry(zipEntry); archiveOutputStream.write(clientSideData.getBytes()); archiveOutputStream.closeArchiveEntry(); } archiveOutputStream.close(); } catch (Exception ex) { throw new IOException(ex); } } }; return ResponseEntity.ok().headers(headers).body(responseBody); } protected void addPlanHTMLToZip(ZipArchiveOutputStream archiveOutputStream, Object plan, PlanExportInfo planExportInfo, HtmlExportRenderer htmlExportRenderer, boolean addLogsFolder) throws Exception { String indexFilename = "index.html"; String indexSigFilename = "index.html.sig"; if(addLogsFolder) { indexFilename = "test-logs/" + indexFilename; indexSigFilename = "test-logs/" + indexSigFilename; } ZipArchiveEntry testLog = new ZipArchiveEntry(indexFilename); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyManager.getSigningPrivateKey()); SignatureOutputStream signatureOutputStream = new SignatureOutputStream(archiveOutputStream, signature); String html = htmlExportRenderer.createHtmlForPlan(planExportInfo); byte[] htmlBytes = html.getBytes(StandardCharsets.UTF_8); testLog.setSize(htmlBytes.length); archiveOutputStream.putArchiveEntry(testLog); signatureOutputStream.write(htmlBytes); signatureOutputStream.flush(); signatureOutputStream.close(); archiveOutputStream.closeArchiveEntry(); ZipArchiveEntry signatureFile = new ZipArchiveEntry(indexSigFilename); String encodedSignature = Base64Utils.encodeToUrlSafeString(signature.sign()); signatureFile.setSize(encodedSignature.getBytes().length); archiveOutputStream.putArchiveEntry(signatureFile); archiveOutputStream.write(encodedSignature.getBytes()); archiveOutputStream.closeArchiveEntry(); } protected void addHTMLFileToZip(ZipArchiveOutputStream archiveOutputStream, String htmlFileName, String sigFileName, TestExportInfo export, HtmlExportRenderer htmlExportRenderer) throws Exception { ZipArchiveEntry testLog = new ZipArchiveEntry(htmlFileName); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyManager.getSigningPrivateKey()); SignatureOutputStream signatureOutputStream = new SignatureOutputStream(archiveOutputStream, signature); String html = htmlExportRenderer.createHtmlForTestLogs(export); byte[] htmlBytes = html.getBytes(StandardCharsets.UTF_8); testLog.setSize(htmlBytes.length); archiveOutputStream.putArchiveEntry(testLog); signatureOutputStream.write(htmlBytes); signatureOutputStream.flush(); signatureOutputStream.close(); archiveOutputStream.closeArchiveEntry(); ZipArchiveEntry signatureFile = new ZipArchiveEntry(sigFileName); String encodedSignature = Base64Utils.encodeToUrlSafeString(signature.sign()); signatureFile.setSize(encodedSignature.getBytes().length); archiveOutputStream.putArchiveEntry(signatureFile); archiveOutputStream.write(encodedSignature.getBytes()); archiveOutputStream.closeArchiveEntry(); } @GetMapping(value = "/log/exporthtml/{id}", produces = "application/zip") @ApiOperation(value = "Export test logs as html by test id") @ApiResponses(value = { @ApiResponse(code = 200, message = "Exported successfully"), @ApiResponse(code = 404, message = "Couldn't find given test Id") }) public ResponseEntity<StreamingResponseBody> exportTestHtml( @ApiParam(value = "Id of test") @PathVariable("id") String id, @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly) { List<Document> results = getTestResults(id, null, publicOnly); Optional<?> testInfo = getTestInfo(publicOnly, id); String testModuleName = null; VariantSelection variant = null; if (!testInfo.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else if (testInfo.get() instanceof TestInfo) { testModuleName = ((TestInfo) testInfo.get()).getTestName(); variant = ((TestInfo) testInfo.get()).getVariant(); } else if (testInfo.get() instanceof PublicTestInfo) { testModuleName = ((PublicTestInfo) testInfo.get()).getTestName(); variant = ((PublicTestInfo) testInfo.get()).getVariant(); } HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=\"test-log-" + (Strings.isNullOrEmpty(testModuleName) ? "" : (testModuleName + "-")) + variantSuffix(variant) + id + ".zip\""); final TestExportInfo export = putTestResultToExport(results, testInfo); final String testModuleNameFinal = testModuleName; StreamingResponseBody responseBody = new StreamingResponseBody() { @Override public void writeTo(OutputStream out) throws IOException { try { ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(out); String htmlFileName = TestHelper.generateHtmlFileName(testModuleNameFinal, id); String sigFileName = TestHelper.generateSigFileName(testModuleNameFinal, id); addHTMLFileToZip(archiveOutputStream, htmlFileName, sigFileName, export, htmlExportRenderer); addFilesToZip(archiveOutputStream, "test-log-"+testModuleNameFinal+"-" + id + ".json", "test-log-"+testModuleNameFinal+"-" + id + ".json.sig", export); archiveOutputStream.close(); } catch (Exception ex) { throw new IOException(ex); } } }; return ResponseEntity.ok().headers(headers).body(responseBody); } private static class SignatureOutputStream extends OutputStream { private OutputStream target; private Signature sig; /** * creates a new SignatureOutputStream which writes to * a target OutputStream and updates the Signature object. */ public SignatureOutputStream(OutputStream target, Signature sig) { this.target = target; this.sig = sig; } @Override public void write(int b) throws IOException { write(new byte[]{(byte)b}); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int offset, int len) throws IOException { target.write(b, offset, len); try { sig.update(b, offset, len); } catch(SignatureException ex) { throw new IOException(ex); } } @Override public void flush() throws IOException { target.flush(); } @Override public void close() throws IOException { // we don't close the target stream when we're done because we might keep writing to it later //target.close(); } } }
code-review-doctor/lite-frontend-1
exporter/licences/apps.py
from django.apps import AppConfig class LicencesConfig(AppConfig): name = "exporter.licences"
sandrew1945/bury
bury-core/src/test/java/com/sandrew/bury/model/UserTag.java
<reponame>sandrew1945/bury package com.sandrew.bury.model; import com.sandrew.bury.bean.PO; public class UserTag extends PO { private Integer userId; private String userCode; private String userName; private String tag; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } }
phongcui1510/icommerce
product-service/src/main/java/com/icommerce/product/repository/utils/ProductConverter.java
<reponame>phongcui1510/icommerce package com.icommerce.product.repository.utils; import com.icommerce.product.repository.entity.ProductEntity; import com.icommerce.product.service.product.dto.ProductDTO; import org.springframework.beans.BeanUtils; import java.util.function.Function; public interface ProductConverter { Function<ProductEntity, ProductDTO> toModel = entity -> { final ProductDTO product = new ProductDTO(); BeanUtils.copyProperties(entity, product); return product; }; Function<ProductDTO, ProductEntity> toEntity = product -> { final ProductEntity entity = new ProductEntity(); BeanUtils.copyProperties(product, entity); return entity; }; }
rajarshisarkar/gimel
gimel-dataapi/gimel-sql/src/test/scala/com/paypal/gimel/sql/SQLParserSourceTableSpec.scala
<reponame>rajarshisarkar/gimel<filename>gimel-dataapi/gimel-sql/src/test/scala/com/paypal/gimel/sql/SQLParserSourceTableSpec.scala<gh_stars>100-1000 /* * Copyright 2018 PayPal Inc. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paypal.gimel.sql import org.scalatest.{FunSpec, Matchers} import com.paypal.gimel.logger.Logger import com.paypal.gimel.parser.utilities.SQLNonANSIJoinParser import com.paypal.gimel.sql.SQLMasterList._ class SQLParserSourceTableSpec extends FunSpec with Matchers { private val logger = Logger(this.getClass.getName) describe("getSourceTablesFromNonAnsi") { it("should pick correct table names from the SELECT QUERY") { SQLNonANSIJoinParser.getSourceTablesFromNonAnsi(sqlANSIanNonANSI) should equal( List("a", "b", "c", "d", "k", "l") ) SQLNonANSIJoinParser.getSourceTablesFromNonAnsi(sqlANSISimple) should equal( List("a", "b", "c", "d") ) SQLNonANSIJoinParser.getSourceTablesFromNonAnsi(sqlANSISimpleSubQuery) should equal( List("a", "b", "c", "d") ) SQLNonANSIJoinParser.getSourceTablesFromNonAnsi(sqlANSIOnly) should equal( List() ) SQLNonANSIJoinParser.getSourceTablesFromNonAnsi(joinANSISQLViaUDC) should equal( List() ) SQLNonANSIJoinParser.getSourceTablesFromNonAnsi(mixANSINonANSISQL) should equal( List( "udc.kafka.test.test.emp", "udc.hive.test_cluster.test.calendar", "c", "udc.teradata.test_cluster.testdb.lkp" ) ) } } describe("getAll UDC TableSources") { it("should pick correct table names from the SELECT QUERY") { GimelQueryUtils.getTablesFrom(sqlANSIanNonANSI) should equal(List()) GimelQueryUtils.getTablesFrom(sqlANSISimple) should equal(List()) GimelQueryUtils.getTablesFrom(sqlANSISimpleSubQuery) should equal(List()) GimelQueryUtils.getTablesFrom(sqlANSIOnly) should equal(List()) GimelQueryUtils.getTablesFrom(mixANSINonANSISQL) should equal( List( "udc.kafka.test.test.emp", "udc.hive.test_cluster.test.calendar", "udc.teradata.test_cluster.testdb.lkp" ) ) GimelQueryUtils.getTablesFrom(baSQL4) should equal( List( "pcatalog.teradata.tau.yelp.review", "pcatalog.teradata.tau.yelp.user" ) ) GimelQueryUtils.getTablesFrom(joinANSISQLViaUDC).sorted should equal( List( "udc.kafka.test.emp.address", "udc.kafka.test.emp.loc" ).sorted ) GimelQueryUtils.getAllTableSources(joinANSISQLViaUDC).sorted should equal( List( "testdb.emp", "udc.kafka.test.emp.address", "udc.kafka.test.emp.loc" ).sorted ) } } describe("get All Source Tables") { it("should pick correct table names from the SELECT QUERY") { GimelQueryUtils.getAllTableSources(sqlANSIanNonANSI) should equal( List("a", "b", "c", "d", "k", "l", "t2") ) GimelQueryUtils.getAllTableSources(sqlANSISimple) should equal( List("a", "b", "c", "d") ) GimelQueryUtils.getAllTableSources(sqlANSISimpleSubQuery) should equal( List("a", "b", "c", "d") ) GimelQueryUtils.getAllTableSources(sqlANSIOnly) should equal( List("emp_loc", "testdb.emp") ) GimelQueryUtils.getAllTableSources(joinANSISQLViaUDC).sorted should equal( List( "testdb.emp", "udc.kafka.test.emp.address", "udc.kafka.test.emp.loc" ).sorted ) GimelQueryUtils.getAllTableSources(mixANSINonANSISQL).sorted should equal( List( "testdb.emp", "udc.kafka.test.test.emp", "udc.hive.test_cluster.test.calendar", "c", "udc.teradata.test_cluster.testdb.lkp" ).sorted ) } } describe("isSQLNonANSIJoin") { it( "should pick tell correctly if a SQL is ANSI only or has NON-ANSI joins as well" ) { SQLNonANSIJoinParser.isSQLNonANSIJoin(sqlANSIanNonANSI) should equal(true) } } describe("All DDL DML type") { it("should pick correct table names ") { GimelQueryUtils.getAllTableSources( "collect statistics on yelp.tmp_table" ) should equal(List("yelp.tmp_table")) GimelQueryUtils.getAllTableSources("DELETE ALL yelp.tmp_table") should equal( List("yelp.tmp_table") ) GimelQueryUtils.getAllTableSources("DELETE yelp.tmp_table ALL") should equal( List("yelp.tmp_table") ) GimelQueryUtils.getAllTableSources("DESCRIBE yelp.tmp_table") should equal( List("yelp.tmp_table") ) GimelQueryUtils.getAllTableSources("HELP table yelp.tmp_table") should equal( List("yelp.tmp_table") ) GimelQueryUtils.getAllTableSources("show view yelp.tmp_table") should equal( List("yelp.tmp_table") ) } it("should exclude join desc") { GimelQueryUtils.getAllTableSources("DESC yelp.tmp_table") should equal( List() ) } it("should pick table names from CACHE table") { assert( GimelQueryUtils .getAllTableSources("""cache table work_day_employees as |select * from udc.SFTP.Test.default.Files;""".stripMargin) == List( "work_day_employees", "udc.sftp.test.default.files" ) ) assert( GimelQueryUtils .getAllTableSources( """cache table workday_dump1 as |select |lower(a.ntid) as username |,a.`Employee QID` as employee_qid |,a.`Emplyee Last Name` as last_name |,a.`Employee First Name` as first_name |,concat(a.`Emplyee Last Name`,',',a.`Employee First Name`) as full_name |,a.`Org Description` as org_desc |,a.`Org ID ` as org_id |,a.`Loaction` as location |,lower(a.`Manager ID`) as manager_qid |,lower(b.ntid) as manager_username |from work_day_employees a |left join work_day_employees_b b |on a.`Manager ID` = b.`Employee QID`;""".stripMargin ) == List( "workday_dump1", "work_day_employees", "work_day_employees_b" ) ) assert( GimelQueryUtils .getAllTableSources( """set gimel.jdbc.p.strategy=file; |set gimel.jdbc.p.file=/user/testuser/udc.prod.pass; |set gimel.jdbc.username=testadmin; | |insert into udc.MySql.UDC.pcatalog.workday_dump |select * from workday_dump1 """.stripMargin ) == List("workday_dump1", "udc.mysql.udc.pcatalog.workday_dump") ) } } describe("Check multiple match criteria within same SQL ") { it("should extract valid table names ") { logger.info( GimelQueryUtils.getAllTableSources( "drop table if exists udc.hive.test.testdb.emp" ) ) logger.info( GimelQueryUtils.getAllTableSources( """cache table td_views_hive_all |select distinct * from |( |select * | from | udc.hive.test.default.teradata_db_views_test |union |select * | from | udc.hive.test.default.teradata_2_db_views_test |)""".stripMargin ) ) logger.info( GimelQueryUtils.getAllTableSources( """cache table td_views_hive_all |select distinct tlb.* from |( |select * |from |udc.hive.test.default.teradata_db_views_test |union |select * |from |udc.hive.test.default.teradata_2_db_views_test |) tlb""".stripMargin ) ) } } }
isuhao/ravl2
RAVL2/OS/Compress/Compress.cc
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2005, OmniPerception Ltd. // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //! author="<NAME>" //! docentry="Ravl.OS.Compression" #include "Ravl/Compress.hh" #include <zlib.h> namespace RavlN { //: Compress data into 'buff' bool CompressZLib(const SArray1dC<char> &data,SArray1dC<char> &buff,IntT level) { if(data.Size() == 0) { buff = SArray1dC<char>(); return true; } uLongf len = compressBound(data.Size()); buff = SArray1dC<char>(len); int ret = 0; if((ret = compress2(reinterpret_cast<Bytef *>(&(buff[0])),&len,reinterpret_cast<const Bytef *>(&(data[0])),data.Size(),level)) != Z_OK) { //cerr << "Compress failed " << ret << "\n"; return false; } buff = SArray1dC<char>(buff,len); return true; } //: Decompress buff into data. bool DecompressZLib(const SArray1dC<char> &buff,SArray1dC<char> &data,UIntT originalSize) { if(buff.Size() == 0) { data = SArray1dC<char>(); return true; } uLongf len = originalSize; data = SArray1dC<char>(len); if(uncompress(reinterpret_cast<Bytef *>(&(data[0])),&len,reinterpret_cast<const Bytef *>(&(buff[0])),buff.Size()) != Z_OK) return false; if(len != originalSize) // Need to trim the buffer? data = SArray1dC<char>(data,len); return true; } }
towa0131/libcgss
src/lib/takamori/Utilities.cpp
<reponame>towa0131/libcgss #include "Utilities.h" #ifdef __CGSS_OS_UNIX__ #include <dlfcn.h> #endif CGSS_NS_BEGIN Utilities::HLIB Utilities::LoadDynamicLibrary(LPCSTR lpstrModuleName) { #if defined(__CGSS_OS_WINDOWS__) return LoadLibrary(lpstrModuleName); #elif defined(__CGSS_OS_UNIX__) return dlopen(lpstrModuleName, RTLD_LAZY); #endif } void *Utilities::GetFunctionAddress(Utilities::HLIB hModule, LPCSTR lpstrFuncName) { #if defined(__CGSS_OS_WINDOWS__) return (void *)GetProcAddress(hModule, lpstrFuncName); #elif defined(__CGSS_OS_UNIX__) return dlsym(hModule, lpstrFuncName); #endif } bool_t Utilities::FreeDynamicLibrary(Utilities::HLIB hModule) { #if defined(__CGSS_OS_WINDOWS__) return static_cast<bool_t>(FreeLibrary(hModule)); #elif defined(__CGSS_OS_UNIX__) return static_cast<bool_t>(dlclose(hModule)); #endif } CGSS_NS_END
DenL1/GNISGeoCoder
GNISGeoCoder/GNISGeocoder.h
<reponame>DenL1/GNISGeoCoder<gh_stars>0 // // GNISGeocoder.h // GNISGeoCoder // // Created by Dennis on 2/6/17. // The author disclaims copyright to this source code. // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely. // #import <Foundation/Foundation.h> #import "ForwardGeoResult.h" @import MapKit; // MKCoordinateRegion #define kGNISDatabaseFilename @"gnis_NAmer.sqlite3" // bundle file basename #define kGNISDatabaseTimeout (2.1) // (seconds) default timeout @class GNISGeocoder; @protocol GNISGeocoderDelegate<NSObject> @required // Normal response -(void) GNISGeocodingDidSucceed:(GNISGeocoder *)geocoder withResults:(NSArray<ForwardGeoResult*>*)results; @optional // geocoding server error response -(void) GNISGeocodingDidFail:(GNISGeocoder *)geocoder withErrorCode:(int)errorCode andErrorMessage:(NSString *)errorMessage; @end @interface GNISGeocoder : NSObject -(NSInteger) forwardGeocodeWithQuery:(NSString *)searchQuery mapRegion:(MKCoordinateRegion) mapRegion; -(NSInteger) forwardGeocodeWithQuery:(NSString *)searchQuery; -(instancetype) initWithDelegate:(id<GNISGeocoderDelegate>)aDelegate; // Open the DB, returns YES if sqlite3 db file found and openned ok, NO if failed. // If already open, returns YES. -(BOOL) openDB; @property(nonatomic) BOOL hasOpenedDB; // open successfully @property(nonatomic,weak) id<GNISGeocoderDelegate> delegate; @property(nonatomic) NSInteger queryCount; @property(nonatomic) NSInteger responseCount; @property(nonatomic) NSTimeInterval timeout; // 2.1s default kGNISDatabaseTimeout @property(nonatomic) BOOL resultsAreSortedByDistance; #ifdef TESTCFG @property(nonatomic) NSArray<ForwardGeoResult*>* results; #endif @end
leongold/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/dr/GlusterStorageDomainDRSyncJob.java
<gh_stars>0 package org.ovirt.engine.core.bll.storage.dr; import org.ovirt.engine.core.bll.interfaces.BackendInternal; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.common.action.GlusterStorageSyncCommandParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.gluster.GlusterGeoRepSession; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.StorageDomainDao; import org.ovirt.engine.core.dao.gluster.GlusterGeoRepDao; import org.ovirt.engine.core.di.Injector; import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GlusterStorageDomainDRSyncJob { private static final Logger log = LoggerFactory.getLogger(GlusterStorageDomainDRSyncJob.class); private final StorageDomainDao storageDomainDao; private final GlusterGeoRepDao geoRepDao; private final BackendInternal backend; public GlusterStorageDomainDRSyncJob() { super(); // The @Inject annotation does not work when the GlusterStorageDomainDRSyncJob // is instantiated as part of Quartz trigger - even when the class passed to // quartz is instantiated using Injector.injectMembers. // TBD - change when quartz classes use CDI too backend = Injector.get(BackendInternal.class); storageDomainDao = Injector.get(StorageDomainDao.class); geoRepDao = Injector.get(GlusterGeoRepDao.class); } @OnTimerMethodAnnotation("syncData") public void syncData(String storageDomainId, String geoRepSessionId) { try { // Get storage domain and georep session StorageDomain storageDomain = storageDomainDao.get(new Guid(storageDomainId)); if (storageDomain == null) { log.error("No storage domain found for id '{}'", storageDomainId); return; } GlusterGeoRepSession session = geoRepDao.getById(new Guid(geoRepSessionId)); if (session == null) { log.error("No geo-replication session found for id '{}'", geoRepSessionId); return; } backend.runInternalAction(VdcActionType.GlusterStorageSync, new GlusterStorageSyncCommandParameters(storageDomain.getId(), session.getId()), ExecutionHandler.createInternalJobContext()); } catch (Exception e) { log.error("Error running dr sync", e); } } }
uve/tensorflow
tensorflow/python/ops/bitwise_ops_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for bitwise operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.ops import bitwise_ops from tensorflow.python.ops import gen_bitwise_ops from tensorflow.python.platform import googletest class BitwiseOpTest(test_util.TensorFlowTestCase): def __init__(self, method_name="runTest"): super(BitwiseOpTest, self).__init__(method_name) @test_util.run_deprecated_v1 def testBinaryOps(self): dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64] with self.session(use_gpu=True) as sess: for dtype in dtype_list: lhs = constant_op.constant([0, 5, 3, 14], dtype=dtype) rhs = constant_op.constant([5, 0, 7, 11], dtype=dtype) and_result, or_result, xor_result = sess.run( [bitwise_ops.bitwise_and(lhs, rhs), bitwise_ops.bitwise_or(lhs, rhs), bitwise_ops.bitwise_xor(lhs, rhs)]) self.assertAllEqual(and_result, [0, 0, 3, 10]) self.assertAllEqual(or_result, [5, 5, 7, 15]) self.assertAllEqual(xor_result, [5, 5, 4, 5]) def testPopulationCountOp(self): dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16] raw_inputs = [0, 1, -1, 3, -3, 5, -5, 14, -14, 127, 128, 255, 256, 65535, 65536, 2**31 - 1, 2**31, 2**32 - 1, 2**32, -2**32 + 1, -2**32, -2**63 + 1, 2**63 - 1] def count_bits(x): return sum(bin(z).count("1") for z in six.iterbytes(x.tobytes())) for dtype in dtype_list: with self.cached_session(use_gpu=True) as sess: print("PopulationCount test: ", dtype) inputs = np.array(raw_inputs, dtype=dtype.as_numpy_dtype) truth = [count_bits(x) for x in inputs] input_tensor = constant_op.constant(inputs, dtype=dtype) popcnt_result = self.evaluate( gen_bitwise_ops.population_count(input_tensor)) self.assertAllEqual(truth, popcnt_result) @test_util.run_deprecated_v1 def testInvertOp(self): dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64] inputs = [0, 5, 3, 14] with self.session(use_gpu=True) as sess: for dtype in dtype_list: # Because of issues with negative numbers, let's test this indirectly. # 1. invert(a) and a = 0 # 2. invert(a) or a = invert(0) input_tensor = constant_op.constant(inputs, dtype=dtype) not_a_and_a, not_a_or_a, not_0 = sess.run( [bitwise_ops.bitwise_and( input_tensor, bitwise_ops.invert(input_tensor)), bitwise_ops.bitwise_or( input_tensor, bitwise_ops.invert(input_tensor)), bitwise_ops.invert(constant_op.constant(0, dtype=dtype))]) self.assertAllEqual(not_a_and_a, [0, 0, 0, 0]) self.assertAllEqual(not_a_or_a, [not_0] * 4) # For unsigned dtypes let's also check the result directly. if dtype.is_unsigned: inverted = self.evaluate(bitwise_ops.invert(input_tensor)) expected = [dtype.max - x for x in inputs] self.assertAllEqual(inverted, expected) @test_util.run_deprecated_v1 def testShiftsWithPositiveLHS(self): dtype_list = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64] with self.session(use_gpu=True) as sess: for dtype in dtype_list: lhs = np.array([0, 5, 3, 14], dtype=dtype) rhs = np.array([5, 0, 7, 3], dtype=dtype) left_shift_result, right_shift_result = sess.run( [bitwise_ops.left_shift(lhs, rhs), bitwise_ops.right_shift(lhs, rhs)]) self.assertAllEqual(left_shift_result, np.left_shift(lhs, rhs)) self.assertAllEqual(right_shift_result, np.right_shift(lhs, rhs)) @test_util.run_deprecated_v1 def testShiftsWithNegativeLHS(self): dtype_list = [np.int8, np.int16, np.int32, np.int64] with self.session(use_gpu=True) as sess: for dtype in dtype_list: lhs = np.array([-1, -5, -3, -14], dtype=dtype) rhs = np.array([5, 0, 7, 11], dtype=dtype) left_shift_result, right_shift_result = sess.run( [bitwise_ops.left_shift(lhs, rhs), bitwise_ops.right_shift(lhs, rhs)]) self.assertAllEqual(left_shift_result, np.left_shift(lhs, rhs)) self.assertAllEqual(right_shift_result, np.right_shift(lhs, rhs)) @test_util.run_deprecated_v1 def testImplementationDefinedShiftsDoNotCrash(self): dtype_list = [np.int8, np.int16, np.int32, np.int64] with self.session(use_gpu=True) as sess: for dtype in dtype_list: lhs = np.array([-1, -5, -3, -14], dtype=dtype) rhs = np.array([-2, 64, 101, 32], dtype=dtype) # We intentionally do not test for specific values here since the exact # outputs are implementation-defined. However, we should not crash or # trigger an undefined-behavior error from tools such as # AddressSanitizer. sess.run([bitwise_ops.left_shift(lhs, rhs), bitwise_ops.right_shift(lhs, rhs)]) @test_util.run_deprecated_v1 def testShapeInference(self): dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16] with self.session(use_gpu=True) as sess: for dtype in dtype_list: lhs = constant_op.constant([[0], [3], [5]], dtype=dtype) rhs = constant_op.constant([[1, 2, 4]], dtype=dtype) and_tensor = bitwise_ops.bitwise_and(lhs, rhs) or_tensor = bitwise_ops.bitwise_or(lhs, rhs) xor_tensor = bitwise_ops.bitwise_xor(lhs, rhs) ls_tensor = bitwise_ops.left_shift(lhs, rhs) rs_tensor = bitwise_ops.right_shift(lhs, rhs) and_result, or_result, xor_result, ls_result, rs_result = sess.run( [and_tensor, or_tensor, xor_tensor, ls_tensor, rs_tensor]) # Compare shape inference with result self.assertAllEqual(and_tensor.get_shape().as_list(), and_result.shape) self.assertAllEqual(and_tensor.get_shape().as_list(), [3, 3]) self.assertAllEqual(or_tensor.get_shape().as_list(), or_result.shape) self.assertAllEqual(or_tensor.get_shape().as_list(), [3, 3]) self.assertAllEqual(xor_tensor.get_shape().as_list(), xor_result.shape) self.assertAllEqual(xor_tensor.get_shape().as_list(), [3, 3]) self.assertAllEqual(ls_tensor.get_shape().as_list(), ls_result.shape) self.assertAllEqual(ls_tensor.get_shape().as_list(), [3, 3]) self.assertAllEqual(rs_tensor.get_shape().as_list(), rs_result.shape) self.assertAllEqual(rs_tensor.get_shape().as_list(), [3, 3]) if __name__ == "__main__": googletest.main()
GitHuber228/django_news
settings/migrations/0001_initial.py
# Generated by Django 3.1.2 on 2020-10-31 06:38 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='SiteContactsModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=254, verbose_name='Email')), ('phone_number', models.CharField(max_length=18, verbose_name='Phone number')), ('address', models.CharField(max_length=255, verbose_name='Address')), ], options={ 'verbose_name': 'Contacts', 'verbose_name_plural': 'Contacts', }, ), migrations.CreateModel( name='SiteMainSettingsModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=18, verbose_name='Site title')), ('description', models.TextField(verbose_name='Site description')), ('description_ru', models.TextField(null=True, verbose_name='Site description')), ('description_en', models.TextField(null=True, verbose_name='Site description')), ('logo_1_image', models.ImageField(upload_to='images/settings', verbose_name='Site logo image')), ('logo_2_image', models.ImageField(upload_to='images/settings', verbose_name='Site alternative logo image')), ('user_avatar', models.ImageField(upload_to='images/settings', verbose_name='Default user avatar')), ('guest_avatar', models.ImageField(upload_to='images/settings', verbose_name='Default guest avatar')), ('deleted_avatar', models.ImageField(upload_to='images/settings', verbose_name='Deleted avatar')), ], options={ 'verbose_name': 'Main settings', 'verbose_name_plural': 'Main settings', }, ), migrations.CreateModel( name='SiteSocialNetModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=18, unique=True, verbose_name='Social net')), ('url', models.URLField(verbose_name='URL')), ('image', models.ImageField(blank=True, upload_to='images/settings/social', verbose_name='Image')), ], options={ 'verbose_name': 'Social net', 'verbose_name_plural': 'Social nets', 'ordering': ['title'], }, ), ]
qinyu/refactorguide
tests/__init__.py
<reponame>qinyu/refactorguide """Unit test package for refactorguide."""
sysidos/gollvm
driver/Tool.cpp
<filename>driver/Tool.cpp //===-- Tool.cpp ----------------------------------------------------------===// // // Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // //===----------------------------------------------------------------------===// // // Gollvm driver helper class Tool methods. // //===----------------------------------------------------------------------===// #include "Tool.h" namespace gollvm { namespace driver { Tool::Tool(const char *name, ToolChain &tc, ToolClass klass) : name_(name), toolchain_(tc), klass_(klass) { } Tool::~Tool() { } InternalTool::InternalTool(const char *name, ToolChain &tc) : Tool(name, tc, Tool::Internal) { } InternalTool::~InternalTool() { } ExternalTool::ExternalTool(const char *name, ToolChain &tc) : Tool(name, tc, Tool::External) { } ExternalTool::~ExternalTool() { } } // end namespace driver } // end namespace gollvm
aol/Webservice_Base
src/main/java/com/aol/webservice_base/cache/CacheContainer.java
<reponame>aol/Webservice_Base /* Copyright (c) 2009-2011, AOL Inc. All rights reserved. This code is licensed under a BSD license. <NAME> */ package com.aol.webservice_base.cache; import java.io.Serializable; /** * @author human * */ class CacheContainer implements Serializable { protected String key; protected Object object; public CacheContainer(String key, Object object) { this.key = key; this.object = object; } public Object getObject(String key) { if (this.key.equals(key)) { return object; } else return null; } }
willFederer/taichi
blender/exporter/__init__.py
<filename>blender/exporter/__init__.py bl_info = { "name": "Taichi Exporter", "author": "<NAME> (iterator)", "version": (0, 0, 0), "blender": (2, 7, 8), # "location": "Properties editor > Particles Tabs", "description": (""), "warning": "", # "tracker_url": "http://huyuanming.com", "category": "Object" } export_path = 'C:/tmp/blender_export' #export_path = '/tmp/' import bpy import xml.etree.cElementTree as ET from xml.etree.ElementTree import Element, SubElement, Comment, tostring from xml.dom import minidom import os import sys def prettify(elem): """Return a pretty-printed XML string for the Element. """ rough_string = ET.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") def dump_matrix(mat, name, node): matrix_node = SubElement(node, name) # matrix_node.set('name', name) for row in mat: row_node = SubElement(matrix_node, 'row') row_node.text = ' %+.10f %+.10f %+.10f %+.10f' % (row[0], row[1], row[2], row[3]) def export_scene(scene): bpy.ops.object.select_all(action='DESELECT') def dump_mesh(obj, scene_node, filepath): mesh = obj.to_mesh(scene, True, 'RENDER') transform = obj.matrix_world ffaces_mats = {} mesh_faces = mesh.tessfaces vertices = mesh.vertices mesh_node = SubElement(scene_node, 'mesh') def get_property(name, def_val): try: return obj[name] except: return def_val def write_property(name, def_val=0): SubElement(mesh_node, name).text = str(get_property(name, def_val)) SubElement(mesh_node, 'filepath').text = filepath.lower() write_property('temperature') write_property('const_temp') write_property('need_voxelization') def str_color(color): return str('%f %f %f' % (color.r, color.g, color.b)) if len(obj.material_slots) > 0: material_node = SubElement(mesh_node, 'material') material = bpy.data.materials[obj.material_slots[0].name] emission = material.emit material_type = '' if emission > 0: # light source material_type = 'light_source' emission_color = material.diffuse_color * emission SubElement(material_node, "emission_color").text = str_color(emission_color) else: material_type = 'pbr' # specular (glossy) specular_color = material.specular_color * material.specular_intensity glossiness = material.specular_hardness if glossiness == 511: # reflection glossiness = -1 else: # glossy pass # diffuse diffuse_color = material.diffuse_color * material.diffuse_intensity diffuse_shader = material.diffuse_shader # refraction transparent = material.use_transparency if transparent: ior = material.raytrace_transparency.ior # SSS? # Writing... color = material.diffuse_color SubElement(material_node, "diffuse_color").text = str_color(diffuse_color) SubElement(material_node, "specular_color").text = str_color(specular_color) SubElement(material_node, "glossiness").text = str(glossiness) SubElement(material_node, "transparent").text = str(int(transparent)) if transparent: SubElement(material_node, "ior").text = str(ior) textures_node = SubElement(material_node, "textures") for texture_id in range(len(material.texture_slots)): texture_slot = material.texture_slots[texture_id] if texture_slot is None: continue texture = bpy.data.textures[texture_slot.name] if texture.image is None: continue image = texture.image texture_node = SubElement(textures_node, "texture") SubElement(texture_node, "filepath").text = image.filepath.lower() if texture_slot.use_map_color_diffuse: SubElement(texture_node, "use_map_color_diffuse").text = str(texture_slot.diffuse_color_factor) if texture_slot.use_map_color_spec: SubElement(texture_node, "use_map_color_spec").text = str(texture_slot.specular_color_factor) if texture_slot.use_map_normal: SubElement(texture_node, "use_map_normal").text = str(texture_slot.normal_factor) if texture_slot.use_map_displacement: SubElement(texture_node, "use_map_displacement").text = str(texture_slot.displacement_factor) mesh_node.set('name', obj.name) SubElement(material_node, "type").text = material_type def dump_camera(obj): camera_node = SubElement(scene_node, 'camera') camera_name = bpy.data.cameras[0].name transform = bpy.data.objects[camera_name].matrix_world dump_matrix(transform, 'transform', camera_node) def dump_render(): render_node = SubElement(scene_node, 'render') res_rate = int(bpy.data.scenes[0].render.resolution_percentage) SubElement(render_node, "resolution_x").text = str(res_rate * bpy.data.scenes[0].render.resolution_x // 100) SubElement(render_node, "resolution_y").text = str(res_rate * bpy.data.scenes[0].render.resolution_y // 100) scene_node = Element('scene') meshes_node = SubElement(scene_node, 'meshes') for obj in bpy.data.objects: scene.objects.active = obj obj.select = True if obj.type == 'MESH' and not obj.hide: filepath = os.path.join(export_path, obj.name.lower() + '.obj') dump_mesh(obj, meshes_node, filepath) bpy.ops.export_scene.obj( filepath=filepath, use_selection=True, use_normals=True, use_uvs=True, use_materials=False, use_triangles=True, axis_up='Z', axis_forward='Y', ) elif obj.type == 'CAMERA': dump_camera(obj) obj.select = False dump_render() file_path = export_path + '/' + bpy.data.worlds[0].name + '.xml' with open(file_path, 'w') as f: f.write(prettify(scene_node)) class ExportToTinge(bpy.types.Operator): """Export Current Scene to Tinge for Rendering""" # blender will use this as a tooltip for menu items and buttons. bl_idname = "object.move_x" # unique identifier for buttons and menu items to reference. bl_label = "Export to Tinge" # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. def execute(self, context): # execute() is called by blender when running the operator. scene = context.scene for i in range(10): print() export_scene(scene) return {'FINISHED'} # this lets blender know the operator finished successfully. addon_keymaps = [] def register(): bpy.utils.register_class(ExportToTinge) wm = bpy.context.window_manager km = wm.keyconfigs.addon.keymaps.new(name='Object Mode', space_type='EMPTY') kmi = km.keymap_items.new(ExportToTinge.bl_idname, 'E', 'PRESS', ctrl=True, shift=False) #kmi.properties.total = 4 addon_keymaps.append(km) def unregister(): bpy.utils.unregister_class(ExportToTinge) wm = bpy.context.window_manager for km in addon_keymaps: wm.keyconfigs.addon.keymaps.remove(km) addon_keymaps.clear() # This allows you to run the script directly from blenders text editor # to test the addon without having to install it. if __name__ == "__main__": register()
davide-maestroni/jroutine
core/src/main/java/com/github/dm/jrt/core/log/TemplateLog.java
<reponame>davide-maestroni/jroutine<gh_stars>0 /* * Copyright 2016 <NAME> * * 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.github.dm.jrt.core.log; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; /** * Abstract implementation of a log. * <p> * This class is useful to avoid the need of implementing all the methods defined in the interface. * <p> * A standard format is applied to the log messages. * <br> * The inheriting class may just implement the writing of the formatted message, or customize its * composition. * <p> * Created by davide-maestroni on 10/03/2014. */ @SuppressWarnings("WeakerAccess") public abstract class TemplateLog implements Log { private static final String DATE_FORMAT = "MM/dd HH:mm:ss.SSS z"; private static final String EXCEPTION_FORMAT = " caused by:%n%s"; private static final String LOG_FORMAT = "%s\t%s\t%s\t%s<%s>"; private static String format(@NotNull final Level level, @NotNull final List<Object> contexts, @Nullable final String message) { return String.format(LOG_FORMAT, new SimpleDateFormat(DATE_FORMAT, Locale.getDefault()).format(new Date()), Thread.currentThread().getName(), contexts.toString(), level, message); } public void dbg(@NotNull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { log(Level.DEBUG, contexts, message, throwable); } public void err(@NotNull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { log(Level.ERROR, contexts, message, throwable); } public void wrn(@NotNull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { log(Level.WARNING, contexts, message, throwable); } /** * Formats and then write the specified log message. * * @param level the log level. * @param contexts the log context array. * @param message the log message. * @param throwable the related exception. */ protected void log(@NotNull final Level level, @NotNull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { String formatted = format(level, contexts, message); if (throwable != null) { formatted += String.format(EXCEPTION_FORMAT, Logger.printStackTrace(throwable)); } log(formatted); } /** * Writes the specified message after it's been formatted. * * @param message the message. */ protected void log(@NotNull final String message) { } }
jrinconada/cpp-examples
basico/condicionales.cpp
#include <iostream> int main() { int age = 100; if(age < 18) { std::cout << "Niño" << '\n'; } else if(age == 18) { std::cout << "<NAME>" << '\n'; } else if(age > 18 && age <= 65) { std::cout << "Adulto" << '\n'; } else { if (age > 99) { std::cout << "Muy "; } std::cout << "Anciano" << '\n'; } switch (age) { case 18: std::cout << "Tu primer año de vida adulta" << '\n'; break; // break impide que se evalúen más condiciones case 65: case 99: case 100: std::cout << "¿Qué hay de nuevo viejo?" << '\n'; break; default: // Si no se ha cumplido niguna condición (o no se ha hecho break) std::cout << "Buenos días" << '\n'; } // Operador ternario int people = 1; std::string count = people > 1 ? "Varios" : "Uno"; std::cout << count << '\n'; // if equivalente al operador ternario anterior std::string count2; if (people > 1) { count2 = "Varios"; } else { count2 = "Uno"; } }
alishaoniGDS/smart-answers
lib/smart_answer/calculators/paternity_pay_calculator.rb
<gh_stars>0 module SmartAnswer::Calculators class PaternityPayCalculator < MaternityPayCalculator attr_accessor :paternity_leave_duration def initialize(due_date, leave_type = "paternity") super(due_date, leave_type) end # Pay duration is the same for paternity and paternity_adoption # leave types. def pay_duration paternity_leave_duration == "one_week" ? 1 : 2 end private def rate_for(date) awe = (average_weekly_earnings.to_f * 0.9).round(2) [statutory_rate(date), awe].min end end end
xiki-tempula/spack
var/spack/repos/builtin/packages/glvis/package.py
<filename>var/spack/repos/builtin/packages/glvis/package.py # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Glvis(MakefilePackage): """GLVis: an OpenGL tool for visualization of FEM meshes and functions""" homepage = "http://glvis.org" git = "https://github.com/glvis/glvis.git" maintainers = ['goxberry', 'v-dobrev', 'tzanio'] # glvis (like mfem) is downloaded from a URL shortener at request # of upstream author <NAME> <<EMAIL>>. See here: # https://github.com/mfem/mfem/issues/53 # # The following procedure should be used to verify security when a # new version is added: # # 1. Verify that no checksums on old versions have changed. # # 2. Verify that the shortened URL for the new version is listed at: # http://glvis.org/download/ # # 3. Use http://getlinkinfo.com or similar to verify that the # underling download link for the latest version comes has the # prefix: http://glvis.github.io/releases # # If this quick verification procedure fails, additional discussion # will be required to verify the new version. version('develop', branch='master') version('3.4', sha256='289fbd2e09d4456e5fee6162bdc3e0b4c8c8d54625f3547ad2a69fef319279e7', url='https://bit.ly/glvis-3-4', extension='.tar.gz') version('3.3', sha256='e24d7c5cb53f208b691c872fe82ea898242cfdc0fd68dd0579c739e070dcd800', url='http://goo.gl/C0Oadw', extension='.tar.gz') version('3.2', sha256='c82cb110396e63b6436a770c55eb6d578441eaeaf3f9cc20436c242392e44e80', url='http://goo.gl/hzupg1', extension='.tar.gz') version('3.1', sha256='793e984ddfbf825dcd13dfe1ca00eccd686cd40ad30c8789ba80ee175a1b488c', url='http://goo.gl/gQZuu9', extension='tar.gz') variant('screenshots', default='png', values=('xwd', 'png', 'tiff'), description='Backend used for screenshots') variant('fonts', default=True, description='Use antialiased fonts via freetype & fontconfig') depends_on('mfem@develop', when='@develop') depends_on('mfem@3.4.0', when='@3.4') depends_on('mfem@3.3', when='@3.3') depends_on('mfem@3.2', when='@3.2') depends_on('mfem@3.1', when='@3.1') depends_on('gl') depends_on('glu') depends_on('libx11') depends_on('libpng', when='screenshots=png') depends_on('libtiff', when='screenshots=tiff') depends_on('freetype', when='+fonts') depends_on('fontconfig', when='+fonts') def edit(self, spec, prefix): def yes_no(s): return 'YES' if self.spec.satisfies(s) else 'NO' mfem = spec['mfem'] config_mk = mfem.package.config_mk gl_libs = spec['glu'].libs + spec['gl'].libs + spec['libx11'].libs args = ['CC={0}'.format(env['CC']), 'PREFIX={0}'.format(prefix.bin), 'MFEM_DIR={0}'.format(mfem.prefix), 'CONFIG_MK={0}'.format(config_mk), 'GL_OPTS=-I{0} -I{1} -I{2}'.format( spec['libx11'].prefix.include, spec['gl'].prefix.include, spec['glu'].prefix.include), 'GL_LIBS={0}'.format(gl_libs.ld_flags)] if 'screenshots=png' in spec: args += [ 'USE_LIBPNG=YES', 'USE_LIBTIFF=NO', 'PNG_OPTS=-DGLVIS_USE_LIBPNG -I{0}'.format( spec['libpng'].prefix.include), 'PNG_LIBS={0}'.format(spec['libpng'].libs.ld_flags)] elif 'screenshots=tiff' in spec: args += [ 'USE_LIBPNG=NO', 'USE_LIBTIFF=YES', 'TIFF_OPTS=-DGLVIS_USE_LIBTIFF -I{0}'.format( spec['libtiff'].prefix.include), 'TIFF_LIBS={0}'.format(spec['libtiff'].libs.ld_flags)] else: args += ['USE_LIBPNG=NO', 'USE_LIBTIFF=NO'] args.append('USE_FREETYPE={0}'.format(yes_no('+fonts'))) if '+fonts' in spec: args += [ 'FT_OPTS=-DGLVIS_USE_FREETYPE -I{0} -I{1}'.format( spec['freetype'].prefix.include.freetype2, spec['fontconfig'].prefix.include), 'FT_LIBS={0} {1}'.format( spec['freetype'].libs.ld_flags, spec['fontconfig'].libs.ld_flags)] self.build_targets = args self.install_targets += args
romance-ii/GLGE
src/core/glge_placeable.js
/* GLGE WebGL Graphics Engine Copyright (c) 2010, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of GLGE 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 <NAME> 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. */ /** * @fileOverview * @name glge_placeable.js * @author <EMAIL> */ (function(GLGE){ GLGE.ZUP=[0,0,1]; GLGE.YUP=[0,1,0]; GLGE.XUP=[1,0,0]; /** * @class Abstract class to agument objects that requires position, rotation and scale. */ GLGE.Placeable=function(){ } GLGE.Placeable.prototype.locX=0; GLGE.Placeable.prototype.locY=0; GLGE.Placeable.prototype.locZ=0; GLGE.Placeable.prototype.dLocX=0; GLGE.Placeable.prototype.dLocY=0; GLGE.Placeable.prototype.dLocZ=0; GLGE.Placeable.prototype.quatX=0; GLGE.Placeable.prototype.quatY=0; GLGE.Placeable.prototype.quatZ=0; GLGE.Placeable.prototype.quatW=0; GLGE.Placeable.prototype.rotX=0; GLGE.Placeable.prototype.rotY=0; GLGE.Placeable.prototype.rotZ=0; GLGE.Placeable.prototype.dRotX=0; GLGE.Placeable.prototype.dRotY=0; GLGE.Placeable.prototype.dRotZ=0; GLGE.Placeable.prototype.scaleX=1; GLGE.Placeable.prototype.scaleY=1; GLGE.Placeable.prototype.scaleZ=1; GLGE.Placeable.prototype.dScaleX=0; GLGE.Placeable.prototype.dScaleY=0; GLGE.Placeable.prototype.dScaleZ=0; GLGE.Placeable.prototype.matrix=null; GLGE.Placeable.prototype.rotOrder=GLGE.ROT_XYZ; GLGE.Placeable.prototype.lookAt=null; GLGE.Placeable.prototype.mode=GLGE.P_EULER; GLGE.Placeable.prototype.upAxis=GLGE.ZUP; /** * @name GLGE.Placeable#appened * @event fires when all the object is appened as a child to another * @param {object} event */ /** * @name GLGE.Placeable#removed * @event fires when all the object is removed as a child to another * @param {object} event */ /** * @name GLGE.Placeable#matrixUpdate * @event fires when this object has its transform changed supplies the target object as event.obj * @param {object} event */ /** * @name GLGE.Placeable#childMatrixUpdate * @event fires when any child objects have there transform changed supplies the target object as event.obj * @param {object} event */ /** * Gets the root node object * @returns {object} */ GLGE.Placeable.prototype.getRoot=function(){ if(this.type==GLGE.G_ROOT){ return this; }else if(this.parent){ var value=this.parent.getRoot(); if(!value) return this; else return value; }else{ return this; } } /** * Gets the id string of this text * @returns {string} */ GLGE.Placeable.prototype.getRef=function(){ if(this.id){ return this.id; }else if(this.parent){ return this.parent.getRef(); }else{ return null; } } /** * Sets the id string * @param {string} id The id string */ GLGE.Placeable.prototype.setId=function(id){ this.id=id; return this; } /** * Gets the id string of this text * @returns {string} */ GLGE.Placeable.prototype.getId=function(){ return this.id } /** * gets the object or poisition being looking at * @param {array|object} value the location/object */ GLGE.Placeable.prototype.getLookat=function(){ return this.lookAt; } /** * sets the look at for this object, will be updated every frame * @param {array|object} value the location/objec to look at */ GLGE.Placeable.prototype.setLookat=function(value){ this.lookAt=value; return this; } /** * gets the up axis of the object */ GLGE.Placeable.prototype.getUpAxis=function(){ return this.upAxis; } /** * sets the upAxis for this object * @param {array} value the up axis for the object */ GLGE.Placeable.prototype.setUpAxis=function(value){ this.upAxis=value; return this; } /** * Points the object in the direction of the coords or placeable value * @param {array|object} value the location/objec to look at */ GLGE.Placeable.prototype.Lookat=function(value){ var objpos; var pos=this.getPosition(); if(value.getPosition){ objpos=value.getPosition(); }else{ objpos={x:value[0],y:value[1],z:value[2]}; } var coord=[pos.x-objpos.x,pos.y-objpos.y,pos.z-objpos.z]; var zvec=GLGE.toUnitVec3(coord); var xvec=GLGE.toUnitVec3(GLGE.crossVec3(this.upAxis,zvec)); if(xvec[0]==0 && xvec[1]==0 && xvec[2]==0) xvec[1]=1; var yvec=GLGE.toUnitVec3(GLGE.crossVec3(zvec,xvec)); this.setRotMatrix(GLGE.Mat4([xvec[0], yvec[0], zvec[0], 0, xvec[1], yvec[1], zvec[1], 0, xvec[2], yvec[2], zvec[2], 0, 0, 0, 0, 1])); } /** * Sets the transform mode * @param {mode} value the transform mode */ GLGE.Placeable.prototype.setTransformMode=function(value){ this.mode=value; this.matrix=null; return this; } /** * Gets the euler rotation order * @returns {number} the objects rotation matrix */ GLGE.Placeable.prototype.getRotOrder=function(){ return this.rotOrder; } /** * Sets the euler rotation order * @param {number} value the order to rotate GLGE.ROT_XYZ,GLGE.ROT_XZY,etc.. */ GLGE.Placeable.prototype.setRotOrder=function(value){ this.rotOrder=value; this.matrix=null; this.rotmatrix=null; return this; } /** * Gets the rotaion matrix * @returns {matrix} the objects rotation matrix */ GLGE.Placeable.prototype.getRotMatrix=function(){ if(!this.rotmatrix){ var rotation=this.getRotation(); if(this.mode==GLGE.P_EULER) this.rotmatrix=GLGE.rotateMatrix(rotation.x,rotation.y,rotation.z,this.rotOrder); if(this.mode==GLGE.P_QUAT) this.rotmatrix=GLGE.quatRotation(rotation.x,rotation.y,rotation.z,rotation.w); } return this.rotmatrix; } /** * Sets the rotation matrix * @param {matrix} the objects rotation matrix */ GLGE.Placeable.prototype.setRotMatrix=function(matrix){ this.mode=GLGE.P_MATRIX; this.rotmatrix=matrix; this.updateMatrix(); return this; } /** * Sets the x location of the object * @param {number} value The value to assign to the x position */ GLGE.Placeable.prototype.setLocX=function(value){this.locX=value; this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the y location of the object * @param {number} value The value to assign to the y position */ GLGE.Placeable.prototype.setLocY=function(value){this.locY=value; this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the z location of the object * @param {number} value The value to assign to the z position */ GLGE.Placeable.prototype.setLocZ=function(value){this.locZ=value; this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the location of the object * @param {number} x The value to assign to the x position * @param {number} y The value to assign to the y position * @param {number} z The value to assign to the z position */ GLGE.Placeable.prototype.setLoc=function(x,y,z){this.locX=x;this.locY=y;this.locZ=z; this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the x location displacement of the object, usefull for animation * @param {number} value The value to assign to the x displacement */ GLGE.Placeable.prototype.setDLocX=function(value){this.dLocX=value;this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the y location displacement of the object, usefull for animation * @param {number} value The value to assign to the y displacement */ GLGE.Placeable.prototype.setDLocY=function(value){this.dLocY=value; this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the z location displacement of the object, usefull for animation * @param {number} value The value to assign to the z displacement */ GLGE.Placeable.prototype.setDLocZ=function(value){this.dLocZ=value;this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the location displacement of the object, useful for animation * @param {number} x The value to assign to the x position * @param {number} y The value to assign to the y position * @param {number} z The value to assign to the z position */ GLGE.Placeable.prototype.setDLoc=function(x,y,z){this.dLocX=x;this.dLocY=y;this.dLocZ=z; this.translateMatrix=null;this.staticMatrix=null;this.updateMatrix();return this;} /** * Sets the x quat value * @param {number} value the x quat value */ GLGE.Placeable.prototype.setQuatX=function(value){this.mode=GLGE.P_QUAT;this.quatX=parseFloat(value);this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the y quat value * @param {number} value the y quat value */ GLGE.Placeable.prototype.setQuatY=function(value){this.mode=GLGE.P_QUAT;this.quatY=parseFloat(value);this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the z quat value * @param {number} value the z quat value */ GLGE.Placeable.prototype.setQuatZ=function(value){this.mode=GLGE.P_QUAT;this.quatZ=parseFloat(value);this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the w quat value * @param {number} value the w quat value */ GLGE.Placeable.prototype.setQuatW=function(value){this.mode=GLGE.P_QUAT;this.quatW=parseFloat(value);this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the quaternions * @param {number} x The value to assign to the x * @param {number} y The value to assign to the y * @param {number} z The value to assign to the z * @param {number} w The value to assign to the w */ GLGE.Placeable.prototype.setQuat=function(x,y,z,w){this.mode=GLGE.P_QUAT;this.quatX=x;this.quatY=y;this.quatZ=z;this.quatW=w;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the x rotation of the object * @param {number} value The value to assign to the x rotation */ GLGE.Placeable.prototype.setRotX=function(value){this.mode=GLGE.P_EULER;this.rotX=value;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the y rotation of the object * @param {number} value The value to assign to the y rotation */ GLGE.Placeable.prototype.setRotY=function(value){this.mode=GLGE.P_EULER;this.rotY=value;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the z rotation of the object * @param {number} value The value to assign to the z rotation */ GLGE.Placeable.prototype.setRotZ=function(value){this.mode=GLGE.P_EULER;this.rotZ=value;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the rotation of the object * @param {number} x The value to assign to the x rotation * @param {number} y The value to assign to the y rotation * @param {number} z The value to assign to the z rotation */ GLGE.Placeable.prototype.setRot=function(x,y,z){this.mode=GLGE.P_EULER;this.rotX=x;this.rotY=y;this.rotZ=z;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the x rotation displacement of the object, usefull for animation * @param {number} value The value to assign to the x displacement */ GLGE.Placeable.prototype.setDRotX=function(value){this.mode=GLGE.P_EULER;this.dRotX=value;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the y rotation displacement of the object, usefull for animation * @param {number} value The value to assign to the y displacement */ GLGE.Placeable.prototype.setDRotY=function(value){this.mode=GLGE.P_EULER;this.dRotY=value;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the z rotation displacement of the object, usefull for animation * @param {number} value The value to assign to the z displacement */ GLGE.Placeable.prototype.setDRotZ=function(value){this.mode=GLGE.P_EULER;this.dRotZ=value;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the rotation displacement of the object, useful for animation * @param {number} x The value to assign to the x rotation * @param {number} y The value to assign to the y rotation * @param {number} z The value to assign to the z rotation */ GLGE.Placeable.prototype.setDRot=function(x,y,z){this.mode=GLGE.P_EULER;this.dRotX=x;this.dRotY=y;this.dRotZ=z;this.staticMatrix=null;this.rotmatrix=null;this.updateMatrix();return this;} /** * Sets the x scale of the object * @param {number} value The value to assign to the x scale */ GLGE.Placeable.prototype.setScaleX=function(value){if(this.ScaleX==value) return this;this.scaleX=value;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the y scale of the object * @param {number} value The value to assign to the y scale */ GLGE.Placeable.prototype.setScaleY=function(value){if(this.ScaleY==value) return this;this.scaleY=value;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the z scale of the object * @param {number} value The value to assign to the z scale */ GLGE.Placeable.prototype.setScaleZ=function(value){if(this.ScaleZ==value) return this;this.scaleZ=value;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the scale of the object * @param {number} x The value to assign to the x scale * @param {number} y The value to assign to the y scale * @param {number} z The value to assign to the z scale */ GLGE.Placeable.prototype.setScale=function(x,y,z){if(!y){y=x;z=x}; this.scaleX=x;this.scaleY=y;this.scaleZ=z;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the x scale displacement of the object, usefull for animation * @param {number} value The value to assign to the x displacement */ GLGE.Placeable.prototype.setDScaleX=function(value){if(this.dScaleX==value) return this;this.dScaleX=value;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the y scale displacement of the object, usefull for animation * @param {number} value The value to assign to the y displacement */ GLGE.Placeable.prototype.setDScaleY=function(value){if(this.dScaleY==value) return this;this.dScaleY=value;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the z scale displacement of the object, usefull for animation * @param {number} value The value to assign to the z displacement */ GLGE.Placeable.prototype.setDScaleZ=function(value){if(this.dScaleZ==value) return this;this.dScaleZ=value;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Sets the scale displacement of the object, useful for animation * @param {number} x The value to assign to the x scale * @param {number} y The value to assign to the y scale * @param {number} z The value to assign to the z scale */ GLGE.Placeable.prototype.setDScale=function(x,y,z){this.dScaleX=x;this.dScaleY=y;this.dScaleZ=z;this.staticMatrix=null;this.scaleMatrix=null;this.updateMatrix();return this;} /** * Gets the x location of the object * @returns {number} */ GLGE.Placeable.prototype.getLocX=function(){return parseFloat(this.locX);} /** * Gets the y location of the object * @returns {number} */ GLGE.Placeable.prototype.getLocY=function(){return parseFloat(this.locY);} /** * Gets the z location of the object * @returns {number} */ GLGE.Placeable.prototype.getLocZ=function(){return parseFloat(this.locZ);} /** * Gets the location of the object * @returns {number} */ GLGE.Placeable.prototype.getLoc=function(){return new GLGE.Vec3(parseFloat(this.locX), parseFloat(this.locY), parseFloat(this.locZ));} /** * Gets the x location displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDLocX=function(){return this.dLocX;} /** * Gets the y location displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDLocY=function(){return this.dLocY;} /** * Gets the z location displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDLocZ=function(){return this.dLocZ;} /** * Gets the x quat of the rotation * @returns {number} */ GLGE.Placeable.prototype.getQuatX=function(){return this.quatX;} /** * Gets the y quat of the rotation * @returns {number} */ GLGE.Placeable.prototype.getQuatY=function(){return this.quatY;} /** * Gets the z quat of the rotation * @returns {number} */ GLGE.Placeable.prototype.getQuatZ=function(){return this.quatZ;} /** * Gets the w quat of the rotation * @returns {number} */ GLGE.Placeable.prototype.getQuatW=function(){return this.quatW;} /** * Gets the x rotation of the object * @returns {number} */ GLGE.Placeable.prototype.getRotX=function(){return this.rotX;} /** * Gets the y rotation of the object * @returns {number} */ GLGE.Placeable.prototype.getRotY=function(){return this.rotY;} /** * Gets the z rotation of the object * @returns {number} */ GLGE.Placeable.prototype.getRotZ=function(){return this.rotZ;} /** * Gets the x rotaional displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDRotX=function(){return this.dRotX;} /** * Gets the y rotaional displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDRotY=function(){return this.dRotY;} /** * Gets the z rotaional displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDRotZ=function(){return this.dRotZ;} /** * Gets the x scale of the object * @returns {number} */ GLGE.Placeable.prototype.getScaleX=function(){return this.scaleX;} /** * Gets the y scale of the object * @returns {number} */ GLGE.Placeable.prototype.getScaleY=function(){return this.scaleY;} /** * Gets the z scale of the object * @returns {number} */ GLGE.Placeable.prototype.getScaleZ=function(){return this.scaleZ;} /** * Gets the x scale displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDScaleX=function(){return this.dScaleX;} /** * Gets the y scale displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDScaleY=function(){return this.dScaleY;} /** * Gets the z scale displacement of the object * @returns {number} */ GLGE.Placeable.prototype.getDScaleZ=function(){return this.dScaleZ;} /** * Gets the position of the object * @returns {array} */ GLGE.Placeable.prototype.getPosition=function(){ var position={}; position.x=parseFloat(this.locX)+parseFloat(this.dLocX); position.y=parseFloat(this.locY)+parseFloat(this.dLocY); position.z=parseFloat(this.locZ)+parseFloat(this.dLocZ); return position; } /** * Gets the rotation of the object * @returns {object} */ GLGE.Placeable.prototype.getRotation=function(){ var rotation={}; if(this.mode==GLGE.P_EULER){ rotation.x=parseFloat(this.rotX)+parseFloat(this.dRotX); rotation.y=parseFloat(this.rotY)+parseFloat(this.dRotY); rotation.z=parseFloat(this.rotZ)+parseFloat(this.dRotZ); } if(this.mode==GLGE.P_QUAT){ rotation.x=parseFloat(this.quatX); rotation.y=parseFloat(this.quatY); rotation.z=parseFloat(this.quatZ); rotation.w=parseFloat(this.quatW); } return rotation; } /** * Gets the scale of the object * @returns {object} */ GLGE.Placeable.prototype.getScale=function(){ var scale={}; scale.x=parseFloat(this.scaleX)+parseFloat(this.dScaleX); scale.y=parseFloat(this.scaleY)+parseFloat(this.dScaleY); scale.z=parseFloat(this.scaleZ)+parseFloat(this.dScaleZ); return scale; } /** * Gets the scale matrix * @returns {object} */ GLGE.Placeable.prototype.getScaleMatrix=function(){ if(!this.scaleMatrix){ this.scaleMatrix=GLGE.scaleMatrix(parseFloat(this.scaleX)+parseFloat(this.dScaleX),parseFloat(this.scaleY)+parseFloat(this.dScaleY),parseFloat(this.scaleZ)+parseFloat(this.dScaleZ)); } return this.scaleMatrix; } /** * Gets the translate matrix * @returns {object} */ GLGE.Placeable.prototype.getTranslateMatrix=function(){ if(!this.tmatrix) this.tmatrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; if(!this.translateMatrix){ this.tmatrix[3]=+this.locX+this.dLocX; this.tmatrix[7]=+this.locY+this.dLocY; this.tmatrix[11]=+this.locZ+this.dLocZ; this.translateMatrix=this.tmatrix; } return this.translateMatrix; } /** * Gets the local transform matrix * @returns {object} */ GLGE.Placeable.prototype.getLocalMatrix=function(){ this.getModelMatrix(); return this.localMatrix; } /** * Sets a static transfrom matrix, overrides any rotations and translation that may be set * @returns {object} */ GLGE.Placeable.prototype.setStaticMatrix=function(matrix){ this.staticMatrix=matrix; this.updateMatrix(); return this; } /** * Clears the static matrix if one is set * @returns {object} */ GLGE.Placeable.prototype.clearStaticMatrix=function(){ this.staticMatrix=null; this.updateMatrix(); return this; } /** * Updates the model matrix * @private */ GLGE.Placeable.prototype.updateMatrix=function(){ this.matrix=null; if(this.children){ for(var i=0;i<this.children.length;i++){ this.children[i].updateMatrix(); } } var o=obj=this; obj.fireEvent("matrixUpdate",{obj:o}); if(obj=obj.parent) obj.fireEvent("childMatrixUpdate",{obj:o}); } /** * Gets the model matrix to transform the model within the world */ GLGE.Placeable.prototype.getModelMatrix=function(){ if(!this.matrix){ GLGE.reuseMatrix4(this.invmatrix); GLGE.reuseMatrix4(this.transmatrix); GLGE.reuseMatrix4(this.transinvmatrix); this.invmatrix=null; this.transmatrix=null; this.transinvmatrix=null; if(this.staticMatrix){ var matrix=this.staticMatrix; this.localMatrix=this.staticMatrix; if(this.parent) matrix=GLGE.mulMat4(this.parent.getModelMatrix(),matrix); this.matrix=matrix; }else{ var translate=this.getTranslateMatrix(); var scale=this.getScaleMatrix(); var M1=GLGE.mulMat4(this.getRotMatrix(),scale); var matrix=GLGE.mulMat4(translate,M1); //GLGE.reuseMatrix4(M1); this.localMatrix=matrix; if(this.parent) matrix=GLGE.mulMat4(this.parent.getModelMatrix(),matrix); this.matrix=matrix; } } return this.matrix; } /** * Gets the model inverse matrix to transform the model within the world */ GLGE.Placeable.prototype.getInverseModelMatrix=function(){ if(!this.matrix){ this.getModelMatrix(); } if(!this.invmatrix){ this.invmatrix=GLGE.transposeMat4(this.matrix); } return this.invmatrix; } /** * Gets the model transposed matrix to transform the model within the world */ GLGE.Placeable.prototype.getTransposeModelMatrix=function(){ if(!this.matrix){ this.getModelMatrix(); } if(!this.transmatrix){ this.transmatrix=GLGE.transposeMat4(this.matrix); } return this.transmatrix; } /** * Gets the model inverse transposed matrix to transform the model within the world */ GLGE.Placeable.prototype.getTransposeInverseModelMatrix=function(){ if(!this.matrix){ this.getModelMatrix(); } if(!this.transinvmatrix){ this.invtransmatrix=GLGE.transposeMat4(this.getInverseModelMatrix()); } return this.transinvmatrix; } /** * Moves the object * @returns {array} amount array [x,y,z] to move * @returns {number} reference move with respecct to GLGE.GLOBAL or GLGE.LOCAL */ GLGE.Placeable.prototype.move=function(amount,reference){ if(!reference) reference=GLGE.GLOBAL; switch(reference){ case GLGE.GLOBAL: this.setLocX(+this.locX+amount[0]); this.setLocY(+this.locY+amount[1]); this.setLocZ(+this.locZ+amount[2]); break; case GLGE.LOCAL: var matrix=this.getModelMatrix(); var xAxis=GLGE.toUnitVec3([matrix[0],matrix[1],matrix[2]]); var yAxis=GLGE.toUnitVec3([matrix[4],matrix[5],matrix[6]]); var zAxis=GLGE.toUnitVec3([matrix[8],matrix[9],matrix[10]]); var x=xAxis[0]*amount[0]+xAxis[1]*amount[1]+xAxis[2]*amount[2]; var y=yAxis[0]*amount[0]+yAxis[1]*amount[1]+yAxis[2]*amount[2]; var z=zAxis[0]*amount[0]+zAxis[1]*amount[1]+zAxis[2]*amount[2]; this.setLocX(+this.locX+x); this.setLocY(+this.locY+y); this.setLocZ(+this.locZ+z); break; } return this; } })(GLGE);
Niklas-Seppala/mineload
src/debug.c
<gh_stars>0 #ifdef DEBUG #include <unistd.h> #include "data/queue.h" #include "camera.h" #include "debug.h" #include "ui.h" #include "game.h" #define REC_QUEUE_START_SIZE 64 #define TEXT_QUEUE_START_SIZE 64 #define DOTS_QUEUE_START_SIZE 64 #define PROCSTAT_ITEM_C 7 #define PROCSTAT_STR_SIZE 64 struct draw_rec_args { const Rectangle rec; Color color; }; struct print_args { char buffer[MAX_UI_TEX]; Color color; Vector2 pos; int size; }; struct draw_dot_args { Vector2 pos; float radius; Color color; }; static struct queue *DRAW_RECS; static struct queue *DRAW_TEXTS; static struct queue *DRAW_DOTS; static FILE *PROC_STATS_F = NULL; static void add_rec_draw(const Rectangle *rec, Color color); static void add_dot_draw(Vector2 pos, float radius, Color color); static void draw_text(void *arg); static int strsplit(const char *str, char delim, char **out, size_t n, size_t str_n); void debug_init(void) { DRAW_RECS = queue_create(REC_QUEUE_START_SIZE, sizeof(struct draw_rec_args), DYNAMIC_DATASTRUCT); DRAW_TEXTS = queue_create(TEXT_QUEUE_START_SIZE, sizeof(struct print_args), STATIC_DATASTUCT); DRAW_DOTS = queue_create(DOTS_QUEUE_START_SIZE, sizeof(struct draw_dot_args), DYNAMIC_DATASTRUCT); } void debug_update(void) {} void debug_render(void) { while (queue_get_count(DRAW_RECS) > 0) { struct draw_rec_args args; if (queue_dequeue(DRAW_RECS, &args)) { debug_rec_outlines(&args.rec, args.color); } } while (queue_get_count(DRAW_DOTS) > 0) { struct draw_dot_args args; if (queue_dequeue(DRAW_DOTS, &args)) { debug_dot(args.pos, args.radius, args.color); } } queue_foreach(DRAW_TEXTS, draw_text); } struct proc_stats debug_procstatm(void) { struct proc_stats stats = {0}; static char buffer[PROCSTAT_STR_SIZE]; if (PROC_STATS_F == NULL) { PROC_STATS_F = fopen( "/proc/self/statm", "r" ); } lseek(fileno(PROC_STATS_F), 0, SEEK_SET); if (fgets(buffer, PROCSTAT_STR_SIZE, PROC_STATS_F) == NULL) { return stats; } char* items[PROCSTAT_ITEM_C] = { 0 }; for (int i = 0; i < PROCSTAT_ITEM_C; i++) items[i] = OOM_GUARD(calloc(PROCSTAT_STR_SIZE, sizeof(char))); strsplit(buffer, ' ', items, PROCSTAT_ITEM_C, PROCSTAT_STR_SIZE); stats.memory = atol(items[0]); stats.resident = atol(items[1]); stats.shared = atol(items[2]); stats.text = atol(items[3]); stats.data = atol(items[5]); for (int i = 0; i < PROCSTAT_ITEM_C; i++) free(items[i]); return stats; } void debug_cleanup(void) { queue_free(&DRAW_RECS); queue_free(&DRAW_DOTS); queue_free(&DRAW_TEXTS); fclose(PROC_STATS_F); PROC_STATS_F = NULL; } void debug_printf_world_anywhere(Vector2 pos, int size, Color color, const char *format, ...) { struct print_args args = { .color = color, .size = size, .pos = pos}; va_list varargs; va_start(varargs, format); int rc = vsnprintf(args.buffer, MAX_UI_TEX, format, varargs); va_end(varargs); if (!(rc > 0 && rc < MAX_UI_TEX)) { printf("vsnprintf trucated!\n"); return; } else { queue_enqueue(DRAW_TEXTS, &args); } } void debug_rec_outlines_anywhere(const Rectangle *rec, Color color) { add_rec_draw(rec, color); } void debug_dot_anywhere(Vector2 pos, float radius, Color color) { add_dot_draw(pos, radius, color); } void debug_rec_outlines(const Rectangle *rec, Color color) { const Vector2 TOP_LEFT = (Vector2) { .x = rec->x, .y = rec->y }; const Vector2 TOP_RIGHT = (Vector2) { .x = rec->x + rec->width, .y = rec->y }; const Vector2 BOT_LEFT = (Vector2) { .x = rec->x, .y = rec->y + rec->height }; const Vector2 BOT_RIGHT = (Vector2) { .x = rec->x + rec->width, .y = rec->y + rec->height }; DrawLineV(TOP_LEFT, TOP_RIGHT, color); DrawLineV(TOP_LEFT, BOT_LEFT, color); DrawLineV(BOT_LEFT, BOT_RIGHT, color); DrawLineV(BOT_RIGHT, TOP_RIGHT, color); } void debug_dot(Vector2 pos, float radius, Color color) { DrawCircleV(pos, radius, color); } static void draw_text(void *arg) { struct print_args *args = arg; ui_world_print(args->pos, args->size, args->color, args->buffer); } static void add_dot_draw(Vector2 pos, float radius, Color color) { struct draw_dot_args args = { .color = color, .pos = pos, .radius = radius }; queue_enqueue(DRAW_DOTS, &args); } static void add_rec_draw(const Rectangle *rec, Color color) { struct draw_rec_args args = { .color = color, .rec = *rec }; queue_enqueue(DRAW_RECS, &args); } static int strsplit(const char *str, char delim, char **out, size_t n, size_t str_n) { char c; for (int str_i = 0, read_c = 0; str_i < n; str_i++) { for (int str_out_i = 0; str_out_i < str_n; str_out_i++) { c = str[read_c++]; if (c == '\0' || c == delim) { out[str_i][str_out_i] = '\0'; break; } else { out[str_i][str_out_i] = c; } } } return 0; } #endif
Sukaato/lib-express
server/routes/router.js
<filename>server/routes/router.js import { articleRouter } from './article.router'; import { dashboardArticleRouter } from './dashboard/dashboard.article.router.js'; import { dashboardIndexRouter } from './dashboard/dashboard.index.router.js'; import { dashboardRoleRouter } from './dashboard/dashboard.role.router'; import { dashboardTagRouter } from './dashboard/dashboard.tag.router'; import { dashboardUserRouter } from './dashboard/dashboard.user.router'; import { error404Router } from './errors/error.404.router'; import { error500Router } from './errors/error.500.router'; import { indexRouter } from './index.router'; import { loginRouter } from './login.router'; import { tagRouter } from './tag.router'; export const router = { index: indexRouter, article: articleRouter, tag: tagRouter, login: loginRouter, dashboard: { index: dashboardIndexRouter, article: dashboardArticleRouter, tag: dashboardTagRouter, user: dashboardUserRouter, role: dashboardRoleRouter }, error: { 404: error404Router, 500: error500Router } };
YJBeetle/QtAndroidAPI
android-31/android/text/style/TtsSpan_Builder.hpp
<reponame>YJBeetle/QtAndroidAPI #pragma once #include "../../../JObject.hpp" namespace android::text::style { class TtsSpan; } class JString; namespace android::text::style { class TtsSpan_Builder : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit TtsSpan_Builder(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} TtsSpan_Builder(QJniObject obj); // Constructors TtsSpan_Builder(JString arg0); // Methods android::text::style::TtsSpan build() const; android::text::style::TtsSpan_Builder setIntArgument(JString arg0, jint arg1) const; android::text::style::TtsSpan_Builder setLongArgument(JString arg0, jlong arg1) const; android::text::style::TtsSpan_Builder setStringArgument(JString arg0, JString arg1) const; }; } // namespace android::text::style
perfectsearch/cTAKES
ctakes-utils/src/main/java/org/apache/ctakes/utils/build/InstallPipelineFromPears.java
<gh_stars>1-10 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ctakes.utils.build; import java.io.File; //package org.apache.uima.tools.pear.install; /** * This class is used to install a pear file locally in a directory chosen by the * user and then run the installed AE in CVD. * */ public class InstallPipelineFromPears { // handles if a is null or if any element is null or if <code>i</code> is out of range // by returning null in any of those cases public static String getString(String [] a, int i) { try { return a[i]; } catch (Exception e) { System.err.println(); System.err.println("Error accessing argument " + i); System.err.println("Number of arguments received = " + ( a==null ? -1 : a.length)); e.printStackTrace(System.err); return null; } } public static String quote(String s) { if (s==null) return "[null]"; char DBLQUOTES = '"'; String QUOTE = "'"; if (s.contains(QUOTE)) { return DBLQUOTES + s + DBLQUOTES; } return QUOTE + s + QUOTE; } private static String projects [] = { "core", // install core first as other depend on it "document preprocessor", "POS tagger", "chunker", "context dependent tokenizer", "dictionary lookup", "LVG", "NE contexts", "ctakes-clinical-pipeline", // install last as depends on others }; /** * * @param args * <br>directory where the PEAR files are located * <br>directory where projects are to be installed */ public static void main(String[] args) { String pearFileLocation = getString(args, 0); String installDir = getString(args, 1); if (pearFileLocation==null) { System.err.println("Need to give pear file location."); System.exit(-1); } if (installDir==null) { System.err.println("Need to give pear file location AND the target directory."); System.exit(-1); } System.out.println("Installing " + projects.length + " PEAR files to " + quote(installDir)); for (String proj : projects) { String pearFn = pearFileLocation + File.separator + proj + ".pear"; // System.out.println("Pear file name = " + quote(pearFn)); // System.out.println(" Install dir = " + quote(installDir)); String [] installArgs = new String[2]; installArgs[0] = pearFn; installArgs[1] = installDir; InstallPearSilently.main(installArgs); } System.out.println("Done installing " + projects.length + " PEAR files to " + quote(installDir)); } }
SchrodingerW/electronicTextBook
src/pages/book/lecture_2_4.js
import React from "react"; import { Helmet } from "react-helmet"; import Navbar from "../components/Nav/Navbar"; import Footer from "../components/Footer/Footer"; import Button from "../components/Button/Button"; import './book.css'; const lecture_2_4 = () => { return ( <div> <Helmet> <meta charSet="utf-8" /> <title>Тема 2.4. Модернизация и конфигурирование ЭВМ с учетом решаемых задач</title> </Helmet> <Navbar /> <div className="main"> <div className="main_item"> <h2 className="h2_main">Раздел 2. Текущее техническое обслуживание сети</h2> <h3 className="h3_main">Тема 2.4. Модернизация и конфигурирование ЭВМ с учетом решаемых задач</h3> <Button link_left="/book/lecture_2_3" link_rigth="/book/questions_2" /> <div className="charter_book"> Темпы развития компьютерных технологий растут с каждым годом, опережая самые оптимистические прогнозы, поэтому любые экономические оценки в этой области на период 3-5 лет неизбежно будут неточными. Вместе с тем при сохранении существующих тенденций эта неточность лежит в области скорее недооценки, чем переоценки грядущих технологических скачков и связанных с ними стоимостных показателей.<br></br> Сегодня полная смена поколений компьютерной техники происходит примерно за трехлетний период, а смена модельных рядов ведущих фирм — вообще один-два раза в год. При этом системные блоки нового поколения создаются на основе принципиально иных конструктивных и технологических решений, что приводит к практически полной их несовместимости по элементной базе с системными блоками предыдущего поколения (за счет изменения материнских плат, геометрических размеров блоков и посадочных мест, появления новых типов разъемов и т.п.).<br></br> Практически одновременно с появлением компьютеров нового поколения комплектующие для устаревшей техники снимаются с производства. Это приводит к тому, что уже после трех лет эксплуатации компьютера его ремонт путем замены неисправных блоков экономически нецелесообразен ввиду чрезмерной стоимости устаревших комплектующих, а модернизация затруднена из-за проблемы несовместимости. Существующий же в настоящее время порядок списания компьютерной техники приводит к тому, что на балансе организации нередко «висит» значительное количество устаревшей, неисправной и неремонтопригодной техники.<br></br> Частичным решением этой проблемы может стать своевременная <b>модернизация (upgrade) аппаратных средств</b>. Под ней понимается увеличение производительности компьютера путем замены процессора, расширения оперативной памяти и емкости жесткого диска тогда, когда это еще технически возможно, т. е. не позднее, чем через два года эксплуатации. <h4 className="h3_main">Конфигурирование СВТ с учетом решаемых задач</h4> Для формирования экономически эффективного парка СВТ необходимо определять конфигурацию ПК, которая нужна каждому отдельно взятому работнику.<br></br> Условно можно определить <b>базовую конфигурацию</b> офисного настольного компьютера, которая обеспечивает выполнение минимального набора офисных функций и которая будет являться основой при сборке более сложных специальных конфигураций путем простого улучшения количественных и скоростных показателей (установки большего объема памяти, дополнительных накопителей, более мощного процессора и т. д.).<br></br> Базовая конфигурация подойдет работникам, осуществляющим работу с текстами и электронными таблицами, занятым электронной и обычной перепиской. Компьютеры с базовой конфигурацией подойдут как секретарю или менеджеру, так и аналитику, поэтому ориентироваться на тот или иной отдел нет необходимости. В то же время если секретарь может обойтись жестким диском минимального объема, то аналитикам могут понадобиться дополнительные дисковые массивы. Сократить расходы и повысить надежность хранения информации позволяют сетевые технологии и установка дискового массива на сервере для хранения документов и резервных копий информации со всех ПК, находящихся в сети. Однако отказываться от накопителей на уровне пользовательских ПК и превращать их полностью в «тонкие клиенты» нежелательно, так как обычные офисные приложения очень требовательны к количеству места на жестком диске. В качестве минимального можно рекомендовать объем жесткого диска 125 Гб. Для сервера же минимальный объем жесткого диска составит 250 Гб.<br></br> Важность правильного выбора компьютера обусловлена следующими факторами: <ul> <li>номенклатура выпускаемых ПК очень велика;</li> <li>характеристики компьютеров существенно отличаются друг от друга;</li> <li>стоимость компьютеров достаточно высока.</li> </ul> Основными характеристиками ПК являются: <ul> <li>надежность;</li> <li>разрядность;</li> <li>производительность (тактовая частота);</li> <li>емкость основной памяти;</li> <li>емкость жесткого диска;</li> <li>вид операционной системы;</li> <li>совместимость с другими компонентами СВТ;</li> <li>режимы работы;</li> <li>поддержка сети;</li> <li>габариты.</li> </ul> Очень важно правильно подобрать конфигурацию компьютера. Например, тип основного <b>микропроцессора</b> и <b>материнской платы</b> должны совпадать.<br></br> Далее, в зависимости от поставленных задач, нужно обратить внимание на объем и быстродействие <b>основной и внешней памяти</b> и на номенклатуру устройств внешней памяти. Объем оперативной памяти в 4 Гб можно назвать более чем достаточным для работы операционной системы и любых офисных приложений начального уровня. Если планируется использование графических и издательских пакетов, то необходимо наращивание памяти до 8 Гб. Но превышение этой отметки для офисного ПК нецелесообразно. Основной принцип при выборе объема памяти — «чем больше, тем комфортнее работать с развлекательными задачами». Но если один гигабайт оперативной памяти установить в офисный ПК, то это никак не отразится на скорости набора текста или ввода значений в электронную таблицу.<br></br> Для решения современных офисных задач достаточно и мощности не самого быстрого <b>процессора</b>, выпускаемого несколько лет назад. Для офисных задач оптимальной можно назвать частоту в 2100-3000 МГц. Однако ведущие производители (AMD и Intel), выпуская все более мощные модели, снимают с производства более старые. Частоты новых процессоров начинаются сегодня с фактически ненужных двух гигагерц. Более медленные же процессоры можно найти лишь на рынке б/у комплектующих, что не отвечает требованиям повышенной надежности офисной техники.<br></br> Покупка дополнительного <b>жесткого диска</b> позволит дублировать важную информацию. При поломке одного из жестких дисков данные сохраняются на другом, и работать можно, не дожидаясь замены вышедшего из строя жесткого диска.<br></br> Далее надо определиться с типами системного и локального интерфейсов, выбрать видеокарту, клавиатуру, мышь и монитор и определиться с общим дизайнерским решением. Для обычной офисной работы достаточно интегрированной видеокарты; если же работа сотрудника связана с графикой, то стоит позаботиться о более качественном видео.<br></br> Что касается корпусов системных блоков, то личные вкусы работников чаще всего отодвигаются на задний план корпоративным стилем, но вот при выборе монитора принимать во внимание трудовые функции и личные потребности каждого отдельного сотрудника надо строго обязательно: перед монитором работник проводит огромное количество времени, и от качества экрана зависит его зрение и здоровье!<br></br> Оптимальное рабочее разрешение 17-дюймового ЖК <b>монитора</b> для офисных задач — 1920 х 1080 точек. При этом частота вертикальной развертки должна быть не менее 60 Гц. Каждый монитор необходимо проверить, протестировав его, например, при помощи утилиты Nokia Test, чтобы выявить геометрические искажения и дефекты монитора. Изображение должно быть четким, без цветовых и геометрических «завалов». <br></br> К компьютеру также желательно купить <b>источник бесперебойного питания</b> для защиты от скачков и отключения электричества, от которых не застрахован и не поможет даже самый высококачественный встроенный блок питания компьютера. При этом имеет смысл обратить внимание на ИБП, к которому можно подключить несколько устройств.<br></br> Выбор <b>клавиатуры и манипулятора</b> — задача довольно простая. Беспроводные клавиатуры и мыши — не для офиса: при использовании множества беспроводных устройств могут появляться аппаратные конфликты. Причем у дешевых моделей такие конфликты неизбежны — сигналы будут наводиться друг на друга и печатать текст на экране соседнего компьютера. Кроме того, сотрудники будут постоянно путать мыши и терять их, поэтому клавиатура и мышь должны быть прочно «привязаны» к ПК кабелями.<br></br> Выбирать лучше простые и недорогие устройства. Желательно, чтобы мышь и клавиатура были если не белыми, то светлых тонов, что облегчит контроль за их гигиеническим состоянием. В настоящее время лучше использовать проводную оптическую мышь. Достоинство «оптики» — не только в плавном и точном движении курсора по экрану, но и в отсутствии необходимости чистить шарик и коврик, — ведь оптическая мышь может двигаться практически по любой поверхности.<br></br> При выборе <b>оптического накопителя</b> нужно учитывать потребности работника. Если специфика его деятельности такова, что необходима частая или постоянная запись информации на носители или чтение с них, то экономить здесь нельзя: это может привести к падению производительности, что тут же «съест» любую экономию. Сегодня скорость накопителей на запись начинается с 16х — ее достаточно, чтобы 700 Мб записать быстрее, чем за 8 минут. Для записи следует выбирать и качественные носители. В то же время пока нельзя отказываться и от 3,5-дюймовых дискет, с которыми еще несколько лет придется сталкиваться и работать.<br></br> При необходимости можно дополнить ПК различными <b>периферийными устройствами</b> (принтером, сканером и т. д.). В частности, сканер для работы с текстами подойдет самый дешевый и даже с самыми посредственными характеристиками. Единственное, на что нужно обратить внимание, — это наличие интерфейса USB 3.0, который является определяющим фактором скорости передачи данных со сканера на компьютер.<br></br> Для офиса необходимо обеспечить возможности печати корпоративного уровня — высокоскоростной принтер, включенный в сеть и способный обслуживать всех работников. Однако такие решения достаточно дороги, а потому более целесообразным представляется приобретение <b>многофункциональных устройств (МФУ)</b>, сочетающих в себе функции принтера, сканера, копира и факса. Благодаря такой функциональности в одном корпусе можно сэкономить место на рабочих столах, а заодно сэкономить затраты на отдельные копир, сканер и факс. Несколько таких МФУ вполне смогут заменить корпоративное печатающее устройство и сэкономить денежные средства. При выборе МФУ необходимо ориентироваться на наиболее технологически продвинутые решения и прежде всего — на объемы расхода тонера. Многофункциональные устройства должны быть максимально экономными. «Продвинутые» модели стоят зачастую в два раза дороже моделей, кажущихся аналогичными, но у дешевых печатающих устройств — дорогие картриджи и значительно больше расход тонера. Поэтому, приобретая дорогое устройство, пользователь в итоге очень часто получает экономию на стоимости одной копии. <h4 className="h3_main">Модернизация СВТ с учетом решаемых задач</h4> Даже самый недорогой компьютер должен иметь возможности для модернизации. При отсутствии же таковой в случае роста объемов задач придется не просто модернизировать и повышать мощность СВТ, а полностью менять парк компьютеров. В результате экономия обернется двойными расходами.<br></br> Модернизация компьютера может быть обусловлена следующими причинами: <ul> <li>расширение или изменение круга решаемых задач, т. е. изменение типа ПК;</li> <li>выход из строя комплектующих;</li> <li>замена комплектующих на более производительные.</li> </ul> Выбор комплектующих зависит от типа персонального компьютера и от финансовых возможностей и потребностей покупателя.<br></br> Напрямую производительность компьютера не зависит от одной только мощности процессора — в вычислительной системе все должно быть сбалансировано. Если поставить мощный процессор на слабую материнскую плату, то и он будет работать «вполсилы».<br></br> Условно все компьютеры можно разделить на две группы: <ul> <li><b>«brand name»</b> — собранные фирмами-производителями основных блоков компьютера (IBM, Compaq, HP);</li> <li><b>«no name»</b> — компьютеры, сборку которых осуществляли из комплектующих сторонние производители.</li> </ul> Компьютеры первой группы — более дорогие, но и более надежные, чем компьютеры второй группы.<br></br> Вместо формирования парка СВТ на базе настольных ПК <b>(десктопов)</b> можно рассмотреть другой вариант — приобретение ноутбуков.<br></br> Ноутбуки занимают мало места, потребляют мало энергии и, самое главное, сегодня они доступны по цене: современные высокопроизводительные ноутбуки уже имеют стоимость от 30 000 рублей при практически тех же характеристиках, что и десктопы. Ноутбуки — легкие, компактные, их мощности достаточно для выполнения любых офисных и развлекательных задач. Однако при широком использовании в офисе ноутбуков необходимы дополнительные меры безопасности, которые касаются сохранности как информации, так и самих ноутбуков. Переносные компьютеры являются привлекательными объектами для краж, а сотрудники могут легко стать жертвой грабежа и мошенничества. К со­жалению, ни одна из российских страховых компаний ноутбуки не страхует, поэтому если доступ в офис открыт, то необходимо оборудовать рабочие места гнездами («слотами») для <b>замков Кенсингтона</b> и обязать сотрудников держать ноутбуки «на привязи» в течение всего рабочего дня.<br></br> Резервная копия рабочих данных с жесткого диска каждого корпоративного ноутбука должна сохраняться на сервере компании и при каждом соединении синхронизироваться. Кроме того, требуются дополнительные программные средства для защиты и шифрования информации: в случае кражи ноутбука похититель не должен иметь возможность получить доступ к содержимому его жесткого диска.<br></br> Ноутбук у сотрудника компании производит положительное впечатление на клиентов и партнеров. Сам же сотрудник получает в свое распоряжение функциональность мобильного офиса. На деловой встрече все документы всегда будут под рукой. Ноутбук можно использовать для презентаций. Если захватить с собой переносной принтер, то ваш клиент тут же получит деловое предложение на бумаге. Проект договора или любой другой необходимый документ можно и записать потенциальному клиенту на дискету, оптический диск, карту памяти или флэш-накопитель или даже отправить по e-mail, выйдя в сеть Интернет по каналу GPRS или Wi-Fi.<br></br> Еще одно достоинство — в случае отключения электричества сотрудники смогут работать на компьютере не 5-10 минут, как с использованием ИБП, а около 2-2,5 часов на встроенных аккумуляторных батареях. Средства же беспроводной связи Wi-Fi избавят ваш офис от проводов и облегчат коммуникацию между сотрудниками.<br></br> До покупки ноутбука необходимо узнать, насколько оперативно производится его ремонт различной сложности. Если запасные части поставляются только «под заказ», то любая, даже самая несерьезная поломка может обернуться серьезным простоем. Это — самая главная проблема при формировании парка ноутбуков. Если же ремонт производится оперативно, то компании достаточно иметь резервный десктоп или дополнительный ноутбук, на котором работник сможет работать во время ремонта своего компьютера.<br></br> Для объединения компьютеров в сеть с точки зрения модернизации лучше использовать <b>технологию «тонкий клиент» (терминал)</b>, когда все базы данных хранятся на сервере, а к большинству программ, установленных на сервере, имеется общий доступ. При другой сетевой технологии со временем каждый ПК необходимо модернизировать отдельно, что увеличивает затраты. Кроме того, появляется проблема утилизации устаревших элементов ПК.<br></br> Модернизация терминалов (клиентского парка) при таком подходе не требуется: при росте требований со стороны прикладного ПО наращивается мощность только терминального сервера (или их количество — при приложениях с балансировкой нагрузки), что значительно дешевле, чем модернизация всего парка ПК. Более того, терминальная технология позволит использовать даже устаревший парк ПК с новым программным обеспечением.<br></br> Таким образом, как и двадцать лет назад, технология «тонкий клиент» остается наиболее оптимальным решением для построения компьютерных сетей крупных предприятий, обеспечивая необходимый уровень технологичности, безопасности информации и организации производственного процесса. </div> </div> </div> <Footer /> </div> ) } export default lecture_2_4
kpsuhair/QTRemoteFileEditor
src/utilityfunctions.cpp
<reponame>kpsuhair/QTRemoteFileEditor #include "utilityfunctions.h" #include <QStack> #include <QtDebug> #include <QQueue> /* Launches a Yes or No message box within the context of the given * parent widget. Prompts the user to make a selection. */ QMessageBox::StandardButton Utility::promptYesOrNo(QWidget *parent, QString title, QString prompt) { QMessageBox asker; asker.setEscapeButton(QMessageBox::StandardButton::Cancel); return asker.question(parent, title, prompt, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); } /* Returns true if a closing brace must be inserted into the given string * to create a balanced expression and false otherwise. */ bool Utility::codeBlockNotClosed(QString context, QChar startDelimiter, QChar endDelimiter) { QStack<char> codeBlockStartDelimiters; for (int i = 0; i < context.length(); i++) { char character = context.at(i).toLatin1(); if (character == startDelimiter) { codeBlockStartDelimiters.push(character); } else if (character == endDelimiter && !codeBlockStartDelimiters.empty()) { codeBlockStartDelimiters.pop(); } } return !codeBlockStartDelimiters.empty(); }
dm299770/atcc-serviceplatform
atcc-serviceplatform-common/src/main/java/com/acv/cloud/domain/body/req/notification/NotificationParams.java
<gh_stars>0 package com.acv.cloud.domain.body.req.notification; public class NotificationParams { private Datal data; public void setData(Datal data) { this.data = data; } public Datal getData() { return data; } public NotificationParams(Datal data) { this.data = data; } }
suninformation/ymateplatform
ymateplatform/src/main/java/net/ymate/platform/mvc/web/support/HttpRequestExecutor.java
/* * Copyright 2007-2107 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.platform.mvc.web.support; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import net.ymate.platform.base.YMP; import net.ymate.platform.commons.i18n.I18N; import net.ymate.platform.commons.lang.BlurObject; import net.ymate.platform.commons.util.ClassUtils; import net.ymate.platform.commons.util.ClassUtils.ClassBeanWrapper; import net.ymate.platform.mvc.filter.IFilterChain; import net.ymate.platform.mvc.support.RequestExecutor; import net.ymate.platform.mvc.view.IView; import net.ymate.platform.mvc.web.IUploadFileWrapper; import net.ymate.platform.mvc.web.annotation.CookieValue; import net.ymate.platform.mvc.web.annotation.ModelBind; import net.ymate.platform.mvc.web.annotation.PathVariable; import net.ymate.platform.mvc.web.annotation.RequestHeader; import net.ymate.platform.mvc.web.annotation.RequestParam; import net.ymate.platform.mvc.web.context.WebContext; import net.ymate.platform.mvc.web.view.IWebView; import net.ymate.platform.mvc.web.view.impl.BinaryView; import net.ymate.platform.mvc.web.view.impl.ForwardView; import net.ymate.platform.mvc.web.view.impl.FreeMarkerView; import net.ymate.platform.mvc.web.view.impl.HttpStatusView; import net.ymate.platform.mvc.web.view.impl.JsonView; import net.ymate.platform.mvc.web.view.impl.JspView; import net.ymate.platform.mvc.web.view.impl.RedirectView; import net.ymate.platform.mvc.web.view.impl.TextView; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * <p> * HttpRequestExecutor * </p> * <p> * 基于Web应用的MVC请求执行器; * </p> * * @author 刘镇(<EMAIL>) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-20下午6:26:12</td> * </tr> * </table> */ public class HttpRequestExecutor extends RequestExecutor { private static final Log _LOG = LogFactory.getLog(HttpRequestExecutor.class); /** * 构造器 * * @param meta 请求元数据描述对象 */ public HttpRequestExecutor(HttpRequestMeta meta) { super(meta); } /** * 构造器 * * @param meta 请求元数据描述对象 * @param chain 拦截器执行链对象 */ public HttpRequestExecutor(HttpRequestMeta meta, IFilterChain chain) { super(meta, chain); } protected Object parseCookieValueAnnotation(String paramName, String defaultValue, boolean required, Class<?> type, String defaultParamName) { String _paramName = StringUtils.defaultIfEmpty(paramName, defaultParamName); String _value = StringUtils.defaultIfEmpty(CookieHelper.create().getCookie(_paramName).toStringValue(), defaultValue); _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, _value, "Cookies")); // 若方法存在参数验证注解则放弃此项 if (!hasValidation() && required && StringUtils.isBlank(_value)) { throw new NullPointerException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_null", _paramName)); } validateFieldValues.put(_paramName, _value); return new BlurObject(_value).toObjectValue(type); } protected Object parsePathVariableAnnotation(String paramName, String defaultValue, boolean required, Class<?> type, String defaultParamName) { String _paramName = StringUtils.defaultIfEmpty(paramName, defaultParamName); String _value = StringUtils.defaultIfEmpty((String) WebContext.getContext().get(_paramName), defaultValue); _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, _value, "PathVariable")); if (!hasValidation() && required && StringUtils.isBlank(_value)) { throw new NullPointerException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_null", _paramName)); } validateFieldValues.put(_paramName, _value); return new BlurObject(_value).toObjectValue(type); } protected Object parseRequestHeaderAnnotation(String paramName, String defaultValue, boolean required, Class<?> type, String defaultParamName) { String _paramName = StringUtils.defaultIfEmpty(paramName, defaultParamName); String _value = StringUtils.defaultIfEmpty(WebContext.getRequest().getHeader(_paramName), defaultValue); _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, _value, "Header")); if (!hasValidation() && required && StringUtils.isBlank(_value)) { throw new NullPointerException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_null", _paramName)); } validateFieldValues.put(_paramName, _value); return new BlurObject(_value).toObjectValue(type); } protected Object parseRequestParamAnnotation(String prefix, String paramName, String defaultValue, boolean required, Class<?> type, String defaultParamName) { String _paramName = prefix + StringUtils.defaultIfEmpty(paramName, defaultParamName); if (type.isArray()) { if (type.equals(IUploadFileWrapper[].class)) { if (WebContext.getRequest() instanceof MultipartRequestWrapper) { IUploadFileWrapper[] _value = ((MultipartRequestWrapper) WebContext.getRequest()).getFiles(_paramName); _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, _value, "RequestParameter")); validateFieldValues.put(_paramName, _value); return ((MultipartRequestWrapper) WebContext.getRequest()).getFiles(_paramName); } validateFieldValues.put(_paramName, null); return null; } String[] _values = (String[]) WebContext.getRequest().getParameterMap().get(_paramName); if (_values == null || _values.length == 0) { _values = StringUtils.split(defaultValue, ","); } if (_values != null && _values.length > 0) { Class<?> _arrayClassType = ClassUtils.getArrayClassType(type); Object[] _tempParams = (Object[]) Array.newInstance(_arrayClassType, _values.length); for (int _tempIdx = 0; _tempIdx < _values.length; _tempIdx++) { _tempParams[_tempIdx] = new BlurObject(_values[_tempIdx]).toObjectValue(_arrayClassType); } _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, (_tempParams != null ? _tempParams.toString() : ""), "RequestParameter")); validateFieldValues.put(_paramName, _tempParams); return _tempParams; } else if (!hasValidation() && required) { throw new NullPointerException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_null", _paramName)); } validateFieldValues.put(_paramName, null); return null; } else if (type.equals(IUploadFileWrapper.class)) { if (WebContext.getRequest() instanceof MultipartRequestWrapper) { IUploadFileWrapper _value = ((MultipartRequestWrapper) WebContext.getRequest()).getFile(_paramName); _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, (_value != null ? _value.getName() : ""), "RequestParameter")); validateFieldValues.put(_paramName, _value); return _value; } validateFieldValues.put(_paramName, null); return null; } String _value = StringUtils.defaultIfEmpty(WebContext.getRequest().getParameter(_paramName), defaultValue); _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_process", _paramName, _value, "RequestParameter")); if (!hasValidation() && required && StringUtils.isBlank(_value)) { throw new NullPointerException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.mvc.request_parameter_null", _paramName)); } validateFieldValues.put(_paramName, _value); return new BlurObject(_value).toObjectValue(type); } protected Object parseModelBindAnnotation(Class<?> type) { ClassBeanWrapper<?> _wrapper = ClassUtils.wrapper(type); for (String _fName : _wrapper.getFieldNames()) { Annotation[] _fieldAnnotations = _wrapper.getFieldAnnotations(_fName); for (Annotation _annotation : _fieldAnnotations) { if (_annotation instanceof CookieValue) { CookieValue _anno = (CookieValue) _annotation; Object _value = this.parseCookieValueAnnotation(_anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _wrapper.getFieldType(_fName), _fName); _wrapper.setValue(_fName, _value); break; } else if (_annotation instanceof PathVariable) { PathVariable _anno = (PathVariable) _annotation; Object _value = this.parsePathVariableAnnotation(_anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _wrapper.getFieldType(_fName), _fName); _wrapper.setValue(_fName, _value); break; } else if (_annotation instanceof RequestHeader) { RequestHeader _anno = (RequestHeader) _annotation; Object _value = this.parseRequestHeaderAnnotation(_anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _wrapper.getFieldType(_fName), _fName); _wrapper.setValue(_fName, _value); break; } else if (_annotation instanceof RequestParam) { RequestParam _anno = (RequestParam) _annotation; Object _value = this.parseRequestParamAnnotation(_anno.prefix(), _anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _wrapper.getFieldType(_fName), _fName); _wrapper.setValue(_fName, _value); break; } else if (_annotation instanceof ModelBind) { _wrapper.setValue(_fName, this.parseModelBindAnnotation(_wrapper.getFieldType(_fName))); break; } } } return _wrapper.getTarget(); } /* (non-Javadoc) * @see net.ymate.platform.mvc.support.RequestExecutor#getMethodParams() */ protected Object[] getMethodParams() { Class<?>[] _paramTypes = this.requestMeta.getParameterTypes(); Object[] _params = new Object[_paramTypes.length]; if (_params.length > 0) { Annotation[][] _paramAnnotations = this.requestMeta.getMethod().getParameterAnnotations(); for (int _idx = 0; _idx < _params.length; _idx++) { Annotation[] _annotations = _paramAnnotations[_idx]; for (Annotation _annotation : _annotations) { if (_annotation instanceof CookieValue) { CookieValue _anno = (CookieValue) _annotation; _params[_idx] = this.parseCookieValueAnnotation(_anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _paramTypes[_idx], this.requestMeta.getMethodParamNames()[_idx]); break; } else if (_annotation instanceof PathVariable) { PathVariable _anno = (PathVariable) _annotation; _params[_idx] = this.parsePathVariableAnnotation(_anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _paramTypes[_idx], this.requestMeta.getMethodParamNames()[_idx]); break; } else if (_annotation instanceof RequestHeader) { RequestHeader _anno = (RequestHeader) _annotation; _params[_idx] = this.parseRequestHeaderAnnotation(_anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _paramTypes[_idx], this.requestMeta.getMethodParamNames()[_idx]); break; } else if (_annotation instanceof RequestParam) { RequestParam _anno = (RequestParam) _annotation; _params[_idx] = this.parseRequestParamAnnotation(_anno.prefix(), _anno.value(), StringUtils.defaultIfEmpty(_anno.defaultValue(), null), _anno.required(), _paramTypes[_idx], this.requestMeta.getMethodParamNames()[_idx]); break; } else if (_annotation instanceof ModelBind) { _params[_idx] = this.parseModelBindAnnotation(_paramTypes[_idx]); break; } } } } return _params; } /* (non-Javadoc) * @see net.ymate.platform.mvc.support.RequestExecutor#processMethodResultToView(java.lang.Object) */ protected IView processMethodResultToView(Object result) throws Exception { IView _view = null; if (result == null) { _view = new JspView(); } else if (result instanceof String) { String _viewStr = StringUtils.trimToEmpty((String) result).toLowerCase(); if (StringUtils.startsWith(_viewStr, IWebView.VIEW_REDIRECT)) { _view = new RedirectView(StringUtils.substringAfter(_viewStr, IWebView.VIEW_REDIRECT)); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_FORWARD)) { _view = new ForwardView(StringUtils.substringAfter(_viewStr, IWebView.VIEW_FORWARD)); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_HTTP_STATUS)) { String[] _statusContent = StringUtils.split(StringUtils.substringAfter(_viewStr, IWebView.VIEW_HTTP_STATUS), ","); _view = new HttpStatusView(Integer.parseInt(_statusContent[0]), _statusContent.length >= 2 ? _statusContent[1] : null); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_JSON)) { _view = new JsonView(StringUtils.substringAfter(_viewStr, IWebView.VIEW_JSON)); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_JSP)) { _view = new JspView(StringUtils.substringAfter(_viewStr, IWebView.VIEW_JSP)); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_FTL)) { _view = new FreeMarkerView(StringUtils.substringAfter(_viewStr, IWebView.VIEW_FTL)); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_INLINE_FILE)) { _view = BinaryView.loadFromFile(StringUtils.substringAfter(_viewStr, IWebView.VIEW_INLINE_FILE), false); } else if (StringUtils.startsWith(_viewStr, IWebView.VIEW_FILE)) { _view = BinaryView.loadFromFile(StringUtils.substringAfter(_viewStr, IWebView.VIEW_FILE), true); } else { _view = new TextView(_viewStr); } } else if (result instanceof IView) { _view = (IView) result; } return _view; } }
Andreas237/AndroidPolicyAutomation
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/fasterxml/jackson/databind/exc/UnrecognizedPropertyException.java
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.fasterxml.jackson.databind.exc; import com.fasterxml.jackson.core.JsonLocation; import com.fasterxml.jackson.core.JsonParser; import java.util.Collection; // Referenced classes of package com.fasterxml.jackson.databind.exc: // PropertyBindingException public class UnrecognizedPropertyException extends PropertyBindingException { public UnrecognizedPropertyException(JsonParser jsonparser, String s, JsonLocation jsonlocation, Class class1, String s1, Collection collection) { super(jsonparser, s, jsonlocation, class1, s1, collection); // 0 0:aload_0 // 1 1:aload_1 // 2 2:aload_2 // 3 3:aload_3 // 4 4:aload 4 // 5 6:aload 5 // 6 8:aload 6 // 7 10:invokespecial #12 <Method void PropertyBindingException(JsonParser, String, JsonLocation, Class, String, Collection)> // 8 13:return } public UnrecognizedPropertyException(String s, JsonLocation jsonlocation, Class class1, String s1, Collection collection) { super(s, jsonlocation, class1, s1, collection); // 0 0:aload_0 // 1 1:aload_1 // 2 2:aload_2 // 3 3:aload_3 // 4 4:aload 4 // 5 6:aload 5 // 6 8:invokespecial #19 <Method void PropertyBindingException(String, JsonLocation, Class, String, Collection)> // 7 11:return } public static UnrecognizedPropertyException from(JsonParser jsonparser, Object obj, String s, Collection collection) { if(obj == null) //* 0 0:aload_1 //* 1 1:ifnonnull 12 throw new IllegalArgumentException(); // 2 4:new #25 <Class IllegalArgumentException> // 3 7:dup // 4 8:invokespecial #28 <Method void IllegalArgumentException()> // 5 11:athrow Class class1; if(obj instanceof Class) //* 6 12:aload_1 //* 7 13:instanceof #30 <Class Class> //* 8 16:ifeq 87 class1 = (Class)obj; // 9 19:aload_1 // 10 20:checkcast #30 <Class Class> // 11 23:astore 4 else //* 12 25:new #2 <Class UnrecognizedPropertyException> //* 13 28:dup //* 14 29:aload_0 //* 15 30:new #32 <Class StringBuilder> //* 16 33:dup //* 17 34:invokespecial #33 <Method void StringBuilder()> //* 18 37:ldc1 #35 <String "Unrecognized field \""> //* 19 39:invokevirtual #39 <Method StringBuilder StringBuilder.append(String)> //* 20 42:aload_2 //* 21 43:invokevirtual #39 <Method StringBuilder StringBuilder.append(String)> //* 22 46:ldc1 #41 <String "\" (class "> //* 23 48:invokevirtual #39 <Method StringBuilder StringBuilder.append(String)> //* 24 51:aload 4 //* 25 53:invokevirtual #45 <Method String Class.getName()> //* 26 56:invokevirtual #39 <Method StringBuilder StringBuilder.append(String)> //* 27 59:ldc1 #47 <String "), not marked as ignorable"> //* 28 61:invokevirtual #39 <Method StringBuilder StringBuilder.append(String)> //* 29 64:invokevirtual #50 <Method String StringBuilder.toString()> //* 30 67:aload_0 //* 31 68:invokevirtual #56 <Method JsonLocation JsonParser.getCurrentLocation()> //* 32 71:aload 4 //* 33 73:aload_2 //* 34 74:aload_3 //* 35 75:invokespecial #57 <Method void UnrecognizedPropertyException(JsonParser, String, JsonLocation, Class, String, Collection)> //* 36 78:astore_0 //* 37 79:aload_0 //* 38 80:aload_1 //* 39 81:aload_2 //* 40 82:invokevirtual #61 <Method void prependPath(Object, String)> //* 41 85:aload_0 //* 42 86:areturn class1 = obj.getClass(); // 43 87:aload_1 // 44 88:invokevirtual #67 <Method Class Object.getClass()> // 45 91:astore 4 jsonparser = ((JsonParser) (new UnrecognizedPropertyException(jsonparser, (new StringBuilder()).append("Unrecognized field \"").append(s).append("\" (class ").append(class1.getName()).append("), not marked as ignorable").toString(), jsonparser.getCurrentLocation(), class1, s, collection))); ((UnrecognizedPropertyException) (jsonparser)).prependPath(obj, s); return ((UnrecognizedPropertyException) (jsonparser)); //* 46 93:goto 25 } private static final long serialVersionUID = 1L; }
sbhagat101/titan-talks-2.0
server/node_modules/ss/spec/builder_spec.js
<reponame>sbhagat101/titan-talks-2.0 var Builder = require("crs").Builder; var Domain = require("crs").Domain; var builder = new Builder(); builder.addAggre(Aggre01) .addAggre(Aggre02) .addService(service01) .addService(service02) .addCommandHandle(commandHandle01) .addCommandHandle(commandHandle02) .addEventHandle(eventHandle01) .addEventHandle(eventHandle02); builder.linkDB(db); var domain = new Domain(builder);
mhalaj1/vpp-agent
plugins/vpp/l3plugin/descriptor/proxy_arp.go
<reponame>mhalaj1/vpp-agent<gh_stars>100-1000 // Copyright (c) 2020 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package descriptor import ( "net" "strings" "github.com/pkg/errors" "go.ligato.io/cn-infra/v2/logging" "go.ligato.io/vpp-agent/v3/pkg/models" kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api" ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/descriptor/adapter" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls" l3 "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3" ) const ( // ProxyArpDescriptorName is the name of the descriptor. ProxyArpDescriptorName = "vpp-proxy-arp" // Dependency labels: vrfTableProxyARPDep = "vrf-table-exists" ) // Validation errors: var ( // ErrMissingIP returned when one of IP fields in ProxyARP range is not set. ErrMissingIP = errors.New("missing IP address") // ErrIPWithMask returned when one of IP fields in ProxyARP range is set with a subnet mask. ErrIPWithMask = errors.New("only one IP must be defined (e.g. \"192.0.2.1\"), not a subnet") // ErrInvalidIP returned when one of IP fields in ProxyARP range can not be parsed. ErrInvalidIP = errors.New("invalid IP address") // ErrIPv6NotSupported returned when one of IP fields in ProxyARP range is defined as IPv6. ErrIPv6NotSupported = errors.New("IP address must be IPv4, not IPv6") ) // ProxyArpDescriptor teaches KVScheduler how to configure VPP proxy ARPs. type ProxyArpDescriptor struct { log logging.Logger proxyArpHandler vppcalls.ProxyArpVppAPI scheduler kvs.KVScheduler } // NewProxyArpDescriptor creates a new instance of the ProxyArpDescriptor. func NewProxyArpDescriptor(scheduler kvs.KVScheduler, proxyArpHandler vppcalls.ProxyArpVppAPI, log logging.PluginLogger) *kvs.KVDescriptor { ctx := &ProxyArpDescriptor{ scheduler: scheduler, proxyArpHandler: proxyArpHandler, log: log.NewLogger("proxy-arp-descriptor"), } typedDescr := &adapter.ProxyARPDescriptor{ Name: ProxyArpDescriptorName, NBKeyPrefix: l3.ModelProxyARP.KeyPrefix(), ValueTypeName: l3.ModelProxyARP.ProtoName(), KeySelector: l3.ModelProxyARP.IsKeyValid, ValueComparator: ctx.EquivalentProxyArps, Validate: ctx.Validate, Create: ctx.Create, Update: ctx.Update, Delete: ctx.Delete, Retrieve: ctx.Retrieve, Dependencies: ctx.Dependencies, DerivedValues: ctx.DerivedValues, RetrieveDependencies: []string{ifdescriptor.InterfaceDescriptorName}, } return adapter.NewProxyARPDescriptor(typedDescr) } // Validate validates ProxyARP setup. func (d *ProxyArpDescriptor) Validate(key string, proxyArp *l3.ProxyARP) error { for _, r := range proxyArp.Ranges { if r.FirstIpAddr == "" { return kvs.NewInvalidValueError(ErrMissingIP, "ranges.first_ip_addr") } if r.LastIpAddr == "" { return kvs.NewInvalidValueError(ErrMissingIP, "ranges.last_ip_addr") } if strings.Contains(r.FirstIpAddr, "/") { return kvs.NewInvalidValueError(ErrIPWithMask, "ranges.first_ip_addr") } if strings.Contains(r.LastIpAddr, "/") { return kvs.NewInvalidValueError(ErrIPWithMask, "ranges.last_ip_addr") } firstIP := net.ParseIP(r.FirstIpAddr) if firstIP == nil { return kvs.NewInvalidValueError(ErrInvalidIP, "ranges.first_ip_addr") } lastIP := net.ParseIP(r.LastIpAddr) if lastIP == nil { return kvs.NewInvalidValueError(ErrInvalidIP, "ranges.last_ip_addr") } if firstIP.To4() == nil { return kvs.NewInvalidValueError(ErrIPv6NotSupported, "ranges.first_ip_addr") } if lastIP.To4() == nil { return kvs.NewInvalidValueError(ErrIPv6NotSupported, "ranges.last_ip_addr") } } return nil } // Dependencies lists dependencies for a VPP Proxy ARP. func (d *ProxyArpDescriptor) Dependencies(key string, proxyArp *l3.ProxyARP) []kvs.Dependency { var dependencies []kvs.Dependency for _, r := range proxyArp.Ranges { if r.VrfId == 0 { continue } dependencies = append(dependencies, kvs.Dependency{ Label: vrfTableProxyARPDep, Key: l3.VrfTableKey(r.VrfId, l3.VrfTable_IPV4), }) } return dependencies } // DerivedValues derives l3.ProxyARP_Interface for every interface. func (d *ProxyArpDescriptor) DerivedValues(key string, proxyArp *l3.ProxyARP) (derValues []kvs.KeyValuePair) { for _, iface := range proxyArp.Interfaces { derValues = append(derValues, kvs.KeyValuePair{ Key: l3.ProxyARPInterfaceKey(iface.Name), Value: iface, }) } return derValues } // EquivalentProxyArps compares VPP Proxy ARPs. func (d *ProxyArpDescriptor) EquivalentProxyArps(key string, oldValue, newValue *l3.ProxyARP) bool { if len(newValue.Ranges) != len(oldValue.Ranges) { return false } toAdd, toDelete := calculateRngDiff(newValue.Ranges, oldValue.Ranges) return len(toAdd) == 0 && len(toDelete) == 0 } // Create adds VPP Proxy ARP. func (d *ProxyArpDescriptor) Create(key string, value *l3.ProxyARP) (metadata interface{}, err error) { for _, r := range value.Ranges { firstIP := net.ParseIP(r.FirstIpAddr).To4() lastIP := net.ParseIP(r.LastIpAddr).To4() if err := d.proxyArpHandler.AddProxyArpRange(firstIP, lastIP, r.VrfId); err != nil { return nil, errors.Errorf("failed to add proxy ARP address range %s - %s (VRF: %d): %v", firstIP, lastIP, r.VrfId, err) } } return nil, nil } // Update modifies VPP Proxy ARP. func (d *ProxyArpDescriptor) Update(key string, oldValue, newValue *l3.ProxyARP, oldMetadata interface{}) (newMetadata interface{}, err error) { toAdd, toDelete := calculateRngDiff(newValue.Ranges, oldValue.Ranges) for _, r := range toDelete { firstIP := net.ParseIP(r.FirstIpAddr).To4() lastIP := net.ParseIP(r.LastIpAddr).To4() if err := d.proxyArpHandler.DeleteProxyArpRange(firstIP, lastIP, r.VrfId); err != nil { return nil, errors.Errorf("failed to delete proxy ARP address range %s - %s (VRF: %d): %v", firstIP, lastIP, r.VrfId, err) } } for _, r := range toAdd { firstIP := net.ParseIP(r.FirstIpAddr).To4() lastIP := net.ParseIP(r.LastIpAddr).To4() if err := d.proxyArpHandler.AddProxyArpRange(firstIP, lastIP, r.VrfId); err != nil { return nil, errors.Errorf("failed to add proxy ARP address range %s - %s (VRF: %d): %v", firstIP, lastIP, r.VrfId, err) } } return nil, nil } // Delete deletes VPP Proxy ARP. func (d *ProxyArpDescriptor) Delete(key string, value *l3.ProxyARP, metadata interface{}) error { for _, r := range value.Ranges { firstIP := net.ParseIP(r.FirstIpAddr).To4() lastIP := net.ParseIP(r.LastIpAddr).To4() if err := d.proxyArpHandler.DeleteProxyArpRange(firstIP, lastIP, r.VrfId); err != nil { return errors.Errorf("failed to delete proxy ARP address range %s - %s (VRF: %d): %v", firstIP, lastIP, r.VrfId, err) } } return nil } // Retrieve returns VPP Proxy ARP configuration. func (d *ProxyArpDescriptor) Retrieve(correlate []adapter.ProxyARPKVWithMetadata) ( retrieved []adapter.ProxyARPKVWithMetadata, err error) { // Retrieve VPP configuration rangesDetails, err := d.proxyArpHandler.DumpProxyArpRanges() if err != nil { return nil, err } ifacesDetails, err := d.proxyArpHandler.DumpProxyArpInterfaces() if err != nil { return nil, err } proxyArp := &l3.ProxyARP{} for _, rangeDetail := range rangesDetails { proxyArp.Ranges = append(proxyArp.Ranges, rangeDetail.Range) } for _, ifaceDetail := range ifacesDetails { proxyArp.Interfaces = append(proxyArp.Interfaces, ifaceDetail.Interface) } retrieved = append(retrieved, adapter.ProxyARPKVWithMetadata{ Key: models.Key(proxyArp), Value: proxyArp, Origin: kvs.UnknownOrigin, }) return retrieved, nil } // calculateRngDiff calculates difference between old and new ranges. func calculateRngDiff(newRngs, oldRngs []*l3.ProxyARP_Range) (toAdd, toDelete []*l3.ProxyARP_Range) { // Find missing ranges. for _, newRng := range newRngs { var found bool for _, oldRng := range oldRngs { if newRng.VrfId == oldRng.VrfId && newRng.FirstIpAddr == oldRng.FirstIpAddr && newRng.LastIpAddr == oldRng.LastIpAddr { found = true break } } if !found { toAdd = append(toAdd, newRng) } } // Find obsolete ranges. for _, oldRng := range oldRngs { var found bool for _, newRng := range newRngs { if oldRng.VrfId == newRng.VrfId && oldRng.FirstIpAddr == newRng.FirstIpAddr && oldRng.LastIpAddr == newRng.LastIpAddr { found = true break } } if !found { toDelete = append(toDelete, oldRng) } } return }
bcgov/EDUC-PEN-NOMINAL-ROLL-API
api/src/main/java/ca/bc/gov/educ/pen/nominalroll/api/processor/impl/ExcelXFileProcessor.java
package ca.bc.gov.educ.pen.nominalroll.api.processor.impl; import ca.bc.gov.educ.pen.nominalroll.api.constants.FileTypes; import ca.bc.gov.educ.pen.nominalroll.api.exception.FileUnProcessableException; import ca.bc.gov.educ.pen.nominalroll.api.exception.NominalRollAPIRuntimeException; import ca.bc.gov.educ.pen.nominalroll.api.properties.ApplicationProperties; import ca.bc.gov.educ.pen.nominalroll.api.struct.v1.NominalRollFileProcessResponse; import lombok.extern.slf4j.Slf4j; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; @Slf4j @Service public class ExcelXFileProcessor extends BaseExcelProcessor { public ExcelXFileProcessor(final ApplicationProperties applicationProperties) { super(applicationProperties); } @Override public NominalRollFileProcessResponse processFile(final byte[] fileContents, final String correlationID) throws FileUnProcessableException { try { final File outputFile = this.getFile(fileContents, FileTypes.XLSX.getCode()); try (final OPCPackage pkg = OPCPackage.open(outputFile)) { try (final XSSFWorkbook wb = new XSSFWorkbook(pkg)) { return this.processSheet(wb.getSheetAt(0), correlationID); } } } catch (final IOException | InvalidFormatException e) { log.error("exception", e); throw new NominalRollAPIRuntimeException(e.getMessage()); } } @Override public FileTypes getFileType() { return FileTypes.XLSX; } }
caitp/traceur-compiler
test/feature/Syntax/Error_YieldStarNewLine.js
<filename>test/feature/Syntax/Error_YieldStarNewLine.js<gh_stars>10-100 // Should not compile. // Error: :6:7: Unexpected token * function* yieldStarNewLine() { yield *42; }
elipopovadev/SoftUni-JavaScript-Advanced
ArraysAndNested Arrays-Lab/SmallestTwoNumbers.js
function solve(array){ array.sort((a, b) => a - b); console.log(array[0] + ' ' + array[1]); } solve([3, 0, 10, 4, 7, 3])
ligoj/bootstrap
bootstrap-business/src/main/java/org/ligoj/bootstrap/core/validation/JAXRSBeanValidationImplicitInInterceptor.java
<reponame>ligoj/bootstrap<filename>bootstrap-business/src/main/java/org/ligoj/bootstrap/core/validation/JAXRSBeanValidationImplicitInInterceptor.java<gh_stars>1-10 /* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.bootstrap.core.validation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Payload; import javax.validation.constraints.NotNull; import javax.validation.metadata.ConstraintDescriptor; import javax.ws.rs.QueryParam; import org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor; import org.apache.cxf.logging.FaultListener; import org.apache.cxf.logging.NoOpFaultListener; import org.apache.cxf.message.Message; import org.hibernate.validator.internal.engine.ConstraintViolationImpl; import org.hibernate.validator.internal.engine.path.PathImpl; import org.hibernate.validator.internal.metadata.core.ConstraintHelper; import org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl; import org.hibernate.validator.internal.metadata.location.ConstraintLocation.ConstraintLocationKind; import org.hibernate.validator.internal.util.annotation.ConstraintAnnotationDescriptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; /** * Enforces correct parameters regarding JSR-303 and JSR-349. Eligible beans are all JSR-349 annotated parameters plus * non JAX-RS annotated objects. */ public class JAXRSBeanValidationImplicitInInterceptor extends JAXRSBeanValidationInInterceptor { /** * Excluded parameter annotation name or package. {@link String#startsWith(String)} will be used. */ @Value("#{'${validation.excludes:javax.ws.rs,org.apache.cxf.jaxrs.ext.multipart.Multipart}'.split(',')}") private final Collection<String> excludes = Collections.singleton(QueryParam.class.getPackage().getName()); @Autowired private ValidatorBean validator; /** * {@link NotNull} descriptor */ private static final ConstraintDescriptor<NotNull> NOT_NULL_DESCRIPTOR = new ConstraintDescriptorImpl<>( ConstraintHelper.forAllBuiltinConstraints(), null, new ConstraintAnnotationDescriptor<>(new NotNull() { @Override public Class<? extends Annotation> annotationType() { return NotNull.class; } @Override public String message() { return "NotNull"; } @Override public Class<?>[] groups() { return new Class<?>[0]; } @SuppressWarnings("unchecked") @Override public Class<? extends Payload>[] payload() { return new Class[0]; } }), ConstraintLocationKind.PARAMETER); @Override protected void handleValidation(final Message message, final Object resourceInstance, final Method method, final List<Object> arguments) { super.handleValidation(message, resourceInstance, method, arguments); // Check each parameter final Set<ConstraintViolation<?>> validationErrors = new HashSet<>(); for (var index = 0; index < arguments.size(); index++) { final var parameter = method.getParameters()[index]; if (hasToBeValidated(parameter)) { // This parameter is a not context, path or query parameter validate(arguments.get(index), method, parameter, index, validationErrors); } } // Check the veto if (!validationErrors.isEmpty()) { message.put(FaultListener.class.getName(), new NoOpFaultListener()); throw new ConstraintViolationException(validationErrors); } } /** * Validate a bean of given declared class. * * @param bean the bean to validate. * @param parameter the runtime annotations of this parameter. * @param validationErrors the errors list to fill. */ private void validate(final Object bean, final Method method, final Parameter parameter, final int index, final Set<ConstraintViolation<?>> validationErrors) { if (bean == null) { // Parameter is null, is it manually checked of managed by CXF for // multipart? // All non-body parameters are required by default final var propertyPath = PathImpl.createPathFromString(method.getName()); propertyPath.addParameterNode(parameter.getName(), index); validationErrors.add(ConstraintViolationImpl.forParameterValidation(NotNull.class.getName(), null, null, "interpolated", null, null, null, null, propertyPath, NOT_NULL_DESCRIPTOR, null, null)); return; } final var clazz = bean.getClass(); if (Collection.class.isAssignableFrom(clazz)) { validate((Collection<?>) bean, validationErrors); } else if (clazz.isArray()) { validate((Object[]) bean, validationErrors); } else { validateSimpleBean(bean, validationErrors); } } /** * Validate an array of beans. */ private void validate(final Object[] beans, final Set<ConstraintViolation<?>> validationErrors) { validationErrors.addAll(validator.validate(beans)); } /** * Validate a collection of beans. */ private void validate(final Collection<?> beans, final Set<ConstraintViolation<?>> validationErrors) { validationErrors.addAll(validator.validate(beans)); } /** * Validate a simple beans. */ private void validateSimpleBean(final Object bean, final Set<ConstraintViolation<?>> validationErrors) { validationErrors.addAll(validator.validate(bean)); } /** * Indicates the given annotation is eligible to bean validation. * * @param annotation the {@link Annotation} to check. * @return <code>true</code> the given Annotation is eligible to bean validation. */ private boolean hasToBeValidated(final Annotation annotation) { return excludes.stream().noneMatch(annotation.annotationType().getName()::startsWith); } /** * Indicates all annotations of given {@link Parameter} are eligible to bean validation. * * @param parameter the parameter to check. * @return <code>true</code> the given class is eligible to bean validation. */ private boolean hasToBeValidated(final Parameter parameter) { return Arrays.stream(parameter.getAnnotations()).allMatch(this::hasToBeValidated); } }
the-zebulan/CodeWars
tests/kyu_8_tests/test_whats_the_real_floor.py
<filename>tests/kyu_8_tests/test_whats_the_real_floor.py import unittest from katas.kyu_8.whats_the_real_floor import get_real_floor class GetRealFloorTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(get_real_floor(1), 0) def test_equal_2(self): self.assertEqual(get_real_floor(0), 0) def test_equal_3(self): self.assertEqual(get_real_floor(5), 4) def test_equal_4(self): self.assertEqual(get_real_floor(15), 13) def test_equal_5(self): self.assertEqual(get_real_floor(-3), -3)
jwillemsen/sidecar
GUI/Master/LogAlertsWindow.cc
<filename>GUI/Master/LogAlertsWindow.cc<gh_stars>0 #include "QtCore/QRegExp" #include "QtGui/QSyntaxHighlighter" #include "QtGui/QTextCharFormat" #include "QtWidgets/QScrollBar" #include "App.h" #include "LogAlertsWindow.h" #include "TreeViewItem.h" #include "ui_LogAlertsWindow.h" using namespace SideCar::GUI::Master; struct LogColorizer : public QSyntaxHighlighter { QTextCharFormat errorFormat_; QRegExp errorRegExp_; LogColorizer(QTextEdit* widget) : QSyntaxHighlighter(widget), errorFormat_(), errorRegExp_() { errorFormat_.setForeground(TreeViewItem::GetFailureColor()); errorRegExp_ = QRegExp("\\b(FATAL|ERROR|WARNING)\\b"); } void highlightBlock(const QString& text) { int pos = text.indexOf(errorRegExp_); while (pos >= 0) { int length = errorRegExp_.matchedLength(); setFormat(pos, length, errorFormat_); pos = text.indexOf(errorRegExp_, pos + length); } } }; LogAlertsWindow::LogAlertsWindow() : Super(), gui_(new Ui::LogAlertsWindow) { gui_->setupUi(this); setObjectName("LogAlertsWindow"); setVisibleAfterRestore(false); makeShowAction(Qt::Key_F3); gui_->alerts_->document()->setMaximumBlockCount(1000); QFont font; font.setPointSize(10); gui_->alerts_->document()->setDefaultFont(font); gui_->alerts_->document()->setUndoRedoEnabled(false); connect(gui_->actionCopy, SIGNAL(triggered()), gui_->alerts_, SLOT(copy())); connect(gui_->actionClear, SIGNAL(triggered()), gui_->alerts_, SLOT(clear())); new LogColorizer(gui_->alerts_); } void LogAlertsWindow::addAlerts(const QStringList& entries) { // If the user has scrolled up to look at an earlier entry, then record the current vertical scrollbar // position for restoration later after appending the alert entries. // int vPos = -1; if (gui_->alerts_->cursorRect().top() > gui_->alerts_->viewport()->height() && isVisible()) { vPos = gui_->alerts_->verticalScrollBar()->value(); } // Add the entries to the end of the buffer. // foreach (QString entry, entries) { gui_->alerts_->textCursor().insertText(entry); gui_->alerts_->moveCursor(QTextCursor::End); } // Show and raise the window if not visible, but don't be obnoxious and do that if the window is visible, // but not active. // if (!isVisible()) { show(); raise(); } else if (vPos != -1) { // User has scrolled up. Don't be obnoxious and scroll to the end. // gui_->alerts_->verticalScrollBar()->setValue(vPos); } }
Anatoly1010/Atomize_NIOCH
atomize/tests/pulse_epr/11_dqc.py
<reponame>Anatoly1010/Atomize_NIOCH import sys import signal import datetime import numpy as np import atomize.general_modules.general_functions as general import atomize.device_modules.PB_ESR_500_pro as pb_pro import atomize.device_modules.Spectrum_M4I_4450_X8 as spectrum import atomize.device_modules.Mikran_X_band_MW_bridge as mwBridge import atomize.device_modules.BH_15 as bh import atomize.device_modules.SR_PTC_10 as sr import atomize.general_modules.csv_opener_saver as openfile # 10.1007/0-306-47109-4_9 -> phase cycling # 10.1039/C5CP03671B -> timings ### Experimental parameters POINTS = 401 STEP = 20 # in NS FIELD = 3389 AVERAGES = 50 SCANS = 1 process = 'None' # PULSES REP_RATE = '500 Hz' PULSE_1_LENGTH = '16 ns' PULSE_2_LENGTH = '32 ns' PULSE_3_LENGTH = '16 ns' PULSE_4_LENGTH = '32 ns' PULSE_5_LENGTH = '16 ns' PULSE_6_LENGTH = '32 ns' PULSE_1_START = '0 ns' PULSE_2_START = '120 ns' PULSE_3_START = '240 ns' # this delta is 35 ns in 10.1039/C5CP03671B # we can use only pi-pulse length + 40 ns PULSE_4_START = '312 ns' PULSE_5_START = '384 ns' PULSE_6_START = '6384 ns' PULSE_SIGNAL_START = '12384 ns' # NAMES EXP_NAME = 'DQC' CURVE_NAME = 'exp1' # cycle_data_x = np.zeros( 64 ) cycle_data_y = np.zeros( 64 ) data_x = np.zeros(POINTS) data_y = np.zeros(POINTS) # STEP*6 ?!?! what is the time axis?! x_axis = np.linspace(0, (POINTS - 1)*STEP, num = POINTS) ### # initialization of the devices file_handler = openfile.Saver_Opener() ptc10 = sr.SR_PTC_10() mw = mwBridge.Mikran_X_band_MW_bridge() pb = pb_pro.PB_ESR_500_Pro() bh15 = bh.BH_15() dig4450 = spectrum.Spectrum_M4I_4450_X8() def cleanup(*args): dig4450.digitizer_stop() dig4450.digitizer_close() pb.pulser_stop() file_handler.save_data(file_data, np.c_[x_axis, data_x, data_y], header = header, mode = 'w') sys.exit(0) signal.signal(signal.SIGTERM, cleanup) bh15.magnet_setup(FIELD, 1) bh15.magnet_field(FIELD) dig4450.digitizer_read_settings() dig4450.digitizer_number_of_averages(AVERAGES) #tb = dig4450.digitizer_number_of_points() * int( 1000 / float( dig4450.digitizer_sample_rate().split(' ')[0] ) ) tb = dig4450.digitizer_window() # probably 3D; but in the 10.1039/C5CP03671B the step of t1 is equal to the step of t2; t3 was fixed # additionally 8 cycles with delta_P0_P1 = delta_P1_P2 = t1 and delta_P2_P3 = delta_P3_P4 = t2 # delta_t1 = delta_t2 = 16 ns; to get rid of D modulation pb.pulser_pulse(name = 'P0', channel = 'MW', start = PULSE_1_START, length = PULSE_1_LENGTH, \ phase_list = ['+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y']) pb.pulser_pulse(name = 'P1', channel = 'MW', start = PULSE_2_START, length = PULSE_2_LENGTH, delta_start = str(STEP) + ' ns', \ phase_list = ['+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y']) pb.pulser_pulse(name = 'P2', channel = 'MW', start = PULSE_3_START, length = PULSE_3_LENGTH, delta_start = str(2 * STEP) + ' ns', \ phase_list = ['+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', \ '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y', '+x', '+y', '-x', '-y']) pb.pulser_pulse(name = 'P3', channel = 'MW', start = PULSE_4_START, length = PULSE_4_LENGTH, delta_start = str(3 * STEP) + ' ns', \ phase_list = ['+x', '+x', '+x', '+x', '+y', '+y', '+y', '+y', '-x', '-x', '-x', '-x', '-y', '-y', '-y', '-y', \ '+x', '+x', '+x', '+x', '+y', '+y', '+y', '+y', '-x', '-x', '-x', '-x', '-y', '-y', '-y', '-y', \ '+x', '+x', '+x', '+x', '+y', '+y', '+y', '+y', '-x', '-x', '-x', '-x', '-y', '-y', '-y', '-y', \ '+x', '+x', '+x', '+x', '+y', '+y', '+y', '+y', '-x', '-x', '-x', '-x', '-y', '-y', '-y', '-y']) pb.pulser_pulse(name = 'P4', channel = 'MW', start = PULSE_5_START, length = PULSE_5_LENGTH, delta_start = str(4 * STEP) + ' ns', \ phase_list = ['+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', \ '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', '-x', \ '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y', '+y',\ '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y', '-y']) pb.pulser_pulse(name = 'P5', channel = 'MW', start = PULSE_6_START, length = PULSE_6_LENGTH, delta_start = str(5 * STEP) + ' ns', \ phase_list = ['+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', \ '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', \ '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x',\ '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x', '+x']) pb.pulser_pulse(name = 'P6', channel = 'TRIGGER', start = PULSE_SIGNAL_START, length = '100 ns', delta_start = str(6 * STEP) + ' ns') pb.pulser_repetition_rate( REP_RATE ) # Data saving header = 'Date: ' + str(datetime.datetime.now().strftime("%d-%m-%Y %H-%M-%S")) + '\n' + 'DQC\n' + \ 'Field: ' + str(FIELD) + ' G \n' + str(mw.mw_bridge_att_prm()) + '\n' + \ str(mw.mw_bridge_synthesizer()) + '\n' + \ 'Repetition Rate: ' + str(pb.pulser_repetition_rate()) + '\n' + 'Number of Scans: ' + str(SCANS) + '\n' +\ 'Averages: ' + str(AVERAGES) + '\n' + 'Points: ' + str(POINTS) + '\n' + 'Window: ' + str(tb) + ' ns\n' + \ 'Temperature: ' + str(ptc10.tc_temperature('2A')) + ' K\n' +\ 'Pulse List: ' + '\n' + str(pb.pulser_pulse_list()) + 'Time (trig. delta_start), X (V*s), Y (V*s) ' file_data, file_param = file_handler.create_file_parameters('.param') file_handler.save_header(file_param, header = header, mode = 'w') for j in general.scans(SCANS): for i in range(POINTS): # phase cycle k = 0 while k < 64: pb.pulser_next_phase() cycle_data_x[k], cycle_data_y[k] = dig4450.digitizer_get_curve( integral = True ) k += 1 x, y = pb.pulser_acquisition_cycle(cycle_data_x, cycle_data_y, \ acq_cycle = ['+', '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', '-', \ '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', '-', '+', \ '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', \ '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i', '+i', '-i']) data_x[i] = ( data_x[i] * (j - 1) + x ) / j data_y[i] = ( data_y[i] * (j - 1) + y ) / j process = general.plot_1d(EXP_NAME, x_axis, ( data_x, data_y ), xname = 'Delay',\ xscale = 'ns', yname = 'Area', yscale = 'V*s', timeaxis = 'False', label = CURVE_NAME, pr = process, \ text = 'Scan / Time: ' + str(j) + ' / '+ str(i*STEP)) pb.pulser_shift() pb.pulser_pulse_reset() dig4450.digitizer_stop() dig4450.digitizer_close() pb.pulser_stop() file_handler.save_data(file_data, np.c_[x_axis, data_x, data_y], header = header, mode = 'w')
tdiesler/gravia
resource/src/main/java/org/jboss/gravia/utils/ResourceUtils.java
/* * #%L * Gravia :: Resource * %% * Copyright (C) 2010 - 2014 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.gravia.utils; import org.jboss.gravia.resource.IdentityNamespace; import org.jboss.gravia.resource.Resource; /** * A utility class for {@link Resource} * * @author Thomas.Dies<EMAIL> * @since 16-Sep-2010 */ public final class ResourceUtils { // Hide ctor private ResourceUtils() { } /** * A resource is abstract if it has a 'type' attribute with value 'abstract' or 'reference' */ public static boolean isAbstract(Resource res) { Object attval = res.getIdentityCapability().getAttribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE); return isReference(res) || IdentityNamespace.TYPE_ABSTRACT.equals(attval); } /** * A reference resource has a 'type' attribute with value 'reference' */ public static boolean isReference(Resource res) { Object attval = res.getIdentityCapability().getAttribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE); return IdentityNamespace.TYPE_REFERENCE.equals(attval); } /** * A shared resource has a 'shared' attribute with value 'true' */ public static boolean isShared(Resource resource) { Object attval = resource.getIdentityCapability().getAttribute(IdentityNamespace.CAPABILITY_SHARED_ATTRIBUTE); return Boolean.parseBoolean(attval != null ? attval.toString() : null); } }
crashtech/rails-graphql
lib/rails/graphql/errors.rb
# frozen_string_literal: true module Rails module GraphQL # Error class tha wrappes all the other error classes StandardError = Class.new(::StandardError) # Error class related to problems during the definition process DefinitionError = Class.new(StandardError) # Error class related to validation of a value ValidationError = Class.new(StandardError) # Errors that can happen related to the arguments given to a method ArgumentError = Class.new(DefinitionError) # Errors that can happen when locking for definition objects, like fields NotFoundError = Class.new(DefinitionError) # Errors related to the name of the objects NameError = Class.new(DefinitionError) # Errors related to duplciated objects DuplicatedError = Class.new(NameError) # Error class related to problems during the execution process ExecutionError = Class.new(StandardError) # Error related to the parsing process ParseError = Class.new(ExecutionError) # Error class related to parsing the argumens ArgumentsError = Class.new(ParseError) # Error class related to problems that happened during execution of fields FieldError = Class.new(ExecutionError) # Error class related to when a field was not found on the requested object MissingFieldError = Class.new(FieldError) # Error class related to when a field was found but is marked as disabled DisabledFieldError = Class.new(FieldError) # Error class related to when the captured output value is invalid due to # type checking InvalidValueError = Class.new(FieldError) # Error class related to when a field is unauthorized and can not be used, # similar to disabled fields UnauthorizedFieldError = Class.new(FieldError) # Error class related to execution responses that don't require processing StaticResponse = Class.new(Interrupt) # Error class related to cached responses, which doesn't need processing CachedResponse = Class.new(StaticResponse) # Error class related to a persisted query that has't been persisted yet PersistedQueryNotFound = Class.new(StaticResponse) # A simple module and way to extend errors with extra information ExtendedError = Module.new do delegate_missing_to :@extension def self.extend(error, extension) error.instance_variable_set(:@extension, extension) error.extend(self) error end end end end
JacopoDT/numerare-core
src/P2p/P2pProtocolTypes.h
/*** MIT License Copyright (c) 2018 NUMERARE 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. Parts of this file are originally Copyright (c) 2012-2017 The CryptoNote developers, The Bytecoin developers ***/ #pragma once #include <string.h> #include <tuple> #include <boost/uuid/uuid.hpp> #include "Common/StringTools.h" namespace CryptoNote { typedef boost::uuids::uuid uuid; typedef boost::uuids::uuid net_connection_id; typedef uint64_t PeerIdType; #pragma pack (push, 1) struct NetworkAddress { uint32_t ip; uint32_t port; }; struct PeerlistEntry { NetworkAddress adr; PeerIdType id; uint64_t last_seen; }; struct connection_entry { NetworkAddress adr; PeerIdType id; bool is_income; }; #pragma pack(pop) inline bool operator < (const NetworkAddress& a, const NetworkAddress& b) { return std::tie(a.ip, a.port) < std::tie(b.ip, b.port); } inline bool operator == (const NetworkAddress& a, const NetworkAddress& b) { return memcmp(&a, &b, sizeof(a)) == 0; } inline std::ostream& operator << (std::ostream& s, const NetworkAddress& na) { return s << Common::ipAddressToString(na.ip) << ":" << std::to_string(na.port); } inline uint32_t hostToNetwork(uint32_t n) { return (n << 24) | (n & 0xff00) << 8 | (n & 0xff0000) >> 8 | (n >> 24); } inline uint32_t networkToHost(uint32_t n) { return hostToNetwork(n); // the same } }
lechium/tvOS10Headers
System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/TVLJSDocumentUpdator.h
<filename>System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/TVLJSDocumentUpdator.h<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:07:17 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/ATVLegacyContentKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <ATVLegacyContentKit/ATVLegacyContentKit-Structs.h> @class TVLLegacyJSContext, TVLDocument, TVSXMLDocument; @interface TVLJSDocumentUpdator : NSObject { BOOL _isUsed; TVLLegacyJSContext* _context; TVLDocument* _feedDocument; TVSXMLDocument* _xmlDocument; } @property (nonatomic,retain) TVLLegacyJSContext * context; //@synthesize context=_context - In the implementation block @property (nonatomic,retain) TVLDocument * feedDocument; //@synthesize feedDocument=_feedDocument - In the implementation block @property (nonatomic,retain) TVSXMLDocument * xmlDocument; //@synthesize xmlDocument=_xmlDocument - In the implementation block @property (assign,nonatomic) BOOL isUsed; //@synthesize isUsed=_isUsed - In the implementation block +(id)documentUpdatorForContext:(OpaqueJSContextRef)arg1 xmlDocument:(id)arg2 ; -(TVLLegacyJSContext *)context; -(void)setContext:(TVLLegacyJSContext *)arg1 ; -(TVLDocument *)feedDocument; -(TVSXMLDocument *)xmlDocument; -(void)setFeedDocument:(TVLDocument *)arg1 ; -(BOOL)isUsed; -(void)setIsUsed:(BOOL)arg1 ; -(void)setXmlDocument:(TVSXMLDocument *)arg1 ; -(id)initWithContext:(id)arg1 feedDocument:(id)arg2 xmlDocument:(id)arg3 ; -(void)updateDocument; @end
Hadleyhzy/data_structure_and_algorithm
binary_search/binary_search/275_h_index_2.cpp
<filename>binary_search/binary_search/275_h_index_2.cpp // // 275_h_index_2.cpp // binary_search // // Created by Hadley on 09.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> using namespace std; class Solution { public: int hIndex(vector<int>& citations) { if(citations.empty())return 0; auto n=citations.size(); int l=0; int r=n-1; while(l<=r){ int m=l+(r-l)/2; cout<<l<<" "<<r<<" "<<m<<endl; if(citations[m]>=(n-1)-m+1){ if(m==0||citations[m-1]<(n-1)-m+2){ return (n-1)-m+1; }else{ r=m-1; } }else{ l=m+1; } } return 0; } };
gabrielbmotta/mne-cpp
libraries/disp/viewers/multiview.cpp
//============================================================================================================= /** * @file multiview.cpp * @author <NAME> <<EMAIL>> * @version dev * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors 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. * * * @brief MultiView class definition. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "multiview.h" #include "multiviewwindow.h" #include "rtfiffrawview.h" #include "averagelayoutview.h" #include "butterflyview.h" //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QHBoxLayout> #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISPLIB; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= MultiView::MultiView(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) { this->setDockNestingEnabled(true); if(QWidget* pCentralWidget = this->centralWidget()) { pCentralWidget->hide(); } } //============================================================================================================= MultiView::~MultiView() { } //============================================================================================================= MultiViewWindow* MultiView::addWidgetTop(QWidget* pWidget, const QString& sName) { MultiViewWindow* pDockWidget = new MultiViewWindow(); pDockWidget->setWindowTitle(sName); pDockWidget->setWidget(pWidget); pWidget->layout()->setContentsMargins(0,0,0,0); pDockWidget->layout()->setContentsMargins(0,0,0,0); this->addDockWidget(Qt::DockWidgetArea::TopDockWidgetArea, pDockWidget); connect(pDockWidget, &MultiViewWindow::dockLocationChanged, [=]() { emit dockLocationChanged(pWidget); }); return pDockWidget; } //============================================================================================================= MultiViewWindow* MultiView::addWidgetBottom(QWidget* pWidget, const QString& sName) { MultiViewWindow* pDockWidget = new MultiViewWindow(); pDockWidget->setWindowTitle(sName); pDockWidget->setWidget(pWidget); pWidget->layout()->setContentsMargins(0,0,0,0); pDockWidget->layout()->setContentsMargins(0,0,0,0); if(m_lDockWidgets.isEmpty()) { this->addDockWidget(Qt::DockWidgetArea::BottomDockWidgetArea, pDockWidget); } for(int i = 0; i < m_lDockWidgets.size(); ++i) { this->tabifyDockWidget(m_lDockWidgets.at(i), pDockWidget); } m_lDockWidgets.append(pDockWidget); connect(pDockWidget, &MultiViewWindow::dockLocationChanged, [=]() { emit dockLocationChanged(pWidget); }); return pDockWidget; }
awesome-archive/gnes
gnes/helper.py
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=low-comment-ratio import fcntl import html import logging import os import re import sys import time from copy import copy from functools import wraps from itertools import islice from logging import Formatter from typing import Iterator, Any, Union, List, Callable import numpy as np try: from memory_profiler import memory_usage except ImportError: memory_usage = lambda: [0] from ruamel.yaml import YAML from termcolor import colored __all__ = ['get_sys_info', 'get_optimal_sample_size', 'get_perm', 'time_profile', 'set_logger', 'batch_iterator', 'batching', 'yaml', 'profile_logger', 'doc_logger', 'parse_arg', 'profiling', 'FileLock', 'train_required', 'get_first_available_gpu'] def get_first_available_gpu(): try: import GPUtil r = GPUtil.getAvailable(order='random', maxMemory=0.1, maxLoad=0.1, limit=1) if r: return r[0] else: raise ValueError except ImportError: return 0 except ValueError: return 0 class FileLock(object): """ Implements the Posix based file locking (Linux, Ubuntu, MacOS, etc.) """ def __init__(self, lock_file: str = "LOCK"): self._lock_file = lock_file self._lock_file_fd = None @property def is_locked(self): return self._lock_file_fd is not None def acquire(self): open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC fd = os.open(self._lock_file, open_mode) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) self._lock_file_fd = fd return fd except (IOError, OSError): os.close(fd) return None def release(self): if self.is_locked: fd = self._lock_file_fd self._lock_file_fd = None fcntl.flock(fd, fcntl.LOCK_UN) os.close(fd) def get_sys_info(): from psutil import virtual_memory mem = virtual_memory() # get available memory in (M) avai = mem.available / 1e6 def timer(x, y): stime = time.time() c = np.matmul(x, y) return time.time() - stime x = np.random.random([1000, 1000]) y = np.random.random([1000, 1000]) unit_time = timer(x, y) return avai, unit_time def touch_dir(base_dir: str) -> None: if not os.path.exists(base_dir): os.makedirs(base_dir) def ralloc_estimator(n_lines, num_dim, unit_time, max_mem, max_time=60): est_time = num_dim * num_dim * n_lines / 1e9 * unit_time * 2 est_mem = 60 + 30 * (n_lines * num_dim / 768 / 10000) if (est_time < max_time) and (est_mem < max_mem * 0.5): return n_lines else: return ralloc_estimator(int(n_lines * 0.9), num_dim, unit_time, max_mem, max_time) def get_optimal_sample_size(x): max_mem, unit_time = get_sys_info() num_samples, num_dim = x.shape return ralloc_estimator(num_samples, num_dim, unit_time, max_mem, 30) def get_perm(L, m): n = int(len(L) / m) avg = sum(L) / len(L) * m LR = sorted(enumerate(L), key=lambda x: -x[1]) L = np.reshape([i[1] for i in LR], [m, n]) R = np.reshape([i[0] for i in LR], [m, n]) F = np.zeros([m, n]) reranked = [] for _ in range(n): ind = 0 for i in range(m): if i % 2 == 0: start, direction = 0, 1 else: start, direction = n - 1, -1 while F[i, start] == 1: start += direction if (ind + L[i, start] < avg) or (direction == 1): ind += L[i, start] F[i, start] = 1 reranked.append(R[i, start]) else: start, direction = n - 1, -1 while F[i, start] == 1: start += direction ind += L[i, start] F[i, start] = 1 reranked.append(R[i, start]) return reranked def time_profile(func): @wraps(func) def arg_wrapper(*args, **kwargs): if os.environ.get('GNES_PROFILING', False): start_t = time.perf_counter() if os.environ.get('GNES_PROFILING_MEM', False): start_mem = memory_usage()[0] r = func(*args, **kwargs) elapsed = time.perf_counter() - start_t if os.environ.get('GNES_PROFILING_MEM', False): end_mem = memory_usage()[0] # level_prefix = ''.join('-' for v in inspect.stack() if v and v.index is not None and v.index >= 0) level_prefix = '' if os.environ.get('GNES_PROFILING_MEM', False): mem_status = 'memory: %4.2fM -> %4.2fM' % (start_mem, end_mem) else: mem_status = '' profile_logger.info('%s%s: %3.3fs. %s' % (level_prefix, func.__qualname__, elapsed, mem_status)) else: r = func(*args, **kwargs) return r return arg_wrapper class ColoredFormatter(Formatter): MAPPING = { 'DEBUG': dict(color='white', on_color=None), # white 'INFO': dict(color='white', on_color=None), # cyan 'WARNING': dict(color='red', on_color='on_yellow'), # yellow 'ERROR': dict(color='white', on_color='on_red'), # 31 for red 'CRITICAL': dict(color='red', on_color='on_white'), # white on red bg } PREFIX = '\033[' SUFFIX = '\033[0m' def __init__(self, pattern, **kwargs): super().__init__(pattern, **kwargs) def format(self, record): cr = copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white cr.msg = colored(cr.msg, **seq) return super().format(cr) def set_logger(context, verbose=False): if os.name == 'nt': # for Windows return NTLogger(context, verbose) # Remove all handlers associated with the root logger object. for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) logger = logging.getLogger(context) logger.propagate = False if not logger.handlers: logger.setLevel(logging.DEBUG if verbose else logging.INFO) formatter = ColoredFormatter( '%(levelname)-.1s:' + context + ':[%(filename).3s:%(funcName).3s:%(lineno)3d]:%(message)s', datefmt= '%m-%d %H:%M:%S') console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG if verbose else logging.INFO) console_handler.setFormatter(formatter) logger.handlers = [] logger.addHandler(console_handler) return logger class NTLogger: def __init__(self, context, verbose): self.context = context self.verbose = verbose def info(self, msg, **kwargs): print('I:%s:%s' % (self.context, msg), flush=True) def debug(self, msg, **kwargs): if self.verbose: print('D:%s:%s' % (self.context, msg), flush=True) def error(self, msg, **kwargs): print('E:%s:%s' % (self.context, msg), flush=True) def warning(self, msg, **kwargs): print('W:%s:%s' % (self.context, msg), flush=True) class TimeContext: def __init__(self, msg): self._msg = msg def __enter__(self): self.start = time.perf_counter() print(self._msg, end=' ...\t', flush=True) def __exit__(self, typ, value, traceback): self.duration = time.perf_counter() - self.start print(colored(' [%3.3f secs]' % self.duration, 'green'), flush=True) class Tokenizer: def __init__(self, dict_path: str = None): import jieba self._jieba = jieba.Tokenizer() self._jieba.cache_file = "gnes.jieba_wrapper.cache" if dict_path is not None: self._jieba.load_userdict(dict_path) def tokenize(self, text, with_position=False): if not with_position: return self._jieba.lcut(text) # resulted token list else: return self._jieba.tokenize(text) # triple data consisting of (token, start_pos, end_pos) class SentenceSplitter: def __init__(self, min_len=2, max_len=20): self.min_len = min_len self.max_len = max_len self.must_split = r"[.。!?!?]+" self.maybe_split = r"[,,、.。::;;(())\s]+" def _is_ascii(self, s): return len(s) == len(s.encode()) def _get_printable(self, p): p = html.unescape(p) # decode html entity p = ''.join(c for c in p if c.isprintable()) # remove unprintable char p = ''.join(p.split()) # remove space return p def _check_p(self, p): if (len(p) > self.min_len and # must longer not self._is_ascii(p) and # must not all english # len(re.findall('\s', p)) == 0 and # must not contain spaces -> likely spam '\\x' not in p): # must not contain bad unicode char return True def _split(self, p, reg): sent = [s for s in re.split(reg, self._get_printable(p)) if s.strip()] for s in sent: if self._check_p(s): if len(s) > self.max_len and reg != self.maybe_split: for ss in self._split(s, self.maybe_split): yield ss else: yield s def split(self, p): return self._split(p, self.must_split) def batch_iterator(data: Union[Iterator[Any], List[Any], np.ndarray], batch_size: int, axis: int = 0) -> Iterator[Any]: if not batch_size or batch_size <= 0: yield data return if isinstance(data, np.ndarray): if batch_size >= data.shape[axis]: yield data return for _ in range(0, data.shape[axis], batch_size): start = _ end = min(len(data), _ + batch_size) yield np.take(data, range(start, end), axis, mode='clip') elif hasattr(data, '__len__'): if batch_size >= len(data): yield data return for _ in range(0, len(data), batch_size): yield data[_:_ + batch_size] elif isinstance(data, Iterator): # as iterator, there is no way to know the length of it while True: chunk = tuple(islice(data, batch_size)) if not chunk: return yield chunk else: raise TypeError('unsupported type: %s' % type(data)) def get_size(data: Union[Iterator[Any], List[Any], np.ndarray], axis: int = 0) -> int: if isinstance(data, np.ndarray): total_size = data.shape[axis] elif hasattr(data, '__len__'): total_size = len(data) else: total_size = None return total_size def pooling_simple(data_array, pooling_strategy): if pooling_strategy == 'REDUCE_MEAN': _pooled_data = sum(data_array) / (len(data_array) + 1e-10) elif pooling_strategy == 'REDUCE_MAX': _pooled_data = max(data_array) / (len(data_array) + 1e-10) elif pooling_strategy == 'REDUCE_MEAN_MAX': _pooled_data = np.concatenate( (sum(data_array) / (len(data_array) + 1e-10), max(data_array) / (len(data_array) + 1e-10)), axis=0) else: raise ValueError('pooling_strategy: %s has not been implemented' % pooling_strategy) return _pooled_data def pooling_np(data_array, pooling_strategy): if pooling_strategy == 'REDUCE_MEAN': _pooled_data = np.mean(data_array, axis=0) elif pooling_strategy == 'REDUCE_MAX': _pooled_data = np.amax(data_array, axis=0) elif pooling_strategy == 'REDUCE_MEAN_MAX': _pooled_data = np.concatenate( (np.mean(data_array, axis=0), np.amax(data_array, axis=0)), axis=1) else: raise ValueError('pooling_strategy: %s has not been implemented' % pooling_strategy) return _pooled_data def pooling_torch(data_tensor, mask_tensor, pooling_strategy): import torch minus_mask = lambda x, m: x - (1.0 - m).unsqueeze(2) * 1e30 mul_mask = lambda x, m: torch.mul(x, m.unsqueeze(2)) masked_reduce_mean = lambda x, m: torch.div(torch.sum(mul_mask(x, m), dim=1), torch.sum(m.unsqueeze(2), dim=1) + 1e-10) masked_reduce_max = lambda x, m: torch.max(minus_mask(x, m), 1)[0] if pooling_strategy == 'REDUCE_MEAN': output_tensor = masked_reduce_mean(data_tensor, mask_tensor) elif pooling_strategy == 'REDUCE_MAX': output_tensor = masked_reduce_max(data_tensor, mask_tensor) elif pooling_strategy == 'REDUCE_MEAN_MAX': output_tensor = torch.cat( (masked_reduce_mean(data_tensor, mask_tensor), masked_reduce_max(data_tensor, mask_tensor)), dim=1) else: raise ValueError('pooling_strategy: %s has not been implemented' % pooling_strategy) return output_tensor def batching(func: Callable[[Any], np.ndarray] = None, *, batch_size: Union[int, Callable] = None, num_batch=None, axis: int = 0): def _batching(func): @wraps(func) def arg_wrapper(self, data, label=None, *args, **kwargs): # priority: decorator > class_attribute b_size = (batch_size(data) if callable(batch_size) else batch_size) or getattr(self, 'batch_size', None) # no batching if b_size is None if b_size is None: if label is None: return func(self, data, *args, **kwargs) else: return func(self, data, label, *args, **kwargs) if hasattr(self, 'logger'): self.logger.info( 'batching enabled for %s(). batch_size=%s\tnum_batch=%s\taxis=%s' % ( func.__qualname__, b_size, num_batch, axis)) total_size1 = get_size(data, axis) total_size2 = b_size * num_batch if num_batch else None if total_size1 is not None and total_size2 is not None: total_size = min(total_size1, total_size2) else: total_size = total_size1 or total_size2 final_result = None done_size = 0 if label is not None: data = (data, label) for b in batch_iterator(data[:total_size], b_size, axis): if label is None: r = func(self, b, *args, **kwargs) else: r = func(self, b[0], b[1], *args, **kwargs) if isinstance(r, np.ndarray): # first result kicks in if final_result is None: if total_size is None: final_result = [] else: d_shape = list(r.shape) d_shape[axis] = total_size final_result = np.zeros(d_shape, dtype=r.dtype) # fill the data into final_result cur_size = get_size(r) if total_size is None: final_result.append(r) else: final_result[done_size:(done_size + cur_size)] = r done_size += cur_size if total_size is not None and done_size >= total_size: break if isinstance(final_result, list): final_result = np.concatenate(final_result, 0) return final_result return arg_wrapper if func: return _batching(func) else: return _batching def _get_yaml(): y = YAML(typ='safe') y.default_flow_style = False return y def parse_arg(v: str): if v.startswith('[') and v.endswith(']'): # function args must be immutable tuples not list tmp = v.replace('[', '').replace(']', '').strip().split(',') if len(tmp) > 0: return [parse_arg(vv.strip()) for vv in tmp] else: return [] try: v = int(v) # parse int parameter except ValueError: try: v = float(v) # parse float parameter except ValueError: if len(v) == 0: # ignore it when the parameter is empty v = None elif v.lower() == 'true': # parse boolean parameter v = True elif v.lower() == 'false': v = False return v def countdown(t: int, logger=None, reason: str = 'I am blocking this thread'): if not logger: sys.stdout.write('\n') sys.stdout.flush() while t > 0: t -= 1 msg = '%ss left: %s' % (colored('%3d' % t, 'yellow'), reason) if logger: logger.info(msg) else: sys.stdout.write('\r%s' % msg) sys.stdout.flush() time.sleep(1) sys.stdout.write('\n') sys.stdout.flush() def train_required(func): @wraps(func) def arg_wrapper(self, *args, **kwargs): if hasattr(self, 'is_trained'): if self.is_trained: return func(self, *args, **kwargs) else: raise RuntimeError('training is required before calling "%s"' % func.__name__) else: raise AttributeError('%r has no attribute "is_trained"' % self) return arg_wrapper profile_logger = set_logger('PROFILE') doc_logger = set_logger('DOC') profiling = time_profile yaml = _get_yaml()
ryanolson/yais
trtlab/memory/include/trtlab/memory/detail/utility.h
// MODIFICATION_MESSAGE // Modification notes: // - removed custom move/forward/swap implementations for std definitions // Copyright (C) 2015-2016 <NAME> <<EMAIL>> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TRTLAB_MEMORY_DETAIL_UTILITY_HPP #define TRTLAB_MEMORY_DETAIL_UTILITY_HPP // implementation of some functions from <utility> to prevent dependencies on it #include <type_traits> #include <utility> namespace trtlab { namespace memory { namespace detail { using std::move; using std::forward; // ADL aware swap template <typename T> void adl_swap(T& a, T& b) noexcept { std::swap(a, b); } // fancier syntax for enable_if // used as (template) parameter // also useful for doxygen // define PREDEFINED: TRTLAB_REQUIRES(x):= #define TRTLAB_REQUIRES(Expr) typename std::enable_if<(Expr), int>::type = 0 // same as above, but as return type // also useful for doxygen: // defined PREDEFINED: TRTLAB_REQUIRES_RET(x,r):=r #define TRTLAB_REQUIRES_RET(Expr, ...) typename std::enable_if<(Expr), __VA_ARGS__>::type // fancier syntax for enable_if on non-templated member function #define TRTLAB_ENABLE_IF(Expr) \ template <typename Dummy = std::true_type, TRTLAB_REQUIRES(Dummy::value && (Expr))> // fancier syntax for general expression SFINAE // used as (template) parameter // also useful for doxygen: // define PREDEFINED: TRTLAB_SFINAE(x):= #define TRTLAB_SFINAE(Expr) decltype((Expr), int()) = 0 // avoids code repetition for one-line forwarding functions #define TRTLAB_AUTO_RETURN(Expr) \ decltype(Expr) \ { \ return Expr; \ } // same as above, but requires certain type #define TRTLAB_AUTO_RETURN_TYPE(Expr, T) \ decltype(Expr) \ { \ static_assert(std::is_same<decltype(Expr), T>::value, \ #Expr " does not have the return type " #T); \ return Expr; \ } // whether or not a type is an instantiation of a template template <template <typename...> class Template, typename T> struct is_instantiation_of : std::false_type { }; template <template <typename...> class Template, typename... Args> struct is_instantiation_of<Template, Template<Args...>> : std::true_type { }; } // namespace detail } } // namespace trtlab::memory #endif //TRTLAB_MEMORY_DETAIL_UTILITY_HPP
MarkStega/CQC
Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Shared/ZWaveUSB3Sh_CtrlIntf.hpp
<filename>Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Shared/ZWaveUSB3Sh_CtrlIntf.hpp // // FILE NAME: ZWaveUSB3Sh_CtrlIntf.hpp // // AUTHOR: <NAME> // // CREATED: 07/24/2017 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (<NAME>.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // In order for the code down here in the shared facility to send and receive // messages (while doing all of the things that need to happen in the process of // doing that) we need to access the server driver. But, he is up in the server // facility. So we define this mixin interface. The driver implements this and // passes it into any calls it makes to the unit related classes so that they can // interact with their associated Z-Wave unit. // // CAVEATS/GOTCHAS: // // LOG: // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) class TZWaveUnit; class TZWOutMsg; // --------------------------------------------------------------------------- // CLASS: MZWaveCtrlIntf // PREFIX: mzwci // --------------------------------------------------------------------------- class ZWUSB3SHEXPORT MZWaveCtrlIntf { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- MZWaveCtrlIntf(const MZWaveCtrlIntf&) = delete; ~MZWaveCtrlIntf() {} // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- MZWaveCtrlIntf& operator=(const MZWaveCtrlIntf&) = delete; // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- virtual tCIDLib::TBoolean bUSB3IsUniqueUnitName ( const TString& strToCheck ) const = 0; virtual tCIDLib::TBoolean bUSB3QueryFldName ( const tCIDLib::TCard4 c4FldId , TString& strToFill ) = 0; virtual tCIDLib::TBoolean bUSB3WaitForMsg ( const TZWaveUnit& unitTar , const tZWaveUSB3Sh::EMsgTypes eType , const tCIDLib::TCard1 c1MsgId , const tCIDLib::TCard1 c1ClassId , const tCIDLib::TCard1 c1CmdId , const tCIDLib::TEncodedTime enctWaitFor , TZWInMsg& zwimReply , const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True ) = 0; virtual tCIDLib::TBoolean bUSB3WaitForMsg ( const tZWaveUSB3Sh::EMsgTypes eType , const tCIDLib::TCard1 c1UnitId , const tCIDLib::TCard1 c1MsgId , const tCIDLib::TCard1 c1ClassId , const tCIDLib::TCard1 c1CmdId , const tCIDLib::TEncodedTime enctWaitFor , TZWInMsg& zwimReply , const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True ) = 0; virtual tCIDLib::TBoolean bUSB3WriteFld ( const tCIDLib::TCard4 c4FldId , const tCIDLib::TBoolean bToStore ) = 0; virtual tCIDLib::TBoolean bUSB3WriteFld ( const tCIDLib::TCard4 c4FldId , const tCIDLib::TCard4 c4ToStore ) = 0; virtual tCIDLib::TBoolean bUSB3WriteFld ( const tCIDLib::TCard4 c4FldId , const tCIDLib::TFloat8 f8ToStore ) = 0; virtual tCIDLib::TBoolean bUSB3WriteFld ( const tCIDLib::TCard4 c4FldId , const tCIDLib::TInt4 i4ToStore ) = 0; virtual tCIDLib::TBoolean bUSB3WriteFld ( const tCIDLib::TCard4 c4FldId , const TString& strToStore ) = 0; virtual tCIDLib::TCard4 c4USB3LookupFldId ( const TString& strName ) const = 0; virtual const TString& strUSB3Moniker() const = 0; virtual tCIDLib::TVoid USB3QEventTrig ( const tCQCKit::EStdDrvEvs eEvent , const TString& strFld , const TString& strVal1 , const TString& strVal2 , const TString& strVal3 , const TString& strVal4 ) = 0; virtual tCIDLib::TVoid USB3Send ( const TZWOutMsg& zwomToSend ) = 0; virtual tCIDLib::TVoid USB3SendCCMsg ( const TZWOutMsg& zwomToSend ) = 0; virtual tCIDLib::TVoid USB3SendCCMsg ( const TZWOutMsg& zwomToSend , TZWInMsg& zwimRep , const tCIDLib::TCard4 c4WaitFor = 2500 ) = 0; virtual tCIDLib::TVoid USB3SendCtrlRes ( const TZWOutMsg& zwomToSend , TZWInMsg& zwimRep , const tCIDLib::TCard4 c4WaitFor = 2000 ) = 0; virtual tCIDLib::TVoid USB3SendUnitRes ( const TZWOutMsg& zwomToSend , TZWInMsg& zwimRep , const tCIDLib::TCard4 c4WaitFor = 2500 ) = 0; virtual tCIDLib::TVoid USB3SendReq ( const TZWOutMsg& zwomToSend , TZWInMsg& zwimRep , const tCIDLib::TCard4 c4WaitFor = 2500 ) = 0; virtual tCIDLib::TVoid USB3SetFieldErr ( const tCIDLib::TCard4 c4FldId ) = 0; protected : // ------------------------------------------------------------------- // Hidden constructors // ------------------------------------------------------------------- MZWaveCtrlIntf() {} }; #pragma CIDLIB_POPPACK
popara/jonny-api
matching/tests.py
from fixures import * from freezegun import freeze_time from datetime import datetime from time import sleep from django.core import mail from django.conf import settings from funcy import is_list, all, str_join from . import tasks as T import fixures from .models import JobStatus, job_status, get_questions, get_anon, \ get_anons_answers, get_details, zipthem, answer_as_str job_id = "simplelogin:190" def data(r): return r.content def job_start(api, job_id): return api.post('/api/job/start/%s' % job_id) def job_apply(api, job_id, user_id): return api.get('/api/job/apply/%s/%s' % (job_id, user_id)) def test_job_start(api, ok, get_job, super_fresh_job, fire_app): status = 'status' super_fresh_job(job_id) job = get_job(job_id) assert status not in job r = job_start(api, job_id) sleep(14) assert r.status_code == ok assert r.data == job_id j = get_job(job_id) assert j[status] == 'drafting' def test_applying_for_job(api, ok, get_job, patch_job, fresh_job): fresh_job(job_id) user = "simplelogin:3" r = job_apply(api, job_id, user) sleep(2) assert r.status_code == ok assert 'first' in data(r) j = get_job(job_id) assert len(j['applicants']) == 1 def test_applying_for_job_nd(api, ok, get_job, patch_job, fresh_job): fresh_job(job_id) user = "simplelogin:3" user2 = "simplelogin:4" user3 = "simplelogin:5" r = job_apply(api, job_id, user) r2 = job_apply(api, job_id, user2) r3 = job_apply(api, job_id, user3) assert r.status_code == ok assert r2.status_code == ok assert r3.status_code == ok assert 'first' in data(r) assert 'second' in data(r2) assert 'third' in data(r3) j = get_job(job_id) assert len(j['applicants']) == 3 def test_already_applied(api, ok, get_job, patch_job, fresh_job): fresh_job(job_id) user = "simplelogin:3" r = job_apply(api, job_id, user) assert r.status_code == ok assert 'first' in data(r) j = get_job(job_id) assert len(j['applicants']) == 1 r = job_apply(api, job_id, user) assert r.status_code == ok assert 'already' in data(r) j = get_job(job_id) assert len(j['applicants']) == 1 def test_getting_expert(available_experts): u = T.get_experts() assert len(u) > 1 def test_sending_emails(): e1 = "<EMAIL>" ex1 = {"name": "Joe", "email": e1, "id": "simplelogin:1"} m = T.dispatch_initial_email(job_id, ex1, {}) m1 = mail.outbox[0] assert len(mail.outbox) == 1 assert m1.to == [e1] def test_notify_experts(available_experts): m = T.notify_experts(available_experts, job_id) assert len(available_experts) == len(mail.outbox) def test_hard_limit_no_applicants(get_job, patch_job): patch_job(job_id, {'applicants': []}) T.hard_limit(job_id) j = get_job(job_id) #teardown patch_job(job_id, {'applicants': []}) assert len(mail.outbox) == 1 assert len(j['applicants']) == 1 def test_hard_limit_with_applicants(get_job, patch_job): A = 'applicants' apl = {"user_id": "simplelogin:1"} patch_job(job_id, {A: [apl]}) T.hard_limit(job_id) j = get_job(job_id) #teardown patch_job(job_id, {'applicants': []}) assert len(mail.outbox) == 0 assert len(j['applicants']) == 1 def test_soft_limit_expires(api, get_job, fresh_job, apply_for_job): fresh_job(job_id) A = 'applicants' u1 = "simplelogin:1" u2 = "simplelogin:2" r = job_apply(api, job_id, u1) r2 = job_apply(api, job_id, u2) assert len(mail.outbox) == 0 j = get_job(job_id) assert j["status"] == "drafting" T.soft_limit(job_id) assert len(mail.outbox) == 1 m1 = mail.outbox[0] assert m1.to == ['<EMAIL>'] def test_queue_filled(api, ok, get_job, fresh_job, apply_for_job): fresh_job(job_id) settings.SOFT_LIMIT_PERIOD = 2 def u(id): return "simplelogin:%s" % id for applicant in range(0, settings.QUEUE_SIZE): job_apply(api, job_id, u(applicant+1)) r = job_apply(api, job_id, u(settings.QUEUE_SIZE+2)) assert r.status_code != ok assert "too late" in data(r) def test_job_state(empty_job, applied_job, full_job): assert empty_job["status"] == JobStatus.drafting def test_getting_questions(): fields = ['id', 'name', 'category', 'text', 'type', 'label'] qs = get_questions() def is_q(q): return all(map(lambda x: x in q, fields)) assert is_list(qs) assert all(map(is_q, qs)) def test_get_anon_answers(): a = "anonymous:-Jr8CygRdKAANrQ5ENax" fields = ['at', 'value', 'id'] ans = get_anons_answers(a) def is_ans(an): return all(map(lambda x: x in an, fields)) assert is_list(ans) assert all(map(is_ans, ans)) def test_match_questions(): ans = [{'id': 'a', 'value': 'aa'}, {'id': 'b', 'value': 'bb'}] qs = [{'id': 'a', 'text': 'what', 'type': 'freeform'}, {'id': 'b', 'text': 'who', 'type': 'bingo'}] r = zipthem(qs, ans) fields = ['question', 'answer'] def is_z(z): return all(map(lambda a: a in z, fields)) assert is_list(r) assert all(map(is_z, r)) def test_zippingthem(questions, user_answers): r = zipthem(questions, user_answers) assert is_list(r) def test_answer_as_string(typed_answers): AT = typed_answers keys = AT.keys() o = AT['checklist']['value'] t = 'check-list' v = answer_as_str(o, t) assert v == str_join(', ', o) o = AT['checklist_2']['value'] v = answer_as_str(o, t) assert 'Somez, Thingzsz' o = AT['bingo']['value'] v = answer_as_str(o, 'bingo') assert v == str_join(', ', o) o = AT['about']['value'] v = answer_as_str(o, 'about') assert v == 'male, 31, straight' o = AT['companydetails']['value'] v = answer_as_str(o, 'company-details') assert '3 Boys' in v assert '34 Girls' in v assert 'partner' not in v assert 'Male friends: 4' in v o = AT['rolling']['value'] v = answer_as_str(o, 'rolling') assert 'Rock star!' == v o = AT['dates']['value'] v = answer_as_str(o, 'dates') assert 'To June 24' in v assert 'flexible' in v o = AT['freeform']['value'] v = answer_as_str(o, 'freeform') assert v == 'Knock the blast' def test_dummy(fire_app): assert fire_app.get('/levels', None) assert fire_app.get('/users', 'simplelogin:190')
KarizCache/serverless
optimal/tompkins/dag.py
from tompkins.ilp import schedule as schedule_tompkins from tompkins.ilp import jobs_when_where from tompkins.util import (reverse_dict, dictify, intersection, merge, unique, groupby) from collections import defaultdict def precedes_to_dag(jobs, precedes): return {a: [b for b in jobs if precedes(a, b)] for a in jobs} def transform_args(dag, agents, compcost, commcost, R, B, M): """ Transform arguments given to dag.schedule to those expected by tompkins inputs: dag - unipartite dag of the form {1: (2, 3)} if job 1 precedes 2 and 3 agents - a list of machines on which we can run each job compcost - a function (job, agent) -> runtime commcost - a function (job, agent, agent) -> communication time R - a function (job) -> start time (usually lambda j: 0) B - a function (job, agent) -> 1/0 - 1 if job can be run on agent M - a maximum makespan outputs: see tompkins.schedule's inputs """ P = unidag_to_P(dag) D = dictify(compcost) C = dictify(commcost) R = dictify(R) B = dictify(B) jobs = dag.keys() return jobs, agents, D, C, R, B, P, M def schedule(dag, agents, compcost, commcost, R=lambda job: 0, # Data available immediately B=lambda job, agent: 1, # All agents can run all jobs M=100000.0, # Large cutoff **kwargs): """ Statically Schedule a DAG of jobs on a set of machines This function wraps tompkins.ilp.schedule inputs: dag - unipartite dag of the form {1: (2, 3)} if job 1 precedes 2 and 3 agents - a list of machines on which we can run each job compcost - a function (job, agent) -> runtime commcost - a function (job, agent, agent) -> communication time R - a function (job) -> start time (usually lambda job: 0) B - a function (job, agent) -> 1/0 - 1 if job can be run on agent M - a maximum makespan outputs: dags - a dict mapping machine to local dag sched - a list of (job, start_time, machine) makespan - the total runtime of the computation """ args = schedule_tompkins( *transform_args(dag, agents, compcost, commcost, R, B, M)) prob, X, S, Cmax = args sched = jobs_when_where(*args) jobson = compute_jobson(sched) dags = manydags(dag, jobson, **kwargs) return dags, sched, Cmax.value() def unidag_to_P(dag): """ Converts a dag dict into one suitable for the tompkins algorithm input like {1: (2, 3)} output like {(1,2): 1, (1, 3): 1} """ d = defaultdict(lambda : 0) for k, v in {(a,b): 1 for a in dag for b in dag[a]}.items(): d[k] = v return d def compute_jobson(sched): """ Given the output of jobs_when_where produce a dict mapping machine to jobs {machine: [jobs]} """ result = {} for job, _, agent in sched: result[agent] = result.get(agent, ()) + (job,) return result def send(from_machine, to_machine, from_job, to_job): return ("send", from_machine, to_machine, from_job, to_job) def recv(from_machine, to_machine, from_job, to_job): return ("recv", from_machine, to_machine, from_job, to_job) def issend(x): return isinstance(x, tuple) and x[0] == "send" def isrecv(x): return isinstance(x, tuple) and x[0] == "recv" def replace_send_recv(dag, fn_send, fn_recv): """ Replaces all instances of tompkins send with a user defined send inputs functions like: fn_send - (from_machine, to_machine, from_job, to_job) -> a send fn_recv - (from_machine, to_machine, from_job, to_job) -> a recv """ def convert(x): if issend(x): return fn_send(*x[1:]) if isrecv(x): return fn_recv(*x[1:]) return x return {convert(key): tuple(map(convert, values)) for key, values in dag.items()} def manydags(dag, jobson, send=send, recv=recv): """ Given a dag and a schedule return many dags with sends/receives inputs: dag - Dictionary containing precedence constraints - specifies DAG: dag[job1] == (job2, job3) 1 if job1 immediately precedes job2 and job3 jobson - Dictionary mapping machine to list of jobs returns: dags - a dict of dags mapping machine to dag {machine: dag} Each dag is represented like dag (see above) New send and receive jobs have been added """ onmachine = {value:key for key, values in jobson.items() for value in values} revdag = reverse_dict(dag) assert unique(sum(jobson.values(), ())) return {machine: merge( # Standard local dag {fromjob: tuple( tojob if tojob in jobson[machine] else send(machine, onmachine[tojob], fromjob, tojob) for tojob in dag[fromjob]) for fromjob in jobson[machine]} , # Add in all of the receives {recv(onmachine[fromjob], machine, fromjob, tojob): intersection(dag[fromjob], jobson[machine]) for tojob in jobson[machine] for fromjob in revdag.get(tojob, ()) # might not have parent if fromjob not in jobson[machine]} , # Add in all of the sends {send(machine, onmachine[tojob], fromjob, tojob): () for fromjob in jobson[machine] for tojob in dag.get(fromjob, ()) if onmachine[tojob] != machine } ) for machine in jobson.keys()} def orderings(sched): nth = lambda n: (lambda x: x[n]) byagent = groupby(nth(2), sched) return {k: map(nth(0), sorted(v, key=nth(1))) for k,v in byagent.items()}
dcealopez/VUPlayer
DecoderMAC.h
<filename>DecoderMAC.h #pragma once #include "Decoder.h" #include "All.h" #include "maclib.h" #include "APETag.h" #include <string> class DecoderMAC : public Decoder { public: // 'filename' - file name. // Throws a std::runtime_error exception if the file could not be loaded. DecoderMAC( const std::wstring& filename ); // Reads sample data. // 'buffer' - output buffer (floating point format scaled to +/-1.0f). // 'sampleCount' - number of samples to read. // Returns the number of samples read, or zero if the stream has ended. long Read( float* buffer, const long sampleCount ) override; // Seeks to a 'position' in the stream, in seconds. // Returns the new position in seconds. float Seek( const float position ) override; private: // APE decompressor. std::unique_ptr<APE::IAPEDecompress> m_decompress; };
ikingye/keras
keras/applications/mobilenet_v2.py
<reponame>ikingye/keras from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2 from tensorflow.keras.applications.mobilenet_v2 import decode_predictions from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
Blubmin/intelligent_camera
intelligent_camera/RenderingSystem.h
#pragma once #include <memory> #include <vector> #include <glm\glm.hpp> #include <engine_base\Entity.h> #include <engine_base\Material.h> #include <engine_base\Program.h> class Mesh; class World; class RenderingSystem { public: RenderingSystem(); ~RenderingSystem(); void render(std::shared_ptr<World> world); private: glm::mat4 getModelMatrix(std::shared_ptr<Entity> entity); void bindMaterial(Material material); void bindGrid(); void drawGrid(std::shared_ptr<World> world); void drawMesh(const Mesh & mesh, GLint mode); void drawEntities(std::shared_ptr<World> world); unsigned long mask; Program phong; Program grid; Program hull; std::vector<glm::vec3> grid_points; std::vector<GLuint> grid_idx; GLuint GRID_VBO; GLuint GRID_VAO; GLuint GRID_IDX; glm::mat4 projection; };
ScalablyTyped/SlinkyTyped
r/react-native/src/main/scala/typingsSlinky/reactNative/mod/TabBarIOSProps.scala
<filename>r/react-native/src/main/scala/typingsSlinky/reactNative/mod/TabBarIOSProps.scala package typingsSlinky.reactNative.mod import typingsSlinky.reactNative.reactNativeStrings.auto import typingsSlinky.reactNative.reactNativeStrings.center import typingsSlinky.reactNative.reactNativeStrings.fill import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait TabBarIOSProps extends ViewProps { /** * Background color of the tab bar */ var barTintColor: js.UndefOr[ColorValue] = js.native /** * Specifies tab bar item positioning. Available values are: * - fill - distributes items across the entire width of the tab bar * - center - centers item in the available tab bar space * - auto (default) - distributes items dynamically according to the * user interface idiom. In a horizontally compact environment (e.g. iPhone 5) * this value defaults to `fill`, in a horizontally regular one (e.g. iPad) * it defaults to center. */ var itemPositioning: js.UndefOr[fill | center | auto] = js.native /** * Color of the currently selected tab icon */ var tintColor: js.UndefOr[ColorValue] = js.native /** * A Boolean value that indicates whether the tab bar is translucent */ var translucent: js.UndefOr[Boolean] = js.native /** * Color of unselected tab icons. Available since iOS 10. */ var unselectedItemTintColor: js.UndefOr[ColorValue] = js.native /** * Color of text on unselected tabs */ var unselectedTintColor: js.UndefOr[ColorValue] = js.native } object TabBarIOSProps { @scala.inline def apply(): TabBarIOSProps = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[TabBarIOSProps] } @scala.inline implicit class TabBarIOSPropsMutableBuilder[Self <: TabBarIOSProps] (val x: Self) extends AnyVal { @scala.inline def setBarTintColor(value: ColorValue): Self = StObject.set(x, "barTintColor", value.asInstanceOf[js.Any]) @scala.inline def setBarTintColorUndefined: Self = StObject.set(x, "barTintColor", js.undefined) @scala.inline def setItemPositioning(value: fill | center | auto): Self = StObject.set(x, "itemPositioning", value.asInstanceOf[js.Any]) @scala.inline def setItemPositioningUndefined: Self = StObject.set(x, "itemPositioning", js.undefined) @scala.inline def setTintColor(value: ColorValue): Self = StObject.set(x, "tintColor", value.asInstanceOf[js.Any]) @scala.inline def setTintColorUndefined: Self = StObject.set(x, "tintColor", js.undefined) @scala.inline def setTranslucent(value: Boolean): Self = StObject.set(x, "translucent", value.asInstanceOf[js.Any]) @scala.inline def setTranslucentUndefined: Self = StObject.set(x, "translucent", js.undefined) @scala.inline def setUnselectedItemTintColor(value: ColorValue): Self = StObject.set(x, "unselectedItemTintColor", value.asInstanceOf[js.Any]) @scala.inline def setUnselectedItemTintColorUndefined: Self = StObject.set(x, "unselectedItemTintColor", js.undefined) @scala.inline def setUnselectedTintColor(value: ColorValue): Self = StObject.set(x, "unselectedTintColor", value.asInstanceOf[js.Any]) @scala.inline def setUnselectedTintColorUndefined: Self = StObject.set(x, "unselectedTintColor", js.undefined) } }
wstong999/AliOS-Things
kernel/rhino/include/k_mm_blk.h
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef K_MM_BLK_H #define K_MM_BLK_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup aos_rhino mm * Pool memory management. Pool memory can be part of heap. * Pool is used to manage the little fixed-size block * * @{ */ #define MM_BLK_SLICE_BIT 10 #define MM_BLK_SLICE_SIZE (1<<MM_BLK_SLICE_BIT) #define MM_BLK_SLICE_NUM (RHINO_CONFIG_MM_TLF_BLK_SIZE/MM_BLK_SLICE_SIZE) #define MM_BLK_SIZE2TYPE(size) (32 - krhino_clz32((uint32_t)(size) - 1)) #define MM_BLK_TYPE2SIZE(type) (1 << (type)) /** * memory pool info */ typedef struct { size_t blk_size; uint32_t fail_cnt; /* alloc fail */ uint32_t freelist_cnt; uint32_t nofree_cnt; /* alloc but not free yet */ uintptr_t slice_cnt; uintptr_t slice_addr; size_t slice_offset; uintptr_t free_head; } mblk_list_t; typedef struct { kspinlock_t blk_lock; const name_t *pool_name; uintptr_t pool_start; uintptr_t pool_end; uint32_t slice_cnt; /* slice have bean used */ char slice_type[MM_BLK_SLICE_NUM]; mblk_list_t blk_list[MM_BLK_SLICE_BIT]; } mblk_pool_t; typedef struct { const name_t *pool_name; size_t pool_size; size_t used_size; size_t max_used_size; size_t max_blk_size; } mblk_info_t; /** * Init a pool. * * @param[in] pool pointer to the pool * @param[in] name name of the pool * @param[in] pool_start start addr of the pool * @param[in] pool_size size of the pool * * @return the operation status, RHINO_SUCCESS is OK, others is error */ kstat_t krhino_mblk_pool_init(mblk_pool_t *pool, const name_t *name, void *pool_start, size_t pool_size); /** * Memory block alloc from the pool. * * @param[in] pool pointer to a pool * @param[in] blk_size need size, and alloced size * * @return the operation status, RHINO_SUCCESS is OK, others is error */ void *krhino_mblk_alloc(mblk_pool_t *pool, uint32_t size); void *krhino_mblk_alloc_nolock(mblk_pool_t *pool, uint32_t size); /** * Memory block free to the pool. * * @param[in] pool pointer to the pool * @param[in] blk pointer to the blk * * @return the operation status, RHINO_SUCCESS is OK, others is error */ kstat_t krhino_mblk_free(mblk_pool_t *pool, void *blk); kstat_t krhino_mblk_free_nolock(mblk_pool_t *pool, void *blk); /** * This function will get information of the pool * @param[in] pool pointer to the pool * @param[out] info info of pool * @return the operation status, RHINO_SUCCESS is OK, others is error */ kstat_t krhino_mblk_info(mblk_pool_t *pool, mblk_info_t *info); kstat_t krhino_mblk_info_nolock(mblk_pool_t *pool, mblk_info_t *info); /** * Check if this a pool block. * * @param[in] pool pointer to the pool * @param[in] blk pointer to the blk * * @return yes return 1, no reture 0 */ #define krhino_mblk_check(pool, blk) \ ((pool) != NULL \ && ((uintptr_t)(blk) >= ((mblk_pool_t*)(pool))->pool_start) \ && ((uintptr_t)(blk) < ((mblk_pool_t*)(pool))->pool_end)) /** * get blk size, should followed by krhino_mblk_check * @param[in] pool pointer to the pool * @param[in] blk pointer to the blk * @return the len of blk */ RHINO_INLINE size_t krhino_mblk_get_size(mblk_pool_t *pool, void *blk) { uint32_t slice_idx; uint32_t blk_type; mblk_list_t *blk_list; slice_idx = ((uintptr_t)blk - pool->pool_start) >> MM_BLK_SLICE_BIT; blk_type = pool->slice_type[slice_idx]; blk_list = &(pool->blk_list[blk_type]); return blk_list->blk_size; } /** @} */ #ifdef __cplusplus } #endif #endif /* K_MM_BLK_H */
panaetov/grpclib
grpclib/stream.py
import abc import struct async def recv_message(stream, codec, message_type): meta = await stream.recv_data(5) if not meta: return compressed_flag = struct.unpack('?', meta[:1])[0] if compressed_flag: raise NotImplementedError('Compression not implemented') message_len = struct.unpack('>I', meta[1:])[0] message_bin = await stream.recv_data(message_len) assert len(message_bin) == message_len, \ '{} != {}'.format(len(message_bin), message_len) message = codec.decode(message_bin, message_type) return message async def send_message(stream, codec, message, message_type, *, end=False): reply_bin = codec.encode(message, message_type) reply_data = (struct.pack('?', False) + struct.pack('>I', len(reply_bin)) + reply_bin) await stream.send_data(reply_data, end_stream=end) class StreamIterator(abc.ABC): @abc.abstractmethod async def recv_message(self): pass def __aiter__(self): return self async def __anext__(self): message = await self.recv_message() if message is None: raise StopAsyncIteration() else: return message
fQuinzan/mcas
src/components/store/hstore/src/non_owner.h
<gh_stars>10-100 /* Copyright [2017-2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef _MCAS__HSTORE_NON_OWNER_H #define _MCAS__HSTORE_NON_OWNER_H /* A struct which resembles unique_ptr or shared_ptr, but for non-owing uses */ template <typename T> struct non_owner { using element_type = T; private: T *_p; public: explicit non_owner() : non_owner(nullptr) {} explicit non_owner(element_type *p_) : _p(p_) {} non_owner(const non_owner &other) = default; non_owner &operator=(const non_owner &other) = default; element_type *get() const { return _p; } operator bool() const { return bool(_p); } element_type * operator->() const { return _p; } element_type &operator*() const { return *_p; } }; #endif
domdomegg/tabula
web/src/main/scala/uk/ac/warwick/tabula/web/controllers/profiles/relationships/meetings/CreateScheduledMeetingRecordController.scala
<filename>web/src/main/scala/uk/ac/warwick/tabula/web/controllers/profiles/relationships/meetings/CreateScheduledMeetingRecordController.scala package uk.ac.warwick.tabula.web.controllers.profiles.relationships.meetings import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation._ import uk.ac.warwick.tabula.ItemNotFoundException import uk.ac.warwick.tabula.JavaImports._ import uk.ac.warwick.tabula.commands.profiles.relationships.meetings._ import uk.ac.warwick.tabula.data.model.{StudentCourseDetails, _} @Controller @RequestMapping(value = Array("/profiles/{relationshipType}/meeting/{studentCourseDetails}/{academicYear}/schedule/create")) class CreateScheduledMeetingRecordController extends AbstractManageScheduledMeetingRecordController with MeetingRecordControllerHelper { @ModelAttribute("command") def getCommand( @PathVariable relationshipType: StudentRelationshipType, @PathVariable studentCourseDetails: StudentCourseDetails, @ModelAttribute("manageableSchedulableRelationships") manageableSchedulableRelationships: Seq[StudentRelationship] ): CreateScheduledMeetingRecordCommand = { manageableSchedulableRelationships match { case Nil => throw new ItemNotFoundException case relationships => val cmd = CreateScheduledMeetingRecordCommand(currentMember, studentCourseDetails, manageableSchedulableRelationships) cmd.relationships = JArrayList(chosenRelationships(relationshipType, relationships, user)) cmd } } }
ItHertzSoGood/DragonBuild
frameworks/Preferences.framework/Headers/PSBadgedTableCell.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Dec 5 2019 09:59:31). // // Copyright (C) 1997-2019 <NAME>. // #import <Preferences/PSTableCell.h> @class UIImageView, UILabel; @interface PSBadgedTableCell : PSTableCell { UIImageView *_badgeImageView; UILabel *_badgeNumberLabel; long long _badgeInt; } + (id)badgeNumberLabelTextColor; + (id)unreadBubbleImage; + (double)badgePadding; + (id)reuseIdentifierForClassAndType:(long long)arg1; // - (void).cxx_destruct; - (BOOL)_shouldUseRoundStyle; - (void)badgeWithInteger:(long long)arg1; - (CGSize)sizeThatFits:(CGSize)arg1; - (void)layoutSubviews; - (void)setSelected:(BOOL)arg1 animated:(BOOL)arg2; - (void)setHighlighted:(BOOL)arg1 animated:(BOOL)arg2; - (void)resetLocale; - (void)refreshCellContentsWithSpecifier:(id)arg1; - (void)dealloc; - (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2 specifier:(id)arg3; @end
refinedmods/refinedstorage2
refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/ConnectionProvider.java
package com.refinedmods.refinedstorage2.api.network; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; import java.util.List; import java.util.Set; public interface ConnectionProvider { Connections findConnections(NetworkNodeContainer pivot, Set<NetworkNodeContainer> existingConnections); List<NetworkNodeContainer> sort(Set<NetworkNodeContainer> containers); }
dgloeckner/calcite
core/src/test/java/org/apache/calcite/plan/volcano/PlannerTests.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.plan.volcano; import org.apache.calcite.plan.Convention; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptCost; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelRule; import org.apache.calcite.plan.RelTrait; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.AbstractRelNode; import org.apache.calcite.rel.BiRel; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.RelWriter; import org.apache.calcite.rel.SingleRel; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.sql.type.SqlTypeFactoryImpl; import java.util.List; /** * Common classes and utility methods for Volcano planner tests. */ class PlannerTests { private PlannerTests() {} /** * Private calling convention representing a physical implementation. */ static final Convention PHYS_CALLING_CONVENTION = new Convention.Impl("PHYS", RelNode.class) { @Override public boolean canConvertConvention(Convention toConvention) { return true; } @Override public boolean useAbstractConvertersForConversion( RelTraitSet fromTraits, RelTraitSet toTraits) { return true; } @Override public RelNode enforce(final RelNode input, final RelTraitSet required) { return null; } }; static final Convention PHYS_CALLING_CONVENTION_2 = new Convention.Impl("PHYS_2", RelNode.class) { }; static final Convention PHYS_CALLING_CONVENTION_3 = new Convention.Impl("PHYS_3", RelNode.class) { @Override public boolean satisfies(RelTrait trait) { if (trait.equals(PHYS_CALLING_CONVENTION)) { return true; } return super.satisfies(trait); } }; static RelOptCluster newCluster(VolcanoPlanner planner) { final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(org.apache.calcite.rel.type.RelDataTypeSystem.DEFAULT); return RelOptCluster.create(planner, new RexBuilder(typeFactory)); } /** Leaf relational expression. */ abstract static class TestLeafRel extends AbstractRelNode { final String label; TestLeafRel(RelOptCluster cluster, RelTraitSet traits, String label) { super(cluster, traits); this.label = label; } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return planner.getCostFactory().makeInfiniteCost(); } @Override protected RelDataType deriveRowType() { final RelDataTypeFactory typeFactory = getCluster().getTypeFactory(); return typeFactory.builder() .add("this", typeFactory.createJavaType(Void.TYPE)) .build(); } @Override public RelWriter explainTerms(RelWriter pw) { return super.explainTerms(pw).item("label", label); } } /** Relational expression with one input. */ abstract static class TestSingleRel extends SingleRel { TestSingleRel(RelOptCluster cluster, RelTraitSet traits, RelNode input) { super(cluster, traits, input); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return planner.getCostFactory().makeInfiniteCost(); } @Override protected RelDataType deriveRowType() { return getInput().getRowType(); } } /** Relational expression with one input and convention NONE. */ static class NoneSingleRel extends TestSingleRel { NoneSingleRel(RelOptCluster cluster, RelNode input) { super(cluster, cluster.traitSetOf(Convention.NONE), input); } @Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { assert traitSet.contains(Convention.NONE); return new NoneSingleRel(getCluster(), sole(inputs)); } } /** Relational expression with two inputs and convention PHYS. */ static class PhysBiRel extends BiRel { PhysBiRel(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right) { super(cluster, traitSet, left, right); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return planner.getCostFactory().makeTinyCost(); } @Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { assert inputs.size() == 2; return new PhysBiRel(getCluster(), traitSet, inputs.get(0), inputs.get(1)); } @Override protected RelDataType deriveRowType() { return getLeft().getRowType(); } } /** Relational expression with zero inputs and convention NONE. */ static class NoneLeafRel extends TestLeafRel { NoneLeafRel(RelOptCluster cluster, String label) { super(cluster, cluster.traitSetOf(Convention.NONE), label); } @Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { assert traitSet.comprises(Convention.NONE); assert inputs.isEmpty(); return this; } } /** Relational expression with zero inputs and convention PHYS. */ static class PhysLeafRel extends TestLeafRel { Convention convention; PhysLeafRel(RelOptCluster cluster, String label) { this(cluster, PHYS_CALLING_CONVENTION, label); } PhysLeafRel(RelOptCluster cluster, Convention convention, String label) { super(cluster, cluster.traitSetOf(convention), label); this.convention = convention; } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return planner.getCostFactory().makeTinyCost(); } @Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { assert traitSet.comprises(convention); assert inputs.isEmpty(); return this; } } /** Relational expression with one input and convention PHYS. */ static class PhysSingleRel extends TestSingleRel { PhysSingleRel(RelOptCluster cluster, RelNode input) { super(cluster, cluster.traitSetOf(PHYS_CALLING_CONVENTION), input); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return planner.getCostFactory().makeTinyCost(); } public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { assert traitSet.contains(PHYS_CALLING_CONVENTION); return new PhysSingleRel(getCluster(), sole(inputs)); } } /** Planner rule that converts {@link NoneLeafRel} to PHYS convention. */ public static class PhysLeafRule extends RelRule<PhysLeafRule.Config> { static final PhysLeafRule INSTANCE = Config.EMPTY .withOperandSupplier(b -> b.operand(NoneLeafRel.class).anyInputs()) .as(Config.class) .toRule(); protected PhysLeafRule(Config config) { super(config); } @Override public Convention getOutConvention() { return PHYS_CALLING_CONVENTION; } @Override public void onMatch(RelOptRuleCall call) { NoneLeafRel leafRel = call.rel(0); call.transformTo( new PhysLeafRel(leafRel.getCluster(), leafRel.label)); } /** Rule configuration. */ public interface Config extends RelRule.Config { @Override default PhysLeafRule toRule() { return new PhysLeafRule(this); } } } /** Planner rule that matches a {@link NoneSingleRel} and succeeds. */ public static class GoodSingleRule extends RelRule<GoodSingleRule.Config> { static final GoodSingleRule INSTANCE = Config.EMPTY .withOperandSupplier(b -> b.operand(NoneSingleRel.class).anyInputs()) .as(Config.class) .toRule(); protected GoodSingleRule(Config config) { super(config); } @Override public Convention getOutConvention() { return PHYS_CALLING_CONVENTION; } @Override public void onMatch(RelOptRuleCall call) { NoneSingleRel single = call.rel(0); RelNode input = single.getInput(); RelNode physInput = convert(input, single.getTraitSet().replace(PHYS_CALLING_CONVENTION)); call.transformTo( new PhysSingleRel(single.getCluster(), physInput)); } /** Rule configuration. */ public interface Config extends RelRule.Config { @Override default GoodSingleRule toRule() { return new GoodSingleRule(this); } } } /** * Planner rule that matches a parent with two children and asserts that they * are not the same. */ public static class AssertOperandsDifferentRule extends RelRule<AssertOperandsDifferentRule.Config> { public static final AssertOperandsDifferentRule INSTANCE = Config.EMPTY.withOperandSupplier(b0 -> b0.operand(PhysBiRel.class).inputs( b1 -> b1.operand(PhysLeafRel.class).anyInputs(), b2 -> b2.operand(PhysLeafRel.class).anyInputs())) .as(Config.class) .toRule(); protected AssertOperandsDifferentRule(Config config) { super(config); } @Override public void onMatch(RelOptRuleCall call) { PhysLeafRel left = call.rel(1); PhysLeafRel right = call.rel(2); assert left != right : left + " should be different from " + right; } /** Rule configuration. */ public interface Config extends RelRule.Config { @Override default AssertOperandsDifferentRule toRule() { return new AssertOperandsDifferentRule(this); } } } }
Governance/dtgov
dtgov-task-api/src/main/java/org/overlord/dtgov/taskapi/types/StatusType.java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.06.10 at 02:58:42 PM EDT // package org.overlord.dtgov.taskapi.types; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for statusType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="statusType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Created"/> * &lt;enumeration value="Ready"/> * &lt;enumeration value="Reserved"/> * &lt;enumeration value="InProgress"/> * &lt;enumeration value="Completed"/> * &lt;enumeration value="Failed"/> * &lt;enumeration value="Error"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "statusType") @XmlEnum public enum StatusType { @XmlEnumValue("Created") CREATED("Created"), //$NON-NLS-1$ @XmlEnumValue("Ready") READY("Ready"), //$NON-NLS-1$ @XmlEnumValue("Reserved") RESERVED("Reserved"), //$NON-NLS-1$ @XmlEnumValue("InProgress") IN_PROGRESS("InProgress"), //$NON-NLS-1$ @XmlEnumValue("Completed") COMPLETED("Completed"), //$NON-NLS-1$ @XmlEnumValue("Failed") FAILED("Failed"), //$NON-NLS-1$ @XmlEnumValue("Error") ERROR("Error"); //$NON-NLS-1$ private final String value; StatusType(String v) { value = v; } public String value() { return value; } public static StatusType fromValue(String v) { for (StatusType c: StatusType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
DBatOWL/tutorials
mapstruct/src/main/java/com/baeldung/mapstruct/mappingCollections/mapper/EmployeeMapper.java
package com.baeldung.mapstruct.mappingCollections.mapper; import com.baeldung.mapstruct.mappingCollections.dto.EmployeeDTO; import com.baeldung.mapstruct.mappingCollections.model.Employee; import org.mapstruct.Mapper; import java.util.List; import java.util.Map; import java.util.Set; @Mapper public interface EmployeeMapper { EmployeeDTO map(Employee employee); List<EmployeeDTO> map(List<Employee> employees); Set<EmployeeDTO> map(Set<Employee> employees); Map<String, EmployeeDTO> map(Map<String, Employee> idEmployeeMap); }
jdelStrother/teepublic-react
src/lib/components/design_tile/DesignTile.test.js
<filename>src/lib/components/design_tile/DesignTile.test.js import React from 'react'; import ReactDOM from 'react-dom'; import DesignTile from './DesignTile'; import renderer from 'react-test-renderer'; import { shallow } from 'enzyme'; import store from '../../../demo/StoreData'; describe('Design Tile Testing', () => { const mockDesign = store._embedded.designs[0]; const mockProductType = mockDesign._embedded.defaultProduct._embedded.defaultSku.productType; const mockStoreId = store.id; const mockBuyProductLinkBuilder = jest.fn( (designId, productType, storeId) => { return `store/${storeId}/design/${designId}/product/${productType}`; } ); const designTile = ( <DesignTile design={mockDesign} buyProductLinkBuilder={mockBuyProductLinkBuilder} storeId={mockStoreId} /> ); it('DesignTile renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(designTile, div); }); it('renders correctly', () => { const tree = renderer.create(designTile).toJSON(); expect(tree).toMatchSnapshot(); }); it('calls buyProductLinkBuilder once', () => { const tile = shallow(designTile); expect(mockBuyProductLinkBuilder).toBeCalledWith( mockDesign.id, mockProductType, mockStoreId ); }); it('Image click routes to BuyProduct link', () => { const tile = shallow(designTile); const imageLink = tile.find('.tp-design-tile__image-link').props().href; expect(imageLink).toBe( mockBuyProductLinkBuilder(mockDesign.id, mockProductType, mockStoreId) ); }); it('Buy Button routes to BuyProduct link', () => { // Hacky way to test it, could't get window location to work const tile = shallow(designTile); const buyOnClick = tile .find('button') .prop('onClick') .toString(); expect(buyOnClick).toBe('() => window.location.href = buyProductLink'); }); });
IvanSanchez16/workspace-POO
src/asesorias/Cuadrado.java
package asesorias; public class Cuadrado { private int L; public Cuadrado(){ L=10; } public Cuadrado(int l){ L=l; } public float Area(){ return L*L; } public int Perimetro(){ return 4*L; } public int getL() { return L; } public void setL(int l) { L = l; } }
coopersystem-fsd/server
app/src/test/java/com/rideaustin/events/listeners/CityApprovalStatusUpdateEventListenerTest.java
<reponame>coopersystem-fsd/server<gh_stars>10-100 package com.rideaustin.events.listeners; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.collect.ImmutableMap; import com.rideaustin.events.CityApprovalStatusUpdateEvent; import com.rideaustin.model.Document; import com.rideaustin.model.enums.CityApprovalStatus; import com.rideaustin.model.enums.DocumentStatus; import com.rideaustin.model.enums.DocumentType; import com.rideaustin.model.user.Driver; import com.rideaustin.repo.dsl.DocumentDslRepository; public class CityApprovalStatusUpdateEventListenerTest { @Mock private DocumentDslRepository documentDslRepository; @Mock private Driver driver; @Mock private Document card; private CityApprovalStatusUpdateEventListener testedInstance; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); testedInstance = new CityApprovalStatusUpdateEventListener(documentDslRepository); } @Test public void testHandleCityApprovalStatusUpdateResolvesNewDocumentStatus() throws Exception { Map<CityApprovalStatus, DocumentStatus> mapping = ImmutableMap.of( CityApprovalStatus.APPROVED, DocumentStatus.APPROVED, CityApprovalStatus.EXPIRED, DocumentStatus.EXPIRED, CityApprovalStatus.PENDING, DocumentStatus.PENDING, CityApprovalStatus.REJECTED_BY_CITY, DocumentStatus.REJECTED, CityApprovalStatus.REJECTED_PHOTO, DocumentStatus.REJECTED ); when(documentDslRepository.findByAvatarAndType(eq(driver), eq(DocumentType.TNC_CARD))).thenReturn(card); for (Map.Entry<CityApprovalStatus, DocumentStatus> entry : mapping.entrySet()) { CityApprovalStatusUpdateEvent event = new CityApprovalStatusUpdateEvent(entry.getKey(), driver); testedInstance.handleCityApprovalStatusUpdate(event); verify(card, atLeastOnce()).setDocumentStatus(eq(entry.getValue())); } } @Test public void testHandleCityApprovalStatusUpdateSavesDocumentIfItsFound() { when(documentDslRepository.findByAvatarAndType(eq(driver), eq(DocumentType.TNC_CARD))).thenReturn(card); CityApprovalStatusUpdateEvent event = new CityApprovalStatusUpdateEvent(CityApprovalStatus.APPROVED, driver); testedInstance.handleCityApprovalStatusUpdate(event); verify(documentDslRepository).save(card); } }
huanyin88/Mod-Pywin32-For-Python3.x-DDE
com/win32comext/bits/src/PyIBackgroundCopyError.cpp
<filename>com/win32comext/bits/src/PyIBackgroundCopyError.cpp // This file implements the IBackgroundCopyError Interface for Python. // Generated by makegw.py #include "bits_pch.h" #include "PyIBackgroundCopyError.h" // @doc - This file contains autoduck documentation // --------------------------------------------------- // // Interface Implementation PyIBackgroundCopyError::PyIBackgroundCopyError(IUnknown *pdisp) : PyIUnknown(pdisp) { ob_type = &type; } PyIBackgroundCopyError::~PyIBackgroundCopyError() {} /* static */ IBackgroundCopyError *PyIBackgroundCopyError::GetI(PyObject *self) { return (IBackgroundCopyError *)PyIUnknown::GetI(self); } // @pymethod |PyIBackgroundCopyError|GetError|Description of GetError. PyObject *PyIBackgroundCopyError::GetError(PyObject *self, PyObject *args) { IBackgroundCopyError *pIBCE = GetI(self); if (pIBCE == NULL) return NULL; if (!PyArg_ParseTuple(args, ":GetError")) return NULL; HRESULT hr; BG_ERROR_CONTEXT context; HRESULT hr_err; PY_INTERFACE_PRECALL; hr = pIBCE->GetError(&context, &hr_err); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr, pIBCE, IID_IBackgroundCopyError); return Py_BuildValue("lk", context, hr_err); } // @pymethod |PyIBackgroundCopyError|GetFile|Description of GetFile. PyObject *PyIBackgroundCopyError::GetFile(PyObject *self, PyObject *args) { IBackgroundCopyError *pIBCE = GetI(self); if (pIBCE == NULL) return NULL; IBackgroundCopyFile *pVal; if (!PyArg_ParseTuple(args, ":GetFile")) return NULL; HRESULT hr; PY_INTERFACE_PRECALL; hr = pIBCE->GetFile(&pVal); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr, pIBCE, IID_IBackgroundCopyError); return PyCom_PyObjectFromIUnknown(pVal, IID_IBackgroundCopyFile, FALSE); } // @pymethod |PyIBackgroundCopyError|GetErrorDescription|Description of GetErrorDescription. PyObject *PyIBackgroundCopyError::GetErrorDescription(PyObject *self, PyObject *args) { IBackgroundCopyError *pIBCE = GetI(self); if (pIBCE == NULL) return NULL; // @pyparm int|LanguageId||Description for LanguageId LPWSTR pErrorDescription; DWORD LanguageId = 0; if (!PyArg_ParseTuple(args, "|l:GetErrorDescription", &LanguageId)) return NULL; HRESULT hr; PY_INTERFACE_PRECALL; hr = pIBCE->GetErrorDescription(LanguageId, &pErrorDescription); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr, pIBCE, IID_IBackgroundCopyError); PyObject *ret = PyWinObject_FromWCHAR(pErrorDescription); CoTaskMemFree(pErrorDescription); return ret; } // @pymethod |PyIBackgroundCopyError|GetErrorContextDescription|Description of GetErrorContextDescription. PyObject *PyIBackgroundCopyError::GetErrorContextDescription(PyObject *self, PyObject *args) { IBackgroundCopyError *pIBCE = GetI(self); if (pIBCE == NULL) return NULL; // @pyparm int|LanguageId||Description for LanguageId LPWSTR pContextDescription; DWORD LanguageId; if (!PyArg_ParseTuple(args, "l:GetErrorContextDescription", &LanguageId)) return NULL; HRESULT hr; PY_INTERFACE_PRECALL; hr = pIBCE->GetErrorContextDescription(LanguageId, &pContextDescription); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr, pIBCE, IID_IBackgroundCopyError); PyObject *ret = PyWinObject_FromWCHAR(pContextDescription); CoTaskMemFree(pContextDescription); return ret; } // @pymethod |PyIBackgroundCopyError|GetProtocol|Description of GetProtocol. PyObject *PyIBackgroundCopyError::GetProtocol(PyObject *self, PyObject *args) { IBackgroundCopyError *pIBCE = GetI(self); if (pIBCE == NULL) return NULL; LPWSTR pProtocol; if (!PyArg_ParseTuple(args, ":GetProtocol")) return NULL; HRESULT hr; PY_INTERFACE_PRECALL; hr = pIBCE->GetProtocol(&pProtocol); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr, pIBCE, IID_IBackgroundCopyError); PyObject *ret = PyWinObject_FromWCHAR(pProtocol); CoTaskMemFree(pProtocol); return ret; } // @object PyIBackgroundCopyError|Description of the interface static struct PyMethodDef PyIBackgroundCopyError_methods[] = { {"GetError", PyIBackgroundCopyError::GetError, 1}, // @pymeth GetError|Description of GetError {"GetFile", PyIBackgroundCopyError::GetFile, 1}, // @pymeth GetFile|Description of GetFile {"GetErrorDescription", PyIBackgroundCopyError::GetErrorDescription, 1}, // @pymeth GetErrorDescription|Description of GetErrorDescription {"GetErrorContextDescription", PyIBackgroundCopyError::GetErrorContextDescription, 1}, // @pymeth GetErrorContextDescription|Description of GetErrorContextDescription {"GetProtocol", PyIBackgroundCopyError::GetProtocol, 1}, // @pymeth GetProtocol|Description of GetProtocol {NULL}}; PyComTypeObject PyIBackgroundCopyError::type("PyIBackgroundCopyError", &PyIUnknown::type, sizeof(PyIBackgroundCopyError), PyIBackgroundCopyError_methods, GET_PYCOM_CTOR(PyIBackgroundCopyError));
smyang2018/genometools
src/match/sfx-bentsedg.c
<gh_stars>1-10 /* Copyright (c) 2007 <NAME> <<EMAIL>> Copyright (c) 2007 Center for Bioinformatics, University of Hamburg Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <limits.h> #include <stdio.h> #include "core/assert_api.h" #include "core/chardef.h" #include "core/divmodmul.h" #include "core/minmax.h" #include "core/arraydef.h" #include "core/unused_api.h" #include "core/types_api.h" #include "core/encseq.h" #include "bcktab.h" #include "kmer2string.h" #include "sfx-radixsort.h" #include "sfx-bltrie.h" #include "sfx-copysort.h" #include "sfx-bentsedg.h" #include "sfx-lcpvalues.h" #include "sfx-suftaborder.h" #include "sfx-suffixgetset.h" #include "sfx-shortreadsort.h" #ifdef GT_THREADS_ENABLED #include "core/thread_api.h" #endif #define ACCESSCHARRAND(POS) gt_encseq_get_encoded_char(bsr->encseq,\ POS,bsr->readmode) #define ACCESSCHARSEQ(ESR) gt_encseq_reader_next_encoded_char(ESR) #define ISNOTEND(POS) ((POS) < bsr->totallength &&\ ISNOTSPECIAL(ACCESSCHARRAND(POS))) #define DEREFSTOPPOSSEQ(VAR,POS,STOPPOS,ESR)\ (((POS) < (STOPPOS) && ISNOTSPECIAL(VAR = ACCESSCHARSEQ(ESR))) ?\ ((GtUword) VAR) : GT_UNIQUEINT(POS)) #define DEREFSEQ(VAR,POS,ESR) DEREFSTOPPOSSEQ(VAR,POS,bsr->totallength,ESR) #define BS_SWAPARRAY(TMP,SUBBUCKETLEFT,IDX1,IDX2)\ if ((IDX1) != (IDX2))\ {\ TMP = gt_suffixsortspace_get(bsr->sssp,SUBBUCKETLEFT,IDX1);\ gt_suffixsortspace_set(bsr->sssp,SUBBUCKETLEFT,IDX1,\ gt_suffixsortspace_get(bsr->sssp,\ SUBBUCKETLEFT,\ IDX2));\ gt_suffixsortspace_set(bsr->sssp,SUBBUCKETLEFT,IDX2,TMP);\ } #define STACKTOP\ bsr->mkvauxstack.spaceGtMKVstack[bsr->mkvauxstack.nextfreeGtMKVstack] #define GT_BSR_UPDATELCP(MINVAL,MAXVAL,LCP)\ if ((MINVAL) > (LCP))\ {\ MINVAL = LCP;\ }\ GT_UPDATE_MAX(MAXVAL,LCP) #define CMPCHARBYCHARPTR2INT(VAR,SUBBUCKETLEFT,TMPVAR,IDX)\ VAR = (((cptr = gt_suffixsortspace_get(bsr->sssp,SUBBUCKETLEFT,IDX)+\ depth)\ < bsr->totallength &&\ ISNOTSPECIAL(TMPVAR = ACCESSCHARRAND(cptr)))\ ? ((GtUword) TMPVAR) : GT_UNIQUEINT(cptr)) typedef GtEndofTwobitencoding GtSfxcmp; #define PTR2INTSTOREPOS(TMPVAR,SUBBUCKETLEFT,IDX,POSASSIGNMENT)\ {\ GtUword pos\ = gt_suffixsortspace_get(bsr->sssp,SUBBUCKETLEFT,IDX);\ POSASSIGNMENT;\ TMPVAR.referstartpos = pos;\ if (pos + depth < bsr->totallength)\ {\ pos += depth;\ (void) gt_encseq_extract2bitencwithtwobitencodingstoppos(&(TMPVAR),\ bsr->esr1,\ bsr->encseq,\ bsr->readmode,\ pos);\ } else\ {\ TMPVAR.tbe = 0;\ TMPVAR.unitsnotspecial = 0;\ }\ } #define PTR2INT(TMPVAR,SUBBUCKETLEFT,IDX)\ PTR2INTSTOREPOS(TMPVAR,SUBBUCKETLEFT,IDX,/* Nothing */) #define Sfxdocompare(COMMONUNITS,X,Y)\ ret##X##Y = gt_encseq_compare_pairof_twobitencodings(bsr->fwd,\ bsr->complement,\ COMMONUNITS,&X,&Y) #define GtSfxcmpEQUAL(X,Y) ret##X##Y == 0 #define GtSfxcmpSMALLER(X,Y) ret##X##Y < 0 #define GtSfxcmpGREATER(X,Y) ret##X##Y > 0 typedef struct { GtUword subbucketleft, width, depth; } GtMKVstack; typedef struct { GtEndofTwobitencoding etbe; GtUword suftaboffset; } GtMedianinfo; typedef GtMedianinfo GtMedianElem; typedef struct { GtUword suffix; unsigned char lcpwithpivot; signed char cmpresult; } GtCountingsortinfo; GT_DECLAREARRAYSTRUCT(GtMKVstack); typedef struct { const GtEncseq *encseq; GtEncseqReader *esr1, *esr2; GtReadmode readmode; bool fwd, complement; GtArrayGtMKVstack mkvauxstack; GtLcpvalues *tableoflcpvalues; const Sfxstrategy *sfxstrategy; GtSuffixsortspace *sssp; GtProcessunsortedsuffixrange processunsortedsuffixrange; void *processunsortedsuffixrangeinfo; unsigned int sortmaxdepth, prefixlength; GtUword countinsertionsort, counttqsort, countshortreadsort, countradixsort, countcountingsort, countbltriesort, srs_maxremain, /* only relevant for short read sort */ radixsortminwidth, radixsortmaxwidth, totallength, shortreadsort_maxwidth, leftlcpdist[GT_UNITSIN2BITENC], rightlcpdist[GT_UNITSIN2BITENC]; bool *equalwithprevious; GtBlindtrie *blindtrie; GtMedianinfo *medianinfospace; GtCountingsortinfo *countingsortinfo; GtShortreadsortworkinfo *srsw; const GtTwobitencoding *twobitencoding; GtRadixsortstringinfo *rsi; } GtBentsedgresources; #ifdef WITHCHECKSTARTPOINTER static unsigned int checkstartpointorder(const GtUword *left, const GtUword *right) { const GtUword *ptr; bool ascending; gt_assert(left < right); gt_assert(*left != *(left+1)); ascending = (*left < *(left+1)) ? true : false; for (ptr = left+1; ptr < right; ptr++) { gt_assert(*ptr != *(ptr+1)); if (*ptr < *(ptr+1)) { if (!ascending) { return 0; } } else { if (*ptr > *(ptr+1)) { if (ascending) { return 0; } } } } return ascending ? 1U : 2U; } #endif static GtUword medianof3cmpcharbychar(const GtBentsedgresources *bsr, GtUword subbucketleft, GtUword depth, GtUword a, GtUword b, GtUword c) { GtUword vala, valb, valc, cptr; GtUchar tmpavar, tmpbvar; CMPCHARBYCHARPTR2INT(vala,subbucketleft,tmpavar,a); CMPCHARBYCHARPTR2INT(valb,subbucketleft,tmpbvar,b); if (vala == valb) { return a; } CMPCHARBYCHARPTR2INT(valc,subbucketleft,tmpavar,c); if (vala == valc || valb == valc) { return c; } return vala < valb ? (valb < valc ? b : (vala < valc ? c : a)) : (valb > valc ? b : (vala < valc ? a : c)); } static GtUword medianof3(const GtBentsedgresources *bsr, GtUword subbucketleft, GtUword depth, GtUword a, GtUword b, GtUword c) { GtSfxcmp vala, valb, valc; GtCommonunits commonunits; int retvalavalb, retvalavalc, retvalbvalc; PTR2INT(vala,subbucketleft,a); PTR2INT(valb,subbucketleft,b); Sfxdocompare(&commonunits,vala,valb); if (GtSfxcmpEQUAL(vala,valb)) { return a; } PTR2INT(valc,subbucketleft,c); Sfxdocompare(&commonunits,vala,valc); if (GtSfxcmpEQUAL(vala,valc)) { return c; } Sfxdocompare(&commonunits,valb,valc); if (GtSfxcmpEQUAL(valb,valc)) { return c; } return GtSfxcmpSMALLER(vala,valb) ? (GtSfxcmpSMALLER(valb,valc) ? b : (GtSfxcmpSMALLER(vala,valc) ? c : a)) : (GtSfxcmpGREATER(valb,valc) ? b : (GtSfxcmpSMALLER(vala,valc) ? a : c)); } static void bs_insertionsort(GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword offset) { GtUword sval1, sval2, pm, pl, startpos1, startpos2, lcplen = 0; int retval; GtCommonunits commonunits; bsr->countinsertionsort++; for (pm = 1UL; pm < width; pm++) { for (pl = pm; pl > 0; pl--) { sval1 = gt_suffixsortspace_get(bsr->sssp,subbucketleft,pl-1); sval2 = gt_suffixsortspace_get(bsr->sssp,subbucketleft,pl); if (bsr->sfxstrategy->cmpcharbychar) { startpos1 = sval1 + offset; if (startpos1 < bsr->totallength) { gt_encseq_reader_reinit_with_readmode(bsr->esr1, bsr->encseq, bsr->readmode, startpos1); } startpos2 = sval2 + offset; if (startpos2 < bsr->totallength) { gt_encseq_reader_reinit_with_readmode(bsr->esr2, bsr->encseq, bsr->readmode, startpos2); } for (;;) { GtUword ccs, cct; GtUchar tmp1, tmp2; ccs = DEREFSEQ(tmp1,startpos1,bsr->esr1); cct = DEREFSEQ(tmp2,startpos2,bsr->esr2); if (ccs != cct) { lcplen = startpos2 - sval2; retval = (ccs < cct) ? -1 : 1; break; } startpos1++; startpos2++; } } else { #ifdef SKDEBUG printf("%s["GT_WU","GT_WU"] at offset" GT_WU"\n",__func__,sval1,sval2,offset); gt_encseq_showatstartpos(stdout, bsr->fwd, bsr->complement, bsr->encseq, sval1); gt_encseq_showatstartpos(stdout, bsr->fwd, bsr->complement, bsr->encseq, sval2); #endif retval = gt_encseq_compare_viatwobitencoding(&commonunits, bsr->encseq, bsr->encseq, bsr->readmode, bsr->esr1, bsr->esr2, sval1, sval2, offset, 0); lcplen = commonunits.finaldepth; } gt_assert(retval != 0); if (bsr->tableoflcpvalues != NULL) { if (pl < pm && retval > 0) { gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,pl+1, gt_lcptab_getvalue(bsr->tableoflcpvalues, subbucketleft,pl)); } gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,pl,lcplen); } if (retval < 0) { break; } gt_suffixsortspace_set(bsr->sssp,subbucketleft,pl-1,sval2); gt_suffixsortspace_set(bsr->sssp,subbucketleft,pl,sval1); } } } static void bs_insertionsortmaxdepth(GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword offset, GtUword sortmaxdepth) { GtUword sval1, sval2, pm, pl, startpos1, startpos2, lcplen = 0, idx = 0; int retval; bool tempb; GtCommonunits commonunits; bsr->countinsertionsort++; for (pm = 1UL; pm < width; pm++) { for (pl = pm; pl > 0; pl--) { sval1 = gt_suffixsortspace_get(bsr->sssp,subbucketleft,pl-1); sval2 = gt_suffixsortspace_get(bsr->sssp,subbucketleft,pl); if (bsr->sfxstrategy->cmpcharbychar) { GtUword endpos1, endpos2; endpos1 = sval1+sortmaxdepth; if (endpos1 > bsr->totallength) { endpos1 = bsr->totallength; } endpos2 = sval2+sortmaxdepth; if (endpos2 > bsr->totallength) { endpos2 = bsr->totallength; } startpos1 = sval1+offset; if (startpos1 < bsr->totallength) { gt_encseq_reader_reinit_with_readmode(bsr->esr1, bsr->encseq, bsr->readmode, startpos1); } startpos2 = sval2+offset; if (startpos2 < bsr->totallength) { gt_encseq_reader_reinit_with_readmode(bsr->esr2, bsr->encseq, bsr->readmode, startpos2); } for (;;) { GtUword ccs, cct; GtUchar tmp1, tmp2; ccs = DEREFSTOPPOSSEQ(tmp1,startpos1,endpos1,bsr->esr1); cct = DEREFSTOPPOSSEQ(tmp2,startpos2,endpos2,bsr->esr2); lcplen = startpos2 - sval2; if (lcplen == sortmaxdepth) { retval = 0; break; } gt_assert(lcplen < sortmaxdepth); if (ccs != cct) { retval = (ccs < cct) ? -1 : 1; break; } startpos1++; startpos2++; } } else { gt_assert(offset < sortmaxdepth); retval = gt_encseq_compare_viatwobitencoding(&commonunits, bsr->encseq, bsr->encseq, bsr->readmode, bsr->esr1, bsr->esr2, sval1, sval2, offset, sortmaxdepth); lcplen = commonunits.finaldepth; gt_assert(lcplen <= sortmaxdepth); if (lcplen == sortmaxdepth) { gt_assert(retval == 0); } } #ifdef SKDEBUG printf("cmp "GT_WU" and "GT_WU": retval = %d, lcplen = "GT_WU"\n", sval1, sval2, retval, (GtUword) lcplen); #endif if (bsr->tableoflcpvalues != NULL) { if (pl < pm && retval > 0) { gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,pl+1, gt_lcptab_getvalue(bsr->tableoflcpvalues, subbucketleft,pl)); } gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,pl,lcplen); } if (retval < 0) { break; } idx = pl; if (retval == 0) { gt_assert(idx > 0); bsr->equalwithprevious[idx] = true; break; } gt_suffixsortspace_set(bsr->sssp,subbucketleft,pl-1,sval2); gt_suffixsortspace_set(bsr->sssp,subbucketleft,pl,sval1); tempb = bsr->equalwithprevious[idx-1]; bsr->equalwithprevious[idx-1] = bsr->equalwithprevious[idx]; bsr->equalwithprevious[idx] = tempb; } } if (idx > 0) { GtUword equalsrangewidth = 0, bucketleftidx = gt_suffixsortspace_bucketleftidx_get(bsr->sssp); #ifdef SKDEBUG printf("ordered suffix "GT_WU"\n",gt_suffixsortspace_get(bsr->sssp, subbucketleft,0)); #endif for (idx = 1UL; idx < width; idx++) { #ifdef SKDEBUG printf("ordered suffix "GT_WU", equalwithprevious=%s\n", gt_suffixsortspace_get(bsr->sssp,subbucketleft,idx), bsr->equalwithprevious[idx] ? "true" : "false"); #endif if (bsr->equalwithprevious[idx]) { bsr->equalwithprevious[idx] = false; equalsrangewidth++; } else { if (equalsrangewidth > 0) { #ifdef SKDEBUG printf("process interval of width "GT_WU"\n", equalsrangewidth + 1); #endif if (bsr->processunsortedsuffixrange != NULL) { bsr->processunsortedsuffixrange(bsr->processunsortedsuffixrangeinfo, bsr->sssp, bucketleftidx + subbucketleft + idx - 1 - equalsrangewidth, equalsrangewidth + 1, sortmaxdepth); } equalsrangewidth = 0; } } } if (equalsrangewidth > 0) { #ifdef SKDEBUG printf("process interval of width "GT_WU"\n", equalsrangewidth + 1); #endif if (bsr->processunsortedsuffixrange != NULL) { bsr->processunsortedsuffixrange(bsr->processunsortedsuffixrangeinfo, bsr->sssp, bucketleftidx + subbucketleft + width - 1 - equalsrangewidth, equalsrangewidth + 1, sortmaxdepth); } } } } #define DOMEDIANCOMPARE(A,B)\ gt_encseq_compare_pairof_twobitencodings(fwd,complement,&commonunits,\ &((A)->etbe),&((B)->etbe)) #define GT_MedianElemGREATER(A,B) (DOMEDIANCOMPARE(A,B) > 0) #define GT_MedianElemSWAP(A,B) {\ register GtMedianElem tmp = *(A);\ *(A) = *(B);\ *(B) = tmp;\ } /* * This Quickselect routine is based on the algorithm described in * "Numerical recipes in C", Second Edition, * Cambridge University Press, 1992, Section 8.5, ISBN 0-521-43108-5 * This code by <NAME> - 1998. Public domain. */ static GtMedianElem *quickmedian (bool fwd,bool complement, GtMedianElem *arr,GtUword width) { GtMedianElem *low, *high, *median, *middle, *ll, *hh; GtCommonunits commonunits; gt_assert(width > 0); low = arr; high = arr + width - 1; median = low + GT_DIV2(width); for (;;) { if (high <= low) /* One element only */ { return median; } if (high == low + 1) { /* Two elements only */ if (GT_MedianElemGREATER(low,high)) { GT_MedianElemSWAP (low, high); } return median; } /* Find median of low, middle and high items; swap into position low */ middle = low + GT_DIV2(high - low + 1); if (GT_MedianElemGREATER(middle,high)) { GT_MedianElemSWAP (middle, high); } if (GT_MedianElemGREATER(low,high)) { GT_MedianElemSWAP (low, high); } if (GT_MedianElemGREATER(middle,low)) { GT_MedianElemSWAP (middle, low); } /* Swap low item (now in position middle) into position (low+1) */ GT_MedianElemSWAP (middle, low + 1); /* Nibble from each end towards middle, swapping items when stuck */ ll = low + 1; hh = high; for (;;) { do { ll++; } while (GT_MedianElemGREATER(low,ll)); do { hh--; } while (GT_MedianElemGREATER(hh,low)); if (hh < ll) { break; } GT_MedianElemSWAP (ll, hh); } /* Swap middle item (in position low) back into correct position */ GT_MedianElemSWAP (low, hh); /* Re-set active partition */ if (hh <= median) { low = ll; } if (hh >= median) { high = hh - 1; } } } #ifdef WITHcheckmedian static void checkmedian(bool fwd, bool complement, const GtMedianinfo *median, const GtMedianinfo *space, GtUword width) { GtUword sum1, sum2, idx, smaller = 0, larger = 0, equal = 0, equalpart; unsigned int commonunits; int cmp; for (idx = 0; idx < width; idx++) { cmp = DOMEDIANCOMPARE(space + idx,median); if (cmp > 0) { larger++; } else { if (cmp < 0) { smaller++; } else { equal++; } } } if (smaller == larger) { return; } for (equalpart = 0; equalpart < equal; equalpart++) { sum1 = smaller + equalpart; sum2 = larger + (equal-1) - equalpart; if (sum1 < sum2) { if (sum1 + 1 == sum2) { return; } } else { if (sum1 > sum2) { if (sum1 == sum2 + 1) { return; } } else { return; } } } fprintf(stderr,"problem with equal="GT_WU",smaller="GT_WU",larger="GT_WU"\n", equal,smaller,larger); exit(GT_EXIT_PROGRAMMING_ERROR); } #endif static GtUword realmedian(const GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword depth) { GtMedianinfo *medianptr; GtUword idx; for (idx = 0; idx < width; idx++) { bsr->medianinfospace[idx].suftaboffset = idx; PTR2INT(bsr->medianinfospace[idx].etbe,subbucketleft,idx); } medianptr = quickmedian(bsr->fwd,bsr->complement,bsr->medianinfospace,width); /* checkmedian(bsr->fwd,bsr->complement,medianptr,medianinfospace,width); */ gt_assert(medianptr != NULL); return medianptr->suftaboffset; } #define MINMEDIANOF9WIDTH 31UL static GtUword cmpcharbychardelivermedian(const GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword depth) { GtUword pl = 0, pm = GT_DIV2(width), pr = width - 1; if (width >= MINMEDIANOF9WIDTH) { /* On big arrays, pseudomedian of 9 */ GtUword offset, doubleoffset; offset = GT_DIV8(width); doubleoffset = GT_MULT2(offset); pl = medianof3cmpcharbychar(bsr,subbucketleft,depth,pl,pl+offset, pl+doubleoffset); pm = medianof3cmpcharbychar(bsr,subbucketleft,depth,pm-offset, pm,pm+offset); pr = medianof3cmpcharbychar(bsr,subbucketleft,depth, pr-doubleoffset,pr-offset, pr); } return medianof3cmpcharbychar(bsr,subbucketleft,depth,pl,pm,pr); } static GtUword blockcmpdelivermedian(const GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword depth, GtUword maxwidthrealmedian) { GtUword pl = 0, pm = GT_DIV2(width), pr = width - 1; if (width >= MINMEDIANOF9WIDTH) { if (width > maxwidthrealmedian) { /* On big arrays, pseudomedian of 9 */ GtUword offset, doubleoffset; offset = GT_DIV8(width); doubleoffset = GT_MULT2(offset); pl = medianof3(bsr,subbucketleft,depth,pl,pl+offset, pl+doubleoffset); pm = medianof3(bsr,subbucketleft,depth,pm-offset,pm,pm+offset); pr = medianof3(bsr,subbucketleft,depth,pr-doubleoffset, pr-offset,pr); pm = medianof3(bsr,subbucketleft,depth,pl,pm,pr); } else /* width <= maxwidthrealmedian */ { pm = realmedian(bsr, subbucketleft,width, depth); } } else { pm = medianof3(bsr,subbucketleft,depth,pl,pm,pr); } return pm; } /* static void showcountingsortinfo(const GtCountingsortinfo *countingsortinfo, GtUword idx) { printf("countingsortinfo["GT_WU"]=("GT_WU",",idx, (GtUword) countingsortinfo[idx].suffix); printf(""GT_WU",",(GtUword) countingsortinfo[idx].lcpwithpivot); printf("%d)\n",countingsortinfo[idx].cmpresult); } */ static bool multistrategysort(GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword depth, GtUword sortmaxdepth) { gt_assert(width > 1UL); if (width <= bsr->sfxstrategy->maxinsertionsort) { if (sortmaxdepth == 0) { bs_insertionsort(bsr,subbucketleft,width,depth); } else { bs_insertionsortmaxdepth(bsr,subbucketleft,width,depth,sortmaxdepth); } return true; } if (width <= bsr->sfxstrategy->maxbltriesort) { gt_blindtrie_suffixsort(bsr->blindtrie, subbucketleft, bsr->tableoflcpvalues, width, depth, sortmaxdepth, bsr->processunsortedsuffixrange, bsr->processunsortedsuffixrangeinfo); bsr->countbltriesort++; return true; } return false; } static void subsort_bentleysedgewick(GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, GtUword depth) { gt_assert(width > 1UL); if (width > 1UL) { #ifdef SKDEBUG if (depth > 0) { gt_checkifprefixesareidentical(__FILE__, __LINE__, bsr->encseq, bsr->readmode, bsr->sssp, subbucketleft, width, depth); } #endif if (bsr->rsi != NULL && width >= bsr->radixsortminwidth && width <= bsr->radixsortmaxwidth) { gt_sfx_radixsort_str(bsr->rsi, depth, bsr->sortmaxdepth, subbucketleft, width, bsr->sssp, bsr->tableoflcpvalues); bsr->countradixsort++; return; } if (bsr->srsw != NULL && !bsr->sfxstrategy->noshortreadsort && width <= bsr->shortreadsort_maxwidth) { gt_shortreadsort_sssp_sort(bsr->srsw, bsr->encseq, bsr->srs_maxremain, bsr->readmode, bsr->esr1, bsr->sssp, subbucketleft, width, depth, (GtUword) bsr->sortmaxdepth); if (bsr->sortmaxdepth > 0) { gt_shortreadsort_sssp_add_unsorted( bsr->srsw, gt_suffixsortspace_bucketleftidx_get(bsr->sssp), subbucketleft, width, (GtUword) bsr->sortmaxdepth, bsr->sssp, bsr->processunsortedsuffixrange, bsr->processunsortedsuffixrangeinfo); } bsr->countshortreadsort++; return; } if (bsr->sortmaxdepth > 0 && depth >= (GtUword) bsr->sortmaxdepth) { if (bsr->processunsortedsuffixrange != NULL) { bsr->processunsortedsuffixrange( bsr->processunsortedsuffixrangeinfo, bsr->sssp, gt_suffixsortspace_bucketleftidx_get(bsr->sssp) + subbucketleft, width,depth); } return; } if (multistrategysort(bsr,subbucketleft,width,depth, (GtUword) bsr->sortmaxdepth)) { return; } /* push */ GT_CHECKARRAYSPACE(&bsr->mkvauxstack,GtMKVstack,1024); STACKTOP.subbucketleft = subbucketleft; STACKTOP.width = width; STACKTOP.depth = depth; bsr->mkvauxstack.nextfreeGtMKVstack++; } } static void sarrcountingsort(GtBentsedgresources *bsr, GtUword subbucketleft, GtUword width, const GtSfxcmp *pivotcmpbits, GtUword pivotidx, GtUword depth) { int cmp; unsigned int maxsmallerwithlcp = 0, maxlargerwithlcp = 0; GtCommonunits commonunits; GtEndofTwobitencoding etbecurrent; GtUword idx, smaller = 0, larger = 0, insertindex, end, equaloffset, currentwidth; GtCountingsortinfo *csiptr; /* const bool cmpcharbychar = false; */ bsr->countcountingsort++; for (idx = 0; idx < width; idx++) { if (idx != pivotidx) { PTR2INTSTOREPOS(etbecurrent,subbucketleft,idx, bsr->countingsortinfo[idx].suffix = pos); cmp = gt_encseq_compare_pairof_twobitencodings(bsr->fwd, bsr->complement, &commonunits, &etbecurrent, pivotcmpbits); gt_assert(commonunits.common <= (unsigned int) GT_UNITSIN2BITENC); bsr->countingsortinfo[idx].lcpwithpivot = commonunits.common; if (cmp > 0) { gt_assert(commonunits.common < (unsigned int) GT_UNITSIN2BITENC); bsr->rightlcpdist[commonunits.common]++; if (maxlargerwithlcp < commonunits.common) { maxlargerwithlcp = commonunits.common; } bsr->countingsortinfo[idx].cmpresult = (char) 1; larger++; } else { if (cmp < 0) { gt_assert(commonunits.common < (unsigned int) GT_UNITSIN2BITENC); bsr->leftlcpdist[commonunits.common]++; if (maxsmallerwithlcp < commonunits.common) { maxsmallerwithlcp = commonunits.common; } bsr->countingsortinfo[idx].cmpresult = (char) -1; smaller++; } else { gt_assert(commonunits.common == (unsigned int) GT_UNITSIN2BITENC); bsr->countingsortinfo[idx].cmpresult = 0; } } } else { bsr->countingsortinfo[idx].suffix = gt_suffixsortspace_get(bsr->sssp,subbucketleft,idx); bsr->countingsortinfo[idx].lcpwithpivot = (unsigned char) GT_UNITSIN2BITENC; bsr->countingsortinfo[idx].cmpresult = (char) 0; } } for (idx = 1UL; idx <= (GtUword) maxsmallerwithlcp; idx++) { bsr->leftlcpdist[idx] += bsr->leftlcpdist[idx-1]; } for (idx = 1UL; idx <= (GtUword) maxlargerwithlcp; idx++) { bsr->rightlcpdist[idx] += bsr->rightlcpdist[idx-1]; } equaloffset = width - larger; for (csiptr = bsr->countingsortinfo + width -1; csiptr >= bsr->countingsortinfo; csiptr--) { switch (csiptr->cmpresult) { case -1: insertindex = --(bsr->leftlcpdist[csiptr->lcpwithpivot]); gt_suffixsortspace_set(bsr->sssp,subbucketleft,insertindex, csiptr->suffix); break; case 0: gt_suffixsortspace_set(bsr->sssp,subbucketleft,--equaloffset, csiptr->suffix); break; case 1: insertindex = --(bsr->rightlcpdist[csiptr->lcpwithpivot]); gt_suffixsortspace_set(bsr->sssp,subbucketleft, width - 1 - insertindex, csiptr->suffix); break; } } for (idx = 0; idx <= (GtUword) maxsmallerwithlcp; idx++) { if (idx < (GtUword) maxsmallerwithlcp) { end = bsr->leftlcpdist[idx+1]; } else { end = smaller; } if (bsr->leftlcpdist[idx] + 1 < end) /* at least two elements */ { currentwidth = end - bsr->leftlcpdist[idx]; subsort_bentleysedgewick(bsr, subbucketleft + bsr->leftlcpdist[idx], currentwidth, depth + idx); } if (bsr->tableoflcpvalues != NULL && bsr->leftlcpdist[idx] < end) { /* at least one element */ gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,end,depth + idx); } bsr->leftlcpdist[idx] = 0; } if (width - smaller - larger > 1UL) { currentwidth = width - smaller - larger; subsort_bentleysedgewick(bsr, subbucketleft + smaller, currentwidth, depth + GT_UNITSIN2BITENC); } for (idx = 0; idx <= (GtUword) maxlargerwithlcp; idx++) { if (idx < (GtUword) maxlargerwithlcp) { end = bsr->rightlcpdist[idx+1]; } else { end = larger; } if (bsr->rightlcpdist[idx] + 1 < end) /* at least two elements */ { currentwidth = end - bsr->rightlcpdist[idx]; subsort_bentleysedgewick(bsr, /* for largest idx use first bucket */ subbucketleft + width - end, currentwidth, depth + idx); } if (bsr->tableoflcpvalues != NULL && bsr->rightlcpdist[idx] < end) { /* at least one element */ gt_assert(width >= end); gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,width - end, depth + idx); } bsr->rightlcpdist[idx] = 0; } } static inline void vectorswap(GtSuffixsortspace *sssp, GtUword subbucketleft1, GtUword subbucketleft2, GtUword width) { GtUword idx, tmp; for (idx = 0; idx < width; idx++) { tmp = gt_suffixsortspace_get(sssp,subbucketleft1,idx); gt_suffixsortspace_set(sssp,subbucketleft1,idx, gt_suffixsortspace_get(sssp,subbucketleft2,idx)); gt_suffixsortspace_set(sssp,subbucketleft2,idx,tmp); } } static void gt_sort_bentleysedgewick(GtBentsedgresources *bsr, GtUword bucketleftidx, GtUword width, GtUword depth) { bsr->mkvauxstack.nextfreeGtMKVstack = 0; gt_suffixsortspace_bucketrange_set(bsr->sssp,bucketleftidx,width); subsort_bentleysedgewick(bsr, 0, width, depth); while (bsr->mkvauxstack.nextfreeGtMKVstack > 0) { GtUword leftplusw, pa, pb, pc, pd, pm, bucketright, cptr, temp, pivotcmpcharbychar = 0, valcmpcharbychar, wtmp, subbucketleft; unsigned int smallermaxlcp, greatermaxlcp, smallerminlcp, greaterminlcp; GtSfxcmp pivotcmpbits, val; int retvalpivotcmpbits; GtUchar tmpvar; GtCommonunits commonunits; const int commonunitsequal = bsr->sfxstrategy->cmpcharbychar ? 1 : GT_UNITSIN2BITENC; /* pop */ bsr->mkvauxstack.nextfreeGtMKVstack--; subbucketleft = STACKTOP.subbucketleft; width = STACKTOP.width; depth = STACKTOP.depth; bucketright = width - 1; if (bsr->sfxstrategy->cmpcharbychar) { pm = cmpcharbychardelivermedian(bsr, subbucketleft, width, depth); BS_SWAPARRAY(temp, subbucketleft, 0, pm); CMPCHARBYCHARPTR2INT(pivotcmpcharbychar, subbucketleft,tmpvar,0); } else { pm = blockcmpdelivermedian(bsr, subbucketleft, width, depth, bsr->sfxstrategy->maxwidthrealmedian); if (width <= bsr->sfxstrategy->maxcountingsort && width >= MINMEDIANOF9WIDTH) { PTR2INT(pivotcmpbits,subbucketleft,pm); gt_assert(width >= bsr->sfxstrategy->maxbltriesort); sarrcountingsort(bsr, subbucketleft, width, &pivotcmpbits, pm, depth); /* new values for subbucketleft, bucketright, depth */ continue; } BS_SWAPARRAY(temp, subbucketleft, 0, pm); PTR2INT(pivotcmpbits,subbucketleft,0UL); } bsr->counttqsort++; /* now pivot element is at index subbucketleft */ /* all elements to be compared are between pb and pc */ /* pa is the position at which the next element smaller than the pivot element is inserted at */ /* pd is the position at which the next element greater than the pivot element is inserted at */ pa = pb = 1UL; pc = pd = bucketright; if (bsr->sfxstrategy->cmpcharbychar) { smallerminlcp = greaterminlcp = smallermaxlcp = greatermaxlcp = 0; for (;;) { while (pb <= pc) { CMPCHARBYCHARPTR2INT(valcmpcharbychar,subbucketleft,tmpvar,pb); if (valcmpcharbychar > pivotcmpcharbychar) { break; } if (valcmpcharbychar == pivotcmpcharbychar) { BS_SWAPARRAY(temp, subbucketleft, pa, pb); pa++; } pb++; } while (pb <= pc) { CMPCHARBYCHARPTR2INT(valcmpcharbychar,subbucketleft,tmpvar,pc); if (valcmpcharbychar < pivotcmpcharbychar) { /* stop for elements < pivot */ break; } if (valcmpcharbychar == pivotcmpcharbychar) { /* exchange equal element and element at index pd */ BS_SWAPARRAY(temp, subbucketleft, pc, pd); pd--; } pc--; } if (pb > pc) { /* no elements to compare to pivot */ break; } BS_SWAPARRAY(temp, subbucketleft, pb, pc); pb++; pc--; } } else { smallermaxlcp = greatermaxlcp = 0; smallerminlcp = greaterminlcp = (unsigned int) GT_UNITSIN2BITENC; for (;;) { /* look for elements identical or smaller than pivot from left */ while (pb <= pc) { PTR2INT(val,subbucketleft,pb); Sfxdocompare(&commonunits,val,pivotcmpbits); if (GtSfxcmpGREATER(val,pivotcmpbits)) { /* stop for elements val > pivot */ GT_BSR_UPDATELCP(greaterminlcp,greatermaxlcp,commonunits.common); break; } if (GtSfxcmpEQUAL(val,pivotcmpbits)) { /* exchange equal element and element at index pa */ BS_SWAPARRAY(temp, subbucketleft, pa, pb); pa++; } else /* smaller */ { GT_BSR_UPDATELCP(smallerminlcp,smallermaxlcp,commonunits.common); } pb++; } /* look for elements identical or greater than pivot from right */ while (pb <= pc) { PTR2INT(val,subbucketleft,pc); Sfxdocompare(&commonunits,val,pivotcmpbits); if (GtSfxcmpSMALLER(val,pivotcmpbits)) { /* stop for elements val < pivot */ GT_BSR_UPDATELCP(smallerminlcp,smallermaxlcp,commonunits.common); break; } if (GtSfxcmpEQUAL(val,pivotcmpbits)) { /* exchange equal element and element at index pa */ BS_SWAPARRAY(temp, subbucketleft, pc, pd); pd--; } else /* greater */ { GT_BSR_UPDATELCP(greaterminlcp,greatermaxlcp,commonunits.common); } pc--; } if (pb > pc) { /* interval is empty */ break; } BS_SWAPARRAY(temp, subbucketleft, pb, pc); pb++; pc--; } } gt_assert(pb >= pa); wtmp = MIN(pa,pb-pa); /* move w elements at the left to the middle */ gt_assert(pb >= wtmp && wtmp <= pb - wtmp); vectorswap(bsr->sssp, subbucketleft, subbucketleft+pb-wtmp, wtmp); gt_assert(pd >= pc); gt_assert(bucketright >= pd); wtmp = MIN(pd-pc, bucketright-pd); /* move w elements at the right to the middle */ gt_assert(bucketright + 1 >= wtmp && pb + wtmp <= bucketright+1-wtmp); vectorswap(bsr->sssp, subbucketleft+pb, subbucketleft+bucketright+1-wtmp, wtmp); /* all elements equal to the pivot are now in the middle namely in the range [subbucketleft + (pb-pa) and bucketright - (pd-pc)] */ /* hence we have to sort the elements in the intervals [subbucketleft..subbucketleft+(pb-pa)-1] and [bucketright-(pd-pc)+1..bucketright] */ gt_assert(pb >= pa); if ((wtmp = pb-pa) > 0) { leftplusw = wtmp; if (bsr->tableoflcpvalues != NULL) { /* left part has suffix with lcp up to length smallermaxlcp w.r.t. to the pivot. This lcp belongs to a suffix on the left which is at a minimum distance to the pivot and thus to an element in the final part of the left side. */ gt_lcptab_update(bsr->tableoflcpvalues,subbucketleft,leftplusw, depth + smallermaxlcp); } if (wtmp > 1UL) { subsort_bentleysedgewick(bsr, subbucketleft, wtmp, depth + smallerminlcp); } } else { leftplusw = 0; } cptr = gt_suffixsortspace_get(bsr->sssp,subbucketleft,leftplusw) + depth; if (ISNOTEND(cptr) && (wtmp = bucketright-(pd-pb)-leftplusw) > 1UL) { subsort_bentleysedgewick(bsr, subbucketleft + leftplusw, wtmp, depth+commonunitsequal); } gt_assert(pd >= pc); if ((wtmp = (GtUword) (pd-pc)) > 0) { if (bsr->tableoflcpvalues != NULL) { /* right part has suffix with lcp up to length largermaxlcp w.r.t. to the pivot. This lcp belongs to a suffix on the right which is at a minimum distance to the pivot and thus to an element in the first part of the right side. */ gt_lcptab_update(bsr->tableoflcpvalues, subbucketleft,bucketright - wtmp + 1, depth + greatermaxlcp); } if (wtmp > 1UL) { subsort_bentleysedgewick(bsr, subbucketleft + bucketright - wtmp + 1, wtmp, depth + greaterminlcp); } } } gt_suffixsortspace_bucketrange_reset(bsr->sssp); } static GtBentsedgresources *bentsedgresources_new( GtSuffixsortspace *suffixsortspace, const GtEncseq *encseq, GtReadmode readmode, unsigned int prefixlength, const GtBcktab *bcktab, unsigned int sortmaxdepth, const Sfxstrategy *sfxstrategy, bool withlcps) { GtBentsedgresources *bsr = (GtBentsedgresources *) gt_malloc(sizeof *bsr); bsr->encseq = encseq; bsr->readmode = readmode; bsr->totallength = gt_encseq_total_length(encseq); bsr->sfxstrategy = sfxstrategy; bsr->sssp = suffixsortspace; bsr->rsi = NULL; bsr->fwd = GT_ISDIRREVERSE(bsr->readmode) ? false : true; bsr->complement = GT_ISDIRCOMPLEMENT(bsr->readmode) ? true : false; bsr->tableoflcpvalues = NULL; bsr->prefixlength = prefixlength; bsr->esr1 = gt_encseq_create_reader_with_readmode(encseq, readmode, 0); bsr->esr2 = gt_encseq_create_reader_with_readmode(encseq, readmode, 0); bsr->radixsortminwidth = gt_radixsort_str_minwidth(); bsr->radixsortmaxwidth = 0; if (gt_encseq_accesstype_get(bsr->encseq) == GT_ACCESS_TYPE_EQUALLENGTH) { bsr->twobitencoding = gt_encseq_twobitencoding_export(bsr->encseq); } else { bsr->twobitencoding = NULL; } if (sortmaxdepth > 0) { if (sortmaxdepth > prefixlength) { bsr->srs_maxremain = sortmaxdepth - (GtUword) prefixlength; } else { bsr->srs_maxremain = 0; } } else { GtUword longestnsp = gt_encseq_lengthoflongestnonspecial(encseq); if (longestnsp > (GtUword) prefixlength) { bsr->srs_maxremain = longestnsp - prefixlength; } else { bsr->srs_maxremain = 0; } } bsr->shortreadsort_maxwidth = gt_shortreadsort_maxwidth(false, bsr->srs_maxremain, gt_size_of_sort_workspace (sfxstrategy)); GT_INITARRAY(&bsr->mkvauxstack,GtMKVstack); bsr->countingsortinfo = NULL; bsr->medianinfospace = NULL; bsr->blindtrie = NULL; bsr->equalwithprevious = NULL; bsr->srsw = NULL; if (!sfxstrategy->cmpcharbychar) { int idx; const bool withmediumsizelcps = (sortmaxdepth > 0 && !withlcps) ? true : false; if (sortmaxdepth == 0 || gt_encseq_has_twobitencoding_stoppos_support(encseq)) { bsr->srsw = gt_shortreadsort_new(0,bsr->srs_maxremain,readmode,false, withmediumsizelcps); } for (idx = 0; idx < GT_UNITSIN2BITENC; idx++) { bsr->leftlcpdist[idx] = bsr->rightlcpdist[idx] = 0; } bsr->countingsortinfo = gt_malloc(sizeof (*bsr->countingsortinfo) * sfxstrategy->maxcountingsort); if (sfxstrategy->maxwidthrealmedian >= MINMEDIANOF9WIDTH) { bsr->medianinfospace = gt_malloc(sizeof (*bsr->medianinfospace) * sfxstrategy->maxwidthrealmedian); } else { bsr->medianinfospace = NULL; } } bsr->blindtrie = gt_blindtrie_new(bsr->sssp, sfxstrategy->maxbltriesort, 0, /* the nodenumberincrement */ encseq, sfxstrategy->cmpcharbychar, bsr->esr1, bsr->esr2, readmode); if (sortmaxdepth > 0 && bsr->sfxstrategy->maxinsertionsort >= 2UL) { GtUword idx; bsr->equalwithprevious = gt_malloc(sizeof (*bsr->equalwithprevious) * bsr->sfxstrategy->maxinsertionsort); for (idx=0; idx < bsr->sfxstrategy->maxinsertionsort; idx++) { bsr->equalwithprevious[idx] = false; } } bsr->sortmaxdepth = sortmaxdepth; bsr->processunsortedsuffixrange = NULL; bsr->processunsortedsuffixrangeinfo = NULL; bsr->countinsertionsort = 0; bsr->counttqsort = 0; bsr->countcountingsort = 0; bsr->countbltriesort = 0; bsr->countshortreadsort = 0; bsr->countradixsort = 0; if (bcktab != NULL && sfxstrategy->withradixsort && gt_encseq_accesstype_get(encseq) == GT_ACCESS_TYPE_EQUALLENGTH && readmode == GT_READMODE_FORWARD) { bsr->rsi = gt_radixsort_str_new(bsr->twobitencoding, gt_encseq_is_mirrored(encseq) ? GT_DIV2(bsr->totallength - 1) : bsr->totallength, 1 + gt_encseq_equallength(encseq), gt_bcktab_nonspecialsmaxsize(bcktab)); bsr->radixsortmaxwidth = gt_radixsort_str_maxwidth(bsr->rsi); } return bsr; } static void gt_bentsedgresources_addlcpinfo(GtBentsedgresources *bsr, GtOutlcpinfo *outlcpinfo, const GtBcktab *bcktab) { if (outlcpinfo != NULL) { bsr->tableoflcpvalues = gt_Outlcpinfo_resizereservoir(outlcpinfo,bcktab); if (bsr->srsw != NULL) { gt_shortreadsort_assigntableoflcpvalues(bsr->srsw,bsr->tableoflcpvalues); } } } size_t gt_size_of_sort_workspace (const Sfxstrategy *sfxstrategy) { size_t sumsize = 0; if (!sfxstrategy->cmpcharbychar) { sumsize += sizeof (GtCountingsortinfo) * sfxstrategy->maxcountingsort; if (sfxstrategy->maxwidthrealmedian >= MINMEDIANOF9WIDTH) { sumsize += sizeof (GtMedianinfo) * sfxstrategy->maxwidthrealmedian; } } sumsize += gt_blindtrie_size(sfxstrategy->maxbltriesort); return sumsize; } static void bentsedgresources_delete(GtBentsedgresources *bsr, GtLogger *logger) { gt_free(bsr->countingsortinfo); bsr->countingsortinfo = NULL; gt_free(bsr->medianinfospace); bsr->medianinfospace = NULL; gt_shortreadsort_delete(bsr->srsw); bsr->srsw = NULL; gt_blindtrie_delete(bsr->blindtrie); gt_encseq_reader_delete(bsr->esr1); gt_encseq_reader_delete(bsr->esr2); gt_free(bsr->equalwithprevious); GT_FREEARRAY(&bsr->mkvauxstack,GtMKVstack); gt_radixsort_str_delete(bsr->rsi); gt_logger_log(logger,"countinsertionsort="GT_WU"",bsr->countinsertionsort); gt_logger_log(logger,"countbltriesort="GT_WU"",bsr->countbltriesort); gt_logger_log(logger,"countcountingsort="GT_WU"",bsr->countcountingsort); gt_logger_log(logger,"countshortreadsort="GT_WU"",bsr->countshortreadsort); gt_logger_log(logger,"countradixsort="GT_WU"",bsr->countradixsort); gt_logger_log(logger,"counttqsort="GT_WU"",bsr->counttqsort); gt_free(bsr); } /* The following function is called in sfx-suffixer.c and sorts all buckets by different suffix comparison methods without the help of other sorting information. GtSuffixsortspace contains the sortspace which is accessed by some negative offset. */ void gt_sortallbuckets(GtSuffixsortspace *suffixsortspace, GtUword numberofsuffixes, GtBucketspec2 *bucketspec2, const GtEncseq *encseq, GtReadmode readmode, GtCodetype mincode, GtCodetype maxcode, const GtBcktab *bcktab, unsigned int numofchars, unsigned int prefixlength, GtOutlcpinfo *outlcpinfo, unsigned int sortmaxdepth, const Sfxstrategy *sfxstrategy, GtProcessunsortedsuffixrange processunsortedsuffixrange, void *processunsortedsuffixrangeinfo, GtUint64 *bucketiterstep, GtLogger *logger) { GtCodetype code; unsigned int rightchar = (unsigned int) (mincode % numofchars); GtBucketspecification bucketspec; GtBentsedgresources *bsr = bentsedgresources_new(suffixsortspace, encseq, readmode, prefixlength, bcktab, sortmaxdepth, sfxstrategy, outlcpinfo != NULL ? true : false); gt_bentsedgresources_addlcpinfo(bsr,outlcpinfo,bcktab); bsr->processunsortedsuffixrangeinfo = processunsortedsuffixrangeinfo; bsr->processunsortedsuffixrange = processunsortedsuffixrange; for (code = mincode; code <= maxcode; code++) { if (bucketspec2 != NULL) { if (gt_copysort_checkhardwork(bucketspec2,code)) { rightchar = (unsigned int) (code % numofchars); } else { continue; } } (*bucketiterstep)++; rightchar = gt_bcktab_calcboundsparts(&bucketspec, bcktab, code, maxcode, numberofsuffixes, rightchar); gt_Outlcpinfo_prebucket(outlcpinfo,code,bucketspec.left); if (bucketspec.nonspecialsinbucket > 0) { if (bucketspec.nonspecialsinbucket > 1UL) { gt_sort_bentleysedgewick(bsr,bucketspec.left, bucketspec.nonspecialsinbucket, (GtUword) prefixlength); } gt_Outlcpinfo_nonspecialsbucket(outlcpinfo, prefixlength, bsr->sssp, bsr->tableoflcpvalues, &bucketspec, code); } gt_Outlcpinfo_postbucket(outlcpinfo, prefixlength, bsr->sssp, bcktab, &bucketspec, code); } bentsedgresources_delete(bsr, logger); } void gt_sortallsuffixesfromstart(GtSuffixsortspace *suffixsortspace, GtUword numberofsuffixes, const GtEncseq *encseq, GtReadmode readmode, GtOutlcpinfo *outlcpinfo, unsigned int sortmaxdepth, const Sfxstrategy *sfxstrategy, GtProcessunsortedsuffixrange processunsortedsuffixrange, void *processunsortedsuffixrangeinfo, GtLogger *logger) { if (numberofsuffixes > 1UL) { GtBentsedgresources *bsr = bentsedgresources_new(suffixsortspace, encseq, readmode, 0, NULL, sortmaxdepth, sfxstrategy, outlcpinfo != NULL ? true : false); gt_bentsedgresources_addlcpinfo(bsr,outlcpinfo,NULL); bsr->processunsortedsuffixrange = processunsortedsuffixrange; bsr->processunsortedsuffixrangeinfo = processunsortedsuffixrangeinfo; gt_sort_bentleysedgewick(bsr,0,numberofsuffixes,0); bentsedgresources_delete(bsr, logger); } } #ifdef GT_THREADS_ENABLED #ifdef GT_THREADS_PARTITION typedef struct { unsigned int numofchars, prefixlength; const GtBcktab *bcktab; GtCodetype mincode, maxcode; GtUword totalwidth; GtBentsedgresources *bsr; unsigned int thread_num; GtThread *thread; } GtBentsedg_partition_thread_info; static void *gt_bentsedg_partition_thread_caller(void *data) { GtCodetype code; GtBentsedg_partition_thread_info *thinfo = (GtBentsedg_partition_thread_info *) data; unsigned int rightchar; rightchar = (unsigned int) (thinfo->mincode % thinfo->numofchars); for (code = thinfo->mincode; code <= thinfo->maxcode; code++) { GtBucketspecification bucketspec; rightchar = gt_bcktab_calcboundsparts(&bucketspec, thinfo->bcktab, code, thinfo->maxcode, thinfo->totalwidth, rightchar); if (bucketspec.nonspecialsinbucket > 1UL) { gt_sort_bentleysedgewick(thinfo->bsr,bucketspec.left, bucketspec.nonspecialsinbucket, (GtUword) thinfo->prefixlength); } } return NULL; } void gt_threaded_partition_sortallbuckets(GtSuffixsortspace *suffixsortspace, const GtSuftabparts *partition_for_threads, const GtEncseq *encseq, GtReadmode readmode, const GtBcktab *bcktab, unsigned int numofchars, unsigned int prefixlength, unsigned int sortmaxdepth, const Sfxstrategy *sfxstrategy, GtProcessunsortedsuffixrange processunsortedsuffixrange, void *processunsortedsuffixrangeinfo, GtLogger *logger) { unsigned int tp, thread_parts; bool haserr = false; GtBentsedg_partition_thread_info *th_tab; GtSuffixsortspace **sssp_tab; gt_assert(partition_for_threads != NULL); thread_parts = gt_suftabparts_numofparts(partition_for_threads); gt_assert(thread_parts > 1U); th_tab = gt_malloc(sizeof *th_tab * thread_parts); sssp_tab = gt_malloc(sizeof *sssp_tab * thread_parts); for (tp = 0; !haserr && tp < thread_parts; tp++) { th_tab[tp].thread_num = tp; th_tab[tp].numofchars = numofchars; th_tab[tp].prefixlength = prefixlength; th_tab[tp].bcktab = bcktab; th_tab[tp].mincode = gt_suftabparts_minindex(tp,partition_for_threads); th_tab[tp].maxcode = gt_suftabparts_maxindex(tp,partition_for_threads); th_tab[tp].totalwidth = gt_suftabparts_sumofwidth(tp,partition_for_threads); if (tp == 0) { sssp_tab[tp] = suffixsortspace; } else { sssp_tab[tp] = gt_suffixsortspace_clone(suffixsortspace,tp,logger); } th_tab[tp].bsr = bentsedgresources_new(sssp_tab[tp], encseq, readmode, prefixlength, bcktab, sortmaxdepth, sfxstrategy, false); th_tab[tp].bsr->processunsortedsuffixrange = processunsortedsuffixrange; th_tab[tp].bsr->processunsortedsuffixrangeinfo = processunsortedsuffixrangeinfo; th_tab[tp].thread = gt_thread_new (gt_bentsedg_partition_thread_caller,th_tab + tp,NULL); if (th_tab[tp].thread == NULL) { haserr = true; } } for (tp = 0; tp < thread_parts; tp++) { if (!haserr) { gt_thread_join(th_tab[tp].thread); } gt_thread_delete(th_tab[tp].thread); } for (tp = 0; tp < thread_parts; tp++) { bentsedgresources_delete(th_tab[tp].bsr, logger); } gt_suffixsortspace_delete_cloned(sssp_tab,thread_parts); gt_free(sssp_tab); gt_free(th_tab); gt_assert(!haserr); } #else typedef struct { GtUword totalwidth, bucketnumber; const GtBcktab *bcktab; GtCodetype code, mincode, maxcode; unsigned int rightchar; GtMutex *mutex; } GtBentsedgIterator; static GtBentsedgIterator *gt_BentsedgIterator_new(GtCodetype mincode, GtCodetype maxcode, GtUword totalwidth, unsigned int numofchars, const GtBcktab *bcktab) { GtBentsedgIterator *bentsedg_iterator = gt_malloc(sizeof *bentsedg_iterator); bentsedg_iterator->code = mincode; bentsedg_iterator->mincode = mincode; bentsedg_iterator->maxcode = maxcode; bentsedg_iterator->totalwidth = totalwidth; bentsedg_iterator->rightchar = (unsigned int) (mincode % numofchars); bentsedg_iterator->bcktab = bcktab; bentsedg_iterator->bucketnumber = 0; bentsedg_iterator->mutex = gt_mutex_new(); return bentsedg_iterator; } static bool gt_BentsedgIterator_next(GtBucketspecification *bucketspec, GtBentsedgIterator *bs_it) { if (bs_it->code <= bs_it->maxcode) { bs_it->rightchar = gt_bcktab_calcboundsparts(bucketspec, bs_it->bcktab, bs_it->code, bs_it->maxcode, bs_it->totalwidth, bs_it->rightchar); bs_it->code++; return true; } else { return false; } } static void gt_BentsedgIterator_delete(GtBentsedgIterator *bs_it) { if (bs_it != NULL) { gt_assert(bs_it->bucketnumber == bs_it->maxcode - bs_it->mincode + 1); gt_mutex_delete(bs_it->mutex); gt_free(bs_it); } } typedef struct { GtUword bucketnumber; } GtPriorecord; typedef struct { GtUword capacity, numofelements; GtPriorecord *elements; } GtBentsedgePrioqueue; static GtBentsedgePrioqueue *gt_bs_priority_queue_new(GtUword numofelements) { GtBentsedgePrioqueue *pq = gt_malloc(sizeof *pq); pq->elements = gt_malloc(sizeof (*pq->elements) * numofelements); pq->capacity = numofelements; pq->numofelements = 0; return pq; } static bool gt_bs_priority_queue_is_empty(const GtBentsedgePrioqueue *pq) { gt_assert(pq != NULL); return pq->numofelements == 0 ? true : false; } static void gt_bs_priority_queue_add(GtBentsedgePrioqueue *pq, GtPriorecord priorecord) { GtPriorecord *ptr; gt_assert(pq != NULL); if (pq->numofelements >= pq->capacity) { pq->capacity *= 2; pq->elements = gt_realloc(pq->elements,sizeof *pq->elements * pq->capacity); } /* store elements in reverse order, i.e.\ with the minimum element at the last index; shift elements to the right until an element larger or equal than the key is found. */ for (ptr = pq->elements + pq->numofelements; ptr > pq->elements && (ptr-1)->bucketnumber < priorecord.bucketnumber; ptr--) { *ptr = *(ptr-1); } pq->numofelements++; gt_assert(ptr >= pq->elements && ptr < pq->elements + pq->numofelements); *ptr = priorecord; } static void gt_bs_priority_queue_delete_min(GtBentsedgePrioqueue *pq) { gt_assert(pq != NULL && !gt_bs_priority_queue_is_empty(pq)); pq->numofelements--; } const GtUword gt_bs_priority_queue_min_bucketnumber( const GtBentsedgePrioqueue *pq) { gt_assert(pq != NULL && !gt_bs_priority_queue_is_empty(pq)); return pq->elements[pq->numofelements-1].bucketnumber; } static void gt_bs_priority_queue_delete(GtBentsedgePrioqueue *pq) { if (pq != NULL) { gt_free(pq->elements); gt_free(pq); } } typedef struct { GtBentsedgePrioqueue *queue; GtUword nextrequest; GtMutex *mutex; } GtBentsedgSynchronizer; static GtBentsedgSynchronizer *gt_bendsedgSynchronizer_new(void) { GtBentsedgSynchronizer *bs_sync = gt_malloc(sizeof *bs_sync); bs_sync->queue = gt_bs_priority_queue_new(gt_jobs); bs_sync->nextrequest = 0; bs_sync->mutex = gt_mutex_new(); return bs_sync; } static void gt_bendsedgSynchronizer_process(GtBentsedgSynchronizer *bs_sync, GtUword bucketnumber) { gt_assert(bs_sync != NULL); if (bs_sync->nextrequest == bucketnumber) { bs_sync->nextrequest++; while (!gt_bs_priority_queue_is_empty(bs_sync->queue) && gt_bs_priority_queue_min_bucketnumber(bs_sync->queue) == bs_sync->nextrequest) { gt_bs_priority_queue_delete_min(bs_sync->queue); bs_sync->nextrequest++; } } else { GtPriorecord priorecord; gt_assert(bs_sync->nextrequest < bucketnumber); priorecord.bucketnumber = bucketnumber; gt_bs_priority_queue_add(bs_sync->queue,priorecord); } } static void gt_bendsedgSynchronizer_delete(GtBentsedgSynchronizer *bs_sync) { if (bs_sync != NULL) { gt_assert(gt_bs_priority_queue_is_empty(bs_sync->queue)); gt_mutex_delete(bs_sync->mutex); gt_bs_priority_queue_delete(bs_sync->queue); gt_free(bs_sync); } } typedef struct { GtBentsedgresources *bsr; unsigned int prefixlength, thread_num; GtBentsedgIterator *bs_it; /* shared, _next-function needs a mutex */ GtBentsedgSynchronizer *bs_sync; /* shared _process-function needs a mutex */ GtThread *thread; } GtBentsedg_stream_thread_info; static void *gt_bentsedg_stream_thread_caller(void *data) { GtBentsedg_stream_thread_info *thinfo = (GtBentsedg_stream_thread_info *) data; while (true) { GtBucketspecification bucketspec; GtUword bucketnumber; gt_mutex_lock(thinfo->bs_it->mutex); if (!gt_BentsedgIterator_next(&bucketspec,thinfo->bs_it)) { gt_mutex_unlock(thinfo->bs_it->mutex); break; } bucketnumber = thinfo->bs_it->bucketnumber++; gt_mutex_unlock(thinfo->bs_it->mutex); if (bucketspec.nonspecialsinbucket > 1UL) { gt_sort_bentleysedgewick(thinfo->bsr,bucketspec.left, bucketspec.nonspecialsinbucket, (GtUword) thinfo->prefixlength); } gt_mutex_lock(thinfo->bs_sync->mutex); gt_bendsedgSynchronizer_process(thinfo->bs_sync,bucketnumber); gt_mutex_unlock(thinfo->bs_sync->mutex); } return NULL; } void gt_threaded_stream_sortallbuckets(GtSuffixsortspace *suffixsortspace, const GtEncseq *encseq, GtReadmode readmode, const GtBcktab *bcktab, GtCodetype mincode, GtCodetype maxcode, GtUword sumofwidth, unsigned int numofchars, unsigned int prefixlength, unsigned int sortmaxdepth, const Sfxstrategy *sfxstrategy, GtProcessunsortedsuffixrange processunsortedsuffixrange, void *processunsortedsuffixrangeinfo, GtLogger *logger) { GtBentsedgIterator *bs_it; GtBentsedgSynchronizer *bs_sync; unsigned int tp; bool haserr = false; GtBentsedg_stream_thread_info *th_tab; GtSuffixsortspace **sssp_tab; gt_assert(gt_jobs > 1U); th_tab = gt_malloc(sizeof *th_tab * gt_jobs); sssp_tab = gt_malloc(sizeof *sssp_tab * gt_jobs); bs_it = gt_BentsedgIterator_new(mincode,maxcode,sumofwidth,numofchars,bcktab); bs_sync = gt_bendsedgSynchronizer_new(); for (tp = 0; !haserr && tp < gt_jobs; tp++) { th_tab[tp].thread_num = tp; th_tab[tp].prefixlength = prefixlength; if (tp == 0) { sssp_tab[tp] = suffixsortspace; } else { sssp_tab[tp] = gt_suffixsortspace_clone(suffixsortspace,tp,logger); } th_tab[tp].bsr = bentsedgresources_new(sssp_tab[tp], encseq, readmode, prefixlength, bcktab, sortmaxdepth, sfxstrategy, false); th_tab[tp].bsr->processunsortedsuffixrange = processunsortedsuffixrange; th_tab[tp].bsr->processunsortedsuffixrangeinfo = processunsortedsuffixrangeinfo; th_tab[tp].bs_it = bs_it; th_tab[tp].bs_sync = bs_sync; th_tab[tp].thread = gt_thread_new (gt_bentsedg_stream_thread_caller,th_tab + tp,NULL); if (th_tab[tp].thread == NULL) { haserr = true; } } for (tp = 0; tp < gt_jobs; tp++) { if (!haserr) { gt_thread_join(th_tab[tp].thread); } gt_thread_delete(th_tab[tp].thread); } for (tp = 0; tp < gt_jobs; tp++) { bentsedgresources_delete(th_tab[tp].bsr, logger); } gt_suffixsortspace_delete_cloned(sssp_tab,gt_jobs); gt_BentsedgIterator_delete(bs_it); gt_bendsedgSynchronizer_delete(bs_sync); gt_free(sssp_tab); gt_free(th_tab); gt_assert(!haserr); } #endif #endif
NUBIC/nucore-open
spec/models/price_group_product_spec.rb
<filename>spec/models/price_group_product_spec.rb require 'spec_helper' describe PriceGroupProduct do before :each do @facility=FactoryGirl.create(:facility) @facility_account=@facility.facility_accounts.create(FactoryGirl.attributes_for(:facility_account)) @instrument = FactoryGirl.create(:instrument, :facility => @facility, :facility_account_id => @facility_account.id) @price_group=FactoryGirl.create(:price_group, :facility => @facility) end it 'should require product' do PriceGroupProduct.new(:price_group => @price_group).should validate_presence_of :product_id end it 'should require price group' do PriceGroupProduct.new(:product => @instrument).should validate_presence_of :price_group_id end it 'should require reservation window' do PriceGroupProduct.new(:product => @instrument, :price_group => @price_group).should validate_presence_of :reservation_window end it 'should not require reservation window' do item=@facility.items.create(FactoryGirl.attributes_for(:item, :facility_account_id => @facility_account.id)) PriceGroupProduct.new(:product => item, :price_group => @price_group).should_not validate_presence_of :reservation_window end end
shabtaisharon/ds3_java_browser
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/util/DateTimeUtils.java
/* * ****************************************************************************** * Copyright 2016-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ****************************************************************************** */ package com.spectralogic.dsbrowser.gui.util; import com.google.common.base.Preconditions; import javax.annotation.Nonnull; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.Temporal; import java.util.Date; public final class DateTimeUtils { private static final DateTimeFormatter DEFAULT_FORMAT = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"); private static final int SECONDS_IN_DAY = (60 * 60 * 24); private static final int SECONDS_IN_HOUR = 60 * 60; private static final int SECONDS_IN_MINUTE = 60; private final DateTimeFormatter formatter; public DateTimeUtils() { this.formatter = DEFAULT_FORMAT; } public DateTimeUtils(@Nonnull final DateTimeFormatter formatter) { Preconditions.checkNotNull(formatter); this.formatter = formatter; } public String nowAsString() { return formatter.format(LocalDateTime.now()); } public String format(final Temporal t) { return formatter.format(t); } public String format(final Instant t) { return formatter.format(t.atZone(ZoneId.systemDefault())); } public String format(final Date date) { if(date == null) { return ""; } else { return formatter.format(date.toInstant().atZone(ZoneId.systemDefault())); } } /** * convert seconds in to appropriate days or hours o rminutes * * @param seconds * @return */ public static String timeConversion(final long seconds) { final long day = (seconds / SECONDS_IN_DAY); if (day >= 1) { if (day == 1) { return day + " day "; } else { return day + " days "; } } final long hour = (seconds / SECONDS_IN_HOUR); if (hour >= 1) { if (hour == 1) { return hour + " hour "; } else { return hour + " hours "; } } final long minute = (seconds / SECONDS_IN_MINUTE); if (minute >= 1) { if (minute == 1) { return minute + " minute "; } else { return minute + " minutes "; } } if (seconds > 1) { return seconds + " seconds "; } else { return seconds + " second "; } } public String formatDate(final long timeInMillis) { return formatter.format(Instant.ofEpochMilli(timeInMillis).atZone(ZoneId.systemDefault())); } }
jlevy/alt-log5j
src/java/com/spinn3r/log5j/factories/StdoutInternalLoggerFactory.java
/* * Copyright 2010 "Tailrank, Inc (Spinn3r)" * * 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.spinn3r.log5j.factories; import com.spinn3r.log5j.*; public class StdoutInternalLoggerFactory implements InternalLoggerFactory { private static final InternalLogger LOGGER = new InternalLogger() { public boolean isEnabled(LogLevel level) { return true; } public void log(LogEvent logEvent) { System.out.println(LogUtils.toString(logEvent)); } }; public InternalLogger create(String logName) { return LOGGER; } public void shutdown() { // do nothing } }
scruffyfox/AsyncHttpClient
library/src/main/java/net/callumtaylor/asynchttp/response/StreamResponseHandler.java
<reponame>scruffyfox/AsyncHttpClient package net.callumtaylor.asynchttp.response; import net.callumtaylor.asynchttp.obj.ClientTaskImpl; import net.callumtaylor.asynchttp.obj.Packet; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Simple response handler that uses an input stream reader rather than appending an string buffer */ public abstract class StreamResponseHandler<E> extends ResponseHandler<E> { protected InputStreamReader reader; @Override public void onReceiveStream(InputStream stream, final ClientTaskImpl client, final long totalLength) throws Exception { if (reader == null) { reader = new InputStreamReader(new BufferedInputStream(stream, 8192) { private long total = 0; @Override public synchronized int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { int len = super.read(buffer, byteOffset, byteCount); onByteChunkReceived(buffer, len, total, totalLength); client.transferProgress(new Packet(total, totalLength, true)); total += byteCount; return len; } }); } if (!client.isCancelled()) { getConnectionInfo().responseLength = totalLength; // we fake the content length, because it can be -1 onByteChunkReceived(null, totalLength, totalLength, totalLength); client.transferProgress(new Packet(totalLength, totalLength, true)); } } }
wangxiao1002/wechat-operation
operation-backend/src/main/java/com/idiot/operationbackend/service/facade/JobTaskService.java
<reponame>wangxiao1002/wechat-operation package com.idiot.operationbackend.service.facade; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import com.idiot.operationbackend.entity.JobTask; import java.util.List; /** * @author <NAME> * @date Created in 14:53 2020/9/23 */ public interface JobTaskService extends IService<JobTask> { /** * 查询需要加载的定时任务 * @author wangxiao * @date 14:57 2020/9/23 * @return java.util.List<com.idiot.operationbackend.entity.JobTask> */ List<JobTask> queryByInitJob(); /** * 查询定时任务 * @author wangxiao * @date 15:38 2020/9/23 * @param taskKey taskKey * @return com.idiot.operationbackend.entity.JobTask */ JobTask queryJobTask(String taskKey); /** * 查询分页定时 * @author wangxiao * @date 17:06 2020/9/23 * @param page page * @param status status * @param ids ids * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.idiot.operationbackend.entity.JobTask> */ Page<JobTask> queryPageJobTask(int page,Integer status,List<String> ids); /** * 删除定时 * @author wangxiao * @date 17:39 2020/10/27 * @param taskKey taskKey */ void removeByTaskKey (String taskKey); }
cryst-al/novoline
src/net/minecraft/block/Block$SoundType.java
package net.minecraft.block; public class Block$SoundType { public final String soundName; public final float volume; public final float frequency; public Block$SoundType(String var1, float var2, float var3) { this.soundName = var1; this.volume = var2; this.frequency = var3; } public float getVolume() { return this.volume; } public float getFrequency() { return this.frequency; } public String getBreakSound() { return "dig." + this.soundName; } public String getStepSound() { return "step." + this.soundName; } public String getPlaceSound() { return this.getBreakSound(); } }
foruever/benchmark-dev
src/main/java/cn/edu/ruc/dao/TsFileDao.java
package cn.edu.ruc.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; import java.util.List; import cn.edu.ruc.model.BenchmarkPoint; public class TsFileDao implements BaseDao { public static void main(String[] args) { BaseDao dao=new TsFileDao(); dao.insertMultiPoints(null); } @Override public long insertMultiPoints(List<BenchmarkPoint> points) { Connection connection = null; Statement statement = null; try { Class.forName("com.corp.tsfile.jdbc.TsfileDriver"); connection = DriverManager.getConnection("jdbc:tsfile://127.0.0.1:6667/", "root", "root"); statement = connection.createStatement(); boolean hasResultSet = statement.execute("select s1 from root.excavator.Beijing.d1"); if (hasResultSet) { ResultSet res = statement.getResultSet(); while (res.next()) { System.out.println(res.getString("Timestamp") + " | " + res.getString("s1")); } } } catch (Exception e) { } finally { if(statement != null){ try { statement.close(); } catch (Exception e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } return 0; } @Override public boolean deleteAllPoints() { return false; } @Override public long selectPointsByTime(Date beginTime, Date endTime, String device, String sensor) { return -1; } @Override public long selectMaxByTimeAndDevice(String sqlId, Date beginTime, Date endTime, String device, List<String> sensors) { // TODO Auto-generated method stub return -1; } }
packagesdev/dejalu
Sources/Backend/hermes/db/HMUnifiedMailStorageView.h
// DejaLu // Copyright (c) 2015 <NAME>. All rights reserved. #ifndef HMUnifiedMailStorageView_hpp #define HMUnifiedMailStorageView_hpp #include <MailCore/MailCore.h> #include "HMMailStorageViewObserver.h" #ifdef __cplusplus namespace hermes { class MailStorage; class MailStorageViewObserver; class MailDBChanges; class MailDBConversationMessagesOperation; class UnifiedMailStorageViewObserver; class MailStorageView; class UnifiedMailStorageView : public mailcore::Object, public hermes::MailStorageViewObserver { public: UnifiedMailStorageView(); virtual ~UnifiedMailStorageView(); virtual void setStorageViews(mailcore::Array * /* MailStorageView */ views); virtual mailcore::Array * storageViews(); virtual void addObserver(UnifiedMailStorageViewObserver * observer); virtual void removeObserver(UnifiedMailStorageViewObserver * observer); virtual unsigned int conversationsCount(); virtual mailcore::HashMap * conversationsInfoAtIndex(unsigned int idx); virtual mailcore::HashMap * conversationsInfoForConversationID(unsigned int accountIndex, int64_t conversationID); virtual bool isLoading(); public: // HMMailStorageView observer virtual void mailStorageViewChanged(MailStorageView * view, mailcore::Array * deleted, mailcore::Array * moved, mailcore::Array * added, mailcore::Array * modified, mailcore::Array * modifiedIDs); private: mailcore::Array * mViews; int mOpenCount; mailcore::Array * mConversations; carray * mObservers; double mLastUpdateTimestamp; mailcore::Set * mModifiedConversationsIDs; bool mScheduledUpdate; void notifyChangesToObserver(mailcore::Array * deleted, mailcore::Array * moved, mailcore::Array * added, mailcore::Array * modified); void scheduleUpdate(double currentTime); void updateNow(); }; } #endif #endif /* HMUnifiedMailStorageView_hpp */
xlui/Eros
Blog/src/main/java/style/dx/eros/config/Const.java
<gh_stars>0 package style.dx.eros.config; public class Const { public static final int defaultPageSize = 2; }
atsushifx/education-notes-for-moocs
Archives/coursera/duke/java02-solving/week03-parseCSV/exercise-parseExports/parseExport.java
<filename>Archives/coursera/duke/java02-solving/week03-parseCSV/exercise-parseExports/parseExport.java import edu.duke.*; import org.apache.commons.csv.*; /** * parseExport * 輸出物csv読み込み * * @author <NAME> * @version 1.0.0 */ public class parseExport { /** * countryInfo * */ private String countryInfo(CSVParser parser, String country) { for (CSVRecord record : parser ) { String recCountry = record.get("Country"); if (recCountry.contains(country)) { String result = recCountry; result += ": " + record.get("Exports"); result += ": " + record.get("Value (dollars)"); return result; } } return "NOT FOUND"; } /** * listExportersTwoProducts * get country list from exportItem1,2 */ String listExportersTwoProducts(CSVParser parser, String item1, String item2) { String countryList = ""; for (CSVRecord record : parser) { String exports = record.get("Exports"); String country = record.get("Country"); if (exports.contains(item1) && exports.contains(item2)) { countryList += country + "\n"; } } return countryList; } /** * numberOfExporters * export */ int numberOfExporters(CSVParser parser, String exportItem) { int count = 0; for (CSVRecord record : parser) { if (record.get("Exports").contains(exportItem)) { count++; } } return count; } /** * bigExporters */ void bigExporters(CSVParser parser, String amount) { for (CSVRecord record : parser) { String country = record.get("Country"); String value = record.get("Value (dollars)"); if (value.length() > amount.length()) { String result = country + " " + value; System.out.println(result); } } } /** * parse export country tester */ public void tester() { FileResource fr = new FileResource(); CSVParser parser = fr.getCSVParser(); String result; /* result = countryInfo(parser, "Nauru"); System.out.println(result); */ System.out.println("\n exports 2 items"); result = listExportersTwoProducts(parser, "cotton", "flowers"); System.out.println(result); System.out.println("\n number of export countries"); String item="cocoa"; int n = numberOfExporters(parser, item); parser = fr.getCSVParser(); System.out.println("Export:"+item+" countries:"+n); System.out.println("\n Big Exporters"); parser = fr.getCSVParser(); bigExporters(parser, "$999,999,999,999"); } }
maze-runnar/modal-component
modal/node_modules/simplebar/node_modules/core-js/stable/number/is-integer.js
<reponame>maze-runnar/modal-component<filename>modal/node_modules/simplebar/node_modules/core-js/stable/number/is-integer.js module.exports = require('../../es/number/is-integer');
markbnc/uiutil
src/main/java/com/ecdsinc/security/EcdsSecurityException.java
package com.ecdsinc.security; import com.ecdsinc.util.UtilException; @SuppressWarnings("serial") public class EcdsSecurityException extends UtilException { public EcdsSecurityException(String message) { super(message); } public EcdsSecurityException(String message, Throwable cause) { super(message, cause); } }
tangyan02/ego-chinese-chess
src/main/java/cn/tangyancode/ego/chineseChess/core/GameMap.java
package cn.tangyancode.ego.chineseChess.core; import cn.tangyancode.ego.chineseChess.entity.*; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class GameMap { private HashSet<Unit> units; private Unit[][] map = new Unit[Config.HEIGHT][Config.WIDTH]; private Map<Relation, Point> JIANGPoint = new HashMap<>(); private Map<Relation, Map<Troop, Integer>> relationTroopCount = new HashMap<>(); { relationTroopCount.put(Relation.SELF, new HashMap<>()); relationTroopCount.put(Relation.OPPONENT, new HashMap<>()); } public GameMap(List<Unit> units) { this.units = new HashSet<>(units); units.forEach(unit -> { map[unit.x][unit.y] = unit; //将的记录 if (unit.troop == Troop.JIANG) { JIANGPoint.put(unit.relation, new Point(unit.x, unit.y)); } //数量记录 if (!relationTroopCount.get(unit.relation).containsKey(unit.troop)) { relationTroopCount.get(unit.relation).put(unit.troop, 0); } relationTroopCount.get(unit.relation).put(unit.troop, relationTroopCount.get(unit.relation).get(unit.troop) + 1); }); } public void move(Unit unit, int x, int y) { unit.moveTimes++; if (map[x][y] != null) { units.remove(map[x][y]); relationTroopCount.get(unit.relation).put( unit.troop, relationTroopCount.get(unit.relation).get(unit.troop) - 1 ); } map[unit.x][unit.y] = null; map[x][y] = unit; unit.x = x; unit.y = y; } public void undoMove(Unit unit, int x, int y, Unit last) { unit.moveTimes--; map[unit.x][unit.y] = last; if (last != null) { units.add(last); relationTroopCount.get(last.relation).put( last.troop, relationTroopCount.get(last.relation).get(last.troop) + 1 ); } map[x][y] = unit; unit.x = x; unit.y = y; } public HashSet<Unit> getUnits() { return new HashSet<>(units); } public Unit getUnit(int x, int y) { return map[x][y]; } public boolean moveAble(int x, int y) { if (!inMap(x, y)) { return false; } if (map[x][y] != null) { return false; } return true; } public boolean attackAble(int x, int y) { if (!inMap(x, y)) { return false; } if (map[x][y] != null) { return true; } return false; } public boolean moveOrAttackAble(int x, int y) { if (!inMap(x, y)) { return false; } return true; } public boolean inMap(int x, int y) { if (x < 0 || x >= Config.HEIGHT) return false; if (y < 0 || y >= Config.WIDTH) return false; return true; } public Map<Relation, Point> getJIANGPoint() { return JIANGPoint; } public Map<Relation, Map<Troop, Integer>> getRelationTroopCount() { return relationTroopCount; } }
italiangrid/voms-admin-server
voms-admin-server/src/main/java/org/glite/security/voms/admin/notification/dispatchers/VOMembershipNotificationDispatcher.java
/** * Copyright (c) <NAME> Fisica Nucleare (INFN). 2006-2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glite.security.voms.admin.notification.dispatchers; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import org.glite.security.voms.admin.event.Event; import org.glite.security.voms.admin.event.EventCategory; import org.glite.security.voms.admin.event.request.VOMembershipRequestApprovedEvent; import org.glite.security.voms.admin.event.request.VOMembershipRequestConfirmedEvent; import org.glite.security.voms.admin.event.request.VOMembershipRequestRejectedEvent; import org.glite.security.voms.admin.event.request.VOMembershipRequestSubmittedEvent; import org.glite.security.voms.admin.notification.BaseNotificationDispatcher; import org.glite.security.voms.admin.notification.NotificationServiceFactory; import org.glite.security.voms.admin.notification.NotificationUtil; import org.glite.security.voms.admin.notification.messages.ConfirmRequest; import org.glite.security.voms.admin.notification.messages.HandleRequest; import org.glite.security.voms.admin.notification.messages.RequestApproved; import org.glite.security.voms.admin.notification.messages.RequestRejected; import org.glite.security.voms.admin.operations.VOMSContext; import org.glite.security.voms.admin.operations.VOMSPermission; public class VOMembershipNotificationDispatcher extends BaseNotificationDispatcher { private static VOMembershipNotificationDispatcher instance; public static VOMembershipNotificationDispatcher instance() { if (instance == null) instance = new VOMembershipNotificationDispatcher(); return instance; } private VOMembershipNotificationDispatcher() { super(EnumSet.of(EventCategory.VOMembershipRequestEvent)); } public List<String> resolveEmailAddresses( VOMembershipRequestConfirmedEvent e) { if (e.getPayload() .getRequesterInfo() .getManagerEmail() == null) { return NotificationUtil.getAdministratorsEmailList( VOMSContext.getVoContext(), VOMSPermission.getRequestsRWPermissions()); } return Arrays.asList(e.getPayload() .getRequesterInfo() .getManagerEmail()); } public void fire(Event e) { if (e instanceof VOMembershipRequestSubmittedEvent) { VOMembershipRequestSubmittedEvent ee = (VOMembershipRequestSubmittedEvent) e; String recipient = ee.getPayload() .getRequesterInfo() .getEmailAddress(); ConfirmRequest msg = new ConfirmRequest(recipient, ee.getConfirmURL(), ee.getCancelURL()); NotificationServiceFactory.getNotificationService() .send(msg); } else if (e instanceof VOMembershipRequestConfirmedEvent) { VOMembershipRequestConfirmedEvent ee = (VOMembershipRequestConfirmedEvent) e; List<String> admins = resolveEmailAddresses(ee); HandleRequest msg = new HandleRequest(ee.getPayload(), ee.getUrl(), admins); NotificationServiceFactory.getNotificationService() .send(msg); } else if (e instanceof VOMembershipRequestApprovedEvent) { RequestApproved msg = new RequestApproved( ((VOMembershipRequestApprovedEvent) e).getPayload()); NotificationServiceFactory.getNotificationService() .send(msg); } else if (e instanceof VOMembershipRequestRejectedEvent) { RequestRejected msg = new RequestRejected( ((VOMembershipRequestRejectedEvent) e).getPayload(), null); NotificationServiceFactory.getNotificationService() .send(msg); } } }
samhatem/Ghost-Admin
lib/koenig-editor/app/helpers/clean-basic-html.js
<filename>lib/koenig-editor/app/helpers/clean-basic-html.js export {default} from 'koenig-editor/helpers/clean-basic-html';
tomzhang/aiida_core
aiida/common/test_folders.py
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida_core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### from __future__ import absolute_import import unittest class FoldersTest(unittest.TestCase): """ Tests for the Folder class. """ def test_unicode(self): """ Check that there are no exceptions raised when using unicode folders. """ from aiida.common.folders import Folder import os, tempfile tmpsource = tempfile.mkdtemp() tmpdest = tempfile.mkdtemp() with open(os.path.join(tmpsource, "sąžininga"), 'w') as f: f.write("test") with open(os.path.join(tmpsource, "žąsis"), 'w') as f: f.write("test") fd = Folder(tmpdest) fd.insert_path(tmpsource, "destination") fd.insert_path(tmpsource, u"šaltinis") fd = Folder(os.path.join(tmpsource, u"šaltinis")) fd.insert_path(tmpsource, "destination") fd.insert_path(tmpdest, u"kitas-šaltinis") def test_get_abs_path_without_limit(self): from aiida.common.folders import Folder fd = Folder('/tmp') # Should not raise any exception self.assertEquals(fd.get_abs_path('test_file.txt'), '/tmp/test_file.txt')
hexie2108/mikuclub
App/src/main/java/org/mikuclub/app/utils/GeneralUtils.java
<reponame>hexie2108/mikuclub package org.mikuclub.app.utils; import android.content.Context; import android.content.res.Resources; import android.text.Html; import android.util.DisplayMetrics; import android.util.Patterns; import org.apache.commons.text.StringEscapeUtils; import org.mikuclub.app.config.GlobalConfig; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * 通用实用方法集 * Common utility class */ public class GeneralUtils { /** * 去除字符串中的html标签 * * @param text * @return */ public static String removeHTMLTag(String text) { String output = ""; if (text != null && !text.isEmpty()) { //安卓新版本 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { output = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY).toString(); } //兼容安卓旧版本的 else { output = Html.fromHtml(text).toString(); } } return output; } /** * 把DP转换成PX * * @param dp * @param context * @return */ public static float convertDpToPixel(float dp, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * (metrics.densityDpi / 160f); return px; } /** * 检测列表是否为空 或者 列表包含的第一个元素是空字符串或者0 * * @param list * @return 是否是空 */ public static boolean listIsNullOrHasEmptyElement(List list) { boolean output = true; //如果不是空 if (list != null && !list.isEmpty()) { //获取第一个元素 Object element = list.get(0); //如果是字符串 if (element instanceof String) { //检测是否是空字符串 output = ((String) element).trim().isEmpty(); } //如果是整数 else if (element instanceof Integer) { //如果是0 返回 true output = ((int) element == 0); } //其他情况返回否 else { output = false; } } return output; } /** * 根据图片地址 获取对应的微缩图地址 * * @param imageSrc * @return */ public static String getThumbnailSrcByImageSrc(String imageSrc) { StringBuilder sb = new StringBuilder(imageSrc); //在最后后点号位置 插入 "-500x280" 来获取对应的缩微图 sb.insert(sb.lastIndexOf("."), GlobalConfig.THUMBNAIL_SIZE); return sb.toString(); } /** * 按照特定格式 把日期转换输出成字符串 * * @param date * @return 字符串格式的日期 */ public static String DateToString(Date date) { String dateString = new SimpleDateFormat(GlobalConfig.DISPLAY_DATE_FORMAT).format(date); return dateString; } /** * 恢复 文本内 被html转义的特殊符号 * * @param text * @return */ public static String unescapeHtml(String text) { return StringEscapeUtils.unescapeHtml4(text); } /** * 检测email字符串是否是个有效的邮箱地址 * * @param emailText * @return */ public final static boolean isValidEmail(CharSequence emailText) { Boolean isValid = false; if (emailText != null) { isValid = android.util.Patterns.EMAIL_ADDRESS.matcher(emailText).matches(); } return isValid; } /** * 检测URL字符串是否是个有效的链接地址 * * @param urlText * @return */ public final static boolean isValidUrl(String urlText) { Boolean isValid = false; if (Patterns.WEB_URL.matcher(urlText).matches()) { isValid = true; } return isValid; } /** * 修正乱码字符串, 忽视错误 * * @param text * @return */ public static String fixStringEncoding(String text) { return new String(text.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); } }
divyakumarjain/bo-framework
repository/src/main/java/org/divy/common/bo/repository/BORepository.java
<reponame>divyakumarjain/bo-framework package org.divy.common.bo.repository; import org.divy.common.bo.query.Query; import java.util.List; import java.util.Optional; import java.util.stream.Stream; public interface BORepository<E extends BusinessObject<I>, I> { E create(E businessObject); E update(I id, E businessObject); E delete(E businessObject); List<E> list(); List<E> search(Query businessObjectQuery); Stream<E> stream(); Stream<E> searchStream(Query businessObjectQuery); E deleteById(I id); Optional<E> get(I identity); }
BeaconFramework/osffm
src/java/OSFFM_ORC/Utils/SFC_NFV/GenericVNFcontainer.java
/**Copyright 2016, University of Messina. * * 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 OSFFM_ORC.Utils.SFC_NFV; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; /** * * @author <NAME> */ public abstract class GenericVNFcontainer { //<editor-fold defaultstate="collapsed" desc="Variable"> protected HashMap<String,Object> topologyTemplates; protected HashMap<String,JSONObject> nodeTemplates; protected String tosca_definitions_version,description; //</editor-fold> public String getTosca_definitions_version() { return tosca_definitions_version; } public void setTosca_definitions_version(String tosca_definitions_version) { this.tosca_definitions_version = tosca_definitions_version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public HashMap<String, JSONObject> getNodeTemplates() { return nodeTemplates; } public GenericVNFcontainer() { this.topologyTemplates = new HashMap<String,Object>(); this.nodeTemplates = new HashMap<String,JSONObject>(); this.tosca_definitions_version = ""; this.description = ""; } public String toString(){ try{ return this.getTemplate(); } catch(JSONException je){ return je.getMessage(); } } public abstract void addINtopologytemplates(String key, Object node) throws JSONException; public abstract void addINnodetemplates(String key, JSONObject node) throws JSONException; public abstract String getTemplate() throws JSONException; public HashMap<String,Object> getTopologyTemplates(){ return this.topologyTemplates; } }
noamran/genie
genie-web/src/main/java/com/netflix/genie/web/scripts/AgentLauncherSelectorManagedScript.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.scripts; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.web.agent.launchers.AgentLauncher; import com.netflix.genie.web.exceptions.checked.ResourceSelectionException; import com.netflix.genie.web.properties.AgentLauncherSelectorScriptProperties; import com.netflix.genie.web.selectors.AgentLauncherSelectionContext; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import java.util.Map; /** * Extension of {@link ResourceSelectorScript} that delegates selection of a job's agent launcher when more than one * choice is available. See also: {@link com.netflix.genie.web.selectors.AgentLauncherSelector}. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentLauncherSelectorManagedScript extends ResourceSelectorScript<AgentLauncher, AgentLauncherSelectionContext> { static final String AGENT_LAUNCHERS_BINDING = "agentLaunchersParameter"; /** * Constructor. * * @param scriptManager script manager * @param properties script manager properties * @param registry meter registry * @param propertyMapCache dynamic properties map cache */ public AgentLauncherSelectorManagedScript( final ScriptManager scriptManager, final AgentLauncherSelectorScriptProperties properties, final MeterRegistry registry, final PropertiesMapCache propertyMapCache ) { super(scriptManager, properties, registry, propertyMapCache); } /** * {@inheritDoc} */ @Override public ResourceSelectorScriptResult<AgentLauncher> selectResource( final AgentLauncherSelectionContext context ) throws ResourceSelectionException { log.debug( "Called to attempt to select agent launcher from {} for job {}", context.getAgentLaunchers(), context.getJobId() ); return super.selectResource(context); } /** * {@inheritDoc} */ @Override protected void addParametersForScript( final Map<String, Object> parameters, final AgentLauncherSelectionContext context ) { super.addParametersForScript(parameters, context); // TODO: Remove once internal scripts migrate to use context directly parameters.put(AGENT_LAUNCHERS_BINDING, context.getAgentLaunchers()); } }