max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
681
# global import pytest from typing import List, Tuple, Dict, Optional, Union # local import ivy def _fn0(xs: Optional[List[ivy.Array]] = None): return xs def _fn1( a: Union[ivy.Array, ivy.NativeArray], b: str = "hello", c: int = None, d: ivy.NativeArray = None, ): return a, b, c, d def _fn2( a: Tuple[Union[ivy.Array, ivy.NativeArray, ivy.Container]], bs: Tuple[str] = ("a", "b", "c"), cs: Dict[str, ivy.Array] = None, ): return a, bs, cs @pytest.mark.parametrize( "fn_n_spec", [ (_fn0, [[(0, "xs"), "optional", int]]), (_fn1, [[(0, "a")], [(3, "d"), "optional"]]), (_fn2, [[(0, "a"), int], [(2, "cs"), "optional", str]]), ], ) def test_fn_array_spec(fn_n_spec): fn, spec = fn_n_spec assert ivy.fn_array_spec(fn) == spec
393
4,253
<gh_stars>1000+ package com.mashibing.entity; import java.sql.Date; import java.util.Objects; public class Emp { private Integer empno; private String ename; private String job; private Integer mgr; private Date hiredate; private Double sal; private Double comm; private Integer deptno; public Emp() { } public Emp(Integer empno, String ename) { this.empno = empno; this.ename = ename; } public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Double sal, Double comm, Integer deptno) { this.empno = empno; this.ename = ename; this.job = job; this.mgr = mgr; this.hiredate = hiredate; this.sal = sal; this.comm = comm; this.deptno = deptno; } public Integer getEmpno() { return empno; } public void setEmpno(Integer empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Integer getMgr() { return mgr; } public void setMgr(Integer mgr) { this.mgr = mgr; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } public Double getComm() { return comm; } public void setComm(Double comm) { this.comm = comm; } public Integer getDeptno() { return deptno; } public void setDeptno(Integer deptno) { this.deptno = deptno; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Emp)) return false; Emp emp = (Emp) o; return Objects.equals(empno, emp.empno) && Objects.equals(ename, emp.ename) && Objects.equals(job, emp.job) && Objects.equals(mgr, emp.mgr) && Objects.equals(hiredate, emp.hiredate) && Objects.equals(sal, emp.sal) && Objects.equals(comm, emp.comm) && Objects.equals(deptno, emp.deptno); } @Override public int hashCode() { return Objects.hash(empno, ename, job, mgr, hiredate, sal, comm, deptno); } @Override public String toString() { return "Emp{" + "empno=" + empno + ", ename='" + ename + '\'' + ", job='" + job + '\'' + ", mgr=" + mgr + ", hiredate=" + hiredate + ", sal=" + sal + ", comm=" + comm + ", deptno=" + deptno + '}'; } }
1,486
575
{ "name": "Login screen APIs in-session test extension", "version": "0.4", "manifest_version": 2, "description": "In session extension for testing the chrome.login extension API", "background": { "scripts": ["background.js"] }, "permissions": [ "login" ] }
95
351
<filename>tryalgo/two_sat.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Solving 2-SAT boolean formulas <NAME> et <NAME> - 2015-2019 """ from tryalgo.strongly_connected_components import tarjan # snip{ def _vertex(lit): # integer encoding of a litteral if lit > 0: return 2 * (lit - 1) return 2 * (-lit - 1) + 1 def two_sat(formula): """Solving a 2-SAT boolean formula :param formula: list of clauses, a clause is pair of literals over X1,...,Xn for some n. a literal is an integer, for example -1 = not X1, 3 = X3 :returns: table with boolean assignment satisfying the formula or None :complexity: linear """ # num_variables is the number of variables num_variables = max(abs(clause[p]) for p in (0, 1) for clause in formula) graph = [[] for node in range(2 * num_variables)] for x_idx, y_idx in formula: # x_idx or y_idx graph[_vertex(-x_idx)].append(_vertex(y_idx)) # -x_idx => y_idx graph[_vertex(-y_idx)].append(_vertex(x_idx)) # -y_idx => x_idx sccp = tarjan(graph) comp_id = [None] * (2 * num_variables) # each node's component ID assignment = [None] * (2 * num_variables) for component in sccp: rep = min(component) # representative of the component for vtx in component: comp_id[vtx] = rep if assignment[vtx] is None: assignment[vtx] = True assignment[vtx ^ 1] = False # complementary literal for i in range(num_variables): if comp_id[2 * i] == comp_id[2 * i + 1]: return None # insatisfiable formula return assignment[::2] # snip}
822
337
/* * Copyright 2019 The Polycube 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. */ #pragma once #include <list> #include <fstream> #include <chrono> #include "../base/PacketcaptureBase.h" #include "Packet.h" #include "Globalheader.h" #include <tins/ethernetII.h> #include <tins/tins.h> #include <linux/filter.h> using namespace polycube::service::model; using polycube::service::ProgramType; using polycube::service::Direction; class Packetcapture : public PacketcaptureBase { std::shared_ptr<Globalheader> global_header; std::list<std::shared_ptr<Packet>> packets_captured; uint8_t CapStatus; bool network_mode_flag; bool writeHeader; std::ofstream myFile; std::string dt; std::string temp_folder; std::string random_number; std::chrono::system_clock::time_point timeP; std::chrono::nanoseconds temp_offset; std::string filter; bool bootstrap = true; /* variable used to set default filter when the service is created */ bool dumpFlag = false; /* variable used to know if the user set a custom dump folder */ bool ts = false; /* true when service not TC type or sk_buff->tstamp == 0 see line 412 in cbpf2c.cpp */ polycube::service::CubeType cubeType; private: struct sock_fprog cbpf; std::string filterCode; public: void addPacket(const std::vector<uint8_t> &packet); void to_timeval(std::chrono::system_clock::duration& d, struct timeval& tv); public: Packetcapture(const std::string name, const PacketcaptureJsonObject &conf); virtual ~Packetcapture(); void packet_in(polycube::service::Direction direction, polycube::service::PacketInMetadata &md, const std::vector<uint8_t> &packet) override; void attach() override; /// <summary> /// Packet capture status /// </summary> PacketcaptureCaptureEnum getCapture() override; void setCapture(const PacketcaptureCaptureEnum &value) override; /// <summary> /// /// </summary> bool getAnonimize() override; void setAnonimize(const bool &value) override; /// <summary> /// dump capture /// </summary> std::string getDump() override; void setDump(const std::string &value) override; /// <summary> /// Operating mode /// </summary> bool getNetworkmode() override; void setNetworkmode(const bool &value) override; /// <summary> /// filtering string (e.g., 'host 1.2.3.4 and src port 80') /// </summary> void setFilter(const std::string &value) override; std::string getFilter() override; /// <summary> /// /// </summary> std::shared_ptr<Packet> getPacket() override; void addPacket(const PacketJsonObject &value) override; void replacePacket(const PacketJsonObject &conf) override; void delPacket() override; /// <summary> /// /// </summary> std::shared_ptr<Globalheader> getGlobalheader() override; void addGlobalheader(const GlobalheaderJsonObject &value) override; void replaceGlobalheader(const GlobalheaderJsonObject &conf) override; void delGlobalheader() override; /// <summary> /// Snapshot length /// </summary> uint32_t getSnaplen() override; void setSnaplen(const uint32_t &value) override; void updateFilter(); void writeDump(const std::vector<uint8_t> &packet); void filterCompile(std::string str, struct sock_fprog *cbpf); std::string replaceAll(std::string str, const std::string &from, const std::string &to); };
1,222
865
<gh_stars>100-1000 #include <iostream> #include <string> #include "ParseHelper.h" #include "ParseListener.h" #include "Interpreter.h" const std::string STD_PROMPT = ">>> "; const std::string MULTILINE_PROMPT = "... "; struct InterpreterRelay : public ParseListener { Interpreter* m_interpreter; InterpreterRelay( ): m_interpreter( new Interpreter ) { } virtual void parseEvent( const ParseMessage& msg ) { if ( msg.errorCode ) { std::cout << "(" << msg.errorCode << ") " << msg.message << "\n"; return; } else { int err; std::string res = m_interpreter->interpret( msg.message, &err ); std::cout << "(" << msg.errorCode << ") " << res << "\n"; } } }; int main( int argc, char *argv[] ) { Interpreter::Initialize( ); const std::string* prompt = &STD_PROMPT; ParseHelper helper; ParseListener* listener = new InterpreterRelay; helper.subscribe( listener ); std::string str; std::cout << *prompt; std::getline( std::cin, str ); while ( str != "quit" ) { std::cout << str << "\n"; helper.process( str ); if ( helper.buffered( ) ) { prompt = &MULTILINE_PROMPT; } else { prompt = &STD_PROMPT; } std::cout << *prompt; std::getline( std::cin, str ); } Interpreter::Finalize( ); return 0; }
709
3,372
<filename>aws-java-sdk-networkmanager/src/main/java/com/amazonaws/services/networkmanager/AbstractAWSNetworkManagerAsync.java /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.networkmanager; import javax.annotation.Generated; import com.amazonaws.services.networkmanager.model.*; /** * Abstract implementation of {@code AWSNetworkManagerAsync}. Convenient method forms pass through to the corresponding * overload that takes a request object and an {@code AsyncHandler}, which throws an * {@code UnsupportedOperationException}. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AbstractAWSNetworkManagerAsync extends AbstractAWSNetworkManager implements AWSNetworkManagerAsync { protected AbstractAWSNetworkManagerAsync() { } @Override public java.util.concurrent.Future<AssociateCustomerGatewayResult> associateCustomerGatewayAsync(AssociateCustomerGatewayRequest request) { return associateCustomerGatewayAsync(request, null); } @Override public java.util.concurrent.Future<AssociateCustomerGatewayResult> associateCustomerGatewayAsync(AssociateCustomerGatewayRequest request, com.amazonaws.handlers.AsyncHandler<AssociateCustomerGatewayRequest, AssociateCustomerGatewayResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<AssociateLinkResult> associateLinkAsync(AssociateLinkRequest request) { return associateLinkAsync(request, null); } @Override public java.util.concurrent.Future<AssociateLinkResult> associateLinkAsync(AssociateLinkRequest request, com.amazonaws.handlers.AsyncHandler<AssociateLinkRequest, AssociateLinkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<AssociateTransitGatewayConnectPeerResult> associateTransitGatewayConnectPeerAsync( AssociateTransitGatewayConnectPeerRequest request) { return associateTransitGatewayConnectPeerAsync(request, null); } @Override public java.util.concurrent.Future<AssociateTransitGatewayConnectPeerResult> associateTransitGatewayConnectPeerAsync( AssociateTransitGatewayConnectPeerRequest request, com.amazonaws.handlers.AsyncHandler<AssociateTransitGatewayConnectPeerRequest, AssociateTransitGatewayConnectPeerResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateConnectionResult> createConnectionAsync(CreateConnectionRequest request) { return createConnectionAsync(request, null); } @Override public java.util.concurrent.Future<CreateConnectionResult> createConnectionAsync(CreateConnectionRequest request, com.amazonaws.handlers.AsyncHandler<CreateConnectionRequest, CreateConnectionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateDeviceResult> createDeviceAsync(CreateDeviceRequest request) { return createDeviceAsync(request, null); } @Override public java.util.concurrent.Future<CreateDeviceResult> createDeviceAsync(CreateDeviceRequest request, com.amazonaws.handlers.AsyncHandler<CreateDeviceRequest, CreateDeviceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateGlobalNetworkResult> createGlobalNetworkAsync(CreateGlobalNetworkRequest request) { return createGlobalNetworkAsync(request, null); } @Override public java.util.concurrent.Future<CreateGlobalNetworkResult> createGlobalNetworkAsync(CreateGlobalNetworkRequest request, com.amazonaws.handlers.AsyncHandler<CreateGlobalNetworkRequest, CreateGlobalNetworkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateLinkResult> createLinkAsync(CreateLinkRequest request) { return createLinkAsync(request, null); } @Override public java.util.concurrent.Future<CreateLinkResult> createLinkAsync(CreateLinkRequest request, com.amazonaws.handlers.AsyncHandler<CreateLinkRequest, CreateLinkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateSiteResult> createSiteAsync(CreateSiteRequest request) { return createSiteAsync(request, null); } @Override public java.util.concurrent.Future<CreateSiteResult> createSiteAsync(CreateSiteRequest request, com.amazonaws.handlers.AsyncHandler<CreateSiteRequest, CreateSiteResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteConnectionResult> deleteConnectionAsync(DeleteConnectionRequest request) { return deleteConnectionAsync(request, null); } @Override public java.util.concurrent.Future<DeleteConnectionResult> deleteConnectionAsync(DeleteConnectionRequest request, com.amazonaws.handlers.AsyncHandler<DeleteConnectionRequest, DeleteConnectionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteDeviceResult> deleteDeviceAsync(DeleteDeviceRequest request) { return deleteDeviceAsync(request, null); } @Override public java.util.concurrent.Future<DeleteDeviceResult> deleteDeviceAsync(DeleteDeviceRequest request, com.amazonaws.handlers.AsyncHandler<DeleteDeviceRequest, DeleteDeviceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteGlobalNetworkResult> deleteGlobalNetworkAsync(DeleteGlobalNetworkRequest request) { return deleteGlobalNetworkAsync(request, null); } @Override public java.util.concurrent.Future<DeleteGlobalNetworkResult> deleteGlobalNetworkAsync(DeleteGlobalNetworkRequest request, com.amazonaws.handlers.AsyncHandler<DeleteGlobalNetworkRequest, DeleteGlobalNetworkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteLinkResult> deleteLinkAsync(DeleteLinkRequest request) { return deleteLinkAsync(request, null); } @Override public java.util.concurrent.Future<DeleteLinkResult> deleteLinkAsync(DeleteLinkRequest request, com.amazonaws.handlers.AsyncHandler<DeleteLinkRequest, DeleteLinkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteSiteResult> deleteSiteAsync(DeleteSiteRequest request) { return deleteSiteAsync(request, null); } @Override public java.util.concurrent.Future<DeleteSiteResult> deleteSiteAsync(DeleteSiteRequest request, com.amazonaws.handlers.AsyncHandler<DeleteSiteRequest, DeleteSiteResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeregisterTransitGatewayResult> deregisterTransitGatewayAsync(DeregisterTransitGatewayRequest request) { return deregisterTransitGatewayAsync(request, null); } @Override public java.util.concurrent.Future<DeregisterTransitGatewayResult> deregisterTransitGatewayAsync(DeregisterTransitGatewayRequest request, com.amazonaws.handlers.AsyncHandler<DeregisterTransitGatewayRequest, DeregisterTransitGatewayResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeGlobalNetworksResult> describeGlobalNetworksAsync(DescribeGlobalNetworksRequest request) { return describeGlobalNetworksAsync(request, null); } @Override public java.util.concurrent.Future<DescribeGlobalNetworksResult> describeGlobalNetworksAsync(DescribeGlobalNetworksRequest request, com.amazonaws.handlers.AsyncHandler<DescribeGlobalNetworksRequest, DescribeGlobalNetworksResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DisassociateCustomerGatewayResult> disassociateCustomerGatewayAsync(DisassociateCustomerGatewayRequest request) { return disassociateCustomerGatewayAsync(request, null); } @Override public java.util.concurrent.Future<DisassociateCustomerGatewayResult> disassociateCustomerGatewayAsync(DisassociateCustomerGatewayRequest request, com.amazonaws.handlers.AsyncHandler<DisassociateCustomerGatewayRequest, DisassociateCustomerGatewayResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DisassociateLinkResult> disassociateLinkAsync(DisassociateLinkRequest request) { return disassociateLinkAsync(request, null); } @Override public java.util.concurrent.Future<DisassociateLinkResult> disassociateLinkAsync(DisassociateLinkRequest request, com.amazonaws.handlers.AsyncHandler<DisassociateLinkRequest, DisassociateLinkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DisassociateTransitGatewayConnectPeerResult> disassociateTransitGatewayConnectPeerAsync( DisassociateTransitGatewayConnectPeerRequest request) { return disassociateTransitGatewayConnectPeerAsync(request, null); } @Override public java.util.concurrent.Future<DisassociateTransitGatewayConnectPeerResult> disassociateTransitGatewayConnectPeerAsync( DisassociateTransitGatewayConnectPeerRequest request, com.amazonaws.handlers.AsyncHandler<DisassociateTransitGatewayConnectPeerRequest, DisassociateTransitGatewayConnectPeerResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetConnectionsResult> getConnectionsAsync(GetConnectionsRequest request) { return getConnectionsAsync(request, null); } @Override public java.util.concurrent.Future<GetConnectionsResult> getConnectionsAsync(GetConnectionsRequest request, com.amazonaws.handlers.AsyncHandler<GetConnectionsRequest, GetConnectionsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetCustomerGatewayAssociationsResult> getCustomerGatewayAssociationsAsync(GetCustomerGatewayAssociationsRequest request) { return getCustomerGatewayAssociationsAsync(request, null); } @Override public java.util.concurrent.Future<GetCustomerGatewayAssociationsResult> getCustomerGatewayAssociationsAsync(GetCustomerGatewayAssociationsRequest request, com.amazonaws.handlers.AsyncHandler<GetCustomerGatewayAssociationsRequest, GetCustomerGatewayAssociationsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetDevicesResult> getDevicesAsync(GetDevicesRequest request) { return getDevicesAsync(request, null); } @Override public java.util.concurrent.Future<GetDevicesResult> getDevicesAsync(GetDevicesRequest request, com.amazonaws.handlers.AsyncHandler<GetDevicesRequest, GetDevicesResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetLinkAssociationsResult> getLinkAssociationsAsync(GetLinkAssociationsRequest request) { return getLinkAssociationsAsync(request, null); } @Override public java.util.concurrent.Future<GetLinkAssociationsResult> getLinkAssociationsAsync(GetLinkAssociationsRequest request, com.amazonaws.handlers.AsyncHandler<GetLinkAssociationsRequest, GetLinkAssociationsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetLinksResult> getLinksAsync(GetLinksRequest request) { return getLinksAsync(request, null); } @Override public java.util.concurrent.Future<GetLinksResult> getLinksAsync(GetLinksRequest request, com.amazonaws.handlers.AsyncHandler<GetLinksRequest, GetLinksResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetSitesResult> getSitesAsync(GetSitesRequest request) { return getSitesAsync(request, null); } @Override public java.util.concurrent.Future<GetSitesResult> getSitesAsync(GetSitesRequest request, com.amazonaws.handlers.AsyncHandler<GetSitesRequest, GetSitesResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetTransitGatewayConnectPeerAssociationsResult> getTransitGatewayConnectPeerAssociationsAsync( GetTransitGatewayConnectPeerAssociationsRequest request) { return getTransitGatewayConnectPeerAssociationsAsync(request, null); } @Override public java.util.concurrent.Future<GetTransitGatewayConnectPeerAssociationsResult> getTransitGatewayConnectPeerAssociationsAsync( GetTransitGatewayConnectPeerAssociationsRequest request, com.amazonaws.handlers.AsyncHandler<GetTransitGatewayConnectPeerAssociationsRequest, GetTransitGatewayConnectPeerAssociationsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetTransitGatewayRegistrationsResult> getTransitGatewayRegistrationsAsync(GetTransitGatewayRegistrationsRequest request) { return getTransitGatewayRegistrationsAsync(request, null); } @Override public java.util.concurrent.Future<GetTransitGatewayRegistrationsResult> getTransitGatewayRegistrationsAsync(GetTransitGatewayRegistrationsRequest request, com.amazonaws.handlers.AsyncHandler<GetTransitGatewayRegistrationsRequest, GetTransitGatewayRegistrationsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) { return listTagsForResourceAsync(request, null); } @Override public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request, com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<RegisterTransitGatewayResult> registerTransitGatewayAsync(RegisterTransitGatewayRequest request) { return registerTransitGatewayAsync(request, null); } @Override public java.util.concurrent.Future<RegisterTransitGatewayResult> registerTransitGatewayAsync(RegisterTransitGatewayRequest request, com.amazonaws.handlers.AsyncHandler<RegisterTransitGatewayRequest, RegisterTransitGatewayResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) { return tagResourceAsync(request, null); } @Override public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request, com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) { return untagResourceAsync(request, null); } @Override public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request, com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateConnectionResult> updateConnectionAsync(UpdateConnectionRequest request) { return updateConnectionAsync(request, null); } @Override public java.util.concurrent.Future<UpdateConnectionResult> updateConnectionAsync(UpdateConnectionRequest request, com.amazonaws.handlers.AsyncHandler<UpdateConnectionRequest, UpdateConnectionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateDeviceResult> updateDeviceAsync(UpdateDeviceRequest request) { return updateDeviceAsync(request, null); } @Override public java.util.concurrent.Future<UpdateDeviceResult> updateDeviceAsync(UpdateDeviceRequest request, com.amazonaws.handlers.AsyncHandler<UpdateDeviceRequest, UpdateDeviceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateGlobalNetworkResult> updateGlobalNetworkAsync(UpdateGlobalNetworkRequest request) { return updateGlobalNetworkAsync(request, null); } @Override public java.util.concurrent.Future<UpdateGlobalNetworkResult> updateGlobalNetworkAsync(UpdateGlobalNetworkRequest request, com.amazonaws.handlers.AsyncHandler<UpdateGlobalNetworkRequest, UpdateGlobalNetworkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateLinkResult> updateLinkAsync(UpdateLinkRequest request) { return updateLinkAsync(request, null); } @Override public java.util.concurrent.Future<UpdateLinkResult> updateLinkAsync(UpdateLinkRequest request, com.amazonaws.handlers.AsyncHandler<UpdateLinkRequest, UpdateLinkResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateSiteResult> updateSiteAsync(UpdateSiteRequest request) { return updateSiteAsync(request, null); } @Override public java.util.concurrent.Future<UpdateSiteResult> updateSiteAsync(UpdateSiteRequest request, com.amazonaws.handlers.AsyncHandler<UpdateSiteRequest, UpdateSiteResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } }
6,200
496
<reponame>anshul2807/Automation-scripts<gh_stars>100-1000 import cv2 import numpy as np import pandas as pd import sys # Define the file name of the image INPUT_IMAGE = sys.argv[1] IMAGE_NAME = INPUT_IMAGE[:INPUT_IMAGE.index(".")] OUTPUT_IMAGE = IMAGE_NAME + "_annotated.jpg" output_csv_file = sys.argv[2] # Load the image and store into a variable # -1 means load unchanged image = cv2.imread(INPUT_IMAGE, -1) # Create lists to store all x, y, and annotation values x_vals = [] y_vals = [] annotation_vals = [] # Dictionary containing some colors colors = {'blue': (255, 0, 0), 'green': (0, 255, 0), 'red': (0, 0, 255), 'yellow': (0, 255, 255), 'magenta': (255, 0, 255), 'cyan': (255, 255, 0), 'white': (255, 255, 255), 'black': (0, 0, 0), 'gray': (125, 125, 125), 'rand': np.random.randint(0, high=256, size=(3,)).tolist(), 'dark_gray': (50, 50, 50), 'light_gray': (220, 220, 220)} def draw_circle(event, x, y, flags, param): """ Draws dots on double clicking of the left mouse button """ # Store the height and width of the image # height = image.shape[0] width = image.shape[1] if event == cv2.EVENT_LBUTTONDBLCLK: # Draw the dot cv2.circle(image, (x, y), 5, colors['magenta'], -1) # Annotate the image txt = input("Describe this pixel using one word (e.g. dog) and press ENTER: ") # Append values to the list x_vals.append(x) y_vals.append(y) annotation_vals.append(txt) # Print the coordinates and the annotation to the console print("x = " + str(x) + " y = " + str(y) + " Annotation = " + txt + "\n") # Set the position of the text part of the annotation text_x_pos = None text_y_pos = y if x < (width / 2) : text_x_pos = int(x + (width * 0.075)) else: text_x_pos = int(x - (width * 0.075)) # Write text on the image cv2.putText(image, txt, (text_x_pos, text_y_pos), cv2.FONT_HERSHEY_SIMPLEX, 1, colors['magenta'], 2) cv2.imwrite(OUTPUT_IMAGE, image) # Prompt user for another annotation print("Double click another pixel or press 'q' to quit...\n") print("Welcome to the Image Annotation Program!\n") print("Double click anywhere inside the image to annotate that point...\n") # We create a named window where the mouse callback will be established cv2.namedWindow('Image mouse') # We set the mouse callback function to 'draw_circle': cv2.setMouseCallback('Image mouse', draw_circle) while True: # Show image 'Image mouse': cv2.imshow('Image mouse', image) # Continue until 'q' is pressed: if cv2.waitKey(20) & 0xFF == ord('q'): break # Create a dictionary using lists data = {'X': x_vals, 'Y': y_vals, 'Annotation': annotation_vals} # Create the Pandas DataFrame df = pd.DataFrame(data) print() print(df) print() # Export the dataframe to a csv file df.to_csv(path_or_buf=output_csv_file, index=None, header=True) # Destroy all generated windows: cv2.destroyAllWindows()
1,303
488
typedef struct _HTStream HTStream; struct _HTStream {}; typedef HTStream * HTConverter (void * param); extern HTConverter HTThroughLine; extern HTConverter HTBlackHoleConverter;
65
1,847
/* * Copyright (C) 2017 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. */ #ifndef _LIBUNWINDSTACK_TESTS_ELF_FAKE_H #define _LIBUNWINDSTACK_TESTS_ELF_FAKE_H #include <stdint.h> #include <deque> #include <string> #include <unordered_map> #include <unwindstack/Elf.h> #include <unwindstack/ElfInterface.h> #include <unwindstack/Memory.h> #include <unwindstack/Regs.h> #include <unwindstack/SharedString.h> #include "ElfInterfaceArm.h" namespace unwindstack { struct StepData { StepData(uint64_t pc, uint64_t sp, bool finished) : pc(pc), sp(sp), finished(finished) {} uint64_t pc; uint64_t sp; bool finished; }; struct FunctionData { FunctionData(std::string name, uint64_t offset) : name(name), offset(offset) {} std::string name; uint64_t offset; }; class ElfFake : public Elf { public: ElfFake(Memory* memory) : Elf(memory) { valid_ = true; } virtual ~ElfFake() = default; void FakeSetValid(bool valid) { valid_ = valid; } void FakeSetLoadBias(uint64_t load_bias) { load_bias_ = load_bias; } void FakeSetArch(ArchEnum arch) { arch_ = arch; } void FakeSetInterface(ElfInterface* interface) { interface_.reset(interface); } void FakeSetGnuDebugdataInterface(ElfInterface* interface) { gnu_debugdata_interface_.reset(interface); } }; class ElfInterfaceFake : public ElfInterface { public: ElfInterfaceFake(Memory* memory) : ElfInterface(memory) {} virtual ~ElfInterfaceFake() = default; bool Init(int64_t*) override { return false; } void InitHeaders() override {} std::string GetSoname() override { return fake_soname_; } bool GetFunctionName(uint64_t, SharedString*, uint64_t*) override; bool GetGlobalVariable(const std::string&, uint64_t*) override; std::string GetBuildID() override { return fake_build_id_; } bool Step(uint64_t, Regs*, Memory*, bool*, bool*) override; void FakeSetGlobalVariable(const std::string& global, uint64_t offset) { globals_[global] = offset; } void FakeSetBuildID(std::string& build_id) { fake_build_id_ = build_id; } void FakeSetBuildID(const char* build_id) { fake_build_id_ = build_id; } void FakeSetSoname(const char* soname) { fake_soname_ = soname; } static void FakePushFunctionData(const FunctionData data) { functions_.push_back(data); } static void FakePushStepData(const StepData data) { steps_.push_back(data); } static void FakeClear() { functions_.clear(); steps_.clear(); } void FakeSetErrorCode(ErrorCode code) { last_error_.code = code; } void FakeSetErrorAddress(uint64_t address) { last_error_.address = address; } void FakeSetDataOffset(uint64_t offset) { data_offset_ = offset; } void FakeSetDataVaddrStart(uint64_t vaddr) { data_vaddr_start_ = vaddr; } void FakeSetDataVaddrEnd(uint64_t vaddr) { data_vaddr_end_ = vaddr; } void FakeSetDynamicOffset(uint64_t offset) { dynamic_offset_ = offset; } void FakeSetDynamicVaddrStart(uint64_t vaddr) { dynamic_vaddr_start_ = vaddr; } void FakeSetDynamicVaddrEnd(uint64_t vaddr) { dynamic_vaddr_end_ = vaddr; } void FakeSetGnuDebugdataOffset(uint64_t offset) { gnu_debugdata_offset_ = offset; } void FakeSetGnuDebugdataSize(uint64_t size) { gnu_debugdata_size_ = size; } private: std::unordered_map<std::string, uint64_t> globals_; std::string fake_build_id_; std::string fake_soname_; static std::deque<FunctionData> functions_; static std::deque<StepData> steps_; }; class ElfInterface32Fake : public ElfInterface32 { public: ElfInterface32Fake(Memory* memory) : ElfInterface32(memory) {} virtual ~ElfInterface32Fake() = default; void FakeSetEhFrameOffset(uint64_t offset) { eh_frame_offset_ = offset; } void FakeSetEhFrameSize(uint64_t size) { eh_frame_size_ = size; } void FakeSetDebugFrameOffset(uint64_t offset) { debug_frame_offset_ = offset; } void FakeSetDebugFrameSize(uint64_t size) { debug_frame_size_ = size; } }; class ElfInterface64Fake : public ElfInterface64 { public: ElfInterface64Fake(Memory* memory) : ElfInterface64(memory) {} virtual ~ElfInterface64Fake() = default; void FakeSetEhFrameOffset(uint64_t offset) { eh_frame_offset_ = offset; } void FakeSetEhFrameSize(uint64_t size) { eh_frame_size_ = size; } void FakeSetDebugFrameOffset(uint64_t offset) { debug_frame_offset_ = offset; } void FakeSetDebugFrameSize(uint64_t size) { debug_frame_size_ = size; } }; class ElfInterfaceArmFake : public ElfInterfaceArm { public: ElfInterfaceArmFake(Memory* memory) : ElfInterfaceArm(memory) {} virtual ~ElfInterfaceArmFake() = default; void FakeSetStartOffset(uint64_t offset) { start_offset_ = offset; } void FakeSetTotalEntries(size_t entries) { total_entries_ = entries; } }; } // namespace unwindstack #endif // _LIBUNWINDSTACK_TESTS_ELF_FAKE_H
1,747
1,018
<gh_stars>1000+ # SPDX-License-Identifier: MIT # Copyright (C) 2018-present iced project and contributors # ⚠️This file was generated by GENERATOR!🦹‍♂️ # pylint: disable=invalid-name # pylint: disable=line-too-long # pylint: disable=too-many-lines """ Decoder error """ import typing if typing.TYPE_CHECKING: from ._iced_x86_py import DecoderError else: DecoderError = int NONE: DecoderError = 0 # type: ignore """ No error. The last decoded instruction is a valid instruction """ INVALID_INSTRUCTION: DecoderError = 1 # type: ignore """ It's an invalid instruction or an invalid encoding of an existing instruction (eg. some reserved bit is set/cleared) """ NO_MORE_BYTES: DecoderError = 2 # type: ignore """ There's not enough bytes left to decode the instruction """
250
348
{"nom":"Pontis","dpt":"Alpes-de-Haute-Provence","inscrits":92,"abs":19,"votants":73,"blancs":8,"nuls":1,"exp":64,"res":[{"panneau":"2","voix":35},{"panneau":"1","voix":29}]}
75
421
//<snippet1> #using <System.Xml.dll> using namespace System; using namespace System::Xml; using namespace System::Xml::Schema; ref class XmlDocumentSample { private: static XmlReader^ reader; static String^ filename = "bookdtd.xml"; // Display the validation error. static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) { Console::WriteLine("Validation error loading: {0}", filename); Console::WriteLine(args->Message); } public: static void Main() { ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(XmlDocumentSample::ValidationCallback); try { // Create the validating reader and specify DTD validation. XmlReaderSettings^ settings = gcnew XmlReaderSettings(); settings->DtdProcessing = DtdProcessing::Parse; settings->ValidationType = ValidationType::DTD; settings->ValidationEventHandler += eventHandler; reader = XmlReader::Create(filename, settings); // Pass the validating reader to the XML document. // Validation fails due to an undefined attribute, but the // data is still loaded into the document. XmlDocument^ doc = gcnew XmlDocument(); doc->Load(reader); Console::WriteLine(doc->OuterXml); } finally { if (reader != nullptr) reader->Close(); } } }; int main() { XmlDocumentSample::Main(); return 0; } //</snippet1>
533
335
{ "word": "Waif", "definitions": [ "A homeless, neglected, or abandoned person, especially a child.", "A small, thin person who appears to be undernourished and neglected." ], "parts-of-speech": "Noun" }
90
1,056
<reponame>timfel/netbeans /* * 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.netbeans.modules.subversion.client; import java.io.*; import java.text.ParseException; import java.util.*; import org.netbeans.modules.subversion.Subversion; import org.netbeans.modules.subversion.client.parser.ParserSvnInfo; import org.netbeans.modules.subversion.client.parser.SvnWcUtils; import org.netbeans.modules.subversion.config.KVFile; import org.netbeans.modules.subversion.util.SvnUtils; import org.tigris.subversion.svnclientadapter.ISVNInfo; import org.tigris.subversion.svnclientadapter.ISVNProperty; import org.tigris.subversion.svnclientadapter.SVNClientException; import org.tigris.subversion.svnclientadapter.SVNRevision; /** * Implements properties access that is not supported * by svnClientAdapter library. It access <tt>.svn</tt> * metadata directly: * * <pre> * trunk/ * .svn/ * dir-props (KV file format) * dir-props-base (KV file format) * props/ * filename.svn-base (KV file format) * filename_newprop.svn-base (KV file format) * props-base/ * filename.svn-base (KV file format) * filename * filename_newprop * </pre> * * <b>The implemetation should be moved into svnClientAdpater * library!</b> * * <strong>Works also with 1.7+ working copies, however does not access metadata but calls methods on * {@link org.tigris.subversion.svnclientadapter.ISVNClientAdapter} instead. * Performance comes into question here - that's because svn props are not displayed in Local_changes mode.</strong> * * @author <NAME> */ public final class PropertiesClient { private final File file; /** Creates a new instance of PropertiesClient */ public PropertiesClient(File file) { assert file != null; this.file = file; } /** * Loads BASE properties for given file. * @return property map&lt;String, byte[]> never null */ public Map<String, byte[]> getBaseProperties (boolean contactServer) throws IOException { // XXX: refactor code, join with getProperties() if (hasOldMetadata(file)) { File store; try { store = getPropertyFile(true); } catch (SVNClientException ex) { throw new IOException(ex.getMessage()); } if (store != null && store.isFile()) { KVFile kv = new KVFile(store); return kv.getNormalizedMap(); } else { return new HashMap<String, byte[]>(); } } else { Map<String, byte[]> map = new HashMap<String, byte[]>(); try { if (contactServer) { SvnClient client = Subversion.getInstance().getClient(file); if (client != null) { ISVNInfo info = SvnUtils.getInfoFromWorkingCopy(client, file); if (info != null && (info.getUrl() != null || info.getCopyUrl() != null) && info.getRevision() != null && info.getRevision().getNumber() > -1) { ISVNProperty[] props = client.getProperties(info.getCopyUrl() == null ? info.getUrl() : info.getCopyUrl(), SVNRevision.getRevision(info.getRevision().toString()), SVNRevision.getRevision(info.getRevision().toString()), false); for (ISVNProperty prop : props) { map.put(prop.getName(), prop.getData()); } } } } else { return getProperties(); } return map; } catch (SVNClientException ex) { return map; } catch (ParseException ex) { return map; } } } /** * Loads (locally modified) properties for given file. * @return property map&lt;String, byte[]> never null */ public Map<String, byte[]> getProperties() throws IOException { if (hasOldMetadata(file)) { File store; try { store = getPropertyFile(false); if (store == null) { // if no changes are made, the props.work does not exist // so return the base prop-file - see # store = getPropertyFile(true); } } catch (SVNClientException ex) { throw new IOException(ex.getMessage()); } if (store != null && store.isFile()) { KVFile kv = new KVFile(store); return kv.getNormalizedMap(); } else { return new HashMap<String, byte[]>(); } } else { try { SvnClient client = Subversion.getInstance().getClient(false); Map<String, byte[]> map = new HashMap<String, byte[]>(); if (client != null) { ISVNProperty[] props = client.getProperties(file); for (ISVNProperty prop : props) { map.put(prop.getName(), prop.getData()); } } return map; } catch (SVNClientException ex) { return new HashMap<String, byte[]>(); } } } private File getPropertyFile(boolean base) throws SVNClientException { SvnClient client = Subversion.getInstance().getClient(false); ISVNInfo info = null; try { info = SvnUtils.getInfoFromWorkingCopy(client, file); } catch (SVNClientException ex) { throw ex; } if(info instanceof ParserSvnInfo) { if(base) { return ((ParserSvnInfo) info).getBasePropertyFile(); } else { return ((ParserSvnInfo) info).getPropertyFile(); } } else { return SvnWcUtils.getPropertiesFile(file, base); } } /** Not implemented. */ public Map getProperties(int revision) throws IOException { throw new UnsupportedOperationException(); } public static boolean hasOldMetadata (File file) { File parent; return new File(file, SvnUtils.SVN_ENTRIES_DIR).canRead() || (parent = file.getParentFile()) != null && new File(parent, SvnUtils.SVN_ENTRIES_DIR).canRead() && !new File(parent, SvnUtils.SVN_WC_DB).exists(); } }
3,496
338
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> #include <exception> #include <vector> #include <string> #include "itkImage.h" #include "itkPointSet.h" #include "itkDisplacementFieldToBSplineImageFilter.h" #include "LOCAL_antsImage.h" namespace py = pybind11; template<unsigned int Dimension> py::capsule fitBsplineVectorImageToScatteredDataHelper( py::array_t<double> displacementOrigins, py::array_t<double> displacements, std::vector<double> displacementWeights, py::array_t<double> origin, py::array_t<double> spacing, py::array_t<unsigned int> size, py::array_t<double> direction, unsigned int numberOfFittingLevels, std::vector<unsigned int> numberOfControlPoints, unsigned int splineOrder, bool enforceStationaryBoundary, bool estimateInverse ) { using RealType = float; using ANTsFieldType = itk::VectorImage<RealType, Dimension>; using ANTsFieldPointerType = typename ANTsFieldType::Pointer; using VectorType = itk::Vector<RealType, Dimension>; using PointSetType = itk::PointSet<VectorType, Dimension>; using ITKFieldType = itk::Image<VectorType, Dimension>; using ITKFieldPointerType = typename ITKFieldType::Pointer; using IteratorType = itk::ImageRegionIteratorWithIndex<ITKFieldType>; using BSplineFilterType = itk::DisplacementFieldToBSplineImageFilter<ITKFieldType, PointSetType>; using WeightsContainerType = typename BSplineFilterType::WeightsContainerType; typename BSplineFilterType::Pointer bsplineFilter = BSplineFilterType::New(); //////////////////////////// // // Add the inputs (if they are specified) // auto displacementOriginsP = displacementOrigins.unchecked<2>(); auto displacementsP = displacements.unchecked<2>(); unsigned int numberOfPoints = displacementsP.shape(0); if( numberOfPoints > 0 ) { typename PointSetType::Pointer pointSet = PointSetType::New(); pointSet->Initialize(); typename WeightsContainerType::Pointer weights = WeightsContainerType::New(); unsigned int numberOfPoints = displacementsP.shape(0); for( unsigned int n = 0; n < numberOfPoints; n++ ) { typename PointSetType::PointType point; for( unsigned int d = 0; d < Dimension; d++ ) { point[d] = displacementOriginsP(n, d); } pointSet->SetPoint( n, point ); VectorType data( 0.0 ); for( unsigned int d = 0; d < Dimension; d++ ) { data[d] = displacementsP(n, d); } pointSet->SetPointData( n, data ); weights->InsertElement( n, displacementWeights[n] ); } bsplineFilter->SetPointSet( pointSet ); bsplineFilter->SetPointSetConfidenceWeights( weights ); } //////////////////////////// // // Define the output B-spline field domain // auto originP = origin.unchecked<1>(); auto spacingP = spacing.unchecked<1>(); auto sizeP = size.unchecked<1>(); auto directionP = direction.unchecked<2>(); if( originP.shape(0) == 0 || sizeP.shape(0) == 0 || spacingP.shape(0) == 0 || directionP.shape(0) == 0 ) { throw std::invalid_argument( "one or more b-spline domain definitions are not specified." ); } else { typename ITKFieldType::PointType fieldOrigin; typename ITKFieldType::SpacingType fieldSpacing; typename ITKFieldType::SizeType fieldSize; typename ITKFieldType::DirectionType fieldDirection; for( unsigned int d = 0; d < Dimension; d++ ) { fieldOrigin[d] = originP(d); fieldSpacing[d] = spacingP(d); fieldSize[d] = sizeP(d); for( unsigned int e = 0; e < Dimension; e++ ) { fieldDirection(d, e) = directionP(d, e); } } bsplineFilter->SetBSplineDomain( fieldOrigin, fieldSpacing, fieldSize, fieldDirection ); } typename BSplineFilterType::ArrayType ncps; typename BSplineFilterType::ArrayType isClosed; for( unsigned int d = 0; d < Dimension; d++ ) { ncps[d] = numberOfControlPoints[d]; } bsplineFilter->SetNumberOfControlPoints( ncps ); bsplineFilter->SetSplineOrder( splineOrder ); bsplineFilter->SetNumberOfFittingLevels( numberOfFittingLevels ); bsplineFilter->SetEnforceStationaryBoundary( enforceStationaryBoundary ); bsplineFilter->SetEstimateInverse( estimateInverse ); bsplineFilter->Update(); ////////////////////////// // // Now convert back to vector image type. // ANTsFieldPointerType antsField = ANTsFieldType::New(); antsField->CopyInformation( bsplineFilter->GetOutput() ); antsField->SetRegions( bsplineFilter->GetOutput()->GetRequestedRegion() ); antsField->SetVectorLength( Dimension ); antsField->Allocate(); IteratorType It( bsplineFilter->GetOutput(), bsplineFilter->GetOutput()->GetRequestedRegion() ); for( It.GoToBegin(); !It.IsAtEnd(); ++It ) { VectorType data = It.Value(); typename ANTsFieldType::PixelType antsVector( Dimension ); for( unsigned int d = 0; d < Dimension; d++ ) { antsVector[d] = data[d]; } antsField->SetPixel( It.GetIndex(), antsVector ); } return wrap< ANTsFieldType >( antsField ); } PYBIND11_MODULE(fitBsplineDisplacementFieldToScatteredData, m) { m.def("fitBsplineDisplacementFieldToScatteredDataD2", &fitBsplineVectorImageToScatteredDataHelper<2>); m.def("fitBsplineDisplacementFieldToScatteredDataD3", &fitBsplineVectorImageToScatteredDataHelper<3>); }
1,935
751
<filename>src/plugins/ioam/lib-vxlan-gpe/vxlan_gpe_api.c /* * Copyright (c) 2016 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. */ /* *------------------------------------------------------------------ * vxlan_gpe_api.c - iOAM VxLAN-GPE related APIs to create * and maintain profiles *------------------------------------------------------------------ */ #include <vnet/vnet.h> #include <vnet/plugin/plugin.h> #include <ioam/lib-vxlan-gpe/vxlan_gpe_ioam.h> #include <vlibapi/api_helper_macros.h> #include <vlibapi/api.h> #include <vlibmemory/api.h> #include <vnet/format_fns.h> #include <vnet/ip/ip_types_api.h> #include <vnet/udp/udp_local.h> /* define message IDs */ #include <ioam/lib-vxlan-gpe/ioam_vxlan_gpe.api_enum.h> #include <ioam/lib-vxlan-gpe/ioam_vxlan_gpe.api_types.h> static void vl_api_vxlan_gpe_ioam_enable_t_handler (vl_api_vxlan_gpe_ioam_enable_t * mp) { int rv = 0; vl_api_vxlan_gpe_ioam_enable_reply_t *rmp; clib_error_t *error; /* Ignoring the profile id as currently a single profile * is supported */ error = vxlan_gpe_ioam_enable (mp->trace_enable, mp->pow_enable, mp->trace_ppc); if (error) { clib_error_report (error); rv = clib_error_get_code (error); } REPLY_MACRO (VL_API_VXLAN_GPE_IOAM_ENABLE_REPLY); } static void vl_api_vxlan_gpe_ioam_disable_t_handler (vl_api_vxlan_gpe_ioam_disable_t * mp) { int rv = 0; vl_api_vxlan_gpe_ioam_disable_reply_t *rmp; clib_error_t *error; /* Ignoring the profile id as currently a single profile * is supported */ error = vxlan_gpe_ioam_disable (0, 0, 0); if (error) { clib_error_report (error); rv = clib_error_get_code (error); } REPLY_MACRO (VL_API_VXLAN_GPE_IOAM_DISABLE_REPLY); } static void vl_api_vxlan_gpe_ioam_vni_enable_t_handler (vl_api_vxlan_gpe_ioam_vni_enable_t * mp) { int rv = 0; vl_api_vxlan_gpe_ioam_vni_enable_reply_t *rmp; clib_error_t *error; vxlan4_gpe_tunnel_key_t key4; uword *p = NULL; vxlan_gpe_main_t *gm = &vxlan_gpe_main; vxlan_gpe_tunnel_t *t = 0; vxlan_gpe_ioam_main_t *hm = &vxlan_gpe_ioam_main; u32 vni; if (clib_net_to_host_u32 (mp->local.af) == ADDRESS_IP4 && clib_net_to_host_u32 (mp->remote.af) == ADDRESS_IP4) { clib_memcpy (&key4.local, &mp->local.un.ip4, sizeof (key4.local)); clib_memcpy (&key4.remote, &mp->remote.un.ip4, sizeof (key4.remote)); vni = clib_net_to_host_u32 (mp->vni); key4.vni = clib_host_to_net_u32 (vni << 8); key4.port = clib_host_to_net_u16 (UDP_DST_PORT_VXLAN_GPE); p = hash_get_mem (gm->vxlan4_gpe_tunnel_by_key, &key4); } else { return; } if (!p) return; t = pool_elt_at_index (gm->tunnels, p[0]); error = vxlan_gpe_ioam_set (t, hm->has_trace_option, hm->has_pot_option, hm->has_ppc_option, 0 /* is_ipv6 */ ); if (error) { clib_error_report (error); rv = clib_error_get_code (error); } REPLY_MACRO (VL_API_VXLAN_GPE_IOAM_VNI_ENABLE_REPLY); } static void vl_api_vxlan_gpe_ioam_vni_disable_t_handler (vl_api_vxlan_gpe_ioam_vni_disable_t * mp) { int rv = 0; vl_api_vxlan_gpe_ioam_vni_enable_reply_t *rmp; clib_error_t *error; vxlan4_gpe_tunnel_key_t key4; uword *p = NULL; vxlan_gpe_main_t *gm = &vxlan_gpe_main; vxlan_gpe_tunnel_t *t = 0; u32 vni; if (clib_net_to_host_u32 (mp->local.af) == ADDRESS_IP4 && clib_net_to_host_u32 (mp->remote.af) == ADDRESS_IP4) { clib_memcpy (&key4.local, &mp->local, sizeof (key4.local)); clib_memcpy (&key4.remote, &mp->remote, sizeof (key4.remote)); vni = clib_net_to_host_u32 (mp->vni); key4.vni = clib_host_to_net_u32 (vni << 8); key4.port = clib_host_to_net_u16 (UDP_DST_PORT_VXLAN_GPE); p = hash_get_mem (gm->vxlan4_gpe_tunnel_by_key, &key4); } else { return; } if (!p) return; t = pool_elt_at_index (gm->tunnels, p[0]); error = vxlan_gpe_ioam_clear (t, 0, 0, 0, 0); if (error) { clib_error_report (error); rv = clib_error_get_code (error); } REPLY_MACRO (VL_API_VXLAN_GPE_IOAM_VNI_DISABLE_REPLY); } static void vl_api_vxlan_gpe_ioam_transit_enable_t_handler (vl_api_vxlan_gpe_ioam_transit_enable_t * mp) { int rv = 0; vl_api_vxlan_gpe_ioam_transit_enable_reply_t *rmp; vxlan_gpe_ioam_main_t *sm = &vxlan_gpe_ioam_main; ip46_address_t dst_addr; ip_address_decode (&mp->dst_addr, &dst_addr); bool is_ip6 = clib_net_to_host_u32 (mp->dst_addr.af) == ADDRESS_IP6; rv = vxlan_gpe_enable_disable_ioam_for_dest (sm->vlib_main, dst_addr, ntohl (mp->outer_fib_index), is_ip6, 1 /* is_add */ ); REPLY_MACRO (VL_API_VXLAN_GPE_IOAM_TRANSIT_ENABLE_REPLY); } static void vl_api_vxlan_gpe_ioam_transit_disable_t_handler (vl_api_vxlan_gpe_ioam_transit_disable_t * mp) { int rv = 0; vl_api_vxlan_gpe_ioam_transit_disable_reply_t *rmp; vxlan_gpe_ioam_main_t *sm = &vxlan_gpe_ioam_main; ip46_address_t dst_addr; ip_address_decode (&mp->dst_addr, &dst_addr); bool is_ip6 = clib_net_to_host_u32 (mp->dst_addr.af) == ADDRESS_IP6; rv = vxlan_gpe_ioam_disable_for_dest (sm->vlib_main, dst_addr, ntohl (mp->outer_fib_index), is_ip6); REPLY_MACRO (VL_API_VXLAN_GPE_IOAM_TRANSIT_DISABLE_REPLY); } #include <ioam/lib-vxlan-gpe/ioam_vxlan_gpe.api.c> static clib_error_t * ioam_vxlan_gpe_init (vlib_main_t * vm) { vxlan_gpe_ioam_main_t *sm = &vxlan_gpe_ioam_main; u32 encap_node_index = vxlan_gpe_encap_ioam_v4_node.index; u32 decap_node_index = vxlan_gpe_decap_ioam_v4_node.index; vlib_node_t *vxlan_gpe_encap_node = NULL; vlib_node_t *vxlan_gpe_decap_node = NULL; uword next_node = 0; sm->vlib_main = vm; sm->vnet_main = vnet_get_main (); sm->unix_time_0 = (u32) time (0); /* Store starting time */ sm->vlib_time_0 = vlib_time_now (vm); /* Ask for a correctly-sized block of API message decode slots */ sm->msg_id_base = setup_message_id_table (); /* Hook the ioam-encap node to vxlan-gpe-encap */ vxlan_gpe_encap_node = vlib_get_node_by_name (vm, (u8 *) "vxlan-gpe-encap"); sm->encap_v4_next_node = vlib_node_add_next (vm, vxlan_gpe_encap_node->index, encap_node_index); vxlan_gpe_decap_node = vlib_get_node_by_name (vm, (u8 *) "vxlan4-gpe-input"); next_node = vlib_node_add_next (vm, vxlan_gpe_decap_node->index, decap_node_index); vxlan_gpe_register_decap_protocol (VXLAN_GPE_PROTOCOL_IOAM, next_node); vec_new (vxlan_gpe_ioam_sw_interface_t, pool_elts (sm->sw_interfaces)); sm->dst_by_ip4 = hash_create_mem (0, sizeof (fib_prefix_t), sizeof (uword)); sm->dst_by_ip6 = hash_create_mem (0, sizeof (fib_prefix_t), sizeof (uword)); vxlan_gpe_ioam_interface_init (); return 0; } VLIB_INIT_FUNCTION (ioam_vxlan_gpe_init); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
3,585
347
<reponame>hbraha/ovirt-engine # # ovirt-engine-setup -- ovirt engine setup # # Copyright oVirt Authors # SPDX-License-Identifier: Apache-2.0 # # """Notifier plugin.""" import gettext from otopi import plugin from otopi import util from ovirt_engine import configfile from ovirt_engine_setup.engine import constants as oenginecons from ovirt_setup_lib import dialog def _(m): return gettext.dgettext(message=m, domain='ovirt-engine-setup') @util.export class Plugin(plugin.PluginBase): """Notifier plugin.""" def __init__(self, context): super(Plugin, self).__init__(context=context) @plugin.event( stage=plugin.Stages.STAGE_INIT, ) def _init(self): self.environment.setdefault( oenginecons.ConfigEnv.IGNORE_VDS_GROUP_IN_NOTIFIER, None ) @plugin.event( stage=plugin.Stages.STAGE_VALIDATION, condition=lambda self: self.environment[ oenginecons.CoreEnv.ENABLE ] and not self.environment[ oenginecons.ConfigEnv.IGNORE_VDS_GROUP_IN_NOTIFIER ], ) def _validation(self): config = configfile.ConfigFile( ( oenginecons.FileLocations.OVIRT_ENGINE_NOTIFIER_SERVICE_CONFIG, ), ) filterStr = config.get('FILTER') self.logger.debug('filterStr: %s', filterStr) if filterStr is not None and 'VDS_GROUP' in filterStr: ans = dialog.queryBoolean( dialog=self.dialog, name='OVESETUP_WAIT_NOTIFIER_FILTER', note=_( 'Setup found filter/s in engine-notifier configuration ' 'files in {conf}.d/*.conf containing the string ' '"VDS_GROUP".\n You must manually change "VDS_GROUP" to ' '"CLUSTER" throughout the notifier configuration in ' 'order to get notified on cluster related events.\n Do ' 'you want to continue?\n' '(Answering "no" will stop the upgrade ' '(@VALUES@) [@DEFAULT@]: ' ).format( conf=( oenginecons.FileLocations. OVIRT_ENGINE_NOTIFIER_SERVICE_CONFIG ), ), prompt=True, default=False, ) self.environment[ oenginecons.ConfigEnv.IGNORE_VDS_GROUP_IN_NOTIFIER ] = ans if not ans: raise RuntimeError(_('Aborted by user')) # vim: expandtab tabstop=4 shiftwidth=4
1,326
460
/* * Copyright 2012 Google Inc. 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. */ #include <gtest/gtest.h> #include "BumpTop/BumpTopApp.h" #include "BumpTop/Cube.h" #include "BumpTop/Physics.h" #include "BumpTop/StaticBox.h" #include "BumpTop/PhysicsActor.h" namespace { class PhysicsTest : public ::testing::Test { protected: BumpTopApp *bumptop_; virtual void SetUp() { bumptop_ = BumpTopApp::singleton(); } virtual void TearDown() { bumptop_->ogre_scene_manager()->clearScene(); } }; TEST_F(PhysicsTest, Physics_exists) { Physics *physics = new Physics(); ASSERT_NE(reinterpret_cast<Physics*>(NULL), physics); physics->init(); delete physics; } TEST_F(PhysicsTest, Initialization_works) { Physics *physics = new Physics(); ASSERT_EQ(NULL, physics->dynamics_world()); physics->init(); ASSERT_NE(reinterpret_cast<btDiscreteDynamicsWorld*>(NULL), physics->dynamics_world()); delete physics; } TEST_F(PhysicsTest, Physics_meshes_with_other_stuff) { Physics *physics = new Physics(); physics->init(); // Create cube Cube cube(bumptop_->ogre_scene_manager(), physics, NULL); cube.init(); cube.set_position(Ogre::Vector3(0, 3, 0)); cube.set_size(2); // Create floor StaticBox floor(bumptop_->ogre_scene_manager(), physics, NULL); floor.init(); floor.set_size(Ogre::Vector3(1000, 1, 1000)); cube.applyCentralImpulse(Ogre::Vector3(1.0, 0.0, 0.0)); Ogre::Vector3 previous_position, position; int num_times_position_changed = -1; do { previous_position = cube.position(); physics->stepSimulation(1.f/60.f, 10); position = cube.position(); num_times_position_changed++; } while (previous_position != position); ASSERT_GT(num_times_position_changed, 0); EXPECT_NEAR(0.55, cube.position().x, 0.001); EXPECT_NEAR(1.5, cube.position().y, 0.001); EXPECT_NEAR(0.0, cube.position().z, 0.001); cube.set_position(Ogre::Vector3(2, 1.5, 2)); EXPECT_NEAR(2, cube.position().x, 0.001); EXPECT_NEAR(1.5, cube.position().y, 0.001); EXPECT_NEAR(2, cube.position().z, 0.001); position = cube.position(); physics->stepSimulation(1.f/60.f, 10); // do this a few times physics->stepSimulation(1.f/60.f, 10); physics->stepSimulation(1.f/60.f, 10); physics->stepSimulation(1.f/60.f, 10); physics->stepSimulation(1.f/60.f, 10); EXPECT_NEAR(2, cube.position().x, 0.001); EXPECT_NEAR(1.5, cube.position().y, 0.001); EXPECT_NEAR(2, cube.position().z, 0.001); cube.set_position(Ogre::Vector3(0, 10.0, 0)); ASSERT_EQ(Ogre::Vector3(0, 10.0, 0), cube.position()); num_times_position_changed = -1; do { previous_position = cube.position(); physics->stepSimulation(1.f/60.f, 10); position = cube.position(); num_times_position_changed++; } while (previous_position != position); ASSERT_GT(num_times_position_changed, 1); } } // namespace
1,392
4,047
int func1_in_obj(void); int func2_in_obj(void); int func3_in_obj(void); int main(void) { return func1_in_obj() + func2_in_obj() + func3_in_obj(); }
71
476
<filename>presto-orc/src/test/java/io/prestosql/orc/metadata/statistics/TestBooleanStatisticsBuilder.java /* * 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 io.prestosql.orc.metadata.statistics; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static io.prestosql.orc.metadata.statistics.AbstractStatisticsBuilderTest.StatisticsType.BOOLEAN; import static io.prestosql.orc.metadata.statistics.BooleanStatistics.BOOLEAN_VALUE_BYTES; import static io.prestosql.orc.metadata.statistics.ColumnStatistics.mergeColumnStatistics; import static org.testng.Assert.assertEquals; public class TestBooleanStatisticsBuilder extends AbstractStatisticsBuilderTest<BooleanStatisticsBuilder, Boolean> { public TestBooleanStatisticsBuilder() { super(BOOLEAN, BooleanStatisticsBuilder::new, BooleanStatisticsBuilder::addValue); } @Test public void testAddValueValues() { // add false then true BooleanStatisticsBuilder statisticsBuilder = new BooleanStatisticsBuilder(); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 0, 0); statisticsBuilder.addValue(false); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 1, 0); statisticsBuilder.addValue(false); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 2, 0); statisticsBuilder.addValue(true); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 3, 1); statisticsBuilder.addValue(true); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 4, 2); // add true then false statisticsBuilder = new BooleanStatisticsBuilder(); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 0, 0); statisticsBuilder.addValue(true); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 1, 1); statisticsBuilder.addValue(true); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 2, 2); statisticsBuilder.addValue(false); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 3, 2); statisticsBuilder.addValue(false); assertBooleanStatistics(statisticsBuilder.buildColumnStatistics(), 4, 2); } @Test public void testMerge() { List<ColumnStatistics> statisticsList = new ArrayList<>(); BooleanStatisticsBuilder statisticsBuilder = new BooleanStatisticsBuilder(); statisticsList.add(statisticsBuilder.buildColumnStatistics()); assertMergedBooleanStatistics(statisticsList, 0, 0); statisticsBuilder.addValue(false); statisticsList.add(statisticsBuilder.buildColumnStatistics()); assertMergedBooleanStatistics(statisticsList, 1, 0); statisticsBuilder.addValue(false); statisticsList.add(statisticsBuilder.buildColumnStatistics()); assertMergedBooleanStatistics(statisticsList, 3, 0); statisticsBuilder.addValue(true); statisticsList.add(statisticsBuilder.buildColumnStatistics()); assertMergedBooleanStatistics(statisticsList, 6, 1); statisticsBuilder.addValue(true); statisticsList.add(statisticsBuilder.buildColumnStatistics()); assertMergedBooleanStatistics(statisticsList, 10, 3); } @Test public void testMinAverageValueBytes() { assertMinAverageValueBytes(0L, ImmutableList.of()); assertMinAverageValueBytes(BOOLEAN_VALUE_BYTES, ImmutableList.of(true)); assertMinAverageValueBytes(BOOLEAN_VALUE_BYTES, ImmutableList.of(false)); assertMinAverageValueBytes(BOOLEAN_VALUE_BYTES, ImmutableList.of(true, true, false, true)); } private void assertMergedBooleanStatistics(List<ColumnStatistics> statisticsList, int expectedNumberOfValues, int trueValueCount) { assertBooleanStatistics(mergeColumnStatistics(statisticsList), expectedNumberOfValues, trueValueCount); assertNoColumnStatistics(mergeColumnStatistics(insertEmptyColumnStatisticsAt(statisticsList, 0, 10)), expectedNumberOfValues + 10); assertNoColumnStatistics(mergeColumnStatistics(insertEmptyColumnStatisticsAt(statisticsList, statisticsList.size(), 10)), expectedNumberOfValues + 10); assertNoColumnStatistics(mergeColumnStatistics(insertEmptyColumnStatisticsAt(statisticsList, statisticsList.size() / 2, 10)), expectedNumberOfValues + 10); } private void assertBooleanStatistics(ColumnStatistics columnStatistics, int expectedNumberOfValues, int trueValueCount) { if (expectedNumberOfValues > 0) { assertColumnStatistics(columnStatistics, expectedNumberOfValues, null, null); assertEquals(columnStatistics.getBooleanStatistics().getTrueValueCount(), trueValueCount); } } }
1,725
1,328
<filename>sample/src/main/java/de/keyboardsurfer/app/demo/crouton/AboutFragment.java /* * Copyright 2012 - 2014 <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 de.keyboardsurfer.app.demo.crouton; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import de.keyboardsurfer.app.demo.crouton.R; /** * @author keyboardsurfer * @since 14.12.12 */ public class AboutFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.about, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final String gitHubLink = createLink(getString(R.string.repo_url), "GitHub"); TextView credits = (TextView) view.findViewById(R.id.credits); credits.setText( Html.fromHtml(getString(R.string.credits, createLink(getString(R.string.gplus_url), "<NAME>")))); TextView feedback = (TextView) view.findViewById(R.id.feedback); feedback.setText(Html.fromHtml(getString(R.string.feedback, gitHubLink))); TextView attributions = (TextView) view.findViewById(R.id.attributions); attributions.setText(Html.fromHtml( getString(R.string.attributions, createLink("http://www.apache.org/licenses/LICENSE-2.0 ", "Apache License, V2"), gitHubLink))); setLinkMovementMethod(credits, feedback, attributions); } private String createLink(String url, String title) { return String.format("<a href=\"%s\">%s</a>", url, title); } private void setLinkMovementMethod(TextView... textViews) { for (TextView view : textViews) { view.setMovementMethod(LinkMovementMethod.getInstance()); } } }
840
577
<gh_stars>100-1000 from red import r as R from green import g from pkg.other.color.blue import b as B r = R g # this comment required for unit test b = B
53
36,552
<filename>test/cpp/end2end/counted_service.h // // Copyright 2017 gRPC 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. // #ifndef GRPC_TEST_CPP_END2END_COUNTED_SERVICE_H #define GRPC_TEST_CPP_END2END_COUNTED_SERVICE_H #include "src/core/lib/gprpp/sync.h" namespace grpc { namespace testing { // A wrapper around an RPC service implementation that provides request and // response counting. template <typename ServiceType> class CountedService : public ServiceType { public: size_t request_count() { grpc_core::MutexLock lock(&mu_); return request_count_; } size_t response_count() { grpc_core::MutexLock lock(&mu_); return response_count_; } void IncreaseResponseCount() { grpc_core::MutexLock lock(&mu_); ++response_count_; } void IncreaseRequestCount() { grpc_core::MutexLock lock(&mu_); ++request_count_; } void ResetCounters() { grpc_core::MutexLock lock(&mu_); request_count_ = 0; response_count_ = 0; } private: grpc_core::Mutex mu_; size_t request_count_ ABSL_GUARDED_BY(mu_) = 0; size_t response_count_ ABSL_GUARDED_BY(mu_) = 0; }; } // namespace testing } // namespace grpc #endif // GRPC_TEST_CPP_END2END_COUNTED_SERVICE_H
608
1,761
# Sensor Auto Gain Control # # This example shows off how to control the sensor's gain # using the automatic gain control algorithm. # What's the difference between gain and exposure control? # # Well, by increasing the exposure time for the image you're getting more # light on the camera. This gives you the best signal to noise ratio. You # in general always want to increase the expsoure time... except, when you # increase the exposure time you decrease the maximum possible frame rate # and if anything moves in the image it will start to blur more with a # higher exposure time. Gain control allows you to increase the output per # pixel using analog and digital multipliers... however, it also amplifies # noise. So, it's best to let the exposure increase as much as possible # and then use gain control to make up any remaining ground. # We can achieve the above by setting a gain ceiling on the automatic # gain control algorithm. Once this is set the algorithm will have to # increase the exposure time to meet any gain needs versus using gain # to do so. However, this comes at the price of the exposure time varying # more when the lighting changes versus the exposure being constant and # the gain changing. import sensor, image, time sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) # The gain db ceiling maxes out at about 24 db for the OV7725 sensor. sensor.set_auto_gain(True, gain_db_ceiling = 16.0) # Default gain. # Note! If you set the gain ceiling to low without adjusting the exposure control # target value then you'll just get a lot of oscillation from the exposure # control if it's on. sensor.skip_frames(time = 2000) # Wait for settings take effect. clock = time.clock() # Create a clock object to track the FPS. while(True): clock.tick() # Update the FPS clock. img = sensor.snapshot() # Take a picture and return the image. print("FPS %f, Gain %f dB, Exposure %d us" % \ (clock.fps(), sensor.get_gain_db(), sensor.get_exposure_us()))
648
1,210
/* * Copyright <NAME> 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file type_info_wrapper.hpp * \author <NAME> * \date 15.04.2007 * * The header contains implementation of a type information wrapper. */ #ifndef BOOST_LOG_UTILITY_TYPE_INFO_WRAPPER_HPP_INCLUDED_ #define BOOST_LOG_UTILITY_TYPE_INFO_WRAPPER_HPP_INCLUDED_ #include <typeinfo> #include <string> #include <boost/core/demangle.hpp> #include <boost/core/explicit_operator_bool.hpp> #include <boost/log/detail/config.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if defined(__GNUC__) #pragma message "Boost.Log: This header is deprecated, use Boost.TypeIndex instead." #elif defined(_MSC_VER) #pragma message("Boost.Log: This header is deprecated, use Boost.TypeIndex instead.") #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE /*! * \brief A simple <tt>std::type_info</tt> wrapper that implements value semantic for type information objects * * The type info wrapper is very useful for storing type information objects in containers, * as a key or value. It also provides a number of useful features, such as default construction * and assignment support, an empty state and extended support for human-friendly type names. */ class type_info_wrapper { private: #ifndef BOOST_LOG_DOXYGEN_PASS //! An inaccessible type to indicate an uninitialized state of the wrapper struct BOOST_SYMBOL_VISIBLE uninitialized {}; #endif // BOOST_LOG_DOXYGEN_PASS private: //! A pointer to the actual type info std::type_info const* info; public: /*! * Default constructor * * \post <tt>!*this == true</tt> */ type_info_wrapper() BOOST_NOEXCEPT : info(&typeid(uninitialized)) {} /*! * Copy constructor * * \post <tt>*this == that</tt> * \param that Source type info wrapper to copy from */ type_info_wrapper(type_info_wrapper const& that) BOOST_NOEXCEPT : info(that.info) {} /*! * Conversion constructor * * \post <tt>*this == that && !!*this</tt> * \param that Type info object to be wrapped */ type_info_wrapper(std::type_info const& that) BOOST_NOEXCEPT : info(&that) {} /*! * \return \c true if the type info wrapper was initialized with a particular type, * \c false if the wrapper was default-constructed and not yet initialized */ BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT() /*! * Stored type info getter * * \pre <tt>!!*this</tt> * \return Constant reference to the wrapped type info object */ std::type_info const& get() const BOOST_NOEXCEPT { return *info; } /*! * Swaps two instances of the wrapper */ void swap(type_info_wrapper& that) BOOST_NOEXCEPT { std::type_info const* temp = info; info = that.info; that.info = temp; } /*! * The method returns the contained type name string in a possibly more readable format than <tt>get().name()</tt> * * \pre <tt>!!*this</tt> * \return Type name string */ std::string pretty_name() const { if (!this->operator!()) return boost::core::demangle(info->name()); else return "[uninitialized]"; } /*! * \return \c false if the type info wrapper was initialized with a particular type, * \c true if the wrapper was default-constructed and not yet initialized */ bool operator! () const BOOST_NOEXCEPT { return (info == &typeid(uninitialized) || *info == typeid(uninitialized)); } /*! * Equality comparison * * \param that Comparand * \return If either this object or comparand is in empty state and the other is not, the result is \c false. * If both arguments are empty, the result is \c true. If both arguments are not empty, the result * is \c true if this object wraps the same type as the comparand and \c false otherwise. */ bool operator== (type_info_wrapper const& that) const BOOST_NOEXCEPT { return (info == that.info || *info == *that.info); } /*! * Ordering operator * * \pre <tt>!!*this && !!that</tt> * \param that Comparand * \return \c true if this object wraps type info object that is ordered before * the type info object in the comparand, \c false otherwise * \note The results of this operator are only consistent within a single run of application. * The result may change for the same types after rebuilding or even restarting the application. */ bool operator< (type_info_wrapper const& that) const BOOST_NOEXCEPT { return static_cast< bool >(info->before(*that.info)); } }; //! Inequality operator inline bool operator!= (type_info_wrapper const& left, type_info_wrapper const& right) BOOST_NOEXCEPT { return !left.operator==(right); } //! Ordering operator inline bool operator<= (type_info_wrapper const& left, type_info_wrapper const& right) BOOST_NOEXCEPT { return (left.operator==(right) || left.operator<(right)); } //! Ordering operator inline bool operator> (type_info_wrapper const& left, type_info_wrapper const& right) BOOST_NOEXCEPT { return !(left.operator==(right) || left.operator<(right)); } //! Ordering operator inline bool operator>= (type_info_wrapper const& left, type_info_wrapper const& right) BOOST_NOEXCEPT { return !left.operator<(right); } //! Free swap for type info wrapper inline void swap(type_info_wrapper& left, type_info_wrapper& right) BOOST_NOEXCEPT { left.swap(right); } //! The function for exception serialization to string inline std::string to_string(type_info_wrapper const& ti) { return ti.pretty_name(); } BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_UTILITY_TYPE_INFO_WRAPPER_HPP_INCLUDED_
2,234
892
<filename>advisories/unreviewed/2022/04/GHSA-wq4g-59xh-hgm3/GHSA-wq4g-59xh-hgm3.json { "schema_version": "1.2.0", "id": "GHSA-wq4g-59xh-hgm3", "modified": "2022-04-30T18:16:12Z", "published": "2022-04-30T18:16:12Z", "aliases": [ "CVE-2001-0516" ], "details": "Oracle listener between Oracle 9i and Oracle 8.0 allows remote attackers to cause a denial of service via a malformed connection packet that contains an incorrect requester_version value that does not match an expected offset to the data.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2001-0516" }, { "type": "WEB", "url": "http://otn.oracle.com/deploy/security/pdf/net8_dos_alert.pdf" }, { "type": "WEB", "url": "http://xforce.iss.net/alerts/advise82.php" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
449
555
<filename>easynmt/models/__init__.py from .AutoModel import AutoModel from .OpusMT import OpusMT
32
317
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbStereorectificationDisplacementFieldSource_h #define otbStereorectificationDisplacementFieldSource_h #include "itkImageSource.h" #include "otbGenericRSTransform.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkVector.h" #include "otbMacro.h" namespace otb { /** \class StereorectificationDisplacementFieldSource * \brief Compute the deformation fields for stereo-rectification * * The geometry of acqusition related to stereo pairs is such that * the displacement related to the elevation between the two images * of the pair always occurs along lines that are called epipolar * lines. * * In the case of conic acqusition, these lines are perfectly * parallel by definition, while in push-broom geometry, these lines * might not be exactly parallel due to perturbations during * acquisition, especially when considering a large field of view. * * The purpose of stereo-rectification is to warp both images of the * pairs so that the displacement related to the elevation only * occurs in the horizontal direction (i.e. epipolar lines are * horizontal). This operation is useful for mainly two reasons: it * allows searching for disparities in one direction only, and it * allows deriving anaglyph for 3D viewing with 3D glasses. * * This filter allows you to compute the deformation fields up to the * sensor model precision needed to warp a pair of stereo images into * epipolar geometry. Warping can be done using the * otb::StreamingWarpImageFilter. * * Since lines might not be perfectly regular, the algorithm * performed by this filter uses the otb::GenericRSTransform * capabilities to compute the local epipolar lines, and iteratively * build a resampling grid by propagating along these locally * estimated lines. * * Epipolar images will have a null origin and a size as given by the * GetRectifiedImageSize() method. The deformation fields and size * are derived to produce epipolar images covering the whole extent * of the left image. * * The SetAverageElevation() method allows you to set the elevation * hypothesis on which the epipolar geometry is built. It means that * any pair of pixels in the stereo pair whose elevation is exactly * equal to the average elevation will have a null disparity (no * displacement). The SetElevationOffset() method allows tuning the * elevation offset which is only used for local epipolar lines * estimation. The default value of 50 meters should do. * * Additionally, the SetScale() method allows deriving deformation * fields and images size at a coarser (scale > 1) or finer (scale < * 1) resolution. The SetGridStep() allows tuning the step of the * resampling grid. Please keep in mind that the whole grid is loaded * into memory, and that the epipolar lines direction may only vary * smoothly. When working with large images, a coarse grid-step will * generally be accurate enough and will preserve the memory resources. * * \sa StreamingWarpImageFilter * \sa StereoSensorModelToElevationMapFilter * * \ingroup OTBStereo */ template <class TInputImage, class TOutputImage> class ITK_EXPORT StereorectificationDisplacementFieldSource : public itk::ImageSource<TOutputImage> { public: /** Standard class typedefs */ typedef StereorectificationDisplacementFieldSource Self; typedef itk::ImageSource<TOutputImage> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; // Inputs and outputs relative typedefs typedef TInputImage InputImageType; typedef typename InputImageType::Pointer InputImagePointerType; typedef TOutputImage OutputImageType; typedef typename OutputImageType::Pointer OutputImagePointerType; // Image related typedefs typedef typename OutputImageType::SizeType SizeType; typedef typename OutputImageType::PointType PointType; typedef typename OutputImageType::SpacingType SpacingType; typedef typename OutputImageType::RegionType RegionType; // 3D RS transform // TODO: Allow tuning precision (i.e. double or float) typedef otb::GenericRSTransform<double, 3, 3> RSTransformType; typedef typename RSTransformType::Pointer RSTransformPointerType; // 3D points typedef typename RSTransformType::InputPointType TDPointType; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(StereorectificationDisplacementFieldSource, ImageSource); /** Get/Set the scale */ itkSetMacro(Scale, double); itkGetConstReferenceMacro(Scale, double); /** Get/Set the grid scale */ itkSetMacro(GridStep, double); itkGetMacro(GridStep, double); /** Get/Set left image for stereo-rectification */ itkSetObjectMacro(LeftImage, InputImageType); itkGetObjectMacro(LeftImage, InputImageType); /** Get/Set right image for stereo-rectification */ itkSetObjectMacro(RightImage, InputImageType); itkGetObjectMacro(RightImage, InputImageType); /** Get the size of the rectified image */ itkGetConstReferenceMacro(RectifiedImageSize, SizeType); /** Get the estimated mean baseline ratio */ itkGetConstReferenceMacro(MeanBaselineRatio, double); /** Return the left deformation field (const version) */ const OutputImageType* GetLeftDisplacementFieldOutput() const; /** Return the left deformation field */ OutputImageType* GetLeftDisplacementFieldOutput(); /** Return the left deformation field (const version) */ const OutputImageType* GetRightDisplacementFieldOutput() const; /** Return the left deformation field */ OutputImageType* GetRightDisplacementFieldOutput(); itkSetMacro(UseDEM, bool); itkGetMacro(UseDEM, bool); itkBooleanMacro(UseDEM); protected: /** Constructor */ StereorectificationDisplacementFieldSource(void); /** Destructor */ ~StereorectificationDisplacementFieldSource(void) override{}; /** Generate output images information */ void GenerateOutputInformation() override; /** Enlarge output requested region (no streaming) */ void EnlargeOutputRequestedRegion(itk::DataObject* itkNotUsed(output)) override; /** Compute the deformation field */ void GenerateData() override; /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const override; private: StereorectificationDisplacementFieldSource(const Self&); // purposely // not // implemented void operator=(const Self&) = delete; /** This elevation offset is used to compute the epipolar direction */ double m_ElevationOffset; /** A scale greater than 1 will lead to zoomed stereo-rectified * pairs */ double m_Scale; /** Controls the step of the resampling grid (in pixels). A finer * step will lead to more memory consumption. */ double m_GridStep; /** Left image */ InputImagePointerType m_LeftImage; /** Right image */ InputImagePointerType m_RightImage; /** Left to right transform */ RSTransformPointerType m_LeftToRightTransform; /** Right to left transform */ RSTransformPointerType m_RightToLeftTransform; /** Size of the rectified images */ SizeType m_RectifiedImageSize; /** Output origin in left image (internal use) */ TDPointType m_OutputOriginInLeftImage; /** This variable contains the estimated mean baseline ratio over * the image */ double m_MeanBaselineRatio; /** If set to true, elevation is retrieved through * DEMHandler::GetHeightAboveEllipsoid(). If false, elevation is * retrieved from DEMHandler::GetDefaultHeightAboveEllipsoid() */ bool m_UseDEM; }; } // End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbStereorectificationDisplacementFieldSource.hxx" #endif #endif
2,586
320
"""Utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.contrib import layers from tensorflow.contrib.framework.python.ops import arg_scope from tensorflow.contrib.layers.python.layers import initializers from tensorflow.contrib.layers.python.layers import layers as layers_lib from tensorflow.contrib.layers.python.layers import regularizers def predictron_arg_scope(weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True): batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': batch_norm_scale, 'updates_collections': tf.GraphKeys.UPDATE_OPS, } # Set weight_decay for weights in Conv and FC layers. with arg_scope( [layers.conv2d, layers_lib.fully_connected], weights_regularizer=regularizers.l2_regularizer(weight_decay)): with arg_scope( [layers.conv2d], weights_initializer=initializers.variance_scaling_initializer(), activation_fn=None, normalizer_fn=layers_lib.batch_norm, normalizer_params=batch_norm_params) as sc: return sc class Colour(): ''' Borrowed from https://github.com/brendanator/predictron/blob/master/predictron/util.py Copyright (c) 2016 <NAME> MIT Licence ''' NORMAL = '\033[0m' BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' YELLOW = '\033[33m' BLUE = '\033[34m' MAGENTA = '\033[35m' CYAN = '\033[36m' WHITE = '\033[37m' @classmethod def highlight(cls, input_, success): if success: colour = Colour.GREEN else: colour = Colour.RED return colour + input_ + Colour.NORMAL
752
2,138
<reponame>lbnt1982/jeecg package org.jeecgframework.tag.core.easyui; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.online.util.FreemarkerHelper; import org.jeecgframework.core.util.ApplicationContextUtil; import org.jeecgframework.core.util.ContextHolderUtils; import org.jeecgframework.core.util.MutiLangUtil; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.core.util.SysThemesUtil; import org.jeecgframework.core.util.oConvertUtils; import org.jeecgframework.tag.core.factory.BootstrapTableComponent; import org.jeecgframework.tag.core.factory.ComponentFactory; import org.jeecgframework.tag.vo.easyui.ColumnValue; import org.jeecgframework.tag.vo.easyui.DataGridColumn; import org.jeecgframework.tag.vo.easyui.DataGridUrl; import org.jeecgframework.tag.vo.easyui.OptTypeDirection; import org.jeecgframework.web.cgform.entity.config.CgFormFieldEntity; import org.jeecgframework.web.cgform.entity.config.CgFormHeadEntity; import org.jeecgframework.web.cgform.entity.config.CgSubTableVO; import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI; import org.jeecgframework.web.cgform.util.PublicUtil; import org.jeecgframework.web.system.pojo.base.TSOperation; import org.jeecgframework.web.system.pojo.base.TSType; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import com.google.gson.Gson; /** * * 类描述:DATAGRID标签处理类 * @author 张代浩 * @date: 日期:2012-12-7 时间:上午10:17:45 * @version 1.0 */ @SuppressWarnings({"serial","rawtypes","unchecked","static-access"}) public class DataGridTag extends TagSupport { private static Logger log = Logger.getLogger(DataGridTag.class); private final String DATE_FORMATTER = "yyyy-MM-dd"; private final String DATETIME_FORMATTER = "yyyy-MM-dd hh:mm:ss"; protected String fields = "";// 显示字段 protected String searchFields = "";// 查询字段 Author:qiulu Date:20130618 for:添加对区间查询的支持 protected String name;// 表格标示 protected String title;// 表格标示 protected String idField="id";// 主键字段 protected boolean treegrid = false;// 是否是树形列表 protected List<DataGridUrl> urlList = new ArrayList<DataGridUrl>();// 列表操作显示 protected List<DataGridUrl> toolBarList = new ArrayList<DataGridUrl>();// 工具条列表 protected List<DataGridColumn> columnList = new ArrayList<DataGridColumn>();// 列表操作显示 protected List<ColumnValue> columnValueList = new ArrayList<ColumnValue>();// 值替换集合 protected List<ColumnValue> columnStyleList = new ArrayList<ColumnValue>();// 颜色替换集合 public Map<String, Object> map;// 封装查询条件 private String actionUrl;// 分页提交路径 public int allCount; public int curPageNo; public int pageSize = 10; public boolean pagination = true;// 是否显示分页 private String width; private String height; private boolean checkbox = false;// 是否显示复选框 private boolean showPageList = true;// 定义是否显示页面列表 private boolean openFirstNode = false;//是不是展开第一个节点 private boolean fit = true;// 是否允许表格自动缩放,以适应父容器 private boolean fitColumns = true;// 当为true时,自动展开/合同列的大小,以适应的宽度,防止横向滚动. private boolean collapsible = false;// 当为true时,开启收起/展开,默认不启动. private String sortName;//定义的列进行排序 private String sortOrder = "desc";//定义列的排序顺序,只能是"递增"或"降序". private boolean showRefresh = true;// 定义是否显示刷新按钮 private boolean showText = true;// 定义是否显示刷新按钮 private String style = "easyui";// 列表样式easyui,datatables,jqgrid private String onLoadSuccess;// 数据加载完成调用方法 private String onClick;// 单击事件调用方法 private String onDblClick;// 双击事件调用方法 private String queryMode = "single";//查询模式 private String entityName;//对应的实体对象 private String rowStyler;//rowStyler函数 private String extendParams;//扩展参数,easyui有的,但是jeecg没有的参数进行扩展 private boolean autoLoadData=true; // 列表是否自动加载数据 //private boolean frozenColumn=false; // 是否是冰冻列 默认不是 private String langArg; private boolean nowrap = true; private Boolean singleSelect;//是否单选true,false protected String cssTheme ; private boolean isShowSearch=false;//检索区域是否可收缩 private String treeField;//树形列表展示列 private String btnCls;//列表上方button样式class属性 protected CgFormHeadEntity head; protected Map<String, Object> tableData = new HashMap<String, Object>(); private String configId = ""; private boolean isShowSubGrid=false;//是否显示表体数据 值为true 或者false private String component;//列表组件名称(默认easyui,bootstrap-table) private boolean query=true;//是否显示查询条件(默认true,显示为true,不显示为false) public boolean isQuery() { return query; } public void setQuery(boolean query) { this.query = query; } public void setComponent(String component) { this.component = component; } public String getConfigId() { return configId; } public void setConfigId(String configId) { this.configId = configId; } public boolean getIsShowSubGrid() { return isShowSubGrid; } public void setIsShowSubGrid(boolean isShowSubGrid) { this.isShowSubGrid = isShowSubGrid; } public String getBtnCls() { return btnCls; } public void setBtnCls(String btnCls) { if(checkBrowerIsNotIE()){ this.btnCls = btnCls; }else{ //IE浏览器 this.btnCls = "easyui"; } } public String getCssTheme() { return cssTheme; } public void setCssTheme(String cssTheme) { this.cssTheme = cssTheme; } private boolean queryBuilder = false;// 高级查询器 public boolean isQueryBuilder() { return queryBuilder; } public void setQueryBuilder(boolean queryBulder) { this.queryBuilder = queryBulder; } private boolean superQuery = false; //高级查询器 public boolean getSuperQuery() { return superQuery; } public void setSuperQuery(boolean superQuery) { this.superQuery = superQuery; } private String complexSuperQuery = ""; //根据表的编码是否存在展示高级查询构造器 public String getComplexSuperQuery() { return complexSuperQuery; } public void setComplexSuperQuery(String complexSuperQuery) { this.complexSuperQuery = complexSuperQuery; } public void setTreeField(String treeField) { this.treeField = treeField; } //json转换中的系统保留字 protected static Map<String,String> syscode = new HashMap<String,String>(); static{ syscode.put("class", "clazz"); } @Autowired private static SystemService systemService; public void setOnLoadSuccess(String onLoadSuccess) { this.onLoadSuccess = onLoadSuccess; } public void setOnClick(String onClick) { this.onClick = onClick; } public void setOnDblClick(String onDblClick) { this.onDblClick = onDblClick; } public void setShowText(boolean showText) { this.showText = showText; } public void setPagination(boolean pagination) { this.pagination = pagination; } public void setCheckbox(boolean checkbox) { this.checkbox = checkbox; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setTreegrid(boolean treegrid) { this.treegrid = treegrid; } public void setWidth(String width) { this.width = width; } public void setHeight(String height) { this.height = height; } public void setIdField(String idField) { this.idField = idField; } public void setActionUrl(String actionUrl) { this.actionUrl = actionUrl; } public void setTitle(String title) { this.title = title; } public void setName(String name) { this.name = name; } public void setFit(boolean fit) { this.fit = fit; } public void setShowPageList(boolean showPageList) { this.showPageList = showPageList; } public void setShowRefresh(boolean showRefresh) { this.showRefresh = showRefresh; } public void setSingleSelect(Boolean singleSelect) { this.singleSelect = singleSelect; } public boolean getIsShowSearch() { return isShowSearch; } public void setIsShowSearch(boolean isShowSearch) { this.isShowSearch = isShowSearch; } public void setNowrap(boolean nowrap) { this.nowrap = nowrap; } /** * 设置询问操作URL * @param urlfont * @param urlclass */ public void setConfUrl(String url, String title, String message, String exp,String operationCode, String urlStyle, String urlclass, String urlfont ,boolean inGroup) { DataGridUrl dataGridUrl = new DataGridUrl(); dataGridUrl.setTitle(title); dataGridUrl.setUrl(url); dataGridUrl.setType(OptTypeDirection.Confirm); dataGridUrl.setMessage(message); dataGridUrl.setExp(exp); dataGridUrl.setInGroup(inGroup); if(checkBrowerIsNotIE()){ dataGridUrl.setUrlStyle(urlStyle); dataGridUrl.setUrlclass(urlclass); dataGridUrl.setUrlfont(urlfont); }else if(StringUtil.isEmpty(urlclass) || !"ace_button".equals(urlclass)){ dataGridUrl.setUrlStyle(urlStyle); } installOperationCode(dataGridUrl, operationCode,urlList); } /** * 设置删除操作URL */ public void setDelUrl(String url, String title, String message, String exp, String funname,String operationCode, String urlStyle,String urlclass,String urlfont,boolean inGroup) { DataGridUrl dataGridUrl = new DataGridUrl(); dataGridUrl.setTitle(title); dataGridUrl.setUrl(url); dataGridUrl.setType(OptTypeDirection.Del); dataGridUrl.setMessage(message); dataGridUrl.setExp(exp); dataGridUrl.setFunname(funname); dataGridUrl.setInGroup(inGroup); if(checkBrowerIsNotIE()){ dataGridUrl.setUrlStyle(urlStyle); dataGridUrl.setUrlclass(urlclass); dataGridUrl.setUrlfont(urlfont); }else if(StringUtil.isEmpty(urlclass) || !"ace_button".equals(urlclass)){ dataGridUrl.setUrlStyle(urlStyle); } installOperationCode(dataGridUrl, operationCode,urlList); } /** * 设置默认操作URL */ public void setDefUrl(String url, String title, String exp,String operationCode, String urlStyle,String urlclass,String urlfont,boolean inGroup) { DataGridUrl dataGridUrl = new DataGridUrl(); dataGridUrl.setTitle(title); dataGridUrl.setUrl(url); dataGridUrl.setType(OptTypeDirection.Deff); dataGridUrl.setExp(exp); dataGridUrl.setInGroup(inGroup); if(checkBrowerIsNotIE()){ dataGridUrl.setUrlStyle(urlStyle); dataGridUrl.setUrlclass(urlclass); dataGridUrl.setUrlfont(urlfont); }else if(StringUtil.isEmpty(urlclass) || !"ace_button".equals(urlclass)){ dataGridUrl.setUrlStyle(urlStyle); } installOperationCode(dataGridUrl, operationCode,urlList); } /** * 设置工具条 * @param height2 * @param width2 * @param id */ public void setToolbar(String url, String title, String icon, String exp,String onclick, String funname,String operationCode, String width2, String height2, String id,boolean inGroup) { DataGridUrl dataGridUrl = new DataGridUrl(); dataGridUrl.setTitle(title); dataGridUrl.setUrl(url); dataGridUrl.setType(OptTypeDirection.ToolBar); dataGridUrl.setInGroup(inGroup); if(!checkBrowerIsNotIE()){ //IE浏览器 if(!icon.startsWith("icon")){ dataGridUrl.setIcon("icon-add"); }else{ dataGridUrl.setIcon(icon); } }else{ dataGridUrl.setIcon(icon); } dataGridUrl.setOnclick(onclick); dataGridUrl.setExp(exp); dataGridUrl.setFunname(funname); dataGridUrl.setWidth(String.valueOf(width2)); dataGridUrl.setHeight(String.valueOf(height2)); dataGridUrl.setId(id); installOperationCode(dataGridUrl, operationCode,toolBarList); } /** * 设置自定义函数操作URL */ public void setFunUrl(String title, String exp, String funname,String operationCode, String urlStyle,String urlclass,String urlfont,boolean inGroup) { DataGridUrl dataGridUrl = new DataGridUrl(); dataGridUrl.setTitle(title); dataGridUrl.setType(OptTypeDirection.Fun); dataGridUrl.setExp(exp); dataGridUrl.setFunname(funname); dataGridUrl.setInGroup(inGroup); if(checkBrowerIsNotIE()){ dataGridUrl.setUrlStyle(urlStyle); dataGridUrl.setUrlclass(urlclass); dataGridUrl.setUrlfont(urlfont); }else if(StringUtil.isEmpty(urlclass) || !"ace_button".equals(urlclass)){ dataGridUrl.setUrlStyle(urlStyle); } installOperationCode(dataGridUrl, operationCode,urlList); } /** * 设置自定义函数操作URL * @param urlfont * @param urlclass */ public void setOpenUrl(String url, String title, String width, String height, String exp,String operationCode, String openModel, String urlStyle, String urlclass, String urlfont,boolean inGroup) { DataGridUrl dataGridUrl = new DataGridUrl(); dataGridUrl.setTitle(title); dataGridUrl.setUrl(url); dataGridUrl.setWidth(width); dataGridUrl.setHeight(height); dataGridUrl.setType(OptTypeDirection.valueOf(openModel)); dataGridUrl.setExp(exp); dataGridUrl.setInGroup(inGroup); if(checkBrowerIsNotIE()){ dataGridUrl.setUrlStyle(urlStyle); dataGridUrl.setUrlclass(urlclass); dataGridUrl.setUrlfont(urlfont); }else if(StringUtil.isEmpty(urlclass) || !"ace_button".equals(urlclass)){ dataGridUrl.setUrlStyle(urlStyle); } installOperationCode(dataGridUrl, operationCode,urlList); } /** * * <b>Summary: </b> setColumn(设置字段) * * @param title * @param field * @param width * @param showLen * @param newColumn */ public void setColumn(String title, String field, Integer width,Integer showLen,String rowspan, String colspan, String align, boolean sortable, boolean checkbox, String formatter,String formatterjs, boolean hidden, String replace, String treefield, boolean image,String imageSize, boolean query, String url, String funname, String arg,String queryMode, String dictionary,boolean popup, boolean frozenColumn,String extend, String style,String downloadName,boolean isAuto,String extendParams,String editor,String defaultVal,String showMode, boolean newColumn,String dictCondition,String filterType,boolean optsMenu ,boolean isAjaxDict) { DataGridColumn dataGridColumn = new DataGridColumn(); dataGridColumn.setAlign(align); dataGridColumn.setCheckbox(checkbox); dataGridColumn.setColspan(colspan); dataGridColumn.setField(field); dataGridColumn.setFormatter(formatter); dataGridColumn.setFormatterjs(formatterjs); dataGridColumn.setHidden(hidden); dataGridColumn.setRowspan(rowspan); dataGridColumn.setSortable(sortable); dataGridColumn.setTitle(title); dataGridColumn.setWidth(width); //author:xugj--start--date:2016年5月11日 for:TASK #1080 【UI标签改造】t:dgCol 显示内容长度控制 --> dataGridColumn.setShowLen(showLen); //author:xugj--end---date:2016年5月11日 for:TASK #1080 【UI标签改造】t:dgCol 显示内容长度控制 --> dataGridColumn.setTreefield(treefield); dataGridColumn.setImage(image); dataGridColumn.setImageSize(imageSize); dataGridColumn.setReplace(replace); dataGridColumn.setQuery(query); dataGridColumn.setUrl(url); dataGridColumn.setFunname(funname); dataGridColumn.setArg(arg); dataGridColumn.setQueryMode(queryMode); dataGridColumn.setDictionary(dictionary); dataGridColumn.setPopup(popup); dataGridColumn.setFrozenColumn(frozenColumn); dataGridColumn.setExtend(extend); dataGridColumn.setStyle(style); dataGridColumn.setDownloadName(downloadName); dataGridColumn.setAutocomplete(isAuto); dataGridColumn.setExtendParams(extendParams); dataGridColumn.setEditor(editor); dataGridColumn.setNewColumn(newColumn); dataGridColumn.setDefaultVal(defaultVal); dataGridColumn.setShowMode(showMode); dataGridColumn.setDictCondition(dictCondition); dataGridColumn.setFilterType(filterType); dataGridColumn.setOptsMenu(optsMenu); dataGridColumn.setAjaxDict(isAjaxDict); columnList.add(dataGridColumn); Set<String> operationCodes = (Set<String>) super.pageContext.getRequest().getAttribute(Globals.OPERATIONCODES); if (null!=operationCodes) { for (String MyoperationCode : operationCodes) { if (oConvertUtils.isEmpty(MyoperationCode)) break; systemService = ApplicationContextUtil.getContext().getBean( SystemService.class); TSOperation operation = systemService.getEntity(TSOperation.class, MyoperationCode); if(operation.getOperationcode().equals(field)){ columnList.remove(dataGridColumn); } } } if (field != "opt") { fields += field + ","; if ("group".equals(queryMode)) { searchFields += field + "," + field + "_begin," + field + "_end,"; } else { searchFields += field + ","; } } if (StringUtil.isNotEmpty(replace)) { String[] test = replace.split(","); String lang_key = ""; String text = ""; String value = ""; for (String string : test) { lang_key = string.substring(0, string.indexOf("_")); text += MutiLangUtil.getLang(lang_key) + ","; value += string.substring(string.indexOf("_") + 1) + ","; } setColumn(field, text, value); } if (!StringUtils.isBlank(dictionary)&&(!popup)) { if(dictionary.contains(",")){ String[] dic = dictionary.split(","); String text = ""; String value = ""; String sql = "select " + dic[1] + " as field," + dic[2] + " as text from " + dic[0]; if(!StringUtil.isEmpty(dictCondition)){ sql += " "+dictCondition; } systemService = ApplicationContextUtil.getContext().getBean( SystemService.class); List<Map<String, Object>> list = systemService.findForJdbc(sql); for (Map<String, Object> map : list){ text += map.get("text") + ","; value += map.get("field") + ","; } if(list.size()>0) setColumn(field, text, value); }else{ String text = ""; String value = ""; List<TSType> typeList = ResourceUtil.getCacheTypes(dictionary.toLowerCase()); if (typeList != null && !typeList.isEmpty()) { for (TSType type : typeList) { text += MutiLangUtil.doMutiLang(type.getTypename(), "") + ","; value += type.getTypecode() + ","; } setColumn(field, text, value); } } } if(StringUtil.isNotEmpty(style)){ String[] temp = style.split(","); String text = ""; String value = ""; if(temp.length == 1&&temp[0].indexOf("_")==-1){ text = temp[0]; }else{ for (String string : temp) { text += string.substring(0, string.indexOf("_")) + ","; value += string.substring(string.indexOf("_") + 1) + ","; } } setStyleColumn(field, text, value); } } /** * 设置 颜色替换值 * @param field * @param text * @param value */ private void setStyleColumn(String field, String text, String value) { ColumnValue columnValue = new ColumnValue(); columnValue.setName(field); columnValue.setText(text); columnValue.setValue(value); columnStyleList.add(columnValue); } /** * * <b>Summary: </b> setColumn(设置字段替换值) * * @param name * @param text * @param value */ public void setColumn(String name, String text, String value) { ColumnValue columnValue = new ColumnValue(); columnValue.setName(name); columnValue.setText(text); columnValue.setValue(value); columnValueList.add(columnValue); } public int doStartTag() throws JspTagException { return EVAL_PAGE; } public int doEndTag() throws JspException { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // long start = System.currentTimeMillis(); // log.info("================================ DataGridTag 开始时间:"+sdf.format(new Date())+"=============================="); JspWriter out = null; try { title = MutiLangUtil.doMutiLang(title, langArg); out = this.pageContext.getOut(); if("bootstrap-table".equals(component)){ ComponentFactory componentFactory = new BootstrapTableComponent(); String content = componentFactory.invoke("/org/jeecgframework/tag/core/factory/ftl/component/bootstrapTable.ftl", getDataGridTag()); //log.debug(" content ===>" + content); StringBuffer bst = new StringBuffer(); bst.append(content); if(superQuery) { addSuperQueryBootstrap(bst,btnCls,columnList); } out.print(bst.toString()); }else{ out.print(end().toString()); //log.debug(" end() ===>" + end().toString()); } out.flush(); // String indexStyle =null; // Cookie[] cookies = ((HttpServletRequest) super.pageContext // .getRequest()).getCookies(); // for (Cookie cookie : cookies) { // if (cookie == null || StringUtils.isEmpty(cookie.getName())) { // continue; // } // if (cookie.getName().equalsIgnoreCase("JEECGINDEXSTYLE")) { // indexStyle = cookie.getValue(); // } // } // SysThemesEnum sysThemesEnum = SysThemesUtil.getSysTheme((HttpServletRequest) super.pageContext.getRequest()); // if (style.equals("easyui")) { // if("ace".equals(sysThemesEnum.getStyle())){ // out.print(this.aceStyleTable().toString()); // }else{ // out.print(end().toString()); // out.flush(); // } // }else if("jqgrid".equals(style)){ // out.print(jqGrid().toString()); // out.flush(); // }else{ // out.print(datatables().toString()); // out.flush(); // } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ if(out!=null){ try { out.clearBuffer(); // end().setLength(0); // 清空资源 urlList.clear(); toolBarList.clear(); columnValueList.clear(); columnStyleList.clear(); columnList.clear(); fields = ""; searchFields = ""; } catch (Exception e) { e.printStackTrace(); } } } // long end = System.currentTimeMillis(); // log.info("=============================== DataGridTag 结束时间:"+sdf.format(new Date())+"=============================="); // log.info("================================ DataGridTag 耗时:"+(end-start)+"ms=============================="); return EVAL_PAGE; } /** * jqgrid构建datagrid * @return */ public StringBuffer jqGrid(){ StringBuffer sb = new StringBuffer(); sb.append("<link href=\"plug-in/hplus/css/bootstrap.min.css?v=3.3.6\" rel=\"stylesheet\">"); sb.append("<link type=\"text/css\" rel=\"stylesheet\" href=\"plug-in/hplus/css/plugins/jqgrid/ui.jqgrid.css\">"); sb.append("<script src=\"plug-in/hplus/js/jquery.min.js\"></script>"); sb.append("<link rel=\"stylesheet\" href=\"plug-in/jquery-ui/css/ui-lightness/jquery-ui-1.9.2.custom.min.css\" type=\"text/css\"></link>"); sb.append("<script type=\"text/javascript\" src=\"plug-in/lhgDialog/lhgdialog.min.js\"></script>"); sb.append("<script src=\"plug-in/hplus/js/bootstrap.min.js\"></script>"); sb.append("<script src=\"plug-in/hplus/js/plugins/peity/jquery.peity.min.js\"></script>"); sb.append("<script src=\"plug-in/hplus/js/plugins/jqgrid/i18n/grid.locale-cn.js\"></script>"); sb.append("<script src=\"plug-in/hplus/js/plugins/jqgrid/jquery.jqGrid.min.js\"></script>"); sb.append("<script src=\"plug-in/tools/datagrid_2_jqgrid.js\"></script>"); sb.append("<style>"); sb.append("#t_"+name+"{border-bottom:1px solid #ddd;}"); sb.append("#t_"+name+" .btn{margin-right:10px;}"); sb.append(".search_div{padding:10px;}"); sb.append(".tool_bar_div{padding:10px;}"); sb.append("</style>"); sb.append("<table id=\""+name+"\"></table>"); sb.append("<div id=\"gridPager\"></div>"); sb.append("<script type=\"text/javascript\">"); sb.append("$(document).ready(function() {"); sb.append(" $.jgrid.defaults.styleUI=\"Bootstrap\";"); sb.append("$('#"+name+"').jqGrid({"); sb.append("url:'" + actionUrl + "&dataStyle=jqgrid&field=" + fields + "',"); sb.append("datatype:\"json\","); sb.append("mtype:\"POST\","); sb.append("height:'auto',"); sb.append("autowidth:true,"); sb.append("shrinkToFit: true,"); sb.append("multiselect: true,"); sb.append("toolbar:[true,'top'],"); StringBuffer colNameBuffer = new StringBuffer(); StringBuffer colModelBuffer = new StringBuffer(); for (DataGridColumn column : columnList) { colNameBuffer.append("'"); colNameBuffer.append(column.getTitle()); colNameBuffer.append("',"); if("opt".equals(column.getField())){ colModelBuffer.append("{name:'"); colModelBuffer.append(column.getField()); colModelBuffer.append("',index:'"); colModelBuffer.append(column.getField()); colModelBuffer.append("',width:'"); colModelBuffer.append(column.getWidth()); colModelBuffer.append("',align:'"); colModelBuffer.append(column.getAlign()); colModelBuffer.append("' "); colModelBuffer.append(",hidden:"); colModelBuffer.append(column.isHidden()); colModelBuffer.append(",formatter:currencyFormatter"); colModelBuffer.append("},"); }else{ colModelBuffer.append("{name:'"); colModelBuffer.append(column.getField()); colModelBuffer.append("',index:'"); colModelBuffer.append(column.getField()); colModelBuffer.append("',width:'"); colModelBuffer.append(column.getWidth()); colModelBuffer.append("',align:'"); colModelBuffer.append(column.getAlign()); colModelBuffer.append("' "); if(oConvertUtils.isNotEmpty(column.getFormatter())){ if("yyyy-MM-dd".equals(column.getFormatter())){ colModelBuffer.append(",formatter:'date'"); }else{ colModelBuffer.append(",formatter:"); colModelBuffer.append(column.getFormatter()); } // colModelBuffer.append(date); // colModelBuffer.append("' "); } if(oConvertUtils.isNotEmpty(column.getReplace())){ colModelBuffer.append(",formatter:replaceFormatter"); colModelBuffer.append(",formatoptions:{replace:"); String[] replaceArray = column.getReplace().split(","); StringBuffer replaceBuffer = new StringBuffer(); replaceBuffer.append("{"); if(replaceArray.length > 0){ String text = ""; String value = ""; for (String replaceOri : replaceArray) { String lang_key = replaceOri.split("_")[0]; text = MutiLangUtil.getLang(lang_key); value =replaceOri.split("_")[1]; replaceBuffer.append("'"); replaceBuffer.append(value); replaceBuffer.append("':'"); replaceBuffer.append(text); replaceBuffer.append("',"); } } replaceBuffer.append("}"); colModelBuffer.append(replaceBuffer.toString()); colModelBuffer.append("}"); } if(oConvertUtils.isNotEmpty(column.getFormatterjs())){ colModelBuffer.append(",formatter:"+column.getFormatterjs()); } colModelBuffer.append(",hidden:"); colModelBuffer.append(column.isHidden()); colModelBuffer.append("},"); } } String colNames = colNameBuffer.toString(); colNames = colNames.substring(0,colNames.length()-1); String colModels = colModelBuffer.toString(); colModels = colModels.substring(0,colModels.length()-1); sb.append("colNames:["); sb.append(colNames); sb.append("], colModel:["); sb.append(colModels); sb.append("],"); sb.append("rownumbers:true,"); sb.append("viewrecords: true,"); sb.append("rowNum:"+pageSize+","); sb.append("rowList:["+pageSize+","+2*pageSize+","+3*pageSize+"],"); // sb.append("jsonReader:{"); // sb.append("id: \"blackId\","); // sb.append("repeatitems : false},"); sb.append("pager:$('#gridPager')"); sb.append(",caption:'"); sb.append(title); sb.append("'});"); //自适应表格宽度 // sb.append("$(\"#"+name+"\").setGridWidth($(window).width()*0.99);"); //表格顶部,查询、工具栏 sb.append("$('#t_"+name+"').append('"); if(hasQueryColum(columnList)){ sb.append("<div id=\""+name+"tb\" class=\"search_div row\">"); sb.append("<div name=\"searchColums\" class=\"search-content\"><form name=\""+name+"Form\" id=\""+name+"Form\"></form></div><div class=\"col-sm-1 pull-right\">"); sb.append("<button class=\"btn btn-success\" type=\"button\" onclick=\"javascript:"+name+"search();\"><span><i class=\"fa fa-search\"></i>查询</span></button>"); sb.append("</div></div>"); } sb.append("<div class=\"tool_bar_div bg-info\"></div>"); sb.append("');"); //表格顶部查询 if(hasQueryColum(columnList) && !columnList.isEmpty()){ for (DataGridColumn column : columnList) { if(column.isQuery()){ sb.append("$('#t_"+name+" .search-content form').append('"); sb.append("<label style=\"margin-right:10px;margin-left:10px;\">"); sb.append(column.getTitle()); sb.append("</label>"); String dictionary = column.getDictionary(); if(oConvertUtils.isNotEmpty(dictionary)){ //字典数据信息,存在两种处理方式,一种是表格元素数据,一种是字典表当中的数据 String showMode = column.getShowMode(); if(showMode!=null && "radio".equals(showMode)){ if(dictionary.indexOf(",")>-1){ //表格数据信息 try{ String[] dictionaryArray = dictionary.split(","); if(dictionaryArray.length == 3){ String field = column.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_radio\"/>"); String sql = "select " + dictionaryArray[1]+","+dictionaryArray[2]+" from "+dictionaryArray[0]; List<Map<String, Object>> dictionaryList = systemService.findForJdbc(sql); if(dictionaryList != null && !dictionaryList.isEmpty()){ for (Map<String, Object> map : dictionaryList) { if(map.containsKey(dictionaryArray[1]) && map.containsKey(dictionaryArray[2])){ sb.append(" <input type=\"radio\" value=\"" + map.get(dictionaryArray[1]) + "\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+ field+"_radio').val('" + map.get(dictionaryArray[1]) + "');\" />"); sb.append(map.get(dictionaryArray[2])); } } } } }catch (Exception e) { // TODO: 字典数据异常 } }else{ //字典表数据 List<TSType> typeList = ResourceUtil.getCacheTypes(dictionary.toLowerCase()); if(typeList != null && !typeList.isEmpty()){ String field = column.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_radio\"/>"); for (TSType type : typeList) { sb.append(" <input type=\"radio\" value=\"" + type.getTypecode() + "\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+ field+"_radio').val('" + type.getTypecode() + "');\" />"); sb.append(MutiLangUtil.getLang(type.getTypename())); } } } }else if(showMode!=null && "checkbox".equals(showMode)){ if(dictionary.indexOf(",")>-1){ //表格数据信息 try{ String[] dictionaryArray = dictionary.split(","); if(dictionaryArray.length == 3){ String field = column.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_checkbox\" value=\"\" />"); String sql = "select " + dictionaryArray[1]+","+dictionaryArray[2]+" from "+dictionaryArray[0]; List<Map<String, Object>> dictionaryList = systemService.findForJdbc(sql); if(dictionaryList != null && !dictionaryList.isEmpty()){ for (Map<String, Object> map : dictionaryList) { if(map.containsKey(dictionaryArray[1]) && map.containsKey(dictionaryArray[2])){ String value = map.get(dictionaryArray[1]).toString(); sb.append(" <input type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+value+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+value+",',''));}\" value=\"" + value + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" />"); sb.append(map.get(dictionaryArray[2])); } } } } }catch (Exception e) { // TODO: 字典数据异常 } }else{ //字典表数据 List<TSType> typeList = ResourceUtil.getCacheTypes(dictionary.toLowerCase()); if(typeList != null && !typeList.isEmpty()){ String field = column.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_checkbox\" value=\"\" />"); for (TSType type : typeList) { String typeCode = type.getTypecode(); sb.append(" <input type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+typeCode+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+typeCode+",',''));}\" value=\"" + typeCode + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" />"); sb.append(MutiLangUtil.getLang(type.getTypename())); } } } }else{ sb.append("<select name=\""); sb.append(column.getField()); sb.append("\">"); sb.append("<option value=\"\"></option>"); if(dictionary.indexOf(",")>-1){ //表格数据信息 try{ String[] dictionaryArray = dictionary.split(","); if(dictionaryArray.length == 3){ String sql = "select " + dictionaryArray[1]+","+dictionaryArray[2]+" from "+dictionaryArray[0]; List<Map<String, Object>> dictionaryList = systemService.findForJdbc(sql); if(dictionaryList != null && !dictionaryList.isEmpty()){ for (Map<String, Object> map : dictionaryList) { if(map.containsKey(dictionaryArray[1]) && map.containsKey(dictionaryArray[2])){ sb.append("<option value=\""); sb.append(map.get(dictionaryArray[1])); sb.append("\">"); sb.append(map.get(dictionaryArray[2])); sb.append("</option>"); } } } } }catch (Exception e) { // TODO: 字典数据异常 } }else{ //字典表数据 List<TSType> typeList = ResourceUtil.getCacheTypes(dictionary.toLowerCase()); if(typeList != null && !typeList.isEmpty()){ for (TSType type : typeList) { sb.append("<option value=\""); sb.append(type.getTypecode()); sb.append("\">"); sb.append(MutiLangUtil.getLang(type.getTypename())); sb.append("</option>"); } } } sb.append("</select>"); } }else if(oConvertUtils.isNotEmpty(column.getReplace())){ String showMode = column.getShowMode(); if(showMode!=null && "radio".equals(showMode)){ String field = column.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_radio\"/>"); String[] test = column.getReplace().split(","); String text = ""; String value = ""; for (String string : test) { String lang_key = string.split("_")[0]; text = MutiLangUtil.getLang(lang_key); value =string.split("_")[1]; if(column.getDefaultVal()!=null&&column.getDefaultVal().trim().equals(value)){ sb.append(" <input type=\"radio\" value=\"" + value + "\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+ field+"_radio').val('" + value + "');\" checked=\"checked\" />"+text); sb.append(" <script type=\"text/javascript\">"); sb.append(" $('#"+ field+"_radio').val('"+value+"');"); sb.append(" </script>"); }else{ sb.append(" <input type=\"radio\" value=\"" + value + "\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+ field+"_radio').val('" + value + "');\" />"+text); } } }else if(showMode!=null && "checkbox".equals(showMode)){ String field = column.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_checkbox\" value=\"\" />"); String[] test = column.getReplace().split(","); String text = ""; String value = ""; for (String string : test) { String lang_key = string.split("_")[0]; text = MutiLangUtil.getLang(lang_key); value =string.split("_")[1]; if(column.getDefaultVal()!=null&&column.getDefaultVal().trim().equals(value)){ sb.append(" <input type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+value+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+value+",',''));}\" value=\"" + value + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" checked=\"checked\" />"+text); sb.append(" <script type=\"text/javascript\">"); sb.append(" $(\"#"+ field +"_checkbox\").val($(\"#"+ field +"_checkbox\").val()+,"+value+",);"); sb.append(" </script>"); }else{ sb.append(" <input type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+value+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+value+",',''));}\" value=\"" + value + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" />"+text); } } }else{ sb.append("<select name=\""+column.getField().replaceAll("_","\\.")+"\" WIDTH=\"100\" style=\"width: 104px\"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); String[] test = column.getReplace().split(","); String text = ""; String value = ""; for (String string : test) { String lang_key = string.split("_")[0]; text = MutiLangUtil.getLang(lang_key); value =string.split("_")[1]; if(column.getDefaultVal()!=null&&column.getDefaultVal().trim().equals(value)){ sb.append("<option value =\""+value+"\" selected=\"selected\">"+text+"</option>"); }else{ sb.append("<option value =\""+value+"\" >"+text+"</option>"); } } sb.append("</select>"); } }else{ sb.append("<input onkeypress=\"EnterPress(event)\" onkeydown=\"EnterPress()\" type=\"text\" name=\""+column.getField().replaceAll("_","\\.")+"\" "+extendAttribute(column.getExtend())+" "); if(this.DATE_FORMATTER.equals(column.getFormatter())){ sb.append(" style=\"width: 160px\" class=\"Wdate\" onClick=\"WdatePicker()\" "); }else if(this.DATETIME_FORMATTER.equals(column.getFormatter())){ sb.append(" style=\"width: 160px\" class=\"Wdate\" onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})\" "); }else{ sb.append(" style=\"width: 120px\" class=\"inuptxt\" "); } if(oConvertUtils.isNotEmpty(column.getDefaultVal())){ sb.append(" value=\""+column.getDefaultVal()+"\" "); } sb.append(" />"); } sb.append("');"); } } } //工具栏的处理方式 if(toolBarList.size() > 0){ for (DataGridUrl toolBar : toolBarList) { sb.append("$('#t_"+name+" .tool_bar_div').append('"); sb.append("<button class=\"btn btn-success\""); if(StringUtil.isNotEmpty(toolBar.getId())){ sb.append(" id=\""); sb.append(toolBar.getId()); sb.append("\""); } sb.append(" onclick=\""); sb.append(toolBar.getFunname()); sb.append("(\\'"); sb.append(toolBar.getTitle()); sb.append("\\',\\'"); sb.append(toolBar.getUrl()); sb.append("\\',\\'"); sb.append(name); sb.append("\\',"); String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append(width+","+height+")"); sb.append("\" >"); //工具栏图标显示 String toolBarIcon = toolBar.getIcon(); if(oConvertUtils.isNotEmpty(toolBarIcon)){ if(toolBarIcon.equals("icon-add") ){ sb.append("<i class=\"fa fa-plus\"></i>"); }else if(toolBarIcon.equals("icon-edit") ){ sb.append("<i class=\"fa fa-edit\"></i>"); }else if (toolBarIcon.equals("icon-put") ) { sb.append("<i class=\"fa fa-download\"></i>"); }else if (toolBarIcon.equals("icon-putout")) { sb.append("<i class=\"fa fa-upload\"></i>"); }else if (toolBarIcon.equals("icon-remove") ) { sb.append("<i class=\"fa fa-trash-o\"></i>"); }else if (toolBarIcon.equals("icon-search") ) { sb.append("<i class=\"fa fa-search\"></i>"); }else{ sb.append("<i class=\"fa "+toolBarIcon+"\"></i>"); } } sb.append(toolBar.getTitle()); sb.append("</button>"); sb.append("');"); } } //添加在底部的按钮 // sb.append("$('#"+name+"').navGrid('#gridPager',{edit:false,add:false,del:false,search:false})"); // if(toolBarList.size() > 0){ // for (DataGridUrl toolBar : toolBarList) { // sb.append(".navButtonAdd('#gridPager',{"); // sb.append("caption:'"); // sb.append(toolBar.getTitle()); // sb.append("'"); // sb.append(",buttonicon:'"); // sb.append(toolBar.getIcon()); // sb.append("'"); // sb.append(",onClickButton:"); // sb.append("function(){"); // if(oConvertUtils.isNotEmpty(toolBar.getOnclick())){ // sb.append(toolBar.getOnclick()); // }else{ // sb.append(toolBar.getFunname()); // sb.append("('"); // sb.append(toolBar.getTitle()); // sb.append("','"); // sb.append(toolBar.getUrl()); // sb.append("','"); // sb.append(name); // sb.append("',"); // String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); // String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); // sb.append(width+","+height+")"); // } // sb.append("}"); // sb.append(",position:'last'"); // sb.append("})"); // } // } sb.append("});"); sb.append("function currencyFormatter(cellvalue, options, rec){ "); sb.append("var index = options.pos;"); StringBuffer optSb = new StringBuffer(); this.getOptUrl(optSb); sb.append(optSb.toString()); sb.append("}"); sb.append("function reloadTable(){"); sb.append("try{"); sb.append(" $(\'#\'+gridname).trigger(\"reloadGrid\");" ); sb.append("}catch(ex){}"); sb.append("}"); //数据替换 sb.append("function replaceFormatter(cellvalue,options,rec){"); sb.append("var formatterOptions = options.colModel.formatoptions;"); sb.append("var replace = formatterOptions.replace;"); sb.append("return replace[cellvalue];"); sb.append("}"); //回车查询 sb.append("function EnterPress(e){"); sb.append("var e = e || window.event;"); sb.append("if(e.keyCode == 13){ "); sb.append(name+"search();"); sb.append("}}"); //提交查询 sb.append("function " + name + "search(){"); sb.append("try { if(! $(\"#"+name+"Form\").Validform({tiptype:3}).check()){return false;} } catch (e){}"); sb.append("var queryParams = '';"); sb.append("$(\'#" + name + "tb\').find('*').each(function(){ if($(this).attr('name') != undefined && $(this).val() != ''){queryParams += \"&\" + $(this).attr('name') + \"=\" + $(this).val();}});"); sb.append("console.log(queryParams);"); sb.append("var url = '"+actionUrl+"&dataStyle=jqgrid&field="+searchFields+"' + queryParams;"); sb.append("console.log(url);"); sb.append("$(\'#" + name + "\').jqGrid('setGridParam',{url:url,page:1}).trigger(\"reloadGrid\");" + "}"); sb.append("</script>"); return sb; } /** * datatables构造方法 * * @return */ public StringBuffer datatables() { StringBuffer sb = new StringBuffer(); sb.append("<link href=\"plug-in/hplus/css/plugins/dataTables/dataTables.bootstrap.css\" rel=\"stylesheet\">"); sb.append("<script src=\"plug-in/hplus/js/plugins/dataTables/jquery.dataTables.js\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("$(document).ready(function() {"); sb.append("var oTable = $(\'#userList\').dataTable({"); // sb.append( // "\"sDom\" : \"<\'row\'<\'span6\'l><\'span6\'f>r>t<\'row\'<\'span6\'i><\'span6\'p>>\","); sb.append("\"bProcessing\" : true,");// 当datatable获取数据时候是否显示正在处理提示信息" sb.append("\"bPaginate\" : true,"); // 是否分页" sb.append("\"sPaginationType\" : \"full_numbers\",");// 分页样式full_numbers," sb.append("\"bFilter\" : true,");// 是否使用内置的过滤功能" sb.append("\"bSort\" : true, ");// 排序功能" sb.append("\"bAutoWidth\" : true,");// 自动宽度" sb.append("\"bLengthChange\" : true,");// 是否允许用户自定义每页显示条数" sb.append("\"bInfo\" : true,");// 页脚信息" sb.append("\"sAjaxSource\" : \""+ actionUrl + "&field=" + fields+"\","); sb.append("\"bServerSide\" : true,");// 指定从服务器端获取数据 sb.append("\"oLanguage\" : {" + "\"sLengthMenu\" : \" _MENU_ 条记录\"," + "\"sZeroRecords\" : \"没有检索到数据\"," + "\"sInfo\" : \"第 _START_ 至 _END_ 条数据 共 _TOTAL_ 条\"," + "\"sInfoEmtpy\" : \"没有数据\"," + "\"sProcessing\" : \"正在加载数据...\"," + "\"sSearch\" : \"搜索\"," + "\"oPaginate\" : {" + "\"sFirst\" : \"首页\"," + "\"sPrevious\" : \"前页\", " + "\"sNext\" : \"后页\"," + "\"sLast\" : \"尾页\"" + "}" + "},"); // 汉化 // 获取数据的处理函数 \"data\" : {_dt_json : JSON.stringify(aoData)}, sb.append("\"fnServerData\" : function(sSource, aoData, fnCallback, oSettings) {"); // + "\"data\" : {_dt_json : JSON.stringify(aoData)}," sb.append("oSettings.jqXHR = $.ajax({" + "\"dataType\" : \'json\'," + "\"type\" : \"POST\"," + "\"url\" : sSource," + "\"data\" : aoData," + "\"success\" : fnCallback" + "});},"); sb.append("\"aoColumns\" : [ "); int i = 0; for (DataGridColumn column : columnList) { i++; sb.append("{"); sb.append("\"sTitle\":\"" + column.getTitle() + "\""); if (column.getField().equals("opt")) { sb.append(",\"mData\":\"" + idField + "\""); sb.append(",\"sWidth\":\"20%\""); sb.append(",\"bSortable\":false"); sb.append(",\"bSearchable\":false"); sb.append(",\"mRender\" : function(data, type, rec) {"); this.getOptUrl(sb); sb.append("}"); } else { int colwidth = (column.getWidth() == null) ? column.getTitle().length() * 15 : column.getWidth(); sb.append(",\"sName\":\"" + column.getField() + "\""); sb.append(",\"mDataProp\":\"" + column.getField() + "\""); sb.append(",\"mData\":\"" + column.getField() + "\""); sb.append(",\"sWidth\":\"" + colwidth + "\""); sb.append(",\"bSortable\":" + column.isSortable() + ""); sb.append(",\"bVisible\":" + !column.isHidden() + ""); sb.append(",\"bSearchable\":" + column.isQuery() + ""); } sb.append("}"); if (i < columnList.size()) sb.append(","); } sb.append("]" + "});" + "});" + "</script>"); sb.append("<table width=\"100%\" class=\"" + style + "\" id=\"" + name + "\" toolbar=\"#" + name + "tb\"></table>"); return sb; } public void setStyle(String style) { this.style = style; } public String toString(){ StringBuffer key = new StringBuffer(); key.append("DataGridTag [fields=").append(fields) .append(",searchFields=").append(searchFields) .append(",name=").append(name) .append(",title=").append(title) .append(",idField=").append(idField) .append(",treegrid=").append(treegrid) .append(",actionUrl=").append(actionUrl) .append(",sortName=").append(sortName) .append(",queryMode=").append(queryMode) .append(",entityName=").append(entityName) .append(", cssTheme=").append(cssTheme) .append(",treeField=").append(treeField) .append(",btnCls=").append(btnCls) .append(",queryBuilder=").append(queryBuilder) .append(",collapsible=").append(collapsible) .append(",superQuery=").append(superQuery) .append(",complexSuperQuery=").append(complexSuperQuery); key.append(",urlList=["); for(DataGridUrl url : urlList){ key.append(url.toString()+","); } key.append("]"); key.append(",toolBarList=["); for(DataGridUrl url : toolBarList){ key.append(url.toString()+","); } key.append(",columnList=["); for(DataGridColumn col : columnList){ key.append(col.toString()+","); } key.append("]"); key.append(",columnValueList=["); for(ColumnValue col : columnValueList){ key.append(col.toString()+","); } key.append("]"); key.append(",columnStyleList=["); for(ColumnValue col : columnStyleList){ key.append(col.toString()+","); } key.append("]"); key.append(",sysTheme=").append(SysThemesUtil.getSysTheme(ContextHolderUtils.getRequest()).getStyle()) .append(",brower_type="+ContextHolderUtils.getSession().getAttribute("brower_type")) .append("]"); return key.toString(); }; /** * easyui构造方法 * * @return */ public StringBuffer end() { StringBuffer sb = null; if (style.equals("easyui")) { sb = null; }else if("jqgrid".equals(style)){ sb = jqGrid(); }else{ sb = datatables(); } String grid = ""; sb = new StringBuffer(); if(btnCls!=null && btnCls.indexOf("bootstrap")==0){ sb.append("<link rel=\"stylesheet\" href=\"plug-in/bootstrap/css/bootstrap-btn.css\" type=\"text/css\"></link>"); } boolean hasGroup = hasGroup(); if(hasGroup){ sb.append("<link rel=\"stylesheet\" href=\"plug-in/tools/css/optgroup.css\" type=\"text/css\"></link>"); } width = (width == null) ? "auto" : width; height = (height == null) ? "auto" : height; if(!treegrid && isShowSubGrid){ sb.append("<script type=\"text/javascript\" src=\"plug-in/easyui/extends/datagrid-detailview.js\"></script>"); } sb.append("<script type=\"text/javascript\">"); if(!treegrid && isShowSubGrid){ loadSubData(configId); sb.append("function detailFormatterFun(){"); sb.append("var s = '<div class=\"orderInfoHidden\" style=\"padding:2px;\">'+"); sb.append("'<div class=\"easyui-tabs\" style=\"height:230px;width:800px;\">'+"); String subtableids[] = null; if(head.getSubTableStr()!=null && head.getSubTableStr().length()>=0){ subtableids = head.getSubTableStr().split(","); for (String subtable : subtableids) { sb.append("'<div title=\""+((CgSubTableVO)tableData.get(subtable)).getHead().getContent()+"\" style=\"padding:2px;\">'+"); sb.append("'<table class=\""+((CgSubTableVO)tableData.get(subtable)).getHead().getTableName()+"tablelines\" ></table>'+"); sb.append("'</div>'+"); } } sb.append("'</div>'+"); sb.append("'</div>'; return s;}"); sb.append("function onExpandRowFun(index,row){"); sb.append("var tabs = $(this).datagrid('getRowDetail',index).find('div.easyui-tabs');"); sb.append("tabs.tabs();"); if(subtableids!=null){ for (String ss : subtableids) { CgSubTableVO submap = ((CgSubTableVO)tableData.get(ss)); String linkid = ""; String subfield = ""; String columns = ""; List<Map<String, Object>> subfieldlist = submap.getFieldList(); for (Map<String, Object> map : subfieldlist) { subfield+=map.get("field_name")+","; // if(map.get("main_field")!=null && map.get("main_field").toString().length()>0 && "".equals(linkid)){ // linkid = (String)map.get("field_name"); // } columns += "{title:'"+map.get("content")+"',field:'"+map.get("field_name")+"',align:'left',width:50},"; } List<CgFormFieldEntity> subFields = submap.getHead().getColumns(); for (CgFormFieldEntity subField : subFields) { if(StringUtils.isNotBlank(subField.getMainField())) { linkid=subField.getFieldName(); break; } } sb.append("var "+submap.getHead().getTableName()+"durl = 'cgAutoListController.do?datagrid&configId="+submap.getHead().getTableName()+"&"+linkid+"='+row.id+'&field="+subfield+"&page=1&rows=100';"); sb.append("var "+submap.getHead().getTableName()+"tablelines = $(this).datagrid('getRowDetail',index).find('table."+submap.getHead().getTableName()+"tablelines');"); sb.append(""+submap.getHead().getTableName()+"tablelines.datagrid({"); sb.append("singleSelect:true,"); sb.append("loadMsg:'正在加载',"); sb.append("fitColumns:true,"); sb.append("height:'180',"); sb.append("pageSize : 50,"); sb.append("pageList : [ 50, 150, 200, 250, 300 ],"); sb.append("border:false,"); sb.append("loadMsg:\"\","); sb.append("url: "+submap.getHead().getTableName()+"durl,"); sb.append("idField : 'id',"); sb.append("rownumbers : true,"); sb.append("pagination : false,"); sb.append("onLoadSuccess : function(a,b,c) {},"); sb.append("columns:[["); sb.append(columns); sb.append("{field:'0000',hidden:true}"); sb.append("]]"); sb.append("});"); }} sb.append("}"); } sb.append("$(function(){ storage=$.localStorage;if(!storage)storage=$.cookieStorage;"); sb.append(this.getNoAuthOperButton()); if (treegrid) { grid = "treegrid"; sb.append("$(\'#" + name + "\').treegrid({"); sb.append("idField:'id',"); if(StringUtils.isNotEmpty(treeField)){ sb.append("treeField:'"+treeField+"',"); }else{ sb.append("treeField:'text',"); } sb.append(" onBeforeLoad: function(row,param){\n" + " if (!row) { \n" + " delete param.id; \n" + " }\n" + " },"); } else { grid = "datagrid"; sb.append("$(\'#" + name + "\').datagrid({"); if (this.isFilter()) { sb.append("onHeaderContextMenu: function(e, field){headerMenu(e, field);},"); } sb.append("idField: '" + idField + "',"); } if (title != null) { sb.append("title: \'" + title + "\',"); } if(isShowSubGrid){ sb.append("view: detailview,"); sb.append("detailFormatter:detailFormatterFun,"); sb.append("onExpandRow: onExpandRowFun,"); } if(autoLoadData) sb.append("url:\'" + actionUrl + "&field=" + fields + "\',"); else sb.append("url:\'',"); if(StringUtils.isNotEmpty(rowStyler)){ sb.append("rowStyler: function(index,row){ return "+rowStyler+"(index,row);},"); } if(StringUtils.isNotEmpty(extendParams)){ sb.append(extendParams); } if (fit) { sb.append("fit:true,"); } else { sb.append("fit:false,"); } if(!nowrap){ sb.append("nowrap:false,"); } sb.append("rownumbers: true,"); if(collapsible){ sb.append("collapsible: true,"); } if(hasQueryColum(columnList)){ String queryParams = ""; queryParams += "queryParams:{"; for (DataGridColumn col : columnList) { if (col.isQuery()&&col.getDefaultVal()!=null&&!col.getDefaultVal().trim().equals("")) { //sb.append("queryParams:{documentTitle:'woniu'},"); if(!"group".equals(col.getQueryMode())){ queryParams += col.getField()+":'"+col.getDefaultVal()+"',"; } } } if(queryParams.indexOf(",")>-1){ queryParams = queryParams.substring(0, queryParams.length()-1); } queryParams += "},"; //System.out.println("queryParams===="+queryParams); sb.append(queryParams); } sb.append(StringUtil.replaceAll("loadMsg: \'{0}\',", "{0}", MutiLangUtil.getLang("common.data.loading"))); sb.append("pageSize: " + pageSize + ","); sb.append("pagination:" + pagination + ","); sb.append("pageList:[" + pageSize * 1 + "," + pageSize * 2 + "," + pageSize * 3 + "],"); if(StringUtils.isNotBlank(sortName)){ sb.append("sortName:'" +sortName +"',"); } sb.append("sortOrder:'" + sortOrder + "',"); sb.append("rownumbers:true,"); if(singleSelect==null){ sb.append("singleSelect:" + !checkbox + ","); }else{ sb.append("singleSelect:" + singleSelect + ","); } if (fitColumns) { sb.append("fitColumns:true,"); } else { sb.append("fitColumns:false,"); } sb.append("striped:true,showFooter:true,"); sb.append("frozenColumns:[["); this.getField(sb,0); sb.append("]],"); sb.append("columns:[["); this.getField(sb); sb.append("]],"); sb.append("onLoadSuccess:function(data){$(\"#"+name+"\")."+grid+"(\"clearChecked\");$(\"#"+name+"\")."+grid+"(\"clearSelections\");"); //sb.append(" $(this).datagrid(\"fixRownumber\");"); if(openFirstNode&&treegrid){ sb.append(" if(data==null){"); sb.append(" var firstNode = $(\'#" + name + "\').treegrid('getRoots')[0];"); sb.append(" $(\'#" + name + "\').treegrid('expand',firstNode.id)}"); } sb.append("if(!"+treegrid+"){"); sb.append("if(data.total && data.rows.length==0) {"); sb.append("var grid = $(\'#"+name+"\');"); sb.append("var curr = grid.datagrid(\'getPager\').data(\"pagination\").options.pageNumber;"); sb.append("grid.datagrid({pageNumber:(curr-1)});}}"); sb.append(" try{loadAjaxDict(data);}catch(e){}"); if(hasGroup){ sb.append("optsMenuToggle('"+name+"');"); } if (StringUtil.isNotEmpty(onLoadSuccess)) { sb.append(onLoadSuccess + "(data);"); } sb.append("},"); if (StringUtil.isNotEmpty(onDblClick)) { sb.append("onDblClickRow:function(rowIndex,rowData){" + onDblClick + "(rowIndex,rowData);},"); } if (treegrid) { sb.append("onClickRow:function(rowData){"); } else { sb.append("onClickRow:function(rowIndex,rowData){"); } /**行记录赋值*/ sb.append("rowid=rowData.id;"); sb.append("gridname=\'"+name+"\';"); if (StringUtil.isNotEmpty(onClick)) { if (treegrid) { sb.append("" + onClick + "(rowData);"); }else{ sb.append("" + onClick + "(rowIndex,rowData);"); } } sb.append("}"); sb.append("});"); this.setPager(sb, grid); sb.append("try{restoreheader();}catch(ex){}"); sb.append("});"); sb.append("function reloadTable(){"); sb.append("try{"); sb.append(" $(\'#\'+gridname).datagrid(\'reload\');" ); sb.append(" $(\'#\'+gridname).treegrid(\'reload\');" ); sb.append("}catch(ex){}"); sb.append("}"); sb.append("function reload" + name + "(){" + "$(\'#" + name + "\')." + grid + "(\'reload\');" + "}"); sb.append("function get" + name + "Selected(field){return getSelected(field);}"); sb.append("function getSelected(field){" + "var row = $(\'#\'+gridname)." + grid + "(\'getSelected\');" + "if(row!=null)" + "{" + "value= row[field];" + "}" + "else" + "{" + "value=\'\';" + "}" + "return value;" + "}"); sb.append("function get" + name + "Selections(field){" + "var ids = [];" + "var rows = $(\'#" + name + "\')." + grid + "(\'getSelections\');" + "for(var i=0;i<rows.length;i++){" + "ids.push(rows[i][field]);" + "}" + "ids.join(\',\');" + "return ids" + "};"); sb.append("function getSelectRows(){"); sb.append(" return $(\'#"+name+"\').datagrid('getChecked');"); sb.append("}"); sb.append(" function saveHeader(){"); sb.append(" var columnsFields =null;var easyextends=false;try{columnsFields = $('#"+name+"').datagrid('getColumns');easyextends=true;"); sb.append("}catch(e){columnsFields =$('#"+name+"').datagrid('getColumnFields');}"); sb.append(" var cols = storage.get( '"+name+"hiddenColumns');var init=true; if(cols){init =false;} " + "var hiddencolumns = [];for(var i=0;i< columnsFields.length;i++) {if(easyextends){"); sb.append("hiddencolumns.push({field:columnsFields[i].field,hidden:columnsFields[i].hidden});}else{"); sb.append( " var columsDetail = $('#"+name+"').datagrid(\"getColumnOption\", columnsFields[i]); "); sb.append( "if(init){hiddencolumns.push({field:columsDetail.field,hidden:columsDetail.hidden,visible:(columsDetail.hidden==true?false:true)});}else{"); sb.append("for(var j=0;j<cols.length;j++){"); sb.append(" if(cols[j].field==columsDetail.field){"); sb.append(" hiddencolumns.push({field:columsDetail.field,hidden:columsDetail.hidden,visible:cols[j].visible});"); sb.append(" }"); sb.append("}"); sb.append("}} }"); sb.append("storage.set( '"+name+"hiddenColumns',JSON.stringify(hiddencolumns));"); sb.append( "}"); sb.append(" function isShowBut(){"); sb.append(" var isShowSearchId = $(\'#isShowSearchId\').val();"); sb.append(" if(isShowSearchId == \"true\"){"); sb.append(" $(\"#searchColums\").hide();"); sb.append(" $(\'#isShowSearchId\').val(\"false\");"); sb.append(" $(\'#columsShow\').remove(\"src\");"); sb.append(" $(\'#columsShow\').attr(\"src\",\"plug-in/easyui/themes/default/images/accordion_expand.png\");"); sb.append(" } else{"); sb.append(" $(\"#searchColums\").show();"); sb.append(" $(\'#isShowSearchId\').val(\"true\");"); sb.append(" $(\'#columsShow\').remove(\"src\");"); sb.append(" $(\'#columsShow\').attr(\"src\",\"plug-in/easyui/themes/default/images/accordion_collapse.png\");"); sb.append(" }"); sb.append("}"); sb.append( "function restoreheader(){"); sb.append("var cols = storage.get( '"+name+"hiddenColumns');if(!cols)return;"); sb.append( "for(var i=0;i<cols.length;i++){"); sb.append( " try{"); sb.append("if(cols.visible!=false)$('#"+name+"').datagrid((cols[i].hidden==true?'hideColumn':'showColumn'),cols[i].field);"); sb.append( "}catch(e){"); sb.append( "}"); sb.append( "}"); sb.append( "}"); sb.append( "function resetheader(){"); sb.append("var cols = storage.get( '"+name+"hiddenColumns');if(!cols)return;"); sb.append( "for(var i=0;i<cols.length;i++){"); sb.append( " try{"); sb.append(" $('#"+name+"').datagrid((cols.visible==false?'hideColumn':'showColumn'),cols[i].field);"); sb.append( "}catch(e){"); sb.append( "}"); sb.append( "}"); sb.append( "}"); if (columnList.size() > 0) { sb.append("function " + name + "search(){"); //update by jg_renjie at 2016/1/11 for:TASK #823 增加form实现Form表单验证 sb.append("try { if(! $(\"#"+name+"Form\").Validform({tiptype:3}).check()){return false;} } catch (e){}"); sb.append("if(true){"); //update by jg_renjie at 2016/1/11 for:TASK #823 增加form实现Form表单验证 sb.append("var queryParams=$(\'#" + name + "\').datagrid('options').queryParams;"); sb.append("$(\'#" + name + "tb\').find('*').each(function(){queryParams[$(this).attr('name')]=$(this).val();});"); sb.append("$(\'#" + name + "\')." + grid + "({url:'" + actionUrl + "&field=" + searchFields + "',pageNumber:1});" + "}}"); //高级查询执行方法 sb.append("function dosearch(params){"); sb.append("var jsonparams=$.parseJSON(params);"); sb.append("$(\'#" + name + "\')." + grid + "({url:'" + actionUrl + "&field=" + searchFields + "',queryParams:jsonparams});" + "}"); //searchbox框执行方法 searchboxFun(sb,grid); //生成重置按钮功能js //回车事件 sb.append("function EnterPress(e){"); sb.append("var e = e || window.event;"); sb.append("if(e.keyCode == 13){ "); sb.append(name+"search();"); sb.append("}}"); sb.append("function searchReset(name){"); sb.append(" $(\"#\"+name+\"tb\").find(\":input\").val(\"\");"); //update by jg_renjie at 2016/1/11 for:TASK #823 增加form实现Form表单验证,此处避免reset时走验证,代码做了冗余 //String func = name.trim() + "search();"; //sb.append(func); sb.append("var queryParams=$(\'#" + name + "\').datagrid('options').queryParams;"); sb.append("$(\'#" + name + "tb\').find('*').each(function(){queryParams[$(this).attr('name')]=$(this).val();});"); sb.append("$(\'#" + name + "tb\').find(\"input[type='checkbox']\").each(function(){$(this).attr('checked',false);});"); sb.append("$(\'#" + name + "tb\').find(\"input[type='radio']\").each(function(){$(this).attr('checked',false);});"); sb.append("$(\'#" + name + "\')." + grid + "({url:'" + actionUrl + "&field=" + searchFields + "',pageNumber:1});"); //update by jg_renjie at 2016/1/11 for:TASK #823 增加form实现Form表单验证,此处避免reset时走验证,代码做了冗余 sb.append("}"); } //高级查询避免方法名出现重复 if(oConvertUtils.isNotEmpty(complexSuperQuery)) { sb.append("function "+name+"SuperQuery(queryCode){if(typeof(windowapi)=='undefined'){$.dialog({content:'url:superQueryMainController.do?dialog&code='+queryCode+'&tableName="+name+"',width:880,height:400,zIndex:getzIndex(),title:'高级查询构造器',cache:false,lock:true})}else{$.dialog({content:'url:superQueryMainController.do?dialog&code='+queryCode+'&tableName="+name+"',width:880,height:400,zIndex:getzIndex(),title:title,cache:false,lock:true,parent:windowapi})}};"); } //过滤操作 getFilterFields(sb); sb.append("</script>"); sb.append("<table width=\"100%\" id=\"" + name + "\" toolbar=\"#" + name + "tb\"></table>"); sb.append("<div id=\"" + name + "tb\" style=\"padding:3px; height: auto\">"); if(hasQueryColum(columnList)&&isShowSearch==true){ sb.append("<input id=\"columsShow\" type=\"image\" src=\"plug-in/easyui/themes/default/images/accordion_collapse.png\" onclick=\"isShowBut()\">"); } boolean blink = false; sb.append("<input id=\"_complexSqlbuilder\" name=\"complexSqlbuilder\" type=\"hidden\" />"); if(hasQueryColum(columnList) && "group".equals(getQueryMode())){ blink = true; String searchColumStyle = toolBarList!=null&&toolBarList.size()!=0?"":"style='border-bottom: 0px'"; sb.append("<div name=\"searchColums\" id=\"searchColums\" "+searchColumStyle+">"); sb.append("<input id=\"isShowSearchId\" type=\"hidden\" value=\""+isShowSearch+"\"/>"); //-----longjb1 增加用于高级查询的参数项 sb.append("<input id=\"_sqlbuilder\" name=\"sqlbuilder\" type=\"hidden\" />"); //update by jg_renjie at 2016/1/11 for:TASK #823 增加form实现Form表单验证 sb.append("<form onkeydown='if(event.keyCode==13){" + name + "search();return false;}' id='"+name+"Form'>"); //update by jg_renjie at 2016/1/11 for:TASK #823 sb.append("<span style=\"max-width: 79%;display: inline-block;\">"); sb.append("<span><img style=\"margin-top:-3px;vertical-align:middle;\" src=\"plug-in/easyui/themes/icons/ti.png\" title=\"提示:模糊查询通配符: *,多个关键字用半角逗号 ',' 隔开!\" alt=\"提示:模糊查询通配符: *,多个关键字用半角逗号 ',' 隔开!\" /></span>"); getSearchFormInfo(sb); sb.append("</span>"); sb.append("<span>"); getSearchButton(sb); sb.append("</span>"); sb.append("</form></div>"); }else if(hasQueryColum(columnList) && "advanced".equals(getQueryMode())){ blink = true; String searchColumStyle = toolBarList!=null&&toolBarList.size()!=0?"":"style='border-bottom: 0px'"; sb.append("<div name=\"searchColums\" style=\"display:none;\" id=\"searchColums\" "+searchColumStyle+">"); sb.append("<input id=\"isShowSearchId\" type=\"hidden\" value=\""+isShowSearch+"\"/>"); //-----longjb1 增加用于高级查询的参数项 sb.append("<input id=\"_sqlbuilder\" name=\"sqlbuilder\" type=\"hidden\" />"); sb.append("<form onkeydown='if(event.keyCode==13){" + name + "search();return false;}' id='"+name+"Form'>"); sb.append("<span style=\"max-width: 79%;display: inline-block;\">"); getSearchFormInfo(sb); sb.append("</span>"); sb.append("<span>"); getSearchButton(sb); sb.append("</span>"); sb.append("</form></div>"); } if(toolBarList==null || toolBarList.size()==0){ sb.append("<div style=\"height:0px;\" >"); }else{//TODO sb.append("<div style=\"border-bottom-width:0;\" class=\"datagrid-toolbar\">"); } sb.append("<span style=\"float:left;\" >"); if(toolBarList.size()>0) { Boolean hasMore = false; for (DataGridUrl toolBar : toolBarList) { if(toolBar.isInGroup()){ if(!hasMore){ hasMore = true; } }else{ loadToolbar(toolBar, sb); } } if(hasMore){ loadToolbarMoreBtn(sb,true,null); sb.append("<div class='toolbar-more-container'><ul class='toolbar-more-list'>"); for (DataGridUrl toolBar : toolBarList) { if(toolBar.isInGroup()){ sb.append("<li>"); loadToolbarMoreBtn(sb,false,toolBar); sb.append("</li>"); } } sb.append("</ul></div>"); //sb.append("<div class='btn-group'><button data-toggle='dropdown' class='btn btn-default dropdown-toggle'>操作<span class='caret'></span> </button><ul class='dropdown-menu'><li><a href='buttons.html#'>置顶</a></li><li><a href='buttons.html#' class='font-bold'>修改</a></li><li><a href='buttons.html#'>禁用</a></li><li class='divider'></li> <li><a href='buttons.html#'>删除</a></li> </ul> </div>"); } } sb.append("</span>"); if("single".equals(getQueryMode())&& hasQueryColum(columnList)){//如果表单是单查询 sb.append("<span style=\"float:right\">"); sb.append("<input id=\""+name+"searchbox\" class=\"easyui-searchbox\" data-options=\"searcher:"+name+ StringUtil.replaceAll("searchbox,prompt:\'{0}\',menu:\'#", "{0}", MutiLangUtil.getLang("common.please.input.keyword")) +name+"mm\'\"></input>"); sb.append("<div id=\""+name+"mm\" style=\"width:120px\">"); for (DataGridColumn col : columnList) { if (col.isQuery()) { sb.append("<div data-options=\"name:\'"+col.getField().replaceAll("_","\\.")+"\',iconCls:\'icon-ok\' \">"+col.getTitle()+"</div> "); } } sb.append("</div>"); sb.append("</span>"); }else if ("advanced".equals(getQueryMode()) && hasQueryColum(columnList)) {// 如果表单是高级查询 sb.append("<span style=\"float:right\">"); if (btnCls != null && !btnCls.equals("easyui")) {// 自定以样式 bootstrap按钮样式 if (btnCls.indexOf("bootstrap") == 0) { String defalutCls = "btn btn-info btn-xs"; if (btnCls.replace("bootstrap", "").trim().length() > 0) { defalutCls = btnCls.replace("bootstrap", "").trim(); } if (superQuery) { sb.append("<button class=\"" + defalutCls + "\" type=\"button\" onclick=\"queryBuilder()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">" + MutiLangUtil.getLang("common.superquery") + "</span>"); sb.append("</button>"); sb.append("</span>"); } } else {// 自定以样式 if (superQuery) { sb.append("<a href=\"#\" class=\"" + btnCls + "\" onclick=\"queryBuilder('" + StringUtil .replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.superquery"))); } } } else {// 默认使用easyUI按钮样式 if (superQuery) { sb.append( "<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-search\" onclick=\"queryBuilder('" + StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.superquery"))); } } sb.append("</span>"); } sb.append("<div style=\"clear:both\"></div>"); sb.append("</div>"); if(blink){ sb.insert(0, "<link rel=\"stylesheet\" href=\"plug-in/Validform/css/style.css\" type=\"text/css\">" + "<link rel=\"stylesheet\" href=\"plug-in/Validform/css/tablefrom.css\" type=\"text/css\">" + "<script type=\"text/javascript\" src=\"plug-in/Validform/js/Validform_v5.3.1_min_zh-cn.js\"></script>" + "<script type=\"text/javascript\" src=\"plug-in/Validform/js/Validform_Datatype_zh-cn.js\"></script>" + "<script type=\"text/javascript\" src=\"plug-in/Validform/js/datatype_zh-cn.js\"></script>"); } if(queryBuilder){ if (btnCls != null && !btnCls.equals("easyui")) {//自定以样式 bootstrap按钮样式 addQueryBuilder(sb,btnCls); }else{//默认使用easyUI按钮样式 addQueryBuilder(sb,"easyui-linkbutton"); } } if(superQuery) { if(btnCls != null && !btnCls.equals("easyui")) {//自定义bootstrap按钮样式 addSuperQuery(sb,btnCls,columnList); } else { addSuperQuery(sb,"easyui-linkbutton",columnList); } } if(oConvertUtils.isNotEmpty(complexSuperQuery)){ if(btnCls != null && !btnCls.equals("easyui")) {//自定义bootstrap按钮样式 addAdvancedQuery(sb,btnCls); } else { addAdvancedQuery(sb,"easyui-linkbutton"); } } this.getFilter(sb); return sb; } /** * 仅用于 加载【更多操作】 按钮的方法 * @param sb * @param 是否是【更多操作】按钮,false则为点击【更多操作】后展示的按钮 * @param toolBar */ private void loadToolbarMoreBtn(StringBuffer sb,boolean isShow,DataGridUrl toolBar){ if(isShow){ if (btnCls != null && !btnCls.equals("easyui")) { if(btnCls.indexOf("bootstrap")==0){ if (btnCls.replace("bootstrap", "").trim().length() > 0) { sb.append("<button class=\""+btnCls.replace("bootstrap", "").trim()+"\" "); }else{ sb.append("<button class=\"btn btn-default btn-xs\" "); } sb.append("onclick='toggleMoreToolbars(this)'"); sb.append("><i class=\"fa fa-caret-down\"></i><span class=\"bigger-110 no-text-shadow\">更多操作</span></button>"); }else{ sb.append("<a href=\"javascript:void(0)\" onclick='toggleMoreToolbars(this)' class=\""+btnCls+" " + toolBar.getIcon()+"\" >更多操作</a>"); } }else if(btnCls == null || btnCls.equals("easyui")){ sb.append("<a href=\"javascript:void(0)\" onclick='toggleMoreToolbars(this)' class=\"easyui-linkbutton\" plain=\"true\" icon=\"icon-caret-down\">更多操作</a> "); } }else{ sb.append("<a href='javascript:void(0)' "); if(StringUtil.isNotEmpty(toolBar.getId())){ sb.append(" id=\""); sb.append(toolBar.getId()); sb.append("\" "); } if(StringUtil.isNotEmpty(toolBar.getOnclick())){ sb.append("onclick="+toolBar.getOnclick()+""); }else{ sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")){ sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } if(btnCls == null || btnCls.equals("easyui")){ sb.append("><span class=\"easyui-mycon "+toolBar.getIcon()+"\"></span> "+toolBar.getTitle()); }else{ sb.append("><i class=\""+toolBar.getIcon()+"\"></i> "+toolBar.getTitle()); } sb.append("</a>"); } } private void loadToolbar(DataGridUrl toolBar,StringBuffer sb){ if (btnCls != null && !btnCls.equals("easyui")) {//自定以样式 bootstrap按钮样式 if(btnCls.indexOf("bootstrap")==0){ if (btnCls.replace("bootstrap", "").trim().length() > 0) { sb.append("<button class=\""+btnCls.replace("bootstrap", "").trim()+"\" "); }else{ sb.append("<button class=\"btn btn-default btn-xs\" "); } if(StringUtil.isNotEmpty(toolBar.getId())){ sb.append(" id=\""); sb.append(toolBar.getId()); sb.append("\" "); } if(StringUtil.isNotEmpty(toolBar.getOnclick())) { sb.append("onclick="+toolBar.getOnclick()+""); } else { sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")) { sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } sb.append("><i class=\"" + toolBar.getIcon() + "\"></i><span class=\"bigger-110 no-text-shadow\">"+toolBar.getTitle()+"</span></button>"); }else{ sb.append("<a href=\"#\" class=\""+btnCls+" " + toolBar.getIcon()+"\" "); if(StringUtil.isNotEmpty(toolBar.getId())){ sb.append(" id=\""); sb.append(toolBar.getId()); sb.append("\" "); } if(StringUtil.isNotEmpty(toolBar.getOnclick())) { sb.append("onclick="+toolBar.getOnclick()+""); } else { sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")) { sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } sb.append(">"+toolBar.getTitle()+"</a>"); } }else if(btnCls == null || btnCls.equals("easyui")){//easyUI按钮样式 sb.append("<a href=\"#\" class=\"easyui-linkbutton\" plain=\"true\" icon=\""+toolBar.getIcon()+"\" "); if(StringUtil.isNotEmpty(toolBar.getId())){ sb.append(" id=\""); sb.append(toolBar.getId()); sb.append("\" "); } if(StringUtil.isNotEmpty(toolBar.getOnclick())) { sb.append("onclick="+toolBar.getOnclick()+""); } else { sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")) { sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } sb.append(">"+toolBar.getTitle()+"</a>"); } } private void loadSubData(String id){ CgFormFieldServiceI cgFormFieldService = (CgFormFieldServiceI)ApplicationContextUtil.getContext().getBean("cgFormFieldService"); String tableName = id; String tablename = PublicUtil.replaceTableName(tableName); Map<String, Object> data = new HashMap<String, Object>(); Map configData = null; String jversion = cgFormFieldService.getCgFormVersionByTableName(id); configData = cgFormFieldService.getFtlFormConfig(tableName,jversion); data = new HashMap(configData); //如果该表是主表查出关联的附表 CgFormHeadEntity head = (CgFormHeadEntity)data.get("head"); this.tableData = (Map<String, Object>)data.get("field"); this.head = head; } private void getSearchButton(StringBuffer sb) { if("group".equals(getQueryMode()) && hasQueryColum(columnList)){//如果表单是组合查询 sb.append("<span style=\"float:right;\">"); if (btnCls != null && !btnCls.equals("easyui")) {//自定以样式 bootstrap按钮样式 if(btnCls.indexOf("bootstrap")==0){ String defalutCls = "btn btn-info btn-xs"; if (btnCls.replace("bootstrap", "").trim().length() > 0) { defalutCls = btnCls.replace("bootstrap", "").trim(); } sb.append("<button class=\""+defalutCls+"\" type=\"button\" onclick=\"" + name + "search()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.query")+"</span>"); sb.append("</button>"); sb.append("<button class=\""+defalutCls+"\" type=\"button\" onclick=\"searchReset('" + name + "')\">"); sb.append("<i class=\"fa fa-refresh\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.reset")+"</span>"); sb.append("</button>"); if(queryBuilder){ sb.append("<button class=\""+defalutCls+"\" type=\"button\" onclick=\"queryBuilder()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.querybuilder")+"</span>"); sb.append("</button>"); } if(superQuery) { sb.append("<button class=\""+defalutCls+"\" type=\"button\" onclick=\"queryBuilder()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.superquery")+"</span>"); sb.append("</button>"); } if(oConvertUtils.isNotEmpty(complexSuperQuery)) { sb.append("<button class=\""+defalutCls+"\" type=\"button\" onclick=\""+name+"SuperQuery('"+complexSuperQuery+"')\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.advancedQuery")+"</span>"); sb.append("</button>"); } }else{//自定以样式 sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\""+ name+ StringUtil.replaceAll("search()\">{0}</a>", "{0}", MutiLangUtil.getLang("common.query"))); sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\"searchReset('"+name+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.reset")) ); if(queryBuilder){ sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.querybuilder")) ); } if(superQuery) { sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.superquery")) ); } if(oConvertUtils.isNotEmpty(complexSuperQuery)) { sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\""+name+"SuperQuery('"+complexSuperQuery+"')\">"+MutiLangUtil.getLang("common.advancedQuery")+"</a>"); } } }else{//默认使用easyUI按钮样式 sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-search\" onclick=\""+ name+ StringUtil.replaceAll("search()\">{0}</a>", "{0}", MutiLangUtil.getLang("common.query"))); sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-reload\" onclick=\"searchReset('"+name+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.reset")) ); if(queryBuilder){ sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-search\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.querybuilder")) ); } if(superQuery) { sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-search\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.superquery")) ); } if(oConvertUtils.isNotEmpty(complexSuperQuery)) { sb.append("<a href=\"#\" class=\"easyui-linkbutton\" iconCls=\"icon-search\" onclick=\""+name+"SuperQuery('"+complexSuperQuery+"')\">"+MutiLangUtil.getLang("common.advancedQuery")+"</a>"); } } sb.append("</span>"); } } /** * 构建查询form当中的信息 * @param sb */ private void getSearchFormInfo(StringBuffer sb) { //如果表单是组合查询 if("group".equals(getQueryMode())){ int i = 0; for (DataGridColumn col : columnList) { if (col.isQuery()) { String searchControlAttr= extendAttribute(col.getExtend());//获取extend属性对应的HTML sb.append("<span style=\"display:-moz-inline-box;display:inline-block;margin-bottom:2px;text-align:justify;\">"); if(i==0){ sb.append("<span style=\"vertical-align:middle;display:-moz-inline-box;display:inline-block;width:74px;text-align:right;text-overflow:ellipsis;-o-text-overflow:ellipsis; overflow: hidden;white-space:nowrap; \" title=\""+col.getTitle()+"\">"+"&nbsp;&nbsp;&nbsp;"+col.getTitle()+":"+ (col.getTitle().length()<4?"&nbsp;&nbsp;&nbsp;":"") + "</span>"); }else{ sb.append("<span style=\"vertical-align:middle;display:-moz-inline-box;display:inline-block;width: 90px;text-align:right;text-overflow:ellipsis;-o-text-overflow:ellipsis; overflow: hidden;white-space:nowrap; \" title=\""+col.getTitle()+"\">"+col.getTitle()+":</span>"); } if("single".equals(col.getQueryMode())){ if(!StringUtil.isEmpty(col.getReplace())){ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 120px\" "; } sb.append("<select name=\""+col.getField().replaceAll("_","\\.")+"\" "+searchControlAttr+"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); String[] test = col.getReplace().split(","); String text = ""; String value = ""; for (String string : test) { String lang_key = string.split("_")[0]; text = MutiLangUtil.getLang(lang_key); value =string.split("_")[1]; if(col.getDefaultVal()!=null&&col.getDefaultVal().trim().equals(value)){ sb.append("<option value =\""+value+"\" selected=\"selected\">"+text+"</option>"); }else{ sb.append("<option value =\""+value+"\" >"+text+"</option>"); } } sb.append("</select>"); }else if(!StringUtil.isEmpty(col.getDictionary())){ if(col.getDictionary().contains(",")&&col.isPopup()){ String[] dic = col.getDictionary().split(","); // String sql; // if(!StringUtil.isEmpty(col.getDictCondition())){ // sql = "select " + dic[1] + " as field," + dic[2]+ " as text from " + dic[0]+" "+col.getDictCondition(); // }else{ // sql = "select " + dic[1] + " as field," + dic[2]+ " as text from " + dic[0]; // } //System.out.println(dic[0]+"--"+dic[1]+"--"+dic[2]); // <input type="text" name="order_code" style="width: 100px" class="searchbox-inputtext" value="" onClick="inputClick(this,'account','user_msg');" /> if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 120px\" "; } if(col.getDefaultVal()!=null&&!col.getDefaultVal().trim().equals("")){ sb.append("<input type=\"text\" name=\""+col.getField().replaceAll("_","\\.")+"\" "+searchControlAttr+" class=\"searchbox-inputtext\" onClick=\"popupClick(this,'"+dic[2].replaceAll("@", ",")+"','"+dic[1].replaceAll("@", ",")+"','"+dic[0]+"');\" value=\""+col.getDefaultVal()+"\"/> "); }else{ sb.append("<input type=\"text\" name=\""+col.getField().replaceAll("_","\\.")+"\" "+searchControlAttr+" class=\"searchbox-inputtext\" value=\"\" onClick=\"popupClick(this,'"+dic[2].replaceAll("@", ",")+"','"+dic[1].replaceAll("@", ",")+"','"+dic[0]+"');\" /> "); } }else if(col.getDictionary().contains(",")&&(!col.isPopup())){ String[] dic = col.getDictionary().split(","); String sql; if(!StringUtil.isEmpty(col.getDictCondition())){ sql = "select " + dic[1] + " as field," + dic[2]+ " as text from " + dic[0]+" "+col.getDictCondition(); }else{ sql = "select " + dic[1] + " as field," + dic[2]+ " as text from " + dic[0]; } systemService = ApplicationContextUtil.getContext().getBean( SystemService.class); List<Map<String, Object>> list = systemService.findForJdbc(sql); String showMode = col.getShowMode(); if (null != showMode && "radio".equals(showMode)) { String field = col.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_radio\"/>"); for (Map<String, Object> map : list){ // if(col.getDefaultVal()!=null && col.getDefaultVal().trim().equals(map.get("field"))){ sb.append(" <input "+searchControlAttr+" type=\"radio\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+field+"_radio').val('"+map.get("field")+"');\" value=\""+map.get("field")+"\" checked=\"checked\" />"); sb.append(" <script type=\"text/javascript\">"); sb.append(" $('#"+ field+"_radio').val(\""+map.get("field")+"\");"); sb.append(" </script>"); }else{ sb.append(" <input "+searchControlAttr+" type=\"radio\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+field+"_radio').val('"+map.get("field")+"');\" value=\""+map.get("field")+"\" />"); } sb.append(map.get("text")); } }else if (null != showMode && "checkbox".equals(showMode)) { String field = col.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_checkbox\" value=\"\" />"); for (Map<String, Object> map : list){ // if(col.getDefaultVal()!=null && col.getDefaultVal().trim().equals(map.get("field"))){ sb.append(" <input "+searchControlAttr+" type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+map.get("field")+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+map.get("field")+",',''));}\" value=\"" + map.get("field") + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" checked=\"checked\" />"); sb.append(" <script type=\"text/javascript\">"); sb.append(" $(\"#"+ field +"_checkbox\").val($(\"#"+ field +"_checkbox\").val()+,"+map.get("field")+",);"); sb.append(" </script>"); }else{ sb.append(" <input "+searchControlAttr+" type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+map.get("field")+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+map.get("field")+",',''));}\" value=\"" + map.get("field") + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" />"); } sb.append(map.get("text")); } }else{ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 120px\" "; } sb.append("<select name=\""+col.getField().replaceAll("_","\\.")+"\" "+searchControlAttr+"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); for (Map<String, Object> map : list){ if(col.getDefaultVal()!=null&&col.getDefaultVal().trim().equals(map.get("field"))){ sb.append(" <option value=\""+map.get("field")+"\" selected=\"selected\">"); }else{ sb.append(" <option value=\""+map.get("field")+"\">"); } sb.append(map.get("text")); sb.append(" </option>"); } sb.append("</select>"); } }else{ List<TSType> types = ResourceUtil.getCacheTypes(col.getDictionary().toLowerCase()); String showMode = col.getShowMode(); if (null != showMode && "radio".equals(showMode)) { if (types != null) { String field = col.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_radio\"/>"); for (TSType type : types) { String typeCode = type.getTypecode(); if(col.getDefaultVal()!=null&&col.getDefaultVal().trim().equals(typeCode)){ sb.append(" <input "+searchControlAttr+" type=\"radio\" value=\"" + typeCode + "\" name=\""+field+"_radio\" onclick=\"javascrpt:#('#"+ field+"_radio').val('" + typeCode + "');\" checked=\"checked\" />"); sb.append(" <script type=\"text/javascript\">"); sb.append(" $('#"+ field+"_radio').val('"+typeCode+"');"); sb.append(" </script>"); }else{ sb.append(" <input "+searchControlAttr+" type=\"radio\" value=\"" + typeCode + "\" name=\""+field+"_radio\" onclick=\"javascrpt:$('#"+ field+"_radio').val('" + typeCode + "');\" />"); } sb.append(MutiLangUtil.getLang(type.getTypename())); } } }else if (null != showMode && "checkbox".equals(showMode)) { if (types != null) { String field = col.getField().replaceAll("_","\\."); sb.append("<input type=\"hidden\" name=\""+field+"\" id=\""+field+"_checkbox\" value=\"\" />"); for (TSType type : types) { String typeCode = type.getTypecode(); if(col.getDefaultVal()!=null&&col.getDefaultVal().trim().equals(typeCode)){ sb.append(" <input "+searchControlAttr+" type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+typeCode+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+typeCode+",',''));}\" value=\"" + typeCode + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" checked=\"checked\" />"); sb.append(" <script type=\"text/javascript\">"); sb.append(" $(\"#"+ field +"_checkbox\").val($(\"#"+ field +"_checkbox\").val()+,"+typeCode+",);"); sb.append(" </script>"); }else{ sb.append(" <input "+searchControlAttr+" type=\"checkbox\" onclick=\"javascript:if(this.checked)$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val()+',"+typeCode+",');else{$('#"+ field +"_checkbox').val($('#"+ field +"_checkbox').val().replace(',"+typeCode+",',''));}\" value=\"" + typeCode + "\" name=\"" + field +"_checkbox\" class=\"" + field + "_checkbox\" />"); } sb.append(MutiLangUtil.getLang(type.getTypename())); } } }else{ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 120px\" "; } sb.append("<select name=\""+col.getField().replaceAll("_","\\.")+"\" "+searchControlAttr+"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); if (types != null) { for (TSType type : types) { if(col.getDefaultVal()!=null&&col.getDefaultVal().trim().equals(type.getTypecode())){ sb.append(" <option value=\"" + type.getTypecode() + "\" selected=\"selected\">"); }else{ sb.append(" <option value=\"" + type.getTypecode() + "\">"); } sb.append(MutiLangUtil.getLang(type.getTypename())); sb.append(" </option>"); } } sb.append("</select>"); } } }else if(col.isAutocomplete()){ sb.append(getAutoSpan(col.getField().replaceAll("_","\\."),extendAttribute(col.getExtend()))); }else{ sb.append("<input onkeypress=\"EnterPress(event)\" onkeydown=\"EnterPress()\" type=\"text\" name=\""+col.getField().replaceAll("_","\\.")+"\" "); if(this.DATE_FORMATTER.equals(col.getFormatter())){ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 120px\" "; } sb.append(searchControlAttr+"class=\"Wdate\" onClick=\"WdatePicker()\" "); }else if(this.DATETIME_FORMATTER.equals(col.getFormatter())){ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 160px\" "; } sb.append(searchControlAttr+"class=\"Wdate\" onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})\" "); }else{ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 120px\" "; } sb.append(searchControlAttr+"class=\"inuptxt\" "); } if(oConvertUtils.isNotEmpty(col.getDefaultVal())){ sb.append(" value=\""+col.getDefaultVal()+"\" "); } sb.append(" />"); //sb.append("<input onkeypress=\"EnterPress(event)\" onkeydown=\"EnterPress()\" type=\"text\" name=\""+col.getField().replaceAll("_","\\.")+"\" "+extendAttribute(col.getExtend())+" class=\"inuptxt\" style=\"width: 100px\" value="+col.getDefaultVal()==null?"":"\""+col.getDefaultVal()+"\""+"/>"); } }else if("group".equals(col.getQueryMode())){ if(this.DATE_FORMATTER.equals(col.getFormatter())){ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 100px\" "; } sb.append("<input type=\"text\" name=\""+col.getField()+"_begin\" "+searchControlAttr+" class=\"Wdate\" onClick=\"WdatePicker()\"/>"); sb.append("<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>"); sb.append("<input type=\"text\" name=\""+col.getField()+"_end\" "+searchControlAttr+" class=\"Wdate\" onClick=\"WdatePicker()\"/>"); }else if(this.DATETIME_FORMATTER.equals(col.getFormatter())){ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 140px\" "; } sb.append("<input type=\"text\" name=\""+col.getField()+"_begin\" "+searchControlAttr+" class=\"Wdate\" onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})\"/>"); sb.append("<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>"); sb.append("<input type=\"text\" name=\""+col.getField()+"_end\" "+searchControlAttr+" class=\"Wdate\" onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})\"/>"); }else{ if(oConvertUtils.isEmpty(searchControlAttr)){ searchControlAttr = " style=\"width: 100px\" "; } sb.append("<input type=\"text\" name=\""+col.getField()+"_begin\" "+searchControlAttr+" class=\"inuptxt\"/>"); sb.append("<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>"); sb.append("<input type=\"text\" name=\""+col.getField()+"_end\" "+searchControlAttr+" class=\"inuptxt\"/>"); } } sb.append("</span>"); i++; } } } } /** * 生成扩展属性 * @param field * @return */ private String extendAttribute(String field) { if(StringUtil.isEmpty(field)){ return ""; } field = dealSyscode(field,1); StringBuilder re = new StringBuilder(); try{ JSONObject obj = JSONObject.fromObject(field); Iterator it = obj.keys(); while(it.hasNext()){ String key = String.valueOf(it.next()); JSONObject nextObj = null; try { nextObj =((JSONObject)obj.get(key)); Iterator itvalue =nextObj.keys(); re.append(key+"="+"\""); if(nextObj.size()<=1){ String onlykey = String.valueOf(itvalue.next()); if("value".equals(onlykey)){ re.append(nextObj.get(onlykey)+""); }else{ re.append(onlykey+":"+nextObj.get(onlykey)+""); } }else{ while(itvalue.hasNext()){ String multkey = String.valueOf(itvalue.next()); String multvalue = nextObj.getString(multkey); re.append(multkey+":"+multvalue+";"); } re.deleteCharAt(re.length()-1); } re.append("\" "); } catch (Exception e) { re.append(key+"="+"\""); re.append(obj.get(key)+"\""); re.append("\" "); } } }catch (Exception e) { e.printStackTrace(); return ""; } return dealSyscode(re.toString(), 2); } /** * 生成扩展属性 * @param field * @return */ private String extendAttributeOld(String field) { StringBuffer sb = new StringBuffer(); //增加扩展属性 if (!StringUtils.isBlank(field)) { Gson gson = new Gson(); Map<String, String> mp = gson.fromJson(field, Map.class); for(Map.Entry<String, String> entry: mp.entrySet()) { sb.append(entry.getKey()+"=" + gson.toJson(entry.getValue()) + "\""); } } return sb.toString(); } /** * 处理否含有json转换中的保留字 * @param field * @param flag 1:转换 2:还原 * @return */ private String dealSyscode(String field,int flag) { String change = field; Iterator it = syscode.keySet().iterator(); while(it.hasNext()){ String key = String.valueOf(it.next()); String value = String.valueOf(syscode.get(key)); if(flag==1){ change = field.replaceAll(key, value); }else if(flag==2){ change = field.replaceAll(value, key); } } return change; } /** * 判断是否存在查询字段 * @return hasQuery true表示有查询字段,false表示没有 */ protected boolean hasQueryColum(List<DataGridColumn> columnList ) { boolean hasQuery = false; for (DataGridColumn col : columnList) { if(col.isQuery()){ hasQuery = true; } } return hasQuery; } /** * 拼装操作地址 * * @param sb */ protected void getOptUrl(StringBuffer sb) { //注:操作列表会带入合计列中去,故加此判断 sb.append("if(!rec.id){return '';}"); sb.append("var href='';"); List<DataGridUrl> list = urlList; for (DataGridUrl dataGridUrl : list) { if(!dataGridUrl.isInGroup()){ String url = dataGridUrl.getUrl(); MessageFormat formatter = new MessageFormat(""); if (dataGridUrl.getValue() != null) { String[] testvalue = dataGridUrl.getValue().split(","); List value = new ArrayList<Object>(); for (String string : testvalue) { value.add("\"+rec." + string + " +\""); } url = formatter.format(url, value.toArray()); } if (url != null && dataGridUrl.getValue() == null) { //url = formatUrl(url); url = formatUrlPlus(url); } String exp = dataGridUrl.getExp();// 判断显示表达式 if (StringUtil.isNotEmpty(exp)) { String[] ShowbyFields = exp.split("&&"); for (String ShowbyField : ShowbyFields) { int beginIndex = ShowbyField.indexOf("#"); int endIndex = ShowbyField.lastIndexOf("#"); String exptype = ShowbyField.substring(beginIndex + 1, endIndex);// 表达式类型 String field = ShowbyField.substring(0, beginIndex);// 判断显示依据字段 String[] values = ShowbyField.substring(endIndex + 1, ShowbyField.length()).split(",");// 传入字段值 String value = ""; for (int i = 0; i < values.length; i++) { value += "'" + "" + values[i] + "" + "'"; if (i < values.length - 1) { value += ","; } } if ("eq".equals(exptype)) { sb.append("if($.inArray(rec." + field + ",[" + value + "])>=0){"); } if ("ne".equals(exptype)) { sb.append("if($.inArray(rec." + field + ",[" + value + "])<0){"); } if ("empty".equals(exptype) && value.equals("'true'")) { sb.append("if(rec." + field + "==''){"); } if ("empty".equals(exptype) && value.equals("'false'")) { sb.append("if(rec." + field + "!=''){"); } } } StringBuffer style = new StringBuffer(); if (!StringUtil.isEmpty(dataGridUrl.getUrlStyle())) { style.append(" style=\'"); style.append(dataGridUrl.getUrlStyle()); style.append("\' "); } StringBuffer urlclass = new StringBuffer(); if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){ urlclass.append(" class=\'"); urlclass.append(dataGridUrl.getUrlclass()); urlclass.append("\'"); } StringBuffer urlfont = new StringBuffer(); if(!StringUtil.isEmpty(dataGridUrl.getUrlfont())){ urlfont.append(" <i class=\' fa "); urlfont.append(dataGridUrl.getUrlfont()); urlfont.append("\'></i>"); } if (OptTypeDirection.Confirm.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){ sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=confirm(\'" + url + "\',\'" + dataGridUrl.getMessage() + "\',\'"+name+"\')" + style.toString() + "> "+urlfont.toString()+" \";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=confirm(\'" + url + "\',\'" + dataGridUrl.getMessage() + "\',\'"+name+"\')" + style.toString() + "> \";"); } } if (OptTypeDirection.Del.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=delObj(\'" + url + "\',\'"+name+"\')" + style.toString() + "> "+urlfont.toString()+" \";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=delObj(\'" + url + "\',\'"+name+"\')" + style.toString() + ">\";"); } } if (OptTypeDirection.Fun.equals(dataGridUrl.getType())) { String name = TagUtil.getFunction(dataGridUrl.getFunname()); String parmars = TagUtil.getFunParams(dataGridUrl.getFunname()); if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=" + name + "(" + parmars + ")" + style.toString() + "> "+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=" + name + "(" + parmars + ")" + style.toString() + ">\";"); } } if (OptTypeDirection.OpenWin.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=openwindow('" + dataGridUrl.getTitle() + "','" + url + "','"+name+"'," + dataGridUrl.getWidth() + "," + dataGridUrl.getHeight() + ")" + style.toString() + ">"+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=openwindow('" + dataGridUrl.getTitle() + "','" + url + "','"+name+"'," + dataGridUrl.getWidth() + "," + dataGridUrl.getHeight() + ")" + style.toString() + ">\";"); } } //update-end--Author:liuht Date:20130228 for:弹出窗口设置参数不生效 if (OptTypeDirection.Deff.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){ sb.append("href+=\"<a href=\'" + url + "' "+urlclass.toString()+" title=\'"+dataGridUrl.getTitle()+"\'" + style.toString() + ">"+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'" + url + "' title=\'"+dataGridUrl.getTitle()+"\'" + style.toString() + ">\";"); } } if (OptTypeDirection.OpenTab.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=addOneTab('" + dataGridUrl.getTitle() + "','" + url + "') "+ style.toString() +">"+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=addOneTab('" + dataGridUrl.getTitle() + "','" + url + "') "+ style.toString() +">\";"); } } if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接后面的"]"; sb.append("href+=\"" + dataGridUrl.getTitle() + "</a>&nbsp;\";"); }else{ sb.append("href+=\"" + dataGridUrl.getTitle() + "</a>]\";"); } if (StringUtil.isNotEmpty(exp)) { for (int i = 0; i < exp.split("&&").length; i++) { sb.append("}"); } } } } if(hasGroup()){ getGroupUrl(sb); } sb.append("return href;"); } /** * 分组按钮拼装 * * @param sb */ protected void getGroupUrl(StringBuffer sb) { //注:操作列表会带入合计列中去,故加此判断 List<DataGridUrl> list = urlList; //<i class='fa fa-angle-double-right'></i>更多 sb.append("href+=\"<a href='javascript:void(0)' class='opts-menu-triangle btnmy'> <span class='opts-menu-temp icon-triangle'></span>更多</a>\";"); /* sb.append("href+=\"<div class='opts-menu-triangle icon-triangle' title='更多操作'></div>\";");*/ sb.append("href+=\"<div class='opts-menu-container location-left'>\";"); sb.append("href+=\"<div class='opts-menu-parent'>\";"); sb.append("href+=\"<div class='opts-menu-box'>\";"); for (DataGridUrl dataGridUrl : list) { if(dataGridUrl.isInGroup()){ String url = dataGridUrl.getUrl(); MessageFormat formatter = new MessageFormat(""); if (dataGridUrl.getValue() != null) { String[] testvalue = dataGridUrl.getValue().split(","); List value = new ArrayList<Object>(); for (String string : testvalue) { value.add("\"+rec." + string + " +\""); } url = formatter.format(url, value.toArray()); } if (url != null && dataGridUrl.getValue() == null) { //url = formatUrl(url); url = formatUrlPlus(url); } String exp = dataGridUrl.getExp();// 判断显示表达式 if (StringUtil.isNotEmpty(exp)) { String[] ShowbyFields = exp.split("&&"); for (String ShowbyField : ShowbyFields) { int beginIndex = ShowbyField.indexOf("#"); int endIndex = ShowbyField.lastIndexOf("#"); String exptype = ShowbyField.substring(beginIndex + 1, endIndex);// 表达式类型 String field = ShowbyField.substring(0, beginIndex);// 判断显示依据字段 String[] values = ShowbyField.substring(endIndex + 1, ShowbyField.length()).split(",");// 传入字段值 String value = ""; for (int i = 0; i < values.length; i++) { value += "'" + "" + values[i] + "" + "'"; if (i < values.length - 1) { value += ","; } } if ("eq".equals(exptype)) { sb.append("if($.inArray(rec." + field + ",[" + value + "])>=0){"); } if ("ne".equals(exptype)) { sb.append("if($.inArray(rec." + field + ",[" + value + "])<0){"); } if ("empty".equals(exptype) && value.equals("'true'")) { sb.append("if(rec." + field + "==''){"); } if ("empty".equals(exptype) && value.equals("'false'")) { sb.append("if(rec." + field + "!=''){"); } } } StringBuffer style = new StringBuffer(); if (!StringUtil.isEmpty(dataGridUrl.getUrlStyle())) { style.append(" style=\'"); style.append(dataGridUrl.getUrlStyle()); style.append("\' "); } StringBuffer urlclass = new StringBuffer(); if(StringUtil.isEmpty(dataGridUrl.getUrlclass())){ dataGridUrl.setUrlclass("btn btn-default ops-more"); } urlclass.append(" class=\'"+dataGridUrl.getUrlclass()+"\'"); StringBuffer urlfont = new StringBuffer(); if(!StringUtil.isEmpty(dataGridUrl.getUrlfont())){ urlfont.append(" <i class=\' fa "); urlfont.append(dataGridUrl.getUrlfont()); urlfont.append("\'></i>"); } if (OptTypeDirection.Confirm.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){ sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=confirm(\'" + url + "\',\'" + dataGridUrl.getMessage() + "\',\'"+name+"\')" + style.toString() + "> "+urlfont.toString()+" \";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=confirm(\'" + url + "\',\'" + dataGridUrl.getMessage() + "\',\'"+name+"\')" + style.toString() + "> \";"); } } if (OptTypeDirection.Del.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=delObj(\'" + url + "\',\'"+name+"\')" + style.toString() + "> "+urlfont.toString()+" \";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=delObj(\'" + url + "\',\'"+name+"\')" + style.toString() + ">\";"); } } if (OptTypeDirection.Fun.equals(dataGridUrl.getType())) { String name = TagUtil.getFunction(dataGridUrl.getFunname()); String parmars = TagUtil.getFunParams(dataGridUrl.getFunname()); if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=" + name + "(" + parmars + ")" + style.toString() + "> "+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=" + name + "(" + parmars + ")" + style.toString() + ">\";"); } } if (OptTypeDirection.OpenWin.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=openwindow('" + dataGridUrl.getTitle() + "','" + url + "','"+name+"'," + dataGridUrl.getWidth() + "," + dataGridUrl.getHeight() + ")" + style.toString() + ">"+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=openwindow('" + dataGridUrl.getTitle() + "','" + url + "','"+name+"'," + dataGridUrl.getWidth() + "," + dataGridUrl.getHeight() + ")" + style.toString() + ">\";"); } } //update-end--Author:liuht Date:20130228 for:弹出窗口设置参数不生效 if (OptTypeDirection.Deff.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){ sb.append("href+=\"<a href=\'" + url + "' "+urlclass.toString()+" title=\'"+dataGridUrl.getTitle()+"\'" + style.toString() + ">"+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'" + url + "' title=\'"+dataGridUrl.getTitle()+"\'" + style.toString() + ">\";"); } } if (OptTypeDirection.OpenTab.equals(dataGridUrl.getType())) { if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接前面的"["; sb.append("href+=\"<a href=\'#\' "+urlclass.toString()+" onclick=addOneTab('" + dataGridUrl.getTitle() + "','" + url + "') "+ style.toString() +">"+urlfont.toString()+"\";"); }else{ sb.append("href+=\"[<a href=\'#\' onclick=addOneTab('" + dataGridUrl.getTitle() + "','" + url + "') "+ style.toString() +">\";"); } } if(!StringUtil.isEmpty(dataGridUrl.getUrlclass())){//倘若urlclass不为空,则去掉链接后面的"]"; sb.append("href+=\"" + dataGridUrl.getTitle() + "</a>&nbsp;\";"); }else{ sb.append("href+=\"" + dataGridUrl.getTitle() + "</a>]\";"); } if (StringUtil.isNotEmpty(exp)) { for (int i = 0; i < exp.split("&&").length; i++) { sb.append("}"); } } } } sb.append("href+=\"</div></div><em class='ops_shadeEm' style='display: inline;'></em></div></div>\";"); } /** * 列自定义函数 * * @param sb * @param column */ protected void getFun(StringBuffer sb, DataGridColumn column) { String url = column.getUrl(); url = formatUrlPlus(url); sb.append("var href=\"<a style=\'color:red\' href=\'#\' onclick=" + column.getFunname() + "('" + column.getTitle() + "','" + url + "')>\";"); sb.append("return href+value+\'</a>\';"); } /** * 格式化URL * * @return */ protected String formatUrl(String url) { MessageFormat formatter = new MessageFormat(""); String parurlvalue = ""; if (url.indexOf("&") >= 0) { String beforeurl = url.substring(0, url.indexOf("&"));// 截取请求地址 String parurl = url.substring(url.indexOf("&") + 1, url.length());// 截取参数 String[] pras = parurl.split("&"); List value = new ArrayList<Object>(); int j = 0; for (int i = 0; i < pras.length; i++) { if (pras[i].indexOf("{") >= 0 || pras[i].indexOf("#") >= 0) { String field = pras[i].substring(pras[i].indexOf("{") + 1, pras[i].lastIndexOf("}")); parurlvalue += "&" + pras[i].replace("{" + field + "}", "{" + j + "}"); value.add("\"+rec." + field + " +\""); j++; } else { parurlvalue += "&" + pras[i]; } } url = formatter.format(beforeurl + parurlvalue, value.toArray()); } return url; } /** * formatUrl增强写法 * 支持#{}、{}、##三种传参方式 * @param url * @return */ protected String formatUrlPlus(String url) { boolean isTrans = false; //tsBlackListController.do?doDel&id=#{id} if(url.indexOf("#{") >= 0){ isTrans = true; url = url.replace("#{", "\"+rec."); url = url.replace("}", "+\""); } //tsBlackListController.do?doDel&id={id} if(url.indexOf("{") >= 0 && !isTrans){ url = url.replace("{", "\"+rec."); url = url.replace("}", "+\""); } //tsBlackListController.do?doDel&id=#id# if(url.indexOf("#") > 0 && !isTrans){ Pattern p = Pattern.compile("#", Pattern.CASE_INSENSITIVE); StringBuffer sb = new StringBuffer(); Matcher m = p.matcher(url); int i = 0; while(m.find()) { i++; if(i %2 == 0){ m.appendReplacement(sb, "+\""); } else { m.appendReplacement(sb, "\"+rec."); } } m.appendTail(sb); url = sb.toString(); } return url; } /** * 拼接字段 普通列 * * @param sb * */ protected void getField(StringBuffer sb){ getField( sb,1); } /** * 拼接字段 * * @param sb * @frozen 0 冰冻列 1 普通列 */ protected void getField(StringBuffer sb,int frozen) { // 复选框 if (checkbox&&frozen==0) { sb.append("{field:\'ck\',checkbox:\'true\'},"); } int i = 0; for (DataGridColumn column : columnList) { i++; if((column.isFrozenColumn()&&frozen==0)||(!column.isFrozenColumn()&&frozen==1)){ String field; if (treegrid) { field = column.getTreefield(); if(StringUtils.isEmpty(field)){ field = column.getField(); } } else { field = column.getField(); } sb.append("{"); if(StringUtil.isNotEmpty(field)){ sb.append("field:\'" + field + "\',"); } sb.append("title:\'" + column.getTitle() + "\'"); if(column.getWidth() != null){ sb.append(",width:"+column.getWidth()); } if (column.getAlign()!=null){ sb.append(",align:\'" + column.getAlign() + "\'"); } if(StringUtil.isNotEmpty(column.getRowspan())){ sb.append(",rowspan:" + column.getRowspan()); } if(StringUtils.isNotEmpty(column.getExtendParams())){ StringBuffer comboboxStr =new StringBuffer();//声明一个替换扩展参数中的editor:'combobox'的变量 if(column.getExtendParams().indexOf("editor:'combobox'")>-1){//倘若扩展参数中包含editor:'combobox' if(!StringUtil.isEmpty(column.getDictionary())){//根据数据字典生成editor:'combobox' if(column.getDictionary().contains(",")){ if(column.isPopup()){ //TODO popup值转换处理,此处暂不处理 }else{ if(column.getIsAjaxDict()){ //TODO ajax值转换处理,此处暂不处理 }else{ String[] dic = column.getDictionary().split(","); String sql = "select " + dic[1] + " as field," + dic[2]+ " as text from " + dic[0]; if(!StringUtil.isEmpty(column.getDictCondition())){ sql += " "+column.getDictCondition(); } systemService = ApplicationContextUtil.getContext().getBean(SystemService.class); List<Map<String, Object>> list = systemService.findForJdbc(sql); comboboxStr.append("editor:{type:'combobox',options:{valueField:'typecode',textField:'typename',data:["); for (Map<String, Object> map : list){ comboboxStr.append("{'typecode':'"+map.get("field")+"','typename':'"+map.get("text")+"'},"); } comboboxStr.append("],required:true}}"); //再增加formatter参数 comboboxStr.append(",formatter:function(value,row){"); for (Map<String, Object> map : list){ comboboxStr.append("if(value =='"+map.get("field")+"'){"); comboboxStr.append("return '"+map.get("text")+"';"); comboboxStr.append("}"); } comboboxStr.append("return value;"); comboboxStr.append("}"); } } }else{ List<TSType> types = ResourceUtil.getCacheTypes(column.getDictionary().toLowerCase()); if (types != null) { comboboxStr.append("editor:{type:'combobox',options:{valueField:'typecode',textField:'typename',data:["); for (TSType type : types) { comboboxStr.append("{'typecode':'"+type.getTypecode()+"','typename':'"+MutiLangUtil.getLang(type.getTypename())+"'},"); } comboboxStr.append("],required:true}}"); //再增加formatter参数 comboboxStr.append(",formatter:function(value,row){"); for (TSType type : types) { comboboxStr.append("if(value =='"+type.getTypecode()+"'){"); comboboxStr.append("return '"+MutiLangUtil.getLang(type.getTypename())+"';"); comboboxStr.append("}"); } comboboxStr.append("return row."+field+";"); comboboxStr.append("}"); } } } if(StringUtils.isEmpty(comboboxStr.toString())){ comboboxStr.append("editor:'text'"); } column.setExtendParams(column.getExtendParams().replaceAll("editor:'combobox'", comboboxStr.toString()));//替换扩展参数 //System.out.println("column.getExtendParams()=="+column.getExtendParams()); } //sb.append(","+column.getExtendParams().substring(0,column.getExtendParams().length()-1)); String extendParm = ""; if(column.getExtendParams().endsWith(",") || column.getExtendParams().endsWith("''")){ extendParm = column.getExtendParams().substring(0,column.getExtendParams().length()-1); }else{ extendParm = column.getExtendParams(); } extendParm = extendParm.trim(); if(StringUtils.isNotEmpty(extendParm)){ sb.append(","+extendParm); } } // 隐藏字段 if (column.isHidden()) { sb.append(",hidden:true"); } if (!treegrid) { // 字段排序 if ((column.isSortable()) && StringUtil.isNotEmpty(field) && (field.indexOf("_") <= 0 && field != "opt")) { sb.append(",sortable:" + column.isSortable() + ""); } } if(column.getFormatterjs()!=null){ if(StringUtils.isNotEmpty(column.getExtendParams())&&column.getExtendParams().indexOf("editor:'combobox'")>-1){//倘若扩展参数中包含editor:'combobox' //不再重复增加formatter参数, }else{ sb.append(",formatter:function(value,rec,index){"); sb.append(" return "+column.getFormatterjs()+"(value,rec,index);}"); } }else { // 显示图片 if (column.isImage()) { if (column.getImageSize() != null) {// 自定义显示图片 String[] tld = column.getImageSize().split(","); sb.append(",formatter:function(value,rec,index){"); sb.append(" return '<img width=\"" + tld[0] + "\" height=\"" + tld[1] + "\" border=\"0\" " + " onMouseOver=\"tipImg(this)\" onMouseOut=\"moveTipImg()\" " // + " onMouseOver=\"toolTip('<img src='+value+'>')\" onMouseOut=\"toolTip()\" " + " src=\"'+value+'\"/>';}"); tld = null; }else{ sb.append(",formatter:function(value,rec,index){"); sb.append(" return '<img border=\"0\" src=\"'+value+'\"/>';}"); } } else if(column.getDownloadName() != null){ sb.append(",formatter:function(value,rec,index){"); sb.append("var html = '';"); sb.append("if(value==null || value.length==0){return html;}"); sb.append("if(value.indexOf('.jpg')>-1 || value.indexOf('.png')>-1 || value.indexOf('.jpeg')>-1 || value.indexOf('.gif') > -1){"); sb.append(" html = '<img onMouseOver=\"tipImg(this)\" onMouseOut=\"moveTipImg()\" src=\"'+value+'\" width=50 height=50/>';"); sb.append("}else{"); sb.append(" html = '<a class=\"ace_button fa fa-download\" style=\"padding:3px 5px;\" target=\"_blank\" href=\"systemController/downloadFile.do?filePath='+value+'\">" + column.getDownloadName() + "</a>';}"); sb.append("return html;}"); }else if (column.getUrl() != null) { // 自定义链接 sb.append(",formatter:function(value,rec,index){"); this.getFun(sb, column); sb.append("}"); }else if (StringUtil.isNotEmpty(column.getField()) && column.getField().equals("opt")) {// 加入操作 sb.append(",formatter:function(value,rec,index){"); if(column.isOptsMenu()){ getOptsMenuUrl(sb); }else{ this.getOptUrl(sb); } sb.append("}"); }else if(column.getFormatter()!=null) { sb.append(",formatter:function(value,rec,index){"); sb.append(" return new Date().format('"+column.getFormatter()+"',value);}"); } else if(column.getShowLen()!=null){ //设置了显示多少长度的 sb.append(",formatter:function(value,rec,index){"); sb.append(" if(value==undefined) {return ''} "); sb.append(" if(value.length<=");sb.append(column.getShowLen());sb.append(") {return value}"); sb.append(" else{ return '<a title= '+value+'>'+ value.substring(0,");sb.append(column.getShowLen());sb.append(")+'...';}}"); } else if (columnValueList.size() > 0 && StringUtil.isNotEmpty(column.getField()) && !column.getField().equals("opt")) {// 值替換 if(column.getDictionary()!=null&&column.getDictionary().contains(",")&&column.getIsAjaxDict()){ sb.append(",formatter:function(value,rec,index){"); sb.append("var rtn = \"<span name=\\\"ajaxDict\\\" dictionary=\\\""+column.getDictionary() +"\\\" dictCondition=\\\""+(column.getDictCondition()==null?"":column.getDictCondition()) +"\\\" popup=\\\""+column.isPopup() +"\\\" value=\\\"\"+value+\"\\\"><img src='plug-in/easyui/themes/icons/loading.gif'/></span>\";"); sb.append("return rtn;"); sb.append("}"); }else{ String testString = ""; for (ColumnValue columnValue : columnValueList) { if (columnValue.getName().equals(column.getField())) { String[] value = columnValue.getValue().split(","); String[] text = columnValue.getText().split(","); sb.append(",formatter:function(value,rec,index){"); sb.append("if(value==undefined) return '';"); sb.append("var valArray = value.split(',');"); sb.append("if(valArray.length > 1){"); sb.append("var checkboxValue = '';"); sb.append("for(var k=0; k<valArray.length; k++){"); for(int j = 0; j < value.length; j++){ sb.append("if(valArray[k] == '" + value[j] + "'){ checkboxValue = checkboxValue + \'" + text[j] + "\' + ',';}"); } sb.append("}"); sb.append("return checkboxValue.substring(0,checkboxValue.length-1);"); sb.append("}"); sb.append("else{"); for (int j = 0; j < value.length; j++) { testString += "if(value=='" + value[j] + "'){return \'" + text[j] + "\';}"; } sb.append(testString); sb.append("else{return value;}"); sb.append("}"); sb.append("}"); } } } } } // 背景设置 if (columnStyleList.size() > 0 && StringUtil.isNotEmpty(column.getField()) && !column.getField().equals("opt")) { String testString = ""; for (ColumnValue columnValue : columnStyleList) { if (columnValue.getName().equals(column.getField())) { String[] value = columnValue.getValue().split(","); String[] text = columnValue.getText().split(","); sb.append(",styler:function(value,rec,index){"); if((value.length == 0||StringUtils.isEmpty(value[0]))&&text.length==1){ if(text[0].indexOf("(")>-1){ testString = " return \'" + text[0].replace("(", "(value,rec,index") + "\'"; }else{ testString = " return \'" + text[0] + "\'"; } }else{ for (int j = 0; j < value.length; j++) { testString += "if(value=='" + value[j] + "'){return \'" + text[j] + "\'}"; } } sb.append(testString); sb.append("}"); } } } if(StringUtil.isNotEmpty(column.getColspan())){ sb.append(",colspan:\"" + column.getColspan() + "\""); } sb.append("}"); if(i < columnList.size() && column.isNewColumn()){ sb.append("],["); continue; }//update--begin--author:zhangjiaqiang Date:20170815 for:TASK #2273 【demo】datagrid 多表头demo // 去除末尾, if (i < columnList.size()) { sb.append(","); } } } } /** * 设置分页条信息 * * @param sb */ protected void setPager(StringBuffer sb, String grid) { sb.append("$(\'#" + name + "\')." + grid + "(\'getPager\').pagination({"); sb.append("beforePageText:\'\'," + "afterPageText:\'/{pages}\',"); if (showText) { sb.append("displayMsg:\'{from}-{to}" + MutiLangUtil.getLang("common.total") + " {total}" + MutiLangUtil.getLang("common.item") + "\',"); } else { sb.append("displayMsg:\'\',"); } if (showPageList == true) { sb.append("showPageList:true,"); } else { sb.append("showPageList:false,"); } sb.append("showRefresh:" + showRefresh + ""); sb.append("});");// end getPager sb.append("$(\'#" + name + "\')." + grid + "(\'getPager\').pagination({"); sb.append("onBeforeRefresh:function(pageNumber, pageSize){ $(this).pagination(\'loading\');$(this).pagination(\'loaded\'); }"); sb.append("});"); } //列表查询框函数 protected void searchboxFun(StringBuffer sb,String grid) { sb.append("function "+name+"searchbox(value,name){"); sb.append("var queryParams=$(\'#" + name + "\').datagrid('options').queryParams;"); sb.append("queryParams[name]=value;queryParams.searchfield=name;$(\'#" + name + "\')." + grid + "(\'reload\');}"); sb.append("$(\'#"+name+"searchbox\').searchbox({"); sb.append("searcher:function(value,name){"); sb.append(""+name+"searchbox(value,name);"); sb.append("},"); sb.append("menu:\'#"+name+"mm\',"); sb.append(StringUtil.replaceAll("prompt:\'{0}\'", "{0}", MutiLangUtil.getLang("common.please.input.query.keyword"))); sb.append("});"); } public String getNoAuthOperButton(){ StringBuffer sb = new StringBuffer(); if(ResourceUtil.getSessionUser().getUserName().equals("admin")|| !Globals.BUTTON_AUTHORITY_CHECK){ }else{ Set<String> operationCodes = (Set<String>) super.pageContext.getRequest().getAttribute(Globals.OPERATIONCODES); if (null!=operationCodes) { for (String MyoperationCode : operationCodes) { if (oConvertUtils.isEmpty(MyoperationCode)) break; systemService = ApplicationContextUtil.getContext().getBean( SystemService.class); TSOperation operation = systemService.getEntity(TSOperation.class, MyoperationCode); if (operation.getOperationcode().startsWith(".") || operation.getOperationcode().startsWith("#")){ if (operation.getOperationType().intValue()==Globals.OPERATION_TYPE_HIDE){ //out.append("$(\""+name+"\").find(\"#"+operation.getOperationcode().replaceAll(" ", "")+"\").hide();"); sb.append("$(\""+operation.getOperationcode().replaceAll(" ", "")+"\").hide();"); }else { //out.append("$(\""+name+"\").find(\"#"+operation.getOperationcode().replaceAll(" ", "")+"\").find(\":input\").attr(\"disabled\",\"disabled\");"); sb.append("$(\""+operation.getOperationcode().replaceAll(" ", "")+"\").attr(\"disabled\",\"disabled\");"); sb.append("$(\""+operation.getOperationcode().replaceAll(" ", "")+"\").find(\":input\").attr(\"disabled\",\"disabled\");"); } } } } } //org.jeecgframework.core.util.LogUtil.info("----getNoAuthOperButton-------"+sb.toString()); return sb.toString(); } /** * 描述:组装菜单按钮操作权限 * dateGridUrl:url * operationCode:操作码 * optList: 操作列表 * @version 1.0 */ private void installOperationCode(DataGridUrl dataGridUrl,String operationCode,List optList){ if(ResourceUtil.getSessionUser().getUserName().equals("admin")|| !Globals.BUTTON_AUTHORITY_CHECK){ optList.add(dataGridUrl); }else if(!oConvertUtils.isEmpty(operationCode)){ Set<String> operationCodes = (Set<String>) super.pageContext.getRequest().getAttribute(Globals.OPERATIONCODES); if (null!=operationCodes) { List<String> operationCodesStr = new ArrayList<String>(); for (String MyoperationCode : operationCodes) { if (oConvertUtils.isEmpty(MyoperationCode)) break; systemService = ApplicationContextUtil.getContext().getBean( SystemService.class); TSOperation operation = systemService.getEntity(TSOperation.class, MyoperationCode); operationCodesStr.add(operation.getOperationcode()); } if (!operationCodesStr.contains(operationCode)){ optList.add(dataGridUrl); } } }else { optList.add(dataGridUrl); } } /** * 获取自动补全的panel * @param filed * @author JueYue * @return */ private String getAutoSpan(String filed,String extend){ String id = filed.replaceAll("\\.","_"); StringBuffer nsb = new StringBuffer(); nsb.append("<script type=\"text/javascript\">"); nsb.append("$(document).ready(function() {") .append("$(\"#"+getEntityName()+"_"+id+"\").autocomplete(\"commonController.do?getAutoList\",{") .append("max: 5,minChars: 2,width: 200,scrollHeight: 100,matchContains: true,autoFill: false,extraParams:{") .append("featureClass : \"P\",style : \"full\", maxRows : 10,labelField : \""+filed+"\",valueField : \""+filed+"\",") .append("searchField : \""+filed+"\",entityName : \""+getEntityName()+"\",trem: function(){return $(\"#"+getEntityName()+"_"+id+"\").val();}}"); nsb.append(",parse:function(data){return jeecgAutoParse.call(this,data);}"); nsb.append(",formatItem:function(row, i, max){return row['"+filed+"'];} "); nsb.append("}).result(function (event, row, formatted) {"); nsb.append("$(\"#"+getEntityName()+"_"+id+"\").val(row['"+filed+"']);}); });") .append("</script>") .append("<input class=\"inuptxt\" type=\"text\" id=\""+getEntityName()+"_"+id+"\" name=\""+filed+"\" "+extend+ StringUtil.replace(" nullmsg=\"\" errormsg=\"{0}\"/>", "{0}", MutiLangUtil.getLang("input.error"))); return nsb.toString(); } /** * 获取实体类名称,没有这根据规则设置 * @return */ private String getEntityName() { if(StringUtils.isEmpty(entityName)){ entityName = actionUrl.substring(0,actionUrl.indexOf("Controller")); entityName = (entityName.charAt(0)+"").toUpperCase()+entityName.substring(1)+"Entity"; } return entityName; } public boolean isFitColumns() { return fitColumns; } public void setFitColumns(boolean fitColumns) { this.fitColumns = fitColumns; } public boolean isCollapsible() { return collapsible; } public void setCollapsible(boolean collapsible) { this.collapsible = collapsible; } public String getSortName() { return sortName; } public void setSortName(String sortName) { this.sortName = sortName; } public String getSortOrder() { return sortOrder; } public void setSortOrder(String sortOrder) { this.sortOrder = sortOrder; } public String getQueryMode() { return queryMode; } public void setQueryMode(String queryMode) { this.queryMode = queryMode; } public boolean isAutoLoadData() { return autoLoadData; } public void setAutoLoadData(boolean autoLoadData) { this.autoLoadData = autoLoadData; } public void setOpenFirstNode(boolean openFirstNode) { this.openFirstNode = openFirstNode; } public void setEntityName(String entityName) { this.entityName = entityName; } public void setRowStyler(String rowStyler) { this.rowStyler = rowStyler; } public void setExtendParams(String extendParams) { if(StringUtil.isNotEmpty(extendParams) && !extendParams.endsWith(",")){ extendParams = extendParams + ","; } this.extendParams = extendParams; } public void setLangArg(String langArg) { this.langArg = langArg; } public StringBuffer aceStyleTable() { String grid = ""; StringBuffer sb = new StringBuffer(); if(btnCls!=null && btnCls.indexOf("bootstrap")==0){ sb.append("<link rel=\"stylesheet\" href=\"plug-in/bootstrap/css/bootstrap-btn.css\" type=\"text/css\"></link>"); } width = (width == null) ? "auto" : width; height = (height == null) ? "auto" : height; // sb.append("<link rel=\"stylesheet\" href=\"plug-in/easyui/themes/metro/main.css\" />"); sb.append("<script type=\"text/javascript\">"); sb.append("$(function(){ storage=$.localStorage;if(!storage)storage=$.cookieStorage;"); sb.append(this.getNoAuthOperButton()); if (treegrid) { grid = "treegrid"; sb.append("$(\'#" + name + "\').treegrid({"); sb.append("idField:'id',"); sb.append("treeField:'text',"); } else { grid = "datagrid"; sb.append("$(\'#" + name + "\').datagrid({"); if (this.isFilter()) { sb.append("onHeaderContextMenu: function(e, field){headerMenu(e, field);},"); } sb.append("idField: '" + idField + "',"); } if (title != null) { sb.append("title: \'" + title + "\',"); } if(autoLoadData) sb.append("url:\'" + actionUrl + "&field=" + fields + "\',"); else sb.append("url:\'',"); if(StringUtils.isNotEmpty(rowStyler)){ sb.append("rowStyler: function(index,row){ return "+rowStyler+"(index,row);},"); } if(StringUtils.isNotEmpty(extendParams)){ sb.append(extendParams); } if (fit) { sb.append("fit:true,"); } else { sb.append("fit:false,"); } sb.append(StringUtil.replaceAll("loadMsg: \'{0}\',", "{0}", MutiLangUtil.getLang("common.data.loading"))); sb.append("striped:true,pageSize: " + pageSize + ","); sb.append("pagination:" + pagination + ","); sb.append("pageList:[" + pageSize * 1 + "," + pageSize * 2 + "," + pageSize * 3 + "],"); if(StringUtils.isNotBlank(sortName)){ sb.append("sortName:'" +sortName +"',"); } sb.append("sortOrder:'" + sortOrder + "',"); sb.append("rownumbers:true,"); if(singleSelect==null){ sb.append("singleSelect:" + !checkbox + ","); }else{ sb.append("singleSelect:" + singleSelect + ","); } if (fitColumns) { sb.append("fitColumns:true,"); } else { sb.append("fitColumns:false,"); } sb.append("showFooter:true,"); sb.append("frozenColumns:[["); this.getField(sb,0); sb.append("]],"); sb.append("columns:[["); this.getField(sb); sb.append("]],"); sb.append("onLoadSuccess:function(data){$(\"#"+name+"\")."+grid+"(\"clearSelections\");"); //sb.append(" $(this).datagrid(\"fixRownumber\");"); if(openFirstNode&&treegrid){ sb.append(" if(data==null){"); sb.append(" var firstNode = $(\'#" + name + "\').treegrid('getRoots')[0];"); sb.append(" $(\'#" + name + "\').treegrid('expand',firstNode.id)}"); } if (StringUtil.isNotEmpty(onLoadSuccess)) { sb.append(onLoadSuccess + "(data);"); } sb.append("},"); if (StringUtil.isNotEmpty(onDblClick)) { sb.append("onDblClickRow:function(rowIndex,rowData){" + onDblClick + "(rowIndex,rowData);},"); } if (treegrid) { sb.append("onClickRow:function(rowData){"); } else { sb.append("onClickRow:function(rowIndex,rowData){"); } /**行记录赋值*/ sb.append("rowid=rowData.id;"); sb.append("gridname=\'"+name+"\';"); if (StringUtil.isNotEmpty(onClick)) { if (treegrid) { sb.append("" + onClick + "(rowData);"); }else{ sb.append("" + onClick + "(rowIndex,rowData);"); } } sb.append("}"); sb.append("});"); this.setPager(sb, grid); sb.append("try{restoreheader();}catch(ex){}"); sb.append("});"); sb.append("function reloadTable(){"); sb.append("try{"); sb.append(" $(\'#\'+gridname).datagrid(\'reload\');" ); sb.append(" $(\'#\'+gridname).treegrid(\'reload\');" ); sb.append("}catch(ex){}"); sb.append("}"); sb.append("function reload" + name + "(){" + "$(\'#" + name + "\')." + grid + "(\'reload\');" + "}"); sb.append("function get" + name + "Selected(field){return getSelected(field);}"); sb.append("function getSelected(field){" + "var row = $(\'#\'+gridname)." + grid + "(\'getSelected\');" + "if(row!=null)" + "{" + "value= row[field];" + "}" + "else" + "{" + "value=\'\';" + "}" + "return value;" + "}"); sb.append("function get" + name + "Selections(field){" + "var ids = [];" + "var rows = $(\'#" + name + "\')." + grid + "(\'getSelections\');" + "for(var i=0;i<rows.length;i++){" + "ids.push(rows[i][field]);" + "}" + "ids.join(\',\');" + "return ids" + "};"); sb.append("function getSelectRows(){"); sb.append(" return $(\'#"+name+"\').datagrid('getChecked');}"); sb.append(" function saveHeader(){"); sb.append(" var columnsFields =null;var easyextends=false;try{columnsFields = $('#"+name+"').datagrid('getColumns');easyextends=true;"); sb.append("}catch(e){columnsFields =$('#"+name+"').datagrid('getColumnFields');}"); sb.append(" var cols = storage.get( '"+name+"hiddenColumns');var init=true; if(cols){init =false;} " + "var hiddencolumns = [];for(var i=0;i< columnsFields.length;i++) {if(easyextends){"); sb.append("hiddencolumns.push({field:columnsFields[i].field,hidden:columnsFields[i].hidden});}else{"); sb.append( " var columsDetail = $('#"+name+"').datagrid(\"getColumnOption\", columnsFields[i]); "); sb.append( "if(init){hiddencolumns.push({field:columsDetail.field,hidden:columsDetail.hidden,visible:(columsDetail.hidden==true?false:true)});}else{"); sb.append("for(var j=0;j<cols.length;j++){"); sb.append(" if(cols[j].field==columsDetail.field){"); sb.append(" hiddencolumns.push({field:columsDetail.field,hidden:columsDetail.hidden,visible:cols[j].visible});"); sb.append(" }"); sb.append("}"); sb.append("}} }"); sb.append("storage.set( '"+name+"hiddenColumns',JSON.stringify(hiddencolumns));"); sb.append( "}"); sb.append( "function restoreheader(){"); sb.append("var cols = storage.get( '"+name+"hiddenColumns');if(!cols)return;"); sb.append( "for(var i=0;i<cols.length;i++){"); sb.append( " try{"); sb.append("if(cols.visible!=false)$('#"+name+"').datagrid((cols[i].hidden==true?'hideColumn':'showColumn'),cols[i].field);"); sb.append( "}catch(e){"); sb.append( "}"); sb.append( "}"); sb.append( "}"); sb.append( "function resetheader(){"); sb.append("var cols = storage.get( '"+name+"hiddenColumns');if(!cols)return;"); sb.append( "for(var i=0;i<cols.length;i++){"); sb.append( " try{"); sb.append(" $('#"+name+"').datagrid((cols.visible==false?'hideColumn':'showColumn'),cols[i].field);"); sb.append( "}catch(e){"); sb.append( "}"); sb.append( "}"); sb.append( "}"); if (columnList.size() > 0) { sb.append("function " + name + "search(){"); sb.append("var queryParams=$(\'#" + name + "\').datagrid('options').queryParams;"); sb.append("$(\'#" + name + "tb\').find('*').each(function(){queryParams[$(this).attr('name')]=$(this).val();});"); sb.append("$(\'#" + name + "\')." + grid + "({url:'" + actionUrl + "&field=" + searchFields + "',pageNumber:1});" + "}"); //高级查询执行方法 sb.append("function dosearch(params){"); sb.append("var jsonparams=$.parseJSON(params);"); sb.append("$(\'#" + name + "\')." + grid + "({url:'" + actionUrl + "&field=" + searchFields + "',queryParams:jsonparams});" + "}"); //searchbox框执行方法 searchboxFun(sb,grid); //回车事件 sb.append("function EnterPress(e){"); sb.append("var e = e || window.event;"); sb.append("if(e.keyCode == 13){ "); sb.append(name+"search();"); sb.append("}}"); sb.append("function searchReset(name){"); sb.append(" $(\"#"+name+"tb\").find(\":input\").val(\"\");"); String func = name.trim() + "search();"; sb.append(func); sb.append("}"); } sb.append("</script>"); sb.append("<table width=\"100%\" id=\"" + name + "\" toolbar=\"#" + name + "tb\"></table>"); sb.append("<div id=\"" + name + "tb\" style=\"padding:3px; height: auto\">"); if(hasQueryColum(columnList)){ sb.append("<div name=\"searchColums\">"); sb.append("<input id=\"_sqlbuilder\" name=\"sqlbuilder\" type=\"hidden\" />"); //如果表单是组合查询 if("group".equals(getQueryMode())){ for (DataGridColumn col : columnList) { if (col.isQuery()) { sb.append("<span style=\"display:-moz-inline-box;display:inline-block;\">"); sb.append("<span style=\"vertical-align:middle;display:-moz-inline-box;display:inline-block;width: 80px;text-align:right;text-overflow:ellipsis;-o-text-overflow:ellipsis; overflow: hidden;white-space:nowrap; \" title=\""+col.getTitle()+"\">"+col.getTitle()+":</span>"); if("single".equals(col.getQueryMode())){ if(!StringUtil.isEmpty(col.getReplace())){ sb.append("<select name=\""+col.getField().replaceAll("_","\\.")+"\" WIDTH=\"100\" style=\"width: 104px\"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); String[] test = col.getReplace().split(","); String text = ""; String value = ""; for (String string : test) { String lang_key = string.split("_")[0]; text = MutiLangUtil.getLang(lang_key); value =string.split("_")[1]; sb.append("<option value =\""+value+"\">"+text+"</option>"); } sb.append("</select>"); }else if(!StringUtil.isEmpty(col.getDictionary())){ if(col.getDictionary().contains(",")){ String[] dic = col.getDictionary().split(","); String sql = "select " + dic[1] + " as field," + dic[2] + " as text from " + dic[0]; if(!StringUtil.isEmpty(col.getDictCondition())){ sql += " "+col.getDictCondition(); } systemService = ApplicationContextUtil.getContext().getBean( SystemService.class); List<Map<String, Object>> list = systemService.findForJdbc(sql); sb.append("<select name=\""+col.getField().replaceAll("_","\\.")+"\" WIDTH=\"100\" style=\"width: 104px\"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); for (Map<String, Object> map : list){ sb.append(" <option value=\""+map.get("field")+"\">"); sb.append(map.get("text")); sb.append(" </option>"); } sb.append("</select>"); }else{ List<TSType> types = ResourceUtil.getCacheTypes(col.getDictionary().toLowerCase()); sb.append("<select name=\""+col.getField().replaceAll("_","\\.")+"\" WIDTH=\"100\" style=\"width: 104px\"> "); sb.append(StringUtil.replaceAll("<option value =\"\" >{0}</option>", "{0}", MutiLangUtil.getLang("common.please.select"))); for (TSType type : types) { sb.append(" <option value=\""+type.getTypecode()+"\">"); sb.append(MutiLangUtil.getLang(type.getTypename())); sb.append(" </option>"); } sb.append("</select>"); } }else if(col.isAutocomplete()){ sb.append(getAutoSpan(col.getField().replaceAll("_","\\."),extendAttribute(col.getExtend()))); }else{ sb.append("<input onkeypress=\"EnterPress(event)\" onkeydown=\"EnterPress()\" type=\"text\" name=\""+col.getField().replaceAll("_","\\.")+"\" "+extendAttribute(col.getExtend())+" class=\"inuptxt\"/>"); } }else if("group".equals(col.getQueryMode())){ sb.append("<input type=\"text\" name=\""+col.getField()+"_begin\" "+extendAttribute(col.getExtend())+" class=\"inuptxt\"/>"); sb.append("<span style=\"display:-moz-inline-box;display:inline-block;width: 8px;text-align:right;\">~</span>"); sb.append("<input type=\"text\" name=\""+col.getField()+"_end\" "+extendAttribute(col.getExtend())+" class=\"inuptxt\"/>"); } sb.append("</span>"); } } } sb.append("</div>"); } if(toolBarList==null || toolBarList.size()==0){ sb.append("<div style=\"height:0px;\" >"); }else{//TODO sb.append("<div style=\"border-bottom-width:0;height:auto;\" class=\"datagrid-toolbar\">"); } sb.append("<span style=\"float:left;\" >"); if(toolBarList.size()>0) { for (DataGridUrl toolBar : toolBarList) { if (btnCls != null && !btnCls.equals("easyui")) {//自定以样式 bootstrap按钮样式 if(btnCls.indexOf("bootstrap")==0){ if (btnCls.replace("bootstrap", "").trim().length() > 0) { sb.append("<button class=\""+btnCls.replace("bootstrap", "").trim()+"\" "); }else{ sb.append("<button class=\"btn btn-info btn-xs\" "); } if(StringUtil.isNotEmpty(toolBar.getOnclick())) { sb.append("onclick="+toolBar.getOnclick()+""); } else { sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")) { sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } sb.append("><i class=\"" + toolBar.getIcon() + "\"></i><span class=\"bigger-110 no-text-shadow\">"+toolBar.getTitle()+"</span></button>"); }else{ sb.append("<a href=\"#\" class=\""+btnCls+" " + toolBar.getIcon()+"\" "); if(StringUtil.isNotEmpty(toolBar.getOnclick())) { sb.append("onclick="+toolBar.getOnclick()+""); } else { sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")) { sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } sb.append(">"+toolBar.getTitle()+"</a>"); } }else if(btnCls == null || btnCls.equals("easyui")){//easyUI按钮样式 sb.append("<a href=\"#\" class=\"button\" plain=\"true\" icon=\""+toolBar.getIcon()+"\" "); if(StringUtil.isNotEmpty(toolBar.getOnclick())) { sb.append("onclick="+toolBar.getOnclick()+""); } else { sb.append("onclick=\""+toolBar.getFunname()+"("); if(!toolBar.getFunname().equals("doSubmit")) { sb.append("\'"+toolBar.getTitle()+"\',"); } String width = toolBar.getWidth().contains("%")?"'"+toolBar.getWidth()+"'":toolBar.getWidth(); String height = toolBar.getHeight().contains("%")?"'"+toolBar.getHeight()+"'":toolBar.getHeight(); sb.append("\'"+toolBar.getUrl()+"\',\'"+name+"\',"+width+","+height+")\""); } sb.append(">"+toolBar.getTitle()+"</a>"); } } } sb.append("</span>"); if("group".equals(getQueryMode()) && hasQueryColum(columnList)){//如果表单是组合查询 sb.append("<span style=\"float:right\">"); if (btnCls != null && !btnCls.equals("easyui")) {//自定以样式 bootstrap按钮样式 if(btnCls.indexOf("bootstrap")==0){ String defalutCls = "btn btn-info btn-xs"; if (btnCls.replace("bootstrap", "").trim().length() > 0) { defalutCls = btnCls.replace("bootstrap", "").trim(); } sb.append("<button class=\""+defalutCls+"\" onclick=\"" + name + "search()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.query")+"</span>"); sb.append("</button>"); sb.append("<button class=\""+defalutCls+"\" onclick=\"searchReset('" + name + "')\">"); sb.append("<i class=\"fa fa-refresh\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.reset")+"</span>"); sb.append("</button>"); if(queryBuilder){ sb.append("<button class=\""+defalutCls+"\" onclick=\"queryBuilder()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.querybuilder")+"</span>"); sb.append("</button>"); } if(superQuery) { sb.append("<button class=\""+defalutCls+"\" onclick=\"queryBuilder()\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.superquery")+"</span>"); sb.append("</button>"); } if(oConvertUtils.isNotEmpty(complexSuperQuery)) { sb.append("<button class=\""+defalutCls+"\" onclick=\""+name+"SuperQuery('"+complexSuperQuery+"')\">"); sb.append("<i class=\"fa fa-search\"></i>"); sb.append("<span class=\"bigger-110 no-text-shadow\">"+MutiLangUtil.getLang("common.advancedQuery")+"</span>"); sb.append("</button>"); } }else{//自定以样式 sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\""+ name+ StringUtil.replaceAll("search()\">{0}</a>", "{0}", MutiLangUtil.getLang("common.query"))); sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\"searchReset('"+name+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.reset")) ); if(queryBuilder){ sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.querybuilder")) ); } if(superQuery){ sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.superquery")) ); } if(oConvertUtils.isNotEmpty(complexSuperQuery)){ sb.append("<a href=\"#\" class=\""+btnCls+"\" onclick=\""+name+"SuperQuery('"+complexSuperQuery+"')\">"+MutiLangUtil.getLang("common.advancedQuery")+"</a>"); } } }else{//默认使用easyUI按钮样式 sb.append("<a href=\"#\" class=\"button\" iconCls=\"icon-search\" onclick=\""+ name+ StringUtil.replaceAll("search()\">{0}</a>", "{0}", MutiLangUtil.getLang("common.query"))); sb.append("<a href=\"#\" class=\"button\" iconCls=\"icon-reload\" onclick=\"searchReset('"+name+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.reset")) ); if(queryBuilder){ sb.append("<a href=\"#\" class=\"button\" iconCls=\"icon-search\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.querybuilder")) ); } if(superQuery){ sb.append("<a href=\"#\" class=\"button\" iconCls=\"icon-search\" onclick=\"queryBuilder('"+ StringUtil.replaceAll("')\">{0}</a>", "{0}", MutiLangUtil.getLang("common.superQuery")) ); } if(oConvertUtils.isNotEmpty(complexSuperQuery)){ sb.append("<a href=\"#\" class=\"button\" iconCls=\"icon-search\" onclick=\""+name+"SuperQuery('"+complexSuperQuery+"')\">"+MutiLangUtil.getLang("common.advancedQuery")+"</a>"); } } sb.append("</span>"); }else if("single".equals(getQueryMode())&& hasQueryColum(columnList)){//如果表单是单查询 sb.append("<span style=\"float:right\">"); sb.append("<input id=\""+name+"searchbox\" class=\"easyui-searchbox\" data-options=\"searcher:"+name+ StringUtil.replaceAll("searchbox,prompt:\'{0}\',menu:\'#", "{0}", MutiLangUtil.getLang("common.please.input.keyword")) +name+"mm\'\"></input>"); sb.append("<div id=\""+name+"mm\" style=\"width:120px\">"); for (DataGridColumn col : columnList) { if (col.isQuery()) { sb.append("<div data-options=\"name:\'"+col.getField().replaceAll("_","\\.")+"\',iconCls:\'icon-ok\' "+extendAttribute(col.getExtend())+" \">"+col.getTitle()+"</div> "); } } sb.append("</div>"); sb.append("</span>"); } sb.append("<div style=\"clear:both\"></div>"); sb.append("</div>"); if(queryBuilder){ if (btnCls != null && !btnCls.equals("easyui")) {//自定以样式 bootstrap按钮样式 addQueryBuilder(sb,btnCls); }else{//默认使用easyUI按钮样式 addQueryBuilder(sb,"button"); } } if(superQuery) { if(btnCls != null && !btnCls.equals("easyui")) { addSuperQuery(sb,btnCls,columnList); } else { addSuperQuery(sb,"button",columnList); } } if(oConvertUtils.isNotEmpty(complexSuperQuery)) { if(btnCls != null && !btnCls.equals("easyui")) { addAdvancedQuery(sb,btnCls); } else { addAdvancedQuery(sb,"button"); } } return sb; } private void appendLine(StringBuffer sb,String str) { String format = "\r\n"; //调试 格式化 sb.append(str).append(format); } /** * TODO 语言做成多语翻译,保留历史查询记录 * @param sb */ private void addQueryBuilder(StringBuffer sb,String buttonSytle) { appendLine(sb,"<div style=\"position:relative;overflow:auto;\">"); appendLine(sb,"<div id=\""+name+"_qbwin\" class=\"easyui-window\" data-options=\"closed:true,title:'&nbsp;&nbsp;高级查询构造器'\" style=\"width:600px;height:370px;padding:0px\">"); appendLine(sb," <div class=\"easyui-layout\" data-options=\"fit:true\">"); appendLine(sb," <div data-options=\"region:'east',split:true\" style=\"width:130px;overflow: hidden;\"><div data-options=\"fit:true\" class=\"easyui-accordion\" style=\"width:120px;height:300px;\">"); appendLine(sb,"<div title=\"查询历史\" data-options=\"iconCls:'icon-search'\" style=\"padding:0px;\">"); appendLine( sb, " <ul id=\"" + name + "tt\" class=\"easyui-tree\" data-options=\"onClick:function(node){"); appendLine(sb, "historyQuery( node.id); "); appendLine(sb, "},ondbClick: function(node){"); appendLine(sb, "$(this).tree('beginEdit',node.target);"); appendLine(sb, "},onContextMenu: function(e,node){"); appendLine(sb, " e.preventDefault();"); appendLine(sb, " $(this).tree('select',node.target);"); appendLine(sb, " $('#"+name+"mmTree').menu('show',{"); appendLine(sb, " left: e.pageX,"); appendLine(sb, " top: e.pageY"); appendLine(sb, " });"); appendLine(sb, " }, "); appendLine(sb, " onAfterEdit:function(node){ "); appendLine(sb, " if(node.text!=''){ "+name+"his[node.id].name=node.text; saveHistory();} }"); appendLine(sb, "\">"); appendLine(sb, " </ul>"); appendLine(sb, "</div>"); appendLine(sb, "</div></div>"); appendLine(sb," <div data-options=\"region:'center'\" style=\"width:450px;padding:0px;overflow: hidden;\">"); appendLine(sb," <table id=\""+name+"tg\" class=\"easyui-treegrid\" title=\"查询条件编辑\" style=\"width:450px;height:300px;\""); appendLine(sb," data-options=\""); appendLine(sb," iconCls: 'icon-ok',"); appendLine(sb," rownumbers: true,"); appendLine(sb," animate: true,"); appendLine(sb," fitColumns: true,"); appendLine(sb," //url: 'sqlbuilder.json',//可以预加载条件\r\n"); appendLine(sb," method: 'get',"); appendLine(sb," idField: 'id',"); appendLine(sb," fit:true,"); appendLine(sb,"autoEditing: true, "); appendLine(sb,"extEditing: false, "); appendLine(sb,"singleEditing: false ,"); appendLine(sb," treeField: 'field',toolbar:toolbar,onContextMenu: onContextMenu"); appendLine(sb," \">"); appendLine(sb,"<thead>"); appendLine(sb," <tr>"); sb .append(" <th data-options=\"field:'relation',width:18,formatter:function(value,row){"); appendLine(sb," return value=='and'?'并且':'或者';"); appendLine(sb," },editor:{"); appendLine(sb," type:'combobox',"); appendLine(sb," options:{"); appendLine(sb," valueField:'relationId',"); appendLine(sb," textField:'relationName',"); appendLine(sb," data: "); appendLine(sb," [ "); appendLine(sb," {'relationId':'and','relationName':'并且'}, "); appendLine(sb," {'relationId':'or','relationName':'或者'} "); appendLine(sb," ], "); appendLine(sb," required:true"); appendLine(sb," }}\">关系</th>"); sb .append(" <th data-options=\"field:'field',width:30,formatter:function(value,row){"); appendLine(sb," var data= "); StringBuffer fieldArray=new StringBuffer(); fieldArray.append(" [ "); for (int i=0;i<columnList.size();i++){ DataGridColumn col =columnList.get(i); if("opt".equals(col.getField()))continue;//忽略操作虚拟字段 fieldArray.append(" {'fieldId':'"+getDBFieldName(col.getField())+"','fieldName':'"+col.getTitle()+"'"); if(col.getEditor()!=null){ fieldArray.append(",editor:'"+col.getEditor()+"'"); } fieldArray.append("}"); if(i<columnList.size()-1){ fieldArray.append(","); } } // appendLine(sb," {'fieldId':'office_Phone','fieldName':'办公电话'},"); fieldArray.append("]"); sb.append(fieldArray).append(";"); appendLine(sb,"for(var i=0;i<data.length;i++){"); appendLine(sb,"if(value == data[i]['fieldId']){"); appendLine(sb,"return data[i]['fieldName'];"); appendLine(sb,"}"); appendLine(sb,"}"); appendLine(sb,"return value;"); appendLine(sb,"},editor:{"); appendLine(sb,"type:'combobox',"); appendLine(sb," options:{"); appendLine(sb,"valueField:'fieldId',"); appendLine(sb,"textField:'fieldName',"); appendLine(sb,"data: "); sb.append(fieldArray); appendLine(sb," , "); appendLine(sb, "required:true,onSelect : function(record) {"); appendLine(sb,"var opts = $('#"+name+"tg').treegrid('getColumnOption','value');"); appendLine(sb, " if(record.editor){"); appendLine(sb, " opts.editor=record.editor;"); appendLine(sb, " }else{"); appendLine(sb, " opts.editor='text';"); appendLine(sb, " }"); appendLine(sb, " var tr = $(this).closest('tr.datagrid-row');"); appendLine(sb, " var index = parseInt(tr.attr('node-id'));"); appendLine(sb, " $('#"+name+"tg').treegrid('endEdit', index);"); appendLine(sb, " $('#"+name+"tg').treegrid('beginEdit', index);"); appendLine(sb, "}"); appendLine(sb,"}}\">字段</th>"); appendLine(sb,"<th data-options=\"field:'condition',width:20,align:'right',formatter:function(value,row){"); appendLine(sb," var data= "); appendLine(sb," [ "); List<TSType> types = ResourceUtil.getCacheTypes("rulecon"); if (types != null) { for (int i=0;i<types.size();i++){ TSType type = types.get(i); appendLine(sb," {'conditionId':'"+type.getTypecode()+"','conditionName':'" +MutiLangUtil.getLang(type.getTypename())+"'}"); if(i<types.size()-1){ appendLine(sb,","); } } } appendLine(sb,"];"); appendLine(sb," for(var i=0;i<data.length;i++){"); appendLine(sb," if(value == data[i]['conditionId']){"); appendLine(sb," return data[i]['conditionName'];"); appendLine(sb," }"); appendLine(sb," }"); appendLine(sb," return value;"); appendLine(sb," },editor:{"); appendLine(sb," type:'combobox',"); appendLine(sb," options:{"); appendLine(sb," valueField:'conditionId',"); appendLine(sb," textField:'conditionName', "); appendLine(sb," data: "); appendLine(sb,"["); if (types != null) { for (int i=0;i<types.size();i++){ TSType type = types.get(i); appendLine(sb," {'conditionId':'"+type.getTypecode()+"','conditionName':'" +MutiLangUtil.getLang(type.getTypename())+"'}"); if(i<types.size()-1){ appendLine(sb,","); } } } appendLine(sb," ], "); appendLine(sb," required:true"); appendLine(sb," }}\">条件</th>"); sb .append(" <th data-options=\"field:'value',width:30,editor:'text'\">值</th>"); appendLine(sb,"<th data-options=\"field:'opt',width:30,formatter:function(value,row){"); appendLine(sb," return '<a onclick=\\'removeIt('+row.id+')\\' >删除</a>';}\">操作</th>"); appendLine(sb," </tr>"); appendLine(sb," </thead>"); appendLine(sb," </table>"); appendLine(sb,"</div>"); appendLine(sb,"<div data-options=\"region:'south',border:false\" style=\"text-align:right;padding:5px 0 3px;\">"); if (btnCls != null && !btnCls.equals("easyui")) { String defalutCls = "btn btn-default btn-xs"; if (btnCls.replace("bootstrap", "").trim().length() > 0) { defalutCls = btnCls.replace("bootstrap", "").trim(); } appendLine(sb,"<button class=\""+defalutCls+"\" onclick=\"javascript:queryBuilderSearch()\">&nbsp;<i class=\"fa fa-check\"></i>确定</button>"); appendLine(sb,"<button class=\""+defalutCls+"\" onclick=\"javascript:$('#"+name+"_qbwin').window('close')\">&nbsp;<i class=\"fa fa-close\"></i>取消</button>"); }else{ appendLine(sb,"<a class=\""+buttonSytle+"\" data-options=\"iconCls:'icon-ok'\" href=\"javascript:void(0)\" onclick=\"javascript:queryBuilderSearch()\">确定</a>"); appendLine(sb,"<a class=\""+buttonSytle+"\" data-options=\"iconCls:'icon-cancel'\" href=\"javascript:void(0)\" onclick=\"javascript:$('#"+name+"_qbwin').window('close')\">取消</a>"); } appendLine(sb," </div>"); appendLine(sb," </div> "); appendLine(sb,"</div> "); appendLine(sb,"</div>"); appendLine(sb,"<div id=\"mm\" class=\"easyui-menu\" style=\"width:120px;\">"); appendLine(sb," <div onclick=\"append()\" data-options=\"iconCls:'icon-add'\">添加</div>"); appendLine(sb," <div onclick=\"edit()\" data-options=\"iconCls:'icon-edit'\">编辑</div>"); appendLine(sb," <div onclick=\"save()\" data-options=\"iconCls:'icon-save'\">保存</div>"); appendLine(sb," <div onclick=\"removeIt()\" data-options=\"iconCls:'icon-remove'\">删除</div>"); appendLine(sb," <div class=\"menu-sep\"></div>"); appendLine(sb," <div onclick=\"cancel()\">取消</div>"); appendLine(sb,"<div onclick=\"expand()\">Expand</div>"); appendLine(sb,"</div><div id=\""+name+"mmTree\" class=\"easyui-menu\" style=\"width:100px;\">"); appendLine(sb,"<div onclick=\"editTree()\" data-options=\"iconCls:'icon-edit'\">编辑</div>"); appendLine(sb,"<div onclick=\"deleteTree()\" data-options=\"iconCls:'icon-remove'\">删除</div></div>"); //已在baseTag中引入 // appendLine(sb,"<script type=\"text/javascript\" src=\"plug-in/jquery/jquery.cookie.js\" ></script>"); // appendLine(sb,"<script type=\"text/javascript\" src=\"plug-in/jquery-plugs/storage/jquery.storageapi.min.js\" ></script>"); appendLine(sb,"<script type=\"text/javascript\">"); if (btnCls != null && !btnCls.equals("easyui")) { String defalutCls = "btn btn-info btn-xs"; if (btnCls.replace("bootstrap", "").trim().length() > 0) { defalutCls = btnCls.replace("bootstrap", "").trim(); } sb.append("var toolbar = '<div>"); sb.append("<button class=\""+defalutCls+"\" onclick=\"append()\">&nbsp;<i class=\"fa fa-plus\"></i>&nbsp;</button>"); sb.append("<button class=\""+defalutCls+"\" onclick=\"edit()\">&nbsp;<i class=\"fa fa-pencil-square-o\"></i></button>"); sb.append("<button class=\""+defalutCls+"\" onclick=\"removeIt()\">&nbsp;<i class=\"fa fa-trash\"></i></button>"); sb.append("<button class=\""+defalutCls+"\" onclick=\"save()\">&nbsp;<i class=\"fa fa-save\"></i></button>"); sb.append("</div>';"); }else{ appendLine(sb,"var toolbar = [{"); appendLine(sb," text:'',"); appendLine(sb," iconCls:'icon-add',"); appendLine(sb," handler:function(){append();}"); appendLine(sb,"},{"); appendLine(sb," text:'',"); appendLine(sb," iconCls:'icon-edit',"); appendLine(sb," handler:function(){edit();}"); appendLine(sb,"},{"); appendLine(sb," text:'',"); appendLine(sb," iconCls:'icon-remove',"); appendLine(sb," handler:function(){removeIt();}"); appendLine(sb,"},'-',{"); appendLine(sb," text:'',"); appendLine(sb," iconCls:'icon-save',"); appendLine(sb," handler:function(){save();}"); appendLine(sb," }];"); } appendLine(sb,"function onContextMenu(e,row){"); appendLine(sb," e.preventDefault();"); appendLine(sb," $(this).treegrid('select', row.id);"); appendLine(sb," $('#mm').menu('show',{"); appendLine(sb," left: e.pageX,"); appendLine(sb," top: e.pageY"); appendLine(sb," });"); appendLine(sb,"}"); appendLine(sb," var idIndex = 100;"); appendLine(sb,"function append(){"); appendLine(sb," idIndex++;"); appendLine(sb," var node = $('#"+name+"tg').treegrid('getSelected');"); appendLine(sb," $('#"+name+"tg').treegrid('append',{"); appendLine(sb," data: [{"); appendLine(sb," id: idIndex,"); appendLine(sb," field: '',"); appendLine(sb," condition:'like',"); appendLine(sb," value: '%a%',"); appendLine(sb," relation: 'and'"); appendLine(sb," }]"); appendLine(sb,"});$('#"+name+"tg').datagrid('beginEdit',idIndex);"); appendLine(sb,"}"); appendLine(sb," function removeIt(id){"); appendLine(sb,"var node = $('#"+name+"tg').treegrid('getSelected');"); appendLine(sb,"if(id){"); appendLine(sb,"$('#"+name+"tg').treegrid('remove', id);"); appendLine(sb,"}else if(node){ $('#"+name+"tg').treegrid('remove', node.id);"); appendLine(sb,"}"); appendLine(sb,"}"); appendLine(sb,"function collapse(){"); appendLine(sb," var node = $('#"+name+"tg').treegrid('getSelected');"); appendLine(sb,"if(node){"); appendLine(sb," $('#"+name+"tg').treegrid('collapse', node.id);"); appendLine(sb,"}"); appendLine(sb,"}"); appendLine(sb,"function expand(){"); appendLine(sb,"var node = $('#"+name+"tg').treegrid('getSelected');"); appendLine(sb,"if(node){"); appendLine(sb," $('#"+name+"tg').treegrid('expand', node.id);"); appendLine(sb,"}"); appendLine(sb,"}"); appendLine(sb,"var editingId;"); appendLine(sb,"function edit(id){"); appendLine(sb,"var row = $('#"+name+"tg').treegrid('getSelected');"); appendLine(sb,"if(id){ $('#"+name+"tg').treegrid('beginEdit', id);}else if(row){"); appendLine(sb," $('#"+name+"tg').treegrid('beginEdit', row.id);"); appendLine(sb,"}"); appendLine(sb,"}"); appendLine(sb,"function save(){"); appendLine(sb," var t = $('#"+name+"tg');"); appendLine(sb," var nodes = t.treegrid('getRoots');"); appendLine(sb," for (var i = 0; i < nodes.length; i++) {"); appendLine(sb," t.treegrid('endEdit',nodes[i].id);}"); appendLine(sb," }"); appendLine(sb,"function cancel(){"); appendLine(sb," var t = $('#"+name+"tg');"); appendLine(sb,"var nodes = t.treegrid('getRoots');for (var i = 0; i < nodes.length; i++) {t.treegrid('cancelEdit',nodes[i].id);}"); appendLine(sb,"}"); appendLine(sb, "var "+name+"his=new Array();"); appendLine(sb, " function historyQuery(index) {"); appendLine(sb, " var data = { rows:JSON.parse("+name+"his[index].json)}; "); appendLine(sb, " var t = $('#" + name + "tg');"); appendLine(sb, " var data = t.treegrid('loadData',data);"); appendLine(sb, " $('#_sqlbuilder').val( "+name+"his[index].json); "); appendLine(sb, " "+name+"search();"); appendLine(sb, " }"); appendLine(sb, "function view(){"); appendLine(sb,"save();"); appendLine(sb,"var t = $('#"+name+"tg');"); appendLine(sb,"var data = t.treegrid('getData');"); appendLine(sb,"return JSON.stringify(data) ;"); appendLine(sb,"}"); appendLine(sb," function queryBuilder() {"); appendLine(sb," $('#"+name+"_qbwin').window('open');"); appendLine(sb,"}"); appendLine(sb, "function queryBuilderSearch() {"); appendLine(sb, " var json = view();"); appendLine(sb, " $('#_sqlbuilder').val(json); "); appendLine(sb, " var isnew=true;"); appendLine(sb, "for(var i=0;i< "+name+"his.length;i++){"); appendLine(sb, " if("+name+"his[i]&&"+name+"his[i].json==json){"); appendLine(sb, " isnew=false;"); appendLine(sb, " }"); appendLine(sb, "}"); appendLine(sb, "if(isnew){"); appendLine(sb, " "+name+"his.push({name:'Query'+"+name+"his.length,json:json});saveHistory();"); appendLine(sb, "var name= 'Query'+( "+name+"his.length-1);"); appendLine(sb, " var name= 'Query'+("+name+"his.length-1);"); appendLine(sb, "appendTree("+name+"his.length-1,name);"); appendLine(sb, "}"); appendLine(sb, " " + name + "search();"); appendLine(sb, " }"); appendLine(sb, " $(document).ready(function(){ "); appendLine(sb, " storage=$.localStorage;if(!storage)storage=$.cookieStorage;"); appendLine(sb, " var _qhistory = storage.get('" + name+ "_query_history');"); appendLine(sb, " if(_qhistory){"); appendLine(sb, " "+name+"his=_qhistory;"); // appendLine(sb, " var data = { rows:his[0]};"); appendLine(sb, " for(var i=0;i< "+name+"his.length;i++){"); appendLine(sb, " if("+name+"his[i])appendTree(i,"+name+"his[i].name);"); appendLine(sb, " }restoreheader();"); appendLine(sb, " }});"); appendLine(sb, "function saveHistory(){"); appendLine(sb, " var history=new Array();"); appendLine(sb, " for(var i=0;i<" + name + "his.length;i++){"); appendLine(sb, " if(" + name + "his[i]){"); appendLine(sb, " history.push(" + name + "his[i]);"); appendLine(sb, " }"); appendLine(sb, " }"); appendLine(sb, " storage.set( '"+name+"_query_history',JSON.stringify(history));"); appendLine(sb, "}"); appendLine(sb, "function deleteTree(){"); appendLine(sb, " var tree = $('#" + name + "tt');var node= tree.tree('getSelected');"); appendLine(sb, " " + name + "his[node.id]=null;saveHistory();"); appendLine(sb, " tree.tree('remove', node.target);"); appendLine(sb, "}"); appendLine(sb, "function editTree(){"); appendLine(sb, " var node = $('#" + name + "tt').tree('getSelected');"); appendLine(sb, " $('#" + name + "tt').tree('beginEdit',node.target);"); appendLine(sb, " saveHistory();"); appendLine(sb, "}"); appendLine(sb, "function appendTree(id,name){"); appendLine(sb, " $('#"+name+"tt').tree('append',{"); appendLine(sb, " data:[{"); appendLine(sb, "id : id,"); appendLine(sb, "text :name"); appendLine(sb, " }]"); appendLine(sb, "});"); appendLine(sb, "}"); appendLine(sb, "</script>"); } /** * hibernate字段名转换为数据库名称,只支持标准命名 * 否则转换错误 * @param fieldName * @return */ String getDBFieldName(String fieldName){ StringBuffer sb=new StringBuffer(); for(int i=0;i<fieldName.length();i++){ char c = fieldName.charAt(i); if(c<='Z'&&c>='A'){ sb.append("_").append((char)((int)c+32)); }else{ sb.append(c); } } return sb.toString(); } /** * 高级查询 * @param sb */ private void addSuperQuery(StringBuffer sb,String buttonSytle,List<DataGridColumn> columnList) { FreemarkerHelper free = new FreemarkerHelper(); Map<String, Object> mainConfig = new HashMap<String, Object>(); mainConfig.put("fields", columnList); mainConfig.put("tableName", name); mainConfig.put("valueList", columnValueList); String superQuery = free.parseTemplate("/org/jeecgframework/tag/ftl/superquery.ftl", mainConfig); appendLine(sb,superQuery); } /** * 高级查询bootstrap版 */ private void addSuperQueryBootstrap(StringBuffer sb,String buttonSytle,List<DataGridColumn> columnList) { FreemarkerHelper free = new FreemarkerHelper(); Map<String, Object> mainConfig = new HashMap<String, Object>(); mainConfig.put("fields", columnList); mainConfig.put("tableName", name); mainConfig.put("valueList", columnValueList); String superQuery = free.parseTemplate("/org/jeecgframework/tag/ftl/superqueryBootstrap.ftl", mainConfig); appendLine(sb,superQuery); } //是否启用过滤 protected boolean filter = false; public boolean isFilter() { return filter; } public void setFilter(boolean filter) { this.filter = filter; } public void getFilter(StringBuffer sb){ if (this.isFilter()) { FreemarkerHelper free = new FreemarkerHelper(); Map<String, Object> mainConfig = new HashMap<String, Object>(); mainConfig.put("gridId", name); String superQuery = free.parseTemplate("/org/jeecgframework/tag/ftl/filter.ftl", mainConfig); appendLine(sb,superQuery); } } protected boolean filterBtn = false;//按钮过滤模式是否开启,列表上若有一个按钮可以让其调用xxFilter函数出现过滤行-- public boolean isFilterBtn() { return filterBtn; } public void setFilterBtn(boolean filterBtn) { this.filterBtn = filterBtn; } /** * 获取过滤字段配置 * @return */ private void getFilterFields(StringBuffer sb){ if(this.isFilterBtn()){ StringBuffer ffs = new StringBuffer(); int index = 0; for (DataGridColumn column :columnList) { if(column.getField().equals("opt")){ continue; } if(index!=0){ ffs.append(","); } index++; String filterType = column.getFilterType(); ffs.append("{"); ffs.append("field:'"+column.getField()+"',"); ffs.append("type:'"+filterType+"',"); if("combobox".equals(filterType)){ ffs.append("options:{"); ffs.append("panelHeight:'auto',"); ffs.append("data:[{value:'',text:'All'}"); for (ColumnValue columnValue : columnValueList) { if (columnValue.getName().equals(column.getField())) { String[] value = columnValue.getValue().split(","); String[] text = columnValue.getText().split(","); for (int k = 0; k < value.length; k++) { ffs.append(",{value:'"+value[k]+"',text:'"+text[k]+"'}"); } break; } } ffs.append("],"); ffs.append("onChange:function(value){");//if (value == ''){}$('#"+name+"').datagrid('removeFilterRule', '"+column.getField()+"'); // else { ffs.append("$('#"+name+"').datagrid('addFilterRule', {field: '"+column.getField()+"',op: 'equal',value: value});");//} ffs.append("$('#"+name+"').datagrid('doFilter');}}");//option-end }else{ ffs.append("options:{precision:1},"); if("numberbox".equals(filterType) || "datebox".equals(filterType)|| "datetimebox".equals(filterType)){ ffs.append("op:['equal','lessorequal','greaterorequal']"); }else{ ffs.append("op:['equal','contains']"); } } ffs.append("}"); } sb.append("function "+name+"Filter(){$('#"+name+"').datagrid('enableFilter',["+ffs.toString()+"]);}"); } } /** * 拼装操作地址,新的风格 * @param sb */ private void getOptsMenuUrl(StringBuffer sb){ this.getOptUrl(sb,true,false); StringBuffer groupString = new StringBuffer(); this.getOptUrl(groupString,true,true); if(oConvertUtils.isNotEmpty(groupString.toString())){ sb.append("href+='<div style=\"left:40px;top:-1px\" class=\"opts_menu_container\"><div class=\"opts_menu_btn btn-menu\"><i class=\"fa fa-caret-right\" style=\"margin-top:1px;\"></i></div>';"); sb.append("href+='<div style=\"clear: both;\"></div><div style=\"\" class=\"opts-menus-parent pp_menu_box\"><div class=\"opts_menu_box opts-menus-auto\" style=\"left:18px;\">';"); sb.append(groupString.toString()); sb.append("href+='</div></div><em class=\"ops_shadeEm\" style=\"display: inline;\"></em></div>';"); } sb.append("return href;"); } /** * * 拼装操作地址,新的风格 * @param sb * @param noReturn 是否不在该方法中返回href * @param initGroup 是否加载的是隐藏菜单 */ protected void getOptUrl(StringBuffer sb,boolean noReturn,boolean initGroup) { //注:操作列表会带入合计列中去,故加此判断 List<DataGridUrl> list = urlList; if(!initGroup){ sb.append("if(!rec.id){return '';}"); sb.append("var href='';"); } for (DataGridUrl dataGridUrl : list) { if(initGroup){ //若加载的是组菜单 但该菜单其实不是组菜单则 跳过 if(!dataGridUrl.isInGroup()){ continue; } }else{ //若加载的不是组菜单 但该菜单其实是组菜单则 跳过 if(dataGridUrl.isInGroup()){ continue; } } String url = dataGridUrl.getUrl(); MessageFormat formatter = new MessageFormat(""); if (dataGridUrl.getValue() != null) { String[] testvalue = dataGridUrl.getValue().split(","); List value = new ArrayList<Object>(); for (String string : testvalue) { value.add("\"+rec." + string + " +\""); } url = formatter.format(url, value.toArray()); } if (url != null && dataGridUrl.getValue() == null) { url = formatUrlPlus(url); } String exp = dataGridUrl.getExp();// 判断显示表达式 if (StringUtil.isNotEmpty(exp)) { String[] ShowbyFields = exp.split("&&"); for (String ShowbyField : ShowbyFields) { int beginIndex = ShowbyField.indexOf("#"); int endIndex = ShowbyField.lastIndexOf("#"); String exptype = ShowbyField.substring(beginIndex + 1, endIndex);// 表达式类型 String field = ShowbyField.substring(0, beginIndex);// 判断显示依据字段 String[] values = ShowbyField.substring(endIndex + 1, ShowbyField.length()).split(",");// 传入字段值 String value = ""; for (int i = 0; i < values.length; i++) { value += "'" + "" + values[i] + "" + "'"; if (i < values.length - 1) { value += ","; } } if ("eq".equals(exptype)) { sb.append("if($.inArray(rec." + field + ",[" + value + "])>=0){"); } if ("ne".equals(exptype)) { sb.append("if($.inArray(rec." + field + ",[" + value + "])<0){"); } if ("empty".equals(exptype) && value.equals("'true'")) { sb.append("if(rec." + field + "==''){"); } if ("empty".equals(exptype) && value.equals("'false'")) { sb.append("if(rec." + field + "!=''){"); } } } StringBuffer style = new StringBuffer(); if (!StringUtil.isEmpty(dataGridUrl.getUrlStyle())) { style.append(" style=\'"); style.append(dataGridUrl.getUrlStyle()); style.append("\' "); } StringBuffer urlclass = new StringBuffer(); StringBuffer urlfont = new StringBuffer(); if(initGroup){ urlclass.append(" class=\'btn btn-menu fa "); if(!StringUtil.isEmpty(dataGridUrl.getUrlfont())){ urlclass.append(dataGridUrl.getUrlfont()); }else{ urlclass.append("fa-font"); } urlclass.append(" menu-more\'"); }else{ urlclass.append(" class=\'btn-menu\'"); urlfont.append("<i class=\'fa "); if(!StringUtil.isEmpty(dataGridUrl.getUrlfont())){ urlfont.append(dataGridUrl.getUrlfont()); }else{ urlfont.append("fa-font"); } urlfont.append("\'></i>"); } if (OptTypeDirection.Fun.equals(dataGridUrl.getType())) { String name = TagUtil.getFunction(dataGridUrl.getFunname()); String parmars = TagUtil.getFunParams(dataGridUrl.getFunname()); sb.append("href+=\"<a href=\'#\' title='"+dataGridUrl.getTitle()+"' "+urlclass.toString()+" onclick=" + name + "(" + parmars + ")" + style.toString() + ">"+urlfont.toString()+"\";"); } if (OptTypeDirection.OpenWin.equals(dataGridUrl.getType())) { String funname = dataGridUrl.getFunname(); if(oConvertUtils.isEmpty(funname)){ funname = "openwindow"; } String dgFormWidth = dataGridUrl.getWidth(); if("100%".equals(dgFormWidth)){ dgFormWidth = "'"+dgFormWidth+"'"; }else if(oConvertUtils.isEmpty(dgFormWidth)){ dgFormWidth = "''"; } String dgFormHeight = dataGridUrl.getHeight(); if("100%".equals(dgFormHeight)){ dgFormHeight = "'"+dgFormHeight+"'"; }else if(oConvertUtils.isEmpty(dgFormHeight)){ dgFormHeight = "''"; } sb.append("href+=\"<a href=\'####\' title='"+dataGridUrl.getTitle()+"' "+urlclass.toString()+" onclick="+funname+"('" + dataGridUrl.getTitle() + "','" + url + "','"+name+"'," + dgFormWidth + "," + dgFormHeight + ")" + style.toString() + ">"+urlfont.toString()+"\";"); } sb.append("href+=\"" + "" + "</a>&nbsp;\";"); if (StringUtil.isNotEmpty(exp)) { for (int i = 0; i < exp.split("&&").length; i++) { sb.append("}"); } } } if(!noReturn){ sb.append("return href;"); } } /** * 高级查询构造器 * @param sb */ private void addAdvancedQuery(StringBuffer sb,String buttonSytle) { /*FreemarkerHelper free = new FreemarkerHelper(); Map<String, Object> mainConfig = new HashMap<String, Object>(); mainConfig.put("queryCode", complexSuperQuery); mainConfig.put("tableName", name); String complexSuperQuery = free.parseTemplate("/org/jeecgframework/tag/ftl/complexSuperQuery.ftl", mainConfig); appendLine(sb,complexSuperQuery);*/ } /** * 判断当前浏览器不是IE,采用有bootstrap样式按钮 */ private boolean checkBrowerIsNotIE(){ String browserType = ""; Object brower_type = ContextHolderUtils.getSession().getAttribute("brower_type"); if(brower_type==null){ HttpServletRequest req = ContextHolderUtils.getRequest(); Cookie[] cookies = req.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if("BROWSER_TYPE".equals(cookie.getName())){ browserType = cookie.getValue(); } } }else{ browserType = brower_type.toString(); } if(!"Microsoft%20Internet%20Explorer".equals(browserType)){ return true; } return false; } /** * 列表中是否有分组的按钮 * @param urlList * @return */ public boolean hasGroup(){ boolean flag = false; for (DataGridColumn column : columnList) { if (StringUtil.isNotEmpty(column.getField()) && column.getField().equals("opt")){ if(column.isOptsMenu()){ return false; } } } for (DataGridUrl dataGridUrl : urlList) { if(dataGridUrl.isInGroup()){ flag = true; break; } } return flag; } public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } public String getSearchFields() { return searchFields; } public void setSearchFields(String searchFields) { this.searchFields = searchFields; } public List<DataGridUrl> getUrlList() { return urlList; } public void setUrlList(List<DataGridUrl> urlList) { this.urlList = urlList; } public List<DataGridUrl> getToolBarList() { return toolBarList; } public void setToolBarList(List<DataGridUrl> toolBarList) { this.toolBarList = toolBarList; } public List<DataGridColumn> getColumnList() { return columnList; } public void setColumnList(List<DataGridColumn> columnList) { this.columnList = columnList; } public List<ColumnValue> getColumnValueList() { return columnValueList; } public void setColumnValueList(List<ColumnValue> columnValueList) { this.columnValueList = columnValueList; } public List<ColumnValue> getColumnStyleList() { return columnStyleList; } public void setColumnStyleList(List<ColumnValue> columnStyleList) { this.columnStyleList = columnStyleList; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public int getCurPageNo() { return curPageNo; } public void setCurPageNo(int curPageNo) { this.curPageNo = curPageNo; } public Map<String, Object> getTableData() { return tableData; } public void setTableData(Map<String, Object> tableData) { this.tableData = tableData; } public String getName() { return name; } public String getTitle() { return title; } public String getIdField() { return idField; } public boolean isTreegrid() { return treegrid; } public String getActionUrl() { return actionUrl; } public int getPageSize() { return pageSize; } public boolean isPagination() { return pagination; } public String getWidth() { return width; } public String getHeight() { return height; } public boolean isCheckbox() { return checkbox; } public boolean isShowPageList() { return showPageList; } public boolean isOpenFirstNode() { return openFirstNode; } public boolean isFit() { return fit; } public boolean isShowRefresh() { return showRefresh; } public boolean isShowText() { return showText; } public String getStyle() { return style; } public String getOnLoadSuccess() { return onLoadSuccess; } public String getOnClick() { return onClick; } public String getOnDblClick() { return onDblClick; } public String getRowStyler() { return rowStyler; } public String getExtendParams() { return extendParams; } public String getLangArg() { return langArg; } public boolean isNowrap() { return nowrap; } public Boolean getSingleSelect() { return singleSelect; } public String getTreeField() { return treeField; } public String getComponent() { return component; } public void setShowSearch(boolean isShowSearch) { this.isShowSearch = isShowSearch; } public void setShowSubGrid(boolean isShowSubGrid) { this.isShowSubGrid = isShowSubGrid; } public int getAllCount() { return allCount; } public void setAllCount(int allCount) { this.allCount = allCount; } public DataGridTag getDataGridTag(){ return this; } }
83,863
995
<filename>deps/boost/include/boost/random/discrete_distribution.hpp /* boost random/discrete_distribution.hpp header file * * Copyright <NAME> 2009-2011 * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org for most recent version including documentation. * * $Id$ */ #ifndef BOOST_RANDOM_DISCRETE_DISTRIBUTION_HPP_INCLUDED #define BOOST_RANDOM_DISCRETE_DISTRIBUTION_HPP_INCLUDED #include <vector> #include <limits> #include <numeric> #include <utility> #include <iterator> #include <boost/assert.hpp> #include <boost/random/uniform_01.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/random/detail/config.hpp> #include <boost/random/detail/operators.hpp> #include <boost/random/detail/vector_io.hpp> #ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST #include <initializer_list> #endif #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/random/detail/disable_warnings.hpp> namespace boost { namespace random { namespace detail { template<class IntType, class WeightType> struct integer_alias_table { WeightType get_weight(IntType bin) const { WeightType result = _average; if(bin < _excess) ++result; return result; } template<class Iter> WeightType init_average(Iter begin, Iter end) { WeightType weight_average = 0; IntType excess = 0; IntType n = 0; // weight_average * n + excess == current partial sum // This is a bit messy, but it's guaranteed not to overflow for(Iter iter = begin; iter != end; ++iter) { ++n; if(*iter < weight_average) { WeightType diff = weight_average - *iter; weight_average -= diff / n; if(diff % n > excess) { --weight_average; excess += n - diff % n; } else { excess -= diff % n; } } else { WeightType diff = *iter - weight_average; weight_average += diff / n; if(diff % n < n - excess) { excess += diff % n; } else { ++weight_average; excess -= n - diff % n; } } } _alias_table.resize(static_cast<std::size_t>(n)); _average = weight_average; _excess = excess; return weight_average; } void init_empty() { _alias_table.clear(); _alias_table.push_back(std::make_pair(static_cast<WeightType>(1), static_cast<IntType>(0))); _average = static_cast<WeightType>(1); _excess = static_cast<IntType>(0); } bool operator==(const integer_alias_table& other) const { return _alias_table == other._alias_table && _average == other._average && _excess == other._excess; } static WeightType normalize(WeightType val, WeightType /* average */) { return val; } static void normalize(std::vector<WeightType>&) {} template<class URNG> WeightType test(URNG &urng) const { return uniform_int_distribution<WeightType>(0, _average)(urng); } bool accept(IntType result, WeightType val) const { return result < _excess || val < _average; } static WeightType try_get_sum(const std::vector<WeightType>& weights) { WeightType result = static_cast<WeightType>(0); for(typename std::vector<WeightType>::const_iterator iter = weights.begin(), end = weights.end(); iter != end; ++iter) { if((std::numeric_limits<WeightType>::max)() - result > *iter) { return static_cast<WeightType>(0); } result += *iter; } return result; } template<class URNG> static WeightType generate_in_range(URNG &urng, WeightType max) { return uniform_int_distribution<WeightType>( static_cast<WeightType>(0), max-1)(urng); } typedef std::vector<std::pair<WeightType, IntType> > alias_table_t; alias_table_t _alias_table; WeightType _average; IntType _excess; }; template<class IntType, class WeightType> struct real_alias_table { WeightType get_weight(IntType) const { return WeightType(1.0); } template<class Iter> WeightType init_average(Iter first, Iter last) { std::size_t size = std::distance(first, last); WeightType weight_sum = std::accumulate(first, last, static_cast<WeightType>(0)); _alias_table.resize(size); return weight_sum / size; } void init_empty() { _alias_table.clear(); _alias_table.push_back(std::make_pair(static_cast<WeightType>(1), static_cast<IntType>(0))); } bool operator==(const real_alias_table& other) const { return _alias_table == other._alias_table; } static WeightType normalize(WeightType val, WeightType average) { return val / average; } static void normalize(std::vector<WeightType>& weights) { WeightType sum = std::accumulate(weights.begin(), weights.end(), static_cast<WeightType>(0)); for(typename std::vector<WeightType>::iterator iter = weights.begin(), end = weights.end(); iter != end; ++iter) { *iter /= sum; } } template<class URNG> WeightType test(URNG &urng) const { return uniform_01<WeightType>()(urng); } bool accept(IntType, WeightType) const { return true; } static WeightType try_get_sum(const std::vector<WeightType>& /* weights */) { return static_cast<WeightType>(1); } template<class URNG> static WeightType generate_in_range(URNG &urng, WeightType) { return uniform_01<WeightType>()(urng); } typedef std::vector<std::pair<WeightType, IntType> > alias_table_t; alias_table_t _alias_table; }; template<bool IsIntegral> struct select_alias_table; template<> struct select_alias_table<true> { template<class IntType, class WeightType> struct apply { typedef integer_alias_table<IntType, WeightType> type; }; }; template<> struct select_alias_table<false> { template<class IntType, class WeightType> struct apply { typedef real_alias_table<IntType, WeightType> type; }; }; } /** * The class @c discrete_distribution models a \random_distribution. * It produces integers in the range [0, n) with the probability * of producing each value is specified by the parameters of the * distribution. */ template<class IntType = int, class WeightType = double> class discrete_distribution { public: typedef WeightType input_type; typedef IntType result_type; class param_type { public: typedef discrete_distribution distribution_type; /** * Constructs a @c param_type object, representing a distribution * with \f$p(0) = 1\f$ and \f$p(k|k>0) = 0\f$. */ param_type() : _probabilities(1, static_cast<WeightType>(1)) {} /** * If @c first == @c last, equivalent to the default constructor. * Otherwise, the values of the range represent weights for the * possible values of the distribution. */ template<class Iter> param_type(Iter first, Iter last) : _probabilities(first, last) { normalize(); } #ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST /** * If wl.size() == 0, equivalent to the default constructor. * Otherwise, the values of the @c initializer_list represent * weights for the possible values of the distribution. */ param_type(const std::initializer_list<WeightType>& wl) : _probabilities(wl) { normalize(); } #endif /** * If the range is empty, equivalent to the default constructor. * Otherwise, the elements of the range represent * weights for the possible values of the distribution. */ template<class Range> explicit param_type(const Range& range) : _probabilities(boost::begin(range), boost::end(range)) { normalize(); } /** * If nw is zero, equivalent to the default constructor. * Otherwise, the range of the distribution is [0, nw), * and the weights are found by calling fw with values * evenly distributed between \f$\mbox{xmin} + \delta/2\f$ and * \f$\mbox{xmax} - \delta/2\f$, where * \f$\delta = (\mbox{xmax} - \mbox{xmin})/\mbox{nw}\f$. */ template<class Func> param_type(std::size_t nw, double xmin, double xmax, Func fw) { std::size_t n = (nw == 0) ? 1 : nw; double delta = (xmax - xmin) / n; BOOST_ASSERT(delta > 0); for(std::size_t k = 0; k < n; ++k) { _probabilities.push_back(fw(xmin + k*delta + delta/2)); } normalize(); } /** * Returns a vector containing the probabilities of each possible * value of the distribution. */ std::vector<WeightType> probabilities() const { return _probabilities; } /** Writes the parameters to a @c std::ostream. */ BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm) { detail::print_vector(os, parm._probabilities); return os; } /** Reads the parameters from a @c std::istream. */ BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm) { std::vector<WeightType> temp; detail::read_vector(is, temp); if(is) { parm._probabilities.swap(temp); } return is; } /** Returns true if the two sets of parameters are the same. */ BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs) { return lhs._probabilities == rhs._probabilities; } /** Returns true if the two sets of parameters are different. */ BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type) private: /// @cond show_private friend class discrete_distribution; explicit param_type(const discrete_distribution& dist) : _probabilities(dist.probabilities()) {} void normalize() { impl_type::normalize(_probabilities); } std::vector<WeightType> _probabilities; /// @endcond }; /** * Creates a new @c discrete_distribution object that has * \f$p(0) = 1\f$ and \f$p(i|i>0) = 0\f$. */ discrete_distribution() { _impl.init_empty(); } /** * Constructs a discrete_distribution from an iterator range. * If @c first == @c last, equivalent to the default constructor. * Otherwise, the values of the range represent weights for the * possible values of the distribution. */ template<class Iter> discrete_distribution(Iter first, Iter last) { init(first, last); } #ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST /** * Constructs a @c discrete_distribution from a @c std::initializer_list. * If the @c initializer_list is empty, equivalent to the default * constructor. Otherwise, the values of the @c initializer_list * represent weights for the possible values of the distribution. * For example, given the distribution * * @code * discrete_distribution<> dist{1, 4, 5}; * @endcode * * The probability of a 0 is 1/10, the probability of a 1 is 2/5, * the probability of a 2 is 1/2, and no other values are possible. */ discrete_distribution(std::initializer_list<WeightType> wl) { init(wl.begin(), wl.end()); } #endif /** * Constructs a discrete_distribution from a Boost.Range range. * If the range is empty, equivalent to the default constructor. * Otherwise, the values of the range represent weights for the * possible values of the distribution. */ template<class Range> explicit discrete_distribution(const Range& range) { init(boost::begin(range), boost::end(range)); } /** * Constructs a discrete_distribution that approximates a function. * If nw is zero, equivalent to the default constructor. * Otherwise, the range of the distribution is [0, nw), * and the weights are found by calling fw with values * evenly distributed between \f$\mbox{xmin} + \delta/2\f$ and * \f$\mbox{xmax} - \delta/2\f$, where * \f$\delta = (\mbox{xmax} - \mbox{xmin})/\mbox{nw}\f$. */ template<class Func> discrete_distribution(std::size_t nw, double xmin, double xmax, Func fw) { std::size_t n = (nw == 0) ? 1 : nw; double delta = (xmax - xmin) / n; BOOST_ASSERT(delta > 0); std::vector<WeightType> weights; for(std::size_t k = 0; k < n; ++k) { weights.push_back(fw(xmin + k*delta + delta/2)); } init(weights.begin(), weights.end()); } /** * Constructs a discrete_distribution from its parameters. */ explicit discrete_distribution(const param_type& parm) { param(parm); } /** * Returns a value distributed according to the parameters of the * discrete_distribution. */ template<class URNG> IntType operator()(URNG& urng) const { BOOST_ASSERT(!_impl._alias_table.empty()); IntType result; WeightType test; do { result = uniform_int_distribution<IntType>((min)(), (max)())(urng); test = _impl.test(urng); } while(!_impl.accept(result, test)); if(test < _impl._alias_table[static_cast<std::size_t>(result)].first) { return result; } else { return(_impl._alias_table[static_cast<std::size_t>(result)].second); } } /** * Returns a value distributed according to the parameters * specified by param. */ template<class URNG> IntType operator()(URNG& urng, const param_type& parm) const { if(WeightType limit = impl_type::try_get_sum(parm._probabilities)) { WeightType val = impl_type::generate_in_range(urng, limit); WeightType sum = 0; std::size_t result = 0; for(typename std::vector<WeightType>::const_iterator iter = parm._probabilities.begin(), end = parm._probabilities.end(); iter != end; ++iter, ++result) { sum += *iter; if(sum > val) { return result; } } // This shouldn't be reachable, but round-off error // can prevent any match from being found when val is // very close to 1. return static_cast<IntType>(parm._probabilities.size() - 1); } else { // WeightType is integral and sum(parm._probabilities) // would overflow. Just use the easy solution. return discrete_distribution(parm)(urng); } } /** Returns the smallest value that the distribution can produce. */ result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; } /** Returns the largest value that the distribution can produce. */ result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return static_cast<result_type>(_impl._alias_table.size() - 1); } /** * Returns a vector containing the probabilities of each * value of the distribution. For example, given * * @code * discrete_distribution<> dist = { 1, 4, 5 }; * std::vector<double> p = dist.param(); * @endcode * * the vector, p will contain {0.1, 0.4, 0.5}. * * If @c WeightType is integral, then the weights * will be returned unchanged. */ std::vector<WeightType> probabilities() const { std::vector<WeightType> result(_impl._alias_table.size(), static_cast<WeightType>(0)); std::size_t i = 0; for(typename impl_type::alias_table_t::const_iterator iter = _impl._alias_table.begin(), end = _impl._alias_table.end(); iter != end; ++iter, ++i) { WeightType val = iter->first; result[i] += val; result[static_cast<std::size_t>(iter->second)] += _impl.get_weight(i) - val; } impl_type::normalize(result); return(result); } /** Returns the parameters of the distribution. */ param_type param() const { return param_type(*this); } /** Sets the parameters of the distribution. */ void param(const param_type& parm) { init(parm._probabilities.begin(), parm._probabilities.end()); } /** * Effects: Subsequent uses of the distribution do not depend * on values produced by any engine prior to invoking reset. */ void reset() {} /** Writes a distribution to a @c std::ostream. */ BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, discrete_distribution, dd) { os << dd.param(); return os; } /** Reads a distribution from a @c std::istream */ BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, discrete_distribution, dd) { param_type parm; if(is >> parm) { dd.param(parm); } return is; } /** * Returns true if the two distributions will return the * same sequence of values, when passed equal generators. */ BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(discrete_distribution, lhs, rhs) { return lhs._impl == rhs._impl; } /** * Returns true if the two distributions may return different * sequences of values, when passed equal generators. */ BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(discrete_distribution) private: /// @cond show_private template<class Iter> void init(Iter first, Iter last, std::input_iterator_tag) { std::vector<WeightType> temp(first, last); init(temp.begin(), temp.end()); } template<class Iter> void init(Iter first, Iter last, std::forward_iterator_tag) { size_t input_size = std::distance(first, last); std::vector<std::pair<WeightType, IntType> > below_average; std::vector<std::pair<WeightType, IntType> > above_average; below_average.reserve(input_size); above_average.reserve(input_size); WeightType weight_average = _impl.init_average(first, last); WeightType normalized_average = _impl.get_weight(0); std::size_t i = 0; for(; first != last; ++first, ++i) { WeightType val = impl_type::normalize(*first, weight_average); std::pair<WeightType, IntType> elem(val, static_cast<IntType>(i)); if(val < normalized_average) { below_average.push_back(elem); } else { above_average.push_back(elem); } } typename impl_type::alias_table_t::iterator b_iter = below_average.begin(), b_end = below_average.end(), a_iter = above_average.begin(), a_end = above_average.end() ; while(b_iter != b_end && a_iter != a_end) { _impl._alias_table[static_cast<std::size_t>(b_iter->second)] = std::make_pair(b_iter->first, a_iter->second); a_iter->first -= (_impl.get_weight(b_iter->second) - b_iter->first); if(a_iter->first < normalized_average) { *b_iter = *a_iter++; } else { ++b_iter; } } for(; b_iter != b_end; ++b_iter) { _impl._alias_table[static_cast<std::size_t>(b_iter->second)].first = _impl.get_weight(b_iter->second); } for(; a_iter != a_end; ++a_iter) { _impl._alias_table[static_cast<std::size_t>(a_iter->second)].first = _impl.get_weight(a_iter->second); } } template<class Iter> void init(Iter first, Iter last) { if(first == last) { _impl.init_empty(); } else { typename std::iterator_traits<Iter>::iterator_category category; init(first, last, category); } } typedef typename detail::select_alias_table< (::boost::is_integral<WeightType>::value) >::template apply<IntType, WeightType>::type impl_type; impl_type _impl; /// @endcond }; } } #include <boost/random/detail/enable_warnings.hpp> #endif
10,151
1,443
{ "copyright": "<NAME>", "url": "http://is-uz.com", "email": "<EMAIL>", "format": "txt" }
46
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-r8jj-pf8x-383m", "modified": "2022-04-14T00:00:30Z", "published": "2022-04-07T00:00:20Z", "aliases": [ "CVE-2022-23446" ], "details": "A improper control of a resource through its lifetime in Fortinet FortiEDR version 5.0.3 and earlier allows attacker to make the whole application unresponsive via changing its root directory access permission.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:L/PR:H/UI:N/S:U/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23446" }, { "type": "WEB", "url": "https://fortiguard.com/psirt/FG-IR-22-052" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
432
672
<gh_stars>100-1000 /* * Copyright (c) 2004 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <unistd.h> #include <stdarg.h> #include <sys/sem.h> #include <errno.h> /* * Because KERNEL is defined, including errno.h doesn't define errno, so * we have to do it ourselves. */ extern int * __error(void); #define errno (*__error()) /* * Legacy stub to account for the differences in the ipc_perm structure, * while maintaining binary backward compatibility. */ extern int __semctl(int semid, int semnum, int cmd, void *); int semctl(int semid, int semnum, int cmd, ...) { va_list ap; int rv; int val = 0; struct __semid_ds_new ds; struct __semid_ds_new *ds_new = &ds; struct __semid_ds_old *ds_old = NULL; va_start(ap, cmd); if (cmd == SETVAL) val = va_arg(ap, int); else ds_old = va_arg(ap, struct __semid_ds_old *); va_end(ap); #define _UP_CVT(x) ds_new-> x = ds_old-> x #define _DN_CVT(x) ds_old-> x = ds_new-> x if ((cmd == IPC_SET || cmd == IPC_STAT) && ds_old == NULL) { /* Return EFAULT if ds_old is NULL (like the kernel would do) */ errno = EFAULT; return -1; } if (cmd == IPC_SET) { /* convert before call */ _UP_CVT(sem_perm.uid); _UP_CVT(sem_perm.gid); _UP_CVT(sem_perm.cuid); _UP_CVT(sem_perm.cgid); _UP_CVT(sem_perm.mode); ds_new->sem_perm._seq = ds_old->sem_perm.seq; ds_new->sem_perm._key = ds_old->sem_perm.key; _UP_CVT(sem_base); _UP_CVT(sem_nsems); _UP_CVT(sem_otime); _UP_CVT(sem_pad1); /* binary compatibility */ _UP_CVT(sem_ctime); _UP_CVT(sem_pad2); /* binary compatibility */ _UP_CVT(sem_pad3[0]); /* binary compatibility */ _UP_CVT(sem_pad3[1]); /* binary compatibility */ _UP_CVT(sem_pad3[2]); /* binary compatibility */ _UP_CVT(sem_pad3[3]); /* binary compatibility */ } switch (cmd) { case SETVAL: /* syscall must use LP64 quantities */ rv = __semctl(semid, semnum, cmd, (void *)val); break; case IPC_SET: case IPC_STAT: rv = __semctl(semid, semnum, cmd, ds_new); break; default: rv = __semctl(semid, semnum, cmd, ds_old); break; } if (cmd == IPC_STAT) { /* convert after call */ _DN_CVT(sem_perm.uid); /* warning! precision loss! */ _DN_CVT(sem_perm.gid); /* warning! precision loss! */ _DN_CVT(sem_perm.cuid); /* warning! precision loss! */ _DN_CVT(sem_perm.cgid); /* warning! precision loss! */ _DN_CVT(sem_perm.mode); ds_old->sem_perm.seq = ds_new->sem_perm._seq; ds_old->sem_perm.key = ds_new->sem_perm._key; _DN_CVT(sem_base); _DN_CVT(sem_nsems); _DN_CVT(sem_otime); _DN_CVT(sem_pad1); /* binary compatibility */ _DN_CVT(sem_ctime); _DN_CVT(sem_pad2); /* binary compatibility */ _DN_CVT(sem_pad3[0]); /* binary compatibility */ _DN_CVT(sem_pad3[1]); /* binary compatibility */ _DN_CVT(sem_pad3[2]); /* binary compatibility */ _DN_CVT(sem_pad3[3]); /* binary compatibility */ } return (rv); }
1,549
574
# -*- coding: utf-8 -*- import unittest class DictTest(unittest.TestCase): def test_modify_in_loop(self): data = dict( a=dict() ) for key, value in data.items(): value['b'] = 1 print(data)
134
2,366
/* * ============================================================================= * * Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org) * * 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.thymeleaf.processor.processinginstruction; import org.thymeleaf.model.IModel; /** * <p> * Structure handler class meant to be used by {@link IProcessingInstructionProcessor} implementations. * </p> * <p> * Structure handlers allow processors to instruct the engine to perform a series of actions that cannot * be done directly from the processors themselves, usually because these actions are applied or have effects * on scopes broader than the processed events themselves. * </p> * * @author <NAME> * @see IProcessingInstructionProcessor * @since 3.0.0 * */ public interface IProcessingInstructionStructureHandler { /** * <p> * Resets all actions specified so far for the current processor execution. * </p> */ public void reset(); /** * <p> * Instructs the engine to set new values into the properties of the ProcessingInstruction event being processed. * </p> * * @param target the new target value * @param content the new content value */ public void setProcessingInstruction(final String target, final String content); /** * <p> * Instructs the engine to replace the current event with the specified model (a {@link IModel}). * </p> * * @param model the model to be used as a replacement. * @param processable whether the model should be considered <em>processable</em> or not. */ public void replaceWith(final IModel model, final boolean processable); /** * <p> * Instructs the engine to remove the entire event that is being processed. * </p> */ public void removeProcessingInstruction(); }
747
421
<filename>samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Application.EnableVisualStyles/CPP/form1.cpp //<Snippet1> #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; namespace VStyles { public ref class Form1: public System::Windows::Forms::Form { private: System::Windows::Forms::Button^ button1; public: Form1() { this->button1 = gcnew System::Windows::Forms::Button; this->button1->Location = System::Drawing::Point( 24, 16 ); this->button1->Size = System::Drawing::Size( 120, 100 ); this->button1->FlatStyle = FlatStyle::System; this->button1->Text = "I am themed."; // Sets up how the form should be displayed and adds the controls to the form. this->ClientSize = System::Drawing::Size( 300, 286 ); this->Controls->Add( this->button1 ); this->Text = "Application::EnableVisualStyles Example"; } }; } [STAThread] int main() { Application::EnableVisualStyles(); Application::Run( gcnew VStyles::Form1 ); } //</Snippet1>
527
1,788
<filename>nft-admin/src/main/java/com/fingerchar/service/NftEventService.java package com.fingerchar.service; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.web3j.abi.datatypes.generated.Uint256; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.fingerchar.base.entity.BaseEntity; import com.fingerchar.base.service.IBaseService; import com.fingerchar.constant.CommonStatus; import com.fingerchar.constant.NoticeType; import com.fingerchar.constant.SysConfConstant; import com.fingerchar.dao.ext.FcOrderLogExtMapper; import com.fingerchar.domain.FcContractNft; import com.fingerchar.domain.FcNftItems; import com.fingerchar.domain.FcOrder; import com.fingerchar.domain.FcOrderLog; import com.fingerchar.domain.FcPayToken; import com.fingerchar.domain.FcSystem; import com.fingerchar.domain.FcTxOrder; import com.fingerchar.utils.NftDappEventUtils; import com.fingerchar.vo.EventValuesExt; @Service public class NftEventService { private static final Logger logger = LoggerFactory.getLogger(NftEventService.class); public static final String ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; @Autowired private IBaseService baseService; @Autowired FcOrderLogExtMapper orderLogExtMapper; @Autowired FcNoticeService noticeService; @Autowired FcSystemConfigService configService; @Transactional(rollbackFor = Exception.class) public void processEvent(Map<String, List<EventValuesExt>> map, String block) throws Exception { if (map.isEmpty()) { this.saveLastBlock(block); return; } List<FcOrderLog> list = new ArrayList<>(); List<EventValuesExt> valueList = sortLog(map.get(NftDappEventUtils.BUY_EVENT.getName())); Map<String, Integer> orderTypeMap = new HashMap<>(); if(null != valueList && !valueList.isEmpty()) { this.processBuyEvent(valueList, list, orderTypeMap); } String exchangeToken = this.configService.get(SysConfConstant.NFT_EXCHANGE); if (StringUtils.isEmpty(exchangeToken)) { throw new Exception("Unkown nft exchange token"); } valueList = sortLog(map.get(NftDappEventUtils.CANCEL_EVENT.getName())); if(null != valueList && !valueList.isEmpty()) { this.processCancelEvent(valueList, list); } valueList = sortLog(map.get(NftDappEventUtils.TRANSFER_EVENT.getName())); if(null != valueList && !valueList.isEmpty()) { Map<String, List<EventValuesExt>> valueMap = new HashMap<>(); valueList.stream().forEach(vo -> { if (null == valueMap.get(vo.getTxHash())) { valueMap.put(vo.getTxHash(), new ArrayList<>()); } valueMap.get(vo.getTxHash()).add(vo); }); this.processTransferEvent(valueMap, list, orderTypeMap); } valueList = sortLog(map.get(NftDappEventUtils.SECONDARYSALEFEES_EVENT.getName())); if(null != valueList && !valueList.isEmpty()) { this.processRoyaltiesEvent(valueList); } this.addOrderLog(list); this.saveLastBlock(block); } private List<EventValuesExt> sortLog(List<EventValuesExt> list) { if (null == list) { return null; } Collections.sort(list, new Comparator<EventValuesExt>() { public int compare(EventValuesExt val1, EventValuesExt val2) { return val1.getBlockNumber().compareTo(val2.getBlockNumber()); } }); return list; } @Transactional(rollbackFor = Exception.class) private void processRoyaltiesEvent(List<EventValuesExt> valueList) { if (valueList.isEmpty()) { return; } int len = valueList.size(); for (int i = 0; i < len; i++) { this.processRoyaltiesEvent(valueList.get(i)); } } @Transactional(rollbackFor = Exception.class) private void processRoyaltiesEvent(EventValuesExt eventValues) { BigInteger tokenId = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); @SuppressWarnings("unchecked") List<Uint256> bps = (List<Uint256>) eventValues.getNonIndexedValues().get(2).getValue(); QueryWrapper<FcContractNft> wrapper = new QueryWrapper<>(); wrapper.eq(FcContractNft.ADDRESS, eventValues.getAddress()) .eq(FcContractNft.TOKEN_ID, tokenId.toString()); List<FcContractNft> nftList = this.baseService.findByCondition(FcContractNft.class, wrapper); if (null == nftList || nftList.isEmpty()) { return; } Set<Long> idSet = nftList.stream().map(FcContractNft::getId).collect(Collectors.toSet()); UpdateWrapper<FcContractNft> uwrapper = new UpdateWrapper<>(); List<Long> bpsTemp = bps.stream().map(bi -> bi.getValue().longValueExact()).collect(Collectors.toList()); uwrapper.set(FcContractNft.ROYALTIES, JSON.toJSONString(bpsTemp)); uwrapper.in(BaseEntity.ID, idSet); this.baseService.updateByCondition(FcContractNft.class, uwrapper); } @Transactional(rollbackFor = Exception.class) private void addOrderLog(List<FcOrderLog> logList) { if (logList.size() > 0) { this.baseService.saveBatch(logList); Set<String> txHashList = logList.stream().map(FcOrderLog::getTxHash).collect(Collectors.toSet()); if (txHashList.size() > 0) { UpdateWrapper<FcTxOrder> wrapper = new UpdateWrapper<>(); wrapper.set(FcTxOrder.IS_SYNC, true); wrapper.in(FcTxOrder.TX_HASH, txHashList); this.baseService.updateByCondition(FcTxOrder.class, wrapper); } } } @Transactional(rollbackFor = Exception.class) private void processBuyEvent(List<EventValuesExt> buyList, List<FcOrderLog> logList, Map<String, Integer> orderTypeMap) throws Exception { if (buyList.isEmpty()) { return; } int len = buyList.size(); for (int i = 0; i < len; i++) { this.processBuyEvent(buyList.get(i), logList, orderTypeMap); } } @Transactional(rollbackFor = Exception.class) private void processBuyEvent(EventValuesExt eventValue, List<FcOrderLog> logList, Map<String, Integer> orderTypeMap) throws Exception { String txHash = eventValue.getTxHash(); FcTxOrder txOrder = this.getByHash(txHash); if (null != txOrder) { logger.warn("tx_hash为" + txHash + "已经处理!"); return; } String sellToken = (String) eventValue.getIndexedValues().get(0).getValue(); BigInteger sellTokenId = (BigInteger) eventValue.getIndexedValues().get(1).getValue(); BigInteger sellValue = (BigInteger) eventValue.getNonIndexedValues().get(0).getValue(); String owner = (String) eventValue.getNonIndexedValues().get(1).getValue(); String buyToken = (String) eventValue.getNonIndexedValues().get(2).getValue(); BigInteger buyTokenId = (BigInteger) eventValue.getNonIndexedValues().get(3).getValue(); BigInteger buyValue = (BigInteger) eventValue.getNonIndexedValues().get(4).getValue(); String buyer = (String) eventValue.getNonIndexedValues().get(5).getValue(); BigInteger salt = (BigInteger) eventValue.getNonIndexedValues().get(7).getValue(); FcOrder order = null; QueryWrapper<FcOrder> wrapper = new QueryWrapper<>(); wrapper.eq(FcOrder.SELL_TOKEN, sellToken) .eq(FcOrder.SELL_TOKEN_ID, sellTokenId.toString()) .eq(FcOrder.SALT, salt.toString()) .eq(FcOrder.OWNER, owner) .eq(FcOrder.BUYER_TOKEN, buyToken) .eq(FcOrder.BUYER_TOKEN_ID, buyTokenId.toString()); order = this.baseService.getByCondition(FcOrder.class, wrapper); boolean isMissing = false; if (null == order) { logger.warn("要完成的order未找到, 开始生成order信息=>" + JSON.toJSONString(eventValue)); order = this.createMissingOrder(sellToken, sellValue, sellTokenId, buyToken, buyValue, buyTokenId, owner, salt); isMissing = true; } else { if (!isMissing) { if (order.getDeleted()) { logger.warn("此order已经处理=>" + JSON.toJSONString(eventValue)); return; } } QueryWrapper<FcOrderLog> logWrapper = new QueryWrapper<>(); logWrapper.eq(FcOrderLog.TX_HASH, txHash); FcOrderLog log = this.baseService.getByCondition(FcOrderLog.class, logWrapper); if (null != log) { logger.warn("此order已经处理=>" + JSON.toJSONString(eventValue)); return; } if (order.getOrderType().intValue() == 1) { orderTypeMap.put(txHash, CommonStatus.getStatusByName("Buy").getType()); this.processBuyEvent(owner, sellToken, sellTokenId, txHash, buyer, null != txOrder, logList, order, eventValue.getTimestamp().longValueExact()); } else { orderTypeMap.put(txHash, CommonStatus.getStatusByName("Accept bid").getType()); this.processBuyEvent(owner, buyToken, buyTokenId, txHash, buyer, null != txOrder, logList, order, eventValue.getTimestamp().longValueExact()); } } } @Transactional(rollbackFor = Exception.class) private void processBuyEvent(String owner, String token, BigInteger tokenId, String txHash, String buyer, Boolean hasTxOrder, List<FcOrderLog> logList, FcOrder order, Long timestamp) { UpdateWrapper<FcOrder> updateWrapper = new UpdateWrapper<>(); updateWrapper.set(FcOrder.SELLS, 1); updateWrapper.eq(FcOrder.ID, order.getId()); updateWrapper.set(FcOrder.STATUS, 1).set(FcOrder.EXPIRED, true).set(FcOrder.DELETED, true); if (order.getOrderType().intValue() == 2) { this.expiredBidLog(order.getId()); } this.baseService.updateByCondition(FcOrder.class, updateWrapper); QueryWrapper<FcContractNft> nftQueryWrapper = new QueryWrapper<>(); nftQueryWrapper.eq(FcContractNft.ADDRESS, token).eq(FcContractNft.TOKEN_ID, tokenId); FcContractNft nft = this.baseService.getByCondition(FcContractNft.class, nftQueryWrapper); Integer type = null; String image = null; String name = null; if (null != nft) { image = nft.getImgUrl(); name = nft.getName(); } if (order.getOrderType().intValue() == 1) { type = CommonStatus.getStatusByName("Buy").getType(); } else { type = CommonStatus.getStatusByName("Accept bid").getType(); } logList.add(this.createBuyLog(owner, token, tokenId, buyer, txHash, type, order, timestamp)); if (!hasTxOrder) { this.addTxOrder(txHash); } this.addBuyNotice(order, txHash, buyer, image, name); } @Transactional(rollbackFor = Exception.class) private FcOrder createMissingOrder(String sellToken, BigInteger sellValue, BigInteger sellTokenId, String buyToken, BigInteger buyValue, BigInteger buyTokenId, String owner, BigInteger salt) { FcPayToken token = this.getPayToken(sellToken); Integer type = 1; if (null == token) { type = 2; } FcOrder order = new FcOrder(); order.setBuyerToken(buyToken); order.setBuyerTokenId(buyTokenId.toString()); order.setBuyerValue(buyValue.toString()); order.setOwner(owner); order.setSalt(salt.toString()); order.setSellToken(sellToken); order.setSellTokenId(sellTokenId.toString()); order.setSellValue(sellValue.toString()); order.setStatus(1); order.setExpired(true); order.setDeleted(true); order.setOrderType(type); this.baseService.save(order); return order; } @Transactional(rollbackFor = Exception.class) private void addBuyNotice(FcOrder order, String txHash, String buyer, String image, String name) { try { Map<String, Object> content = new HashMap<>(); content.put("price", order.getBuyerValue()); content.put("sellerAddr", order.getOwner()); content.put("buyerAddr", buyer); content.put("txHash", txHash); content.put("amount", String.valueOf(1)); String noticeType = NoticeType.getNoticeTypeByName("Trade").getType().toString(); if (order.getOrderType() == 1) { FcPayToken payToken = this.getPayToken(order.getBuyerToken()); content.put("priceUint", payToken.getSymbol()); content.put("quantity", order.getSellValue()); content.put("sellerAddr", order.getOwner()); content.put("token", order.getSellToken()); content.put("tokenId", order.getSellTokenId()); Integer type = CommonStatus.getStatusByName("Buy").getType(); this.noticeService.insertNotice(content, order.getOwner(), type.toString(), image, name, noticeType, buyer); type = CommonStatus.getStatusByName("Bought").getType(); this.noticeService.insertNotice(content, buyer, type.toString(), image, name, noticeType, buyer); } else { FcPayToken payToken = this.getPayToken(order.getSellToken()); content.put("priceUint", payToken.getSymbol()); content.put("quantity", order.getBuyerValue()); content.put("buyerAddr", buyer); content.put("token", order.getBuyerToken()); content.put("tokenId", order.getBuyerTokenId()); Integer type = CommonStatus.getStatusByName("Accept bid").getType(); this.noticeService.insertNotice(content, order.getOwner(), type.toString(), image, name, noticeType, buyer); type = CommonStatus.getStatusByName("Bidden").getType(); this.noticeService.insertNotice(content, buyer, type.toString(), image, name, noticeType, buyer); } } catch (Exception e) { logger.error("插入购买消息异常", e); } } @Transactional(rollbackFor = Exception.class) private void expiredSaleOrder(String sellToken, Long sellTokenId, String owner) { UpdateWrapper<FcOrder> wrapper = new UpdateWrapper<>(); wrapper.eq(FcOrder.SELL_TOKEN, sellToken) .eq(FcOrder.ORDER_TYPE, 1) .eq(FcOrder.SELL_TOKEN_ID, sellTokenId) .eq(FcOrder.OWNER, owner) .eq(BaseEntity.DELETED, false) .eq(FcOrder.EXPIRED, false); wrapper.set(BaseEntity.DELETED, true); wrapper.set(FcOrder.EXPIRED, true); this.baseService.updateByCondition(FcOrder.class, wrapper); } @Transactional(rollbackFor = Exception.class) private void expiredBidLog(Long orderId) { this.orderLogExtMapper.updateByOrderId(orderId); } @Transactional(rollbackFor = Exception.class) private FcOrderLog createBuyLog(String owner, String token, BigInteger tokenId, String buyer, String txHash, Integer type, FcOrder order, Long timestamp) { FcOrderLog log = new FcOrderLog(); log.setFrom(owner); log.setOrderId(order.getId()); log.setPreLogId(0L); log.setTo(buyer); log.setTxHash(txHash); log.setType(type); log.setToken(token); log.setTokenId(tokenId.toString()); order.setSells(1L); log.setContent(JSON.toJSONString(order)); log.setExpired(false); log.setDeleted(false); log.setCreateTime(timestamp); log.setUpdateTime(timestamp); return log; } @Transactional(rollbackFor = Exception.class) private void processCancelEvent(List<EventValuesExt> cancelList, List<FcOrderLog> logList) throws Exception { if (cancelList.isEmpty()) { return; } int len = cancelList.size(); for (int i = 0; i < len; i++) { this.processCancelEvent(cancelList.get(i), logList); } } @Transactional(rollbackFor = Exception.class) private void processCancelEvent(EventValuesExt eventValue, List<FcOrderLog> logList) throws Exception { String txHash = eventValue.getTxHash(); FcTxOrder txOrder = this.getByHash(txHash); if (null != txOrder) { logger.warn("tx_hash为" + txHash + "已经处理!"); return; } String sellToken = (String) eventValue.getIndexedValues().get(0).getValue(); BigInteger sellTokenId = (BigInteger) eventValue.getIndexedValues().get(1).getValue(); String owner = (String) eventValue.getNonIndexedValues().get(0).getValue(); String buyToken = (String) eventValue.getNonIndexedValues().get(1).getValue(); BigInteger buyTokenId = (BigInteger) eventValue.getNonIndexedValues().get(2).getValue(); BigInteger salt = (BigInteger) eventValue.getNonIndexedValues().get(3).getValue(); FcOrder order = null; QueryWrapper<FcOrder> wrapper = new QueryWrapper<>(); wrapper.eq(FcOrder.SELL_TOKEN, sellToken) .eq(FcOrder.SELL_TOKEN_ID, sellTokenId.toString()) .eq(FcOrder.SALT, salt.toString()) .eq(FcOrder.OWNER, owner) .eq(FcOrder.BUYER_TOKEN, buyToken) .eq(FcOrder.BUYER_TOKEN_ID, buyTokenId.toString()); wrapper.orderByDesc(BaseEntity.ID); order = this.baseService.getByCondition(FcOrder.class, wrapper); if (null == order) { logger.warn("要取消的order未找到,跳过, order信息=>" + JSON.toJSONString(eventValue)); } else { if (order.getDeleted()) { logger.warn("此order已经处理=>" + JSON.toJSONString(eventValue)); return; } Integer type = null; if (order.getOrderType().intValue() == 1) { type = CommonStatus.getStatusByName("Cancel sale").getType(); this.processCancelEvent(owner, sellToken, sellTokenId, txHash, order, null != txOrder); } else { type = CommonStatus.getStatusByName("Cancel bid").getType(); this.processCancelEvent(owner, buyToken, buyTokenId, txHash, order, null != txOrder); } UpdateWrapper<FcOrder> updateWrapper = new UpdateWrapper<>(); updateWrapper.eq(BaseEntity.ID, order.getId()); updateWrapper.set(FcOrder.EXPIRED, true) .set(FcOrder.STATUS, 2) .set(BaseEntity.DELETED, true); this.baseService.updateByCondition(FcOrder.class, updateWrapper); this.orderLogExtMapper.updateByOrderId(order.getId()); logList.add(this.createCancelLog(owner, txHash, type, order, eventValue.getTimestamp().longValueExact())); } } @Transactional(rollbackFor = Exception.class) private void processCancelEvent(String owner, String token, BigInteger tokenId, String txHash, FcOrder order, boolean hasTxOrder) { FcContractNft nft = null; QueryWrapper<FcContractNft> nftQueryWrapper = new QueryWrapper<>(); nftQueryWrapper.eq(FcContractNft.ADDRESS, token) .eq(FcContractNft.TOKEN_ID, tokenId.toString()) .eq(BaseEntity.DELETED, false); nft = this.baseService.getByCondition(FcContractNft.class, nftQueryWrapper); Integer type = null; FcPayToken payToken = null; Map<String, Object> content = new HashMap<>(); if (order.getOrderType().intValue() == 1) { if (null == nft) { logger.warn("nft未找到:token=>" + token + "; tokenId=>" + tokenId.toString()); return; } QueryWrapper<FcNftItems> itemsQueryWrapper = new QueryWrapper<>(); itemsQueryWrapper.eq(FcNftItems.NFT_ID, nft.getId()) .eq(FcNftItems.ADDRESS, token) .eq(FcNftItems.ITEM_OWNER, owner) .eq(BaseEntity.DELETED, false); FcNftItems items = this.baseService.getByCondition(FcNftItems.class, itemsQueryWrapper); if (null == items) { logger.warn("nft-item未找到:token=>" + token + "; tokenId=>" + tokenId.toString() + "; owner=>" + owner); return; } UpdateWrapper<FcNftItems> itemsUpdateWrapper = new UpdateWrapper<>(); itemsUpdateWrapper.set(FcNftItems.PRICE, "0") .set(FcNftItems.USDT_PRICE, 0L) .set(FcNftItems.ONSELL, false) .set(FcNftItems.SELL_QUANTITY, 0) .set(FcNftItems.PAYTOKEN_ADDRESS, ""); itemsUpdateWrapper.eq(BaseEntity.ID, items.getId()); this.baseService.updateByCondition(FcNftItems.class, itemsUpdateWrapper); type = CommonStatus.getStatusByName("Cancel sale").getType(); payToken = this.getPayToken(order.getBuyerToken()); content.put("price", order.getBuyerValue()); content.put("quantity", order.getSellValue()); } else { UpdateWrapper<FcOrderLog> logUpdateWrapper = new UpdateWrapper<>(); logUpdateWrapper.eq(FcOrderLog.TOKEN, token) .eq(FcOrderLog.TOKEN_ID, tokenId.toString()) .eq(FcOrderLog.FROM, owner) .eq(FcOrderLog.EXPIRED, false); logUpdateWrapper.set(FcOrderLog.EXPIRED, true); this.baseService.updateByCondition(FcOrderLog.class, logUpdateWrapper); type = CommonStatus.getStatusByName("Cancel bid").getType(); payToken = this.getPayToken(order.getSellToken()); content.put("price", order.getSellValue()); content.put("quantity", order.getBuyerValue()); } content.put("priceUint", payToken.getSymbol()); content.put("sellerAddr", order.getOwner()); content.put("token", token); content.put("tokenId", tokenId); content.put("txHash", txHash); this.addCancelNotice(content, nft, type, owner); if (!hasTxOrder) { this.addTxOrder(txHash); } } @Transactional private void addCancelNotice(Map<String, Object> content, FcContractNft nft, Integer type, String owner) { try { String image = null; String name = null; String noticeType = NoticeType.getNoticeTypeByName("Trade").getType().toString(); if (null != nft) { image = nft.getImgUrl(); name = nft.getName(); QueryWrapper<FcNftItems> wrapper = new QueryWrapper<>(); wrapper.eq(FcNftItems.NFT_ID, nft.getId()) .eq(BaseEntity.DELETED, false); FcNftItems item = this.baseService.getByCondition(FcNftItems.class, wrapper); this.noticeService.insertNotice(content, item.getItemOwner(), type.toString(), image, name, noticeType, owner); } this.noticeService.insertNotice(content, owner, type.toString(), image, name, noticeType, owner); } catch (Exception e) { logger.error("插入取消消息异常", e); } } @Transactional(rollbackFor = Exception.class) private FcOrderLog createCancelLog(String owner, String txHash, Integer type, FcOrder order, Long timestamp) { FcOrderLog log = new FcOrderLog(); log.setFrom(owner); log.setOrderId(order.getId()); log.setPreLogId(0L); log.setTo(""); if (order.getOrderType().intValue() == 1) { log.setToken(order.getSellToken()); log.setTokenId(order.getSellTokenId()); } else { log.setToken(order.getBuyerToken()); log.setTokenId(order.getBuyerTokenId()); } log.setTxHash(txHash); log.setContent(JSON.toJSONString(order)); log.setType(type); log.setExpired(false); log.setDeleted(false); log.setCreateTime(timestamp); log.setUpdateTime(timestamp); return log; } @Transactional(rollbackFor = Exception.class) private void processTransferEvent(Map<String, List<EventValuesExt>> valueMap, List<FcOrderLog> logList, Map<String, Integer> orderTypeMap) throws Exception { if (valueMap.isEmpty()) { return; } Iterator<String> it = valueMap.keySet().iterator(); List<EventValuesExt> transferList = null; String txHash = null; int len = 0; while (it.hasNext()) { txHash = it.next(); FcTxOrder txOrder = this.getByHash(txHash); if (null != txOrder && txOrder.getIsSync()) { logger.warn("tx_hash为" + txHash + "已经同步!"); continue; } transferList = valueMap.get(txHash); len = transferList.size(); for (int i = 0; i < len; i++) { this.processTransferEvent(transferList.get(i), logList, orderTypeMap); } Integer type = orderTypeMap.get(txHash); if (null == type) { if (null == txOrder) { this.addTxOrder(txHash); } } } } @Transactional(rollbackFor = Exception.class) private void addTxOrder(String txHash) { FcTxOrder txOrder = new FcTxOrder(); txOrder = new FcTxOrder(); txOrder.setTxHash(txHash); txOrder.setIsSync(false); this.baseService.save(txOrder); } @Transactional(rollbackFor = Exception.class) private void processTransferEvent(EventValuesExt eventValues, List<FcOrderLog> logList, Map<String, Integer> orderTypeMap) throws Exception { String txHash = eventValues.getTxHash(); logger.info("721转移事件"); String from = (String) eventValues.getIndexedValues().get(0).getValue(); String to = (String) eventValues.getIndexedValues().get(1).getValue(); BigInteger tokenId = (BigInteger) eventValues.getIndexedValues().get(2).getValue(); String address = eventValues.getAddress(); Map<String, Object> content = new HashMap<>(); content.put("token", address); content.put("tokenId", tokenId); content.put("from", from); content.put("to", to); content.put("txHash", txHash); Integer type = null; if (ZERO_ADDRESS.equals(from) && !ZERO_ADDRESS.equals(to)) { type = CommonStatus.getStatusByName("Mint").getType(); if (this.processMint(address, tokenId, to, content, type, txHash, eventValues.getTimestamp().longValueExact())) { logList.add(this.createTransferLog(from, to, txHash, tokenId, type, eventValues, address)); } } else if (!ZERO_ADDRESS.equals(from) && ZERO_ADDRESS.equals(to)) { type = CommonStatus.getStatusByName("Burn").getType(); if (this.processBurn(address, tokenId, from, content, type)) { logList.add(this.createTransferLog(from, to, txHash, tokenId, type, eventValues, address)); } } else { Integer orderType = orderTypeMap.get(txHash); boolean result = false; if (null == orderType) { result = this.processTransfer(address, tokenId, from, to, content, txHash, null, eventValues.getTimestamp().longValueExact()); } else { result = this.processTransfer(address, tokenId, from, to, content, txHash, orderType, eventValues.getTimestamp().longValueExact()); } if (result) { if (null == orderType) { type = CommonStatus.getStatusByName("Transfer").getType(); logList.add(this.createTransferLog(from, to, txHash, tokenId, type, eventValues, address)); } } } } private FcPayToken getPayToken(String token) { QueryWrapper<FcPayToken> wrapper = new QueryWrapper<>(); wrapper.eq(FcPayToken.ADDRESS, token); FcPayToken payToken = this.baseService.getByCondition(FcPayToken.class, wrapper); return payToken; } @Transactional(rollbackFor = Exception.class) private FcOrderLog createTransferLog(String from, String to, String txHash, BigInteger tokenId, Integer type, EventValuesExt eventvalue, String token) { FcOrderLog log = new FcOrderLog(); log.setFrom(from); log.setOrderId(null); log.setPreLogId(0L); log.setTo(to); log.setToken(token); log.setContent(JSON.toJSONString(eventvalue)); log.setTokenId(tokenId.toString()); log.setTxHash(txHash); log.setType(type); log.setExpired(false); log.setDeleted(false); log.setCreateTime(eventvalue.getTimestamp().longValueExact()); log.setUpdateTime(eventvalue.getTimestamp().longValueExact()); return log; } @Transactional(rollbackFor = Exception.class) private boolean processTransfer(String address, BigInteger tokenId, String from, String to, Map<String, Object> content, String txHash, Integer orderType, Long time) throws Exception { QueryWrapper<FcContractNft> wrapper = new QueryWrapper<>(); wrapper.eq(FcContractNft.ADDRESS, address) .eq(FcContractNft.TOKEN_ID, tokenId.toString()) .eq(BaseEntity.DELETED, false); FcContractNft nft = this.baseService.getByCondition(FcContractNft.class, wrapper); if (null == nft) { logger.warn("需要转移的nft未找到, 开始生成:token=>" + address + "; tokenId=>" + tokenId.toString()); nft = this.createMissingNft(address, tokenId, from, to, txHash, time); } QueryWrapper<FcNftItems> itemsWrapper = new QueryWrapper<>(); itemsWrapper.eq(FcNftItems.NFT_ID, nft.getId()).eq(FcNftItems.ITEM_OWNER, from); this.baseService.deleteByCondition(FcNftItems.class, itemsWrapper); this.incQuantity(nft, to); if (null == orderType) { try { Integer type = CommonStatus.getStatusByName("Transfer").getType(); String noticeType = NoticeType.getNoticeTypeByName("Trade").getType().toString(); this.noticeService.insertNotice(content, from, type.toString(), nft.getImgUrl(), nft.getName(), noticeType, from); type = CommonStatus.getStatusByName("Receive").getType(); this.noticeService.insertNotice(content, to, type.toString(), nft.getImgUrl(), nft.getName(), noticeType, from); } catch (Exception e) { logger.error("插入转移消息异常", e); } } return true; } @Transactional(rollbackFor = Exception.class) private FcContractNft createMissingNft(String address, BigInteger tokenId, String from, String to, String txHash, Long time) { FcContractNft nft = new FcContractNft(); nft.setAddress(address); nft.setNftVerify(1); nft.setTokenId(tokenId.toString()); nft.setQuantity(1L); nft.setIsSync(true); nft.setRoyalties(""); nft.setDeleted(false); nft.setType(3); nft.setTxHash(txHash); Boolean isMint = NftEventService.ZERO_ADDRESS.equals(from) && !NftEventService.ZERO_ADDRESS.equals(to); if (isMint) { nft.setCreator(to); } else { nft.setCreator(from); } nft.setCategoryId(1L); nft.setCreateTime(time); nft.setUpdateTime(time); this.baseService.save(nft); return nft; } @Transactional(rollbackFor = Exception.class) private FcNftItems addMissingItems(FcContractNft nft, String from, String to, Long time) { FcNftItems items = new FcNftItems(); items.setNftId(nft.getId()); items.setName(nft.getName()); items.setDescription(nft.getDescription()); items.setImgUrl(nft.getImgUrl()); if (ZERO_ADDRESS == from) { items.setItemOwner(to); } else { items.setItemOwner(from); } items.setQuantity(1L); items.setStorageId(nft.getStorageId()); items.setDeleted(false); items.setAddress(nft.getAddress()); items.setIsSync(true); items.setCategoryId(nft.getCategoryId()); items.setOnsell(false); items.setCreateTime(time); items.setUpdateTime(time); items.setTokenId(nft.getTokenId()); this.baseService.save(items); return items; } @Transactional(rollbackFor = Exception.class) private boolean processMint(String address, BigInteger tokenId, String to, Map<String, Object> content, Integer type, String txHash, Long time) throws Exception { logger.info("增发事件"); QueryWrapper<FcContractNft> nftQueryWrapper = new QueryWrapper<>(); nftQueryWrapper.eq(FcContractNft.ADDRESS, address) .eq(FcContractNft.TOKEN_ID, tokenId.toString()) .eq(BaseEntity.DELETED, false); FcContractNft nft = this.baseService.getByCondition(FcContractNft.class, nftQueryWrapper); boolean isMissing = false; if (null == nft) { logger.warn("nft未找到:token=>" + address + "; tokenId=>" + tokenId); nft = this.createMissingNft(address, tokenId, ZERO_ADDRESS, to, txHash, time); isMissing = true; } if (nft.getIsSync() && !isMissing) { logger.warn("nft已经存在:token=>" + address + "; tokenId=>" + tokenId); } QueryWrapper<FcNftItems> wrapper = new QueryWrapper<>(); wrapper.eq(FcNftItems.NFT_ID, nft.getId()) .eq(FcNftItems.ADDRESS, nft.getAddress()) .eq(FcNftItems.ITEM_OWNER, to) .eq(BaseEntity.DELETED, false); FcNftItems items = this.baseService.getByCondition(FcNftItems.class, wrapper); UpdateWrapper<FcContractNft> nftUpdateWrapper = new UpdateWrapper<>(); UpdateWrapper<FcNftItems> itemsUpdateWrapper = new UpdateWrapper<>(); if (null == items) { logger.warn("nft-item未找到:token=>" + address + "; tokenId=>" + tokenId + "; owner=>" + to); items = this.addMissingItems(nft, ZERO_ADDRESS, to, time); } else { if (!items.getItemOwner().equals(to)) { logger.warn("nft-item:token=>" + address + "; tokenId=>" + tokenId + "已经存在,但不属于" + to); return false; } if (isMissing) { itemsUpdateWrapper.set(FcNftItems.NFT_ID, nft.getId()); } } nftUpdateWrapper.set(FcContractNft.IS_SYNC, true); nftUpdateWrapper.eq(BaseEntity.ID, nft.getId()); this.baseService.updateByCondition(FcContractNft.class, nftUpdateWrapper); itemsUpdateWrapper.set(FcNftItems.IS_SYNC, true); itemsUpdateWrapper.eq(BaseEntity.ID, items.getId()); this.baseService.updateByCondition(FcNftItems.class, itemsUpdateWrapper); try { String noticeType = NoticeType.getNoticeTypeByName("Trade").getType().toString(); this.noticeService.insertNotice(content, to, type.toString(), nft.getImgUrl(), nft.getName(), noticeType, to); } catch (Exception e) { logger.error("插入增发消息异常", e); } return true; } @Transactional(rollbackFor = Exception.class) private boolean processBurn(String address, BigInteger tokenId, String from, Map<String, Object> content, Integer type) throws Exception { logger.info("销毁事件"); QueryWrapper<FcContractNft> nftQueryWrapper = new QueryWrapper<>(); nftQueryWrapper.eq(FcContractNft.ADDRESS, address) .eq(FcContractNft.TOKEN_ID, tokenId.toString()) .eq(BaseEntity.DELETED, false); nftQueryWrapper.orderByDesc(BaseEntity.ID); FcContractNft nft = this.baseService.getByCondition(FcContractNft.class, nftQueryWrapper); if (null == nft) { logger.warn("nft未找到,或许已经销毁:token=>" + address + "; tokenId=>" + tokenId); return false; } if (nft.getDeleted()) { logger.warn("nft已经销毁:token=>" + address + "; tokenId=>" + tokenId); } this.baseService.deleteById(FcContractNft.class, nft.getId()); QueryWrapper<FcNftItems> wrapper = new QueryWrapper<>(); wrapper.eq(FcNftItems.NFT_ID, nft.getId()) .eq(FcNftItems.ADDRESS, nft.getAddress()) .eq(FcNftItems.ITEM_OWNER, from); wrapper.orderByDesc(BaseEntity.ID); FcNftItems items = this.baseService.getByCondition(FcNftItems.class, wrapper); if (null == items) { logger.warn("nft-item未找到或者已经销毁:token=>" + address + "; tokenId=>" + tokenId + "; owner=>" + from); return false; } if(items.getDeleted()) { logger.warn("nft-item已经销毁:token=>" + address + "; tokenId=>" + tokenId + "; owner=>" + from); } this.baseService.deleteById(FcNftItems.class, items.getId()); try { String noticeType = NoticeType.getNoticeTypeByName("Trade").getType().toString(); this.noticeService.insertNotice(content, from, type.toString(), nft.getImgUrl(), nft.getName(), noticeType, from); } catch (Exception e) { logger.error("插入销毁信息异常", e); } return true; } @Transactional(rollbackFor = Exception.class) private boolean incQuantity(FcContractNft nft, String owner) { QueryWrapper<FcNftItems> wrapper = new QueryWrapper<>(); wrapper.eq(FcNftItems.NFT_ID, nft.getId()) .eq(FcNftItems.ITEM_OWNER, owner) .eq(BaseEntity.DELETED, false); FcNftItems items = this.baseService.getByCondition(FcNftItems.class, wrapper); if (null == items) { FcNftItems temp = new FcNftItems(); temp.setAddress(nft.getAddress()); temp.setCategoryId(nft.getCategoryId()); temp.setDeleted(false); temp.setDescription(nft.getDescription()); temp.setImgUrl(nft.getImgUrl()); temp.setIsSync(nft.getIsSync()); temp.setItemOwner(owner); temp.setName(nft.getName()); temp.setNftId(nft.getId()); temp.setOnsell(false); temp.setPaytokenAddress(""); temp.setPrice(""); temp.setQuantity(1L); temp.setSellQuantity(0L); temp.setSignature(""); temp.setStorageId(nft.getStorageId()); temp.setUsdtPrice(BigDecimal.ZERO); temp.setTokenId(nft.getTokenId()); this.baseService.save(temp); } return true; } private FcTxOrder getByHash(String txHash) { QueryWrapper<FcTxOrder> wrapper = new QueryWrapper<>(); wrapper.eq(FcTxOrder.TX_HASH, txHash); return baseService.getByCondition(FcTxOrder.class, wrapper); } @Transactional(rollbackFor = Exception.class) void saveLastBlock(String block) { UpdateWrapper<FcSystem> wrapper = new UpdateWrapper<>(); wrapper.eq(FcSystem.KEY_NAME,SysConfConstant.LAST_BLOCK); wrapper.set(FcSystem.KEY_VALUE, block); baseService.updateByCondition(FcSystem.class, wrapper); } }
18,521
3,522
<reponame>dan-mutua/djangowk1 from __future__ import absolute_import, unicode_literals from virtualenv.util.path import Path def handle_store_python(meta, interpreter): if is_store_python(interpreter): meta.symlink_error = "Windows Store Python does not support virtual environments via symlink" return meta def is_store_python(interpreter): parts = Path(interpreter.system_executable).parts return ( len(parts) > 4 and parts[-4] == "Microsoft" and parts[-3] == "WindowsApps" and parts[-2].startswith("PythonSoftwareFoundation.Python.3.") and parts[-1].startswith("python") ) __all__ = ( "handle_store_python", "is_store_python", )
277
692
#include "WebRTCClientTestFixture.h" namespace com { namespace amazonaws { namespace kinesis { namespace video { namespace webrtcclient { // // Global memory allocation counter // UINT64 gTotalWebRtcClientMemoryUsage = 0; // // Global memory counter lock // MUTEX gTotalWebRtcClientMemoryMutex; STATUS createRtpPacketWithSeqNum(UINT16 seqNum, PRtpPacket *ppRtpPacket) { STATUS retStatus = STATUS_SUCCESS; BYTE payload[10]; PRtpPacket pRtpPacket = NULL; CHK_STATUS(createRtpPacket(2, FALSE, FALSE, 0, FALSE, 96, seqNum, 100, 0x1234ABCD, NULL, 0, 0, NULL, payload, 10, &pRtpPacket)); *ppRtpPacket = pRtpPacket; CHK_STATUS(createBytesFromRtpPacket(pRtpPacket, NULL, &pRtpPacket->rawPacketLength)); CHK(NULL != (pRtpPacket->pRawPacket = (PBYTE) MEMALLOC(pRtpPacket->rawPacketLength)), STATUS_NOT_ENOUGH_MEMORY); CHK_STATUS(createBytesFromRtpPacket(pRtpPacket, pRtpPacket->pRawPacket, &pRtpPacket->rawPacketLength)); CleanUp: return retStatus; } WebRtcClientTestBase::WebRtcClientTestBase() : mSignalingClientHandle(INVALID_SIGNALING_CLIENT_HANDLE_VALUE), mAccessKey(NULL), mSecretKey(NULL), mSessionToken(NULL), mRegion(NULL), mCaCertPath(NULL), mAccessKeyIdSet(FALSE) { // Initialize the endianness of the library initializeEndianness(); SRAND(12345); mStreamingRotationPeriod = TEST_STREAMING_TOKEN_DURATION; } void WebRtcClientTestBase::SetUp() { DLOGI("\nSetting up test: %s\n", GetTestName()); mReadyFrameIndex = 0; mDroppedFrameIndex = 0; mExpectedFrameCount = 0; mExpectedDroppedFrameCount = 0; SET_INSTRUMENTED_ALLOCATORS(); mLogLevel = LOG_LEVEL_DEBUG; PCHAR logLevelStr = GETENV(DEBUG_LOG_LEVEL_ENV_VAR); if (logLevelStr != NULL) { ASSERT_EQ(STATUS_SUCCESS, STRTOUI32(logLevelStr, NULL, 10, &mLogLevel)); } SET_LOGGER_LOG_LEVEL(mLogLevel); initKvsWebRtc(); if (NULL != (mAccessKey = getenv(ACCESS_KEY_ENV_VAR))) { mAccessKeyIdSet = TRUE; } mSecretKey = getenv(SECRET_KEY_ENV_VAR); mSessionToken = getenv(SESSION_TOKEN_ENV_VAR); if (NULL == (mRegion = getenv(DEFAULT_REGION_ENV_VAR))) { mRegion = TEST_DEFAULT_REGION; } if (NULL == (mCaCertPath = getenv(CACERT_PATH_ENV_VAR))) { mCaCertPath = (PCHAR) DEFAULT_KVS_CACERT_PATH; } if (mAccessKey) { ASSERT_EQ(STATUS_SUCCESS, createStaticCredentialProvider(mAccessKey, 0, mSecretKey, 0, mSessionToken, 0, MAX_UINT64, &mTestCredentialProvider)); } else { mTestCredentialProvider = nullptr; } // Prepare the test channel name by prefixing with test channel name // and generating random chars replacing a potentially bad characters with '.' STRCPY(mChannelName, TEST_SIGNALING_CHANNEL_NAME); UINT32 testNameLen = STRLEN(TEST_SIGNALING_CHANNEL_NAME); const UINT32 randSize = 16; PCHAR pCur = &mChannelName[testNameLen]; for (UINT32 i = 0; i < randSize; i++) { *pCur++ = SIGNALING_VALID_NAME_CHARS[RAND() % (ARRAY_SIZE(SIGNALING_VALID_NAME_CHARS) - 1)]; } *pCur = '\0'; } void WebRtcClientTestBase::TearDown() { DLOGI("\nTearing down test: %s\n", GetTestName()); deinitKvsWebRtc(); freeStaticCredentialProvider(&mTestCredentialProvider); EXPECT_EQ(STATUS_SUCCESS, RESET_INSTRUMENTED_ALLOCATORS()); } VOID WebRtcClientTestBase::initializeJitterBuffer(UINT32 expectedFrameCount, UINT32 expectedDroppedFrameCount, UINT32 rtpPacketCount) { UINT32 i, timestamp; EXPECT_EQ(STATUS_SUCCESS, createJitterBuffer(testFrameReadyFunc, testFrameDroppedFunc, testDepayRtpFunc, DEFAULT_JITTER_BUFFER_MAX_LATENCY, TEST_JITTER_BUFFER_CLOCK_RATE, (UINT64) this, &mJitterBuffer)); mExpectedFrameCount = expectedFrameCount; mFrame = NULL; if (expectedFrameCount > 0) { mPExpectedFrameArr = (PBYTE*) MEMALLOC(SIZEOF(PBYTE) * expectedFrameCount); mExpectedFrameSizeArr = (PUINT32) MEMALLOC(SIZEOF(UINT32) * expectedFrameCount); } mExpectedDroppedFrameCount = expectedDroppedFrameCount; if (expectedDroppedFrameCount > 0) { mExpectedDroppedFrameTimestampArr = (PUINT32) MEMALLOC(SIZEOF(UINT32) * expectedDroppedFrameCount); } mPRtpPackets = (PRtpPacket*) MEMALLOC(SIZEOF(PRtpPacket) * rtpPacketCount); mRtpPacketCount = rtpPacketCount; // Assume timestamp is on time unit ms for test for (i = 0, timestamp = 0; i < rtpPacketCount; i++, timestamp += 200) { EXPECT_EQ(STATUS_SUCCESS, createRtpPacket(2, FALSE, FALSE, 0, FALSE, 96, i, timestamp, 0x1234ABCD, NULL, 0, 0, NULL, NULL, 0, mPRtpPackets + i)); } } VOID WebRtcClientTestBase::setPayloadToFree() { UINT32 i; for (i = 0; i < mRtpPacketCount; i++) { mPRtpPackets[i]->pRawPacket = mPRtpPackets[i]->payload; } } VOID WebRtcClientTestBase::clearJitterBufferForTest() { UINT32 i; EXPECT_EQ(STATUS_SUCCESS, freeJitterBuffer(&mJitterBuffer)); if (mExpectedFrameCount > 0) { for (i = 0; i < mExpectedFrameCount; i++) { MEMFREE(mPExpectedFrameArr[i]); } MEMFREE(mPExpectedFrameArr); MEMFREE(mExpectedFrameSizeArr); } if (mExpectedDroppedFrameCount > 0) { MEMFREE(mExpectedDroppedFrameTimestampArr); } MEMFREE(mPRtpPackets); EXPECT_EQ(mExpectedFrameCount, mReadyFrameIndex); EXPECT_EQ(mExpectedDroppedFrameCount, mDroppedFrameIndex); if (mFrame != NULL) { MEMFREE(mFrame); } } // Connect two RtcPeerConnections, and wait for them to be connected // in the given amount of time. Return false if they don't go to connected in // the expected amounted of time bool WebRtcClientTestBase::connectTwoPeers(PRtcPeerConnection offerPc, PRtcPeerConnection answerPc, PCHAR pOfferCertFingerprint, PCHAR pAnswerCertFingerprint) { RtcSessionDescriptionInit sdp; auto onICECandidateHdlr = [](UINT64 customData, PCHAR candidateStr) -> void { if (candidateStr != NULL) { std::thread( [customData](std::string candidate) { RtcIceCandidateInit iceCandidate; EXPECT_EQ(STATUS_SUCCESS, deserializeRtcIceCandidateInit((PCHAR) candidate.c_str(), STRLEN(candidate.c_str()), &iceCandidate)); EXPECT_EQ(STATUS_SUCCESS, addIceCandidate((PRtcPeerConnection) customData, iceCandidate.candidate)); }, std::string(candidateStr)) .detach(); } }; EXPECT_EQ(STATUS_SUCCESS, peerConnectionOnIceCandidate(offerPc, (UINT64) answerPc, onICECandidateHdlr)); EXPECT_EQ(STATUS_SUCCESS, peerConnectionOnIceCandidate(answerPc, (UINT64) offerPc, onICECandidateHdlr)); auto onICEConnectionStateChangeHdlr = [](UINT64 customData, RTC_PEER_CONNECTION_STATE newState) -> void { ATOMIC_INCREMENT((PSIZE_T) customData + newState); }; EXPECT_EQ(STATUS_SUCCESS, peerConnectionOnConnectionStateChange(offerPc, (UINT64) this->stateChangeCount, onICEConnectionStateChangeHdlr)); EXPECT_EQ(STATUS_SUCCESS, peerConnectionOnConnectionStateChange(answerPc, (UINT64) this->stateChangeCount, onICEConnectionStateChangeHdlr)); EXPECT_EQ(STATUS_SUCCESS, createOffer(offerPc, &sdp)); EXPECT_EQ(STATUS_SUCCESS, setLocalDescription(offerPc, &sdp)); EXPECT_EQ(STATUS_SUCCESS, setRemoteDescription(answerPc, &sdp)); // Validate the cert fingerprint if we are asked to do so if (pOfferCertFingerprint != NULL) { EXPECT_NE((PCHAR) NULL, STRSTR(sdp.sdp, pOfferCertFingerprint)); } EXPECT_EQ(STATUS_SUCCESS, createAnswer(answerPc, &sdp)); EXPECT_EQ(STATUS_SUCCESS, setLocalDescription(answerPc, &sdp)); EXPECT_EQ(STATUS_SUCCESS, setRemoteDescription(offerPc, &sdp)); if (pAnswerCertFingerprint != NULL) { EXPECT_NE((PCHAR) NULL, STRSTR(sdp.sdp, pAnswerCertFingerprint)); } for (auto i = 0; i <= 100 && ATOMIC_LOAD(&this->stateChangeCount[RTC_PEER_CONNECTION_STATE_CONNECTED]) != 2; i++) { THREAD_SLEEP(HUNDREDS_OF_NANOS_IN_A_SECOND); } return ATOMIC_LOAD(&this->stateChangeCount[RTC_PEER_CONNECTION_STATE_CONNECTED]) == 2; } // Create track and transceiver and adds to PeerConnection void WebRtcClientTestBase::addTrackToPeerConnection(PRtcPeerConnection pRtcPeerConnection, PRtcMediaStreamTrack track, PRtcRtpTransceiver* transceiver, RTC_CODEC codec, MEDIA_STREAM_TRACK_KIND kind) { MEMSET(track, 0x00, SIZEOF(RtcMediaStreamTrack)); EXPECT_EQ(STATUS_SUCCESS, addSupportedCodec(pRtcPeerConnection, codec)); track->kind = kind; track->codec = codec; EXPECT_EQ(STATUS_SUCCESS, generateJSONSafeString(track->streamId, MAX_MEDIA_STREAM_ID_LEN)); EXPECT_EQ(STATUS_SUCCESS, generateJSONSafeString(track->trackId, MAX_MEDIA_STREAM_ID_LEN)); EXPECT_EQ(STATUS_SUCCESS, addTransceiver(pRtcPeerConnection, track, NULL, transceiver)); } void WebRtcClientTestBase::getIceServers(PRtcConfiguration pRtcConfiguration) { UINT32 i, j, iceConfigCount, uriCount; PIceConfigInfo pIceConfigInfo; // Assume signaling client is already created EXPECT_EQ(STATUS_SUCCESS, signalingClientGetIceConfigInfoCount(mSignalingClientHandle, &iceConfigCount)); // Set the STUN server SNPRINTF(pRtcConfiguration->iceServers[0].urls, MAX_ICE_CONFIG_URI_LEN, KINESIS_VIDEO_STUN_URL, TEST_DEFAULT_REGION); for (uriCount = 0, i = 0; i < iceConfigCount; i++) { EXPECT_EQ(STATUS_SUCCESS, signalingClientGetIceConfigInfo(mSignalingClientHandle, i, &pIceConfigInfo)); for (j = 0; j < pIceConfigInfo->uriCount; j++) { STRNCPY(pRtcConfiguration->iceServers[uriCount + 1].urls, pIceConfigInfo->uris[j], MAX_ICE_CONFIG_URI_LEN); STRNCPY(pRtcConfiguration->iceServers[uriCount + 1].credential, pIceConfigInfo->password, MAX_ICE_CONFIG_CREDENTIAL_LEN); STRNCPY(pRtcConfiguration->iceServers[uriCount + 1].username, pIceConfigInfo->userName, MAX_ICE_CONFIG_USER_NAME_LEN); uriCount++; } } } PCHAR WebRtcClientTestBase::GetTestName() { return (PCHAR)::testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); } } // namespace webrtcclient } // namespace video } // namespace kinesis } // namespace amazonaws } // namespace com
4,532
2,062
from django.db import models class Example(models.Model): name = models.CharField(max_length=100)
34
1,074
# the environment module def make_env(spec): from slm_lab.env.openai import OpenAIEnv env = OpenAIEnv(spec) return env
52
2,753
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: <NAME> * */ #ifndef SHOGUN_PARAMETEROBSERVERCV_H #define SHOGUN_PARAMETEROBSERVERCV_H #include <shogun/evaluation/CrossValidationStorage.h> #include <shogun/lib/observers/ParameterObserver.h> #include <shogun/lib/observers/observers_utils.h> namespace shogun { /** * Base ParameterObserver class for CrossValidation. */ class ParameterObserverCV : public ParameterObserver { public: ParameterObserverCV(); ParameterObserverCV(std::vector<std::string>& parameters); ParameterObserverCV(std::vector<ParameterProperties>& properties); ParameterObserverCV( std::vector<std::string>& parameters, std::vector<ParameterProperties>& properties); ParameterObserverCV( const std::string& filename, std::vector<std::string>& parameters, std::vector<ParameterProperties>& properties); ~ParameterObserverCV() override; void on_error(std::exception_ptr ptr) override; void on_complete() override; /** * Get class name. * @return class name */ const char* get_name() const override { return "ParameterObserverCV"; } private: /** * Print data contained into a CrossValidationStorage object. * @param value CrossValidationStorage object */ void print_observed_value(const std::shared_ptr<CrossValidationStorage>& value) const; /** * Print information of a machine * @param machine given machine */ void print_machine_information(const std::shared_ptr<Machine>& machine) const; protected: void on_next_impl(const TimedObservedValue& value) override; }; } #endif // SHOGUN_PARAMETEROBSERVERCV_H
576
1,459
<filename>itext/src/main/java/com/itextpdf/text/pdf/PdfObject.java /* * * This file is part of the iText (R) project. Copyright (c) 1998-2020 iText Group NV * Authors: <NAME>, <NAME>, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: <EMAIL> */ package com.itextpdf.text.pdf; import com.itextpdf.text.pdf.internal.PdfIsoKeys; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; /** * <CODE>PdfObject</CODE> is the abstract superclass of all PDF objects. * <P> * PDF supports seven basic types of objects: Booleans, numbers, strings, names, * arrays, dictionaries and streams. In addition, PDF provides a null object. * Objects may be labeled so that they can be referred to by other objects.<BR> * All these basic PDF objects are described in the 'Portable Document Format * Reference Manual version 1.3' Chapter 4 (pages 37-54). * * @see PdfNull * @see PdfBoolean * @see PdfNumber * @see PdfString * @see PdfName * @see PdfArray * @see PdfDictionary * @see PdfStream * @see PdfIndirectReference */ public abstract class PdfObject implements Serializable { // CONSTANTS /** A possible type of <CODE>PdfObject</CODE> */ public static final int BOOLEAN = 1; /** A possible type of <CODE>PdfObject</CODE> */ public static final int NUMBER = 2; /** A possible type of <CODE>PdfObject</CODE> */ public static final int STRING = 3; /** A possible type of <CODE>PdfObject</CODE> */ public static final int NAME = 4; /** A possible type of <CODE>PdfObject</CODE> */ public static final int ARRAY = 5; /** A possible type of <CODE>PdfObject</CODE> */ public static final int DICTIONARY = 6; /** A possible type of <CODE>PdfObject</CODE> */ public static final int STREAM = 7; /** A possible type of <CODE>PdfObject</CODE> */ public static final int NULL = 8; /** A possible type of <CODE>PdfObject</CODE> */ public static final int INDIRECT = 10; /** An empty string used for the <CODE>PdfNull</CODE>-object and for an empty <CODE>PdfString</CODE>-object. */ public static final String NOTHING = ""; /** * This is the default encoding to be used for converting Strings into * bytes and vice versa. The default encoding is PdfDocEncoding. */ public static final String TEXT_PDFDOCENCODING = "PDF"; /** This is the encoding to be used to output text in Unicode. */ public static final String TEXT_UNICODE = "UnicodeBig"; // CLASS VARIABLES /** The content of this <CODE>PdfObject</CODE> */ protected byte[] bytes; /** The type of this <CODE>PdfObject</CODE> */ protected int type; /** Holds the indirect reference. */ protected PRIndirectReference indRef; // CONSTRUCTORS /** * Constructs a <CODE>PdfObject</CODE> of a certain <VAR>type</VAR> * without any <VAR>content</VAR>. * * @param type type of the new <CODE>PdfObject</CODE> */ protected PdfObject(int type) { this.type = type; } /** * Constructs a <CODE>PdfObject</CODE> of a certain <VAR>type</VAR> * with a certain <VAR>content</VAR>. * * @param type type of the new <CODE>PdfObject</CODE> * @param content content of the new <CODE>PdfObject</CODE> as a * <CODE>String</CODE>. */ protected PdfObject(int type, String content) { this.type = type; bytes = PdfEncodings.convertToBytes(content, null); } /** * Constructs a <CODE>PdfObject</CODE> of a certain <VAR>type</VAR> * with a certain <VAR>content</VAR>. * * @param type type of the new <CODE>PdfObject</CODE> * @param bytes content of the new <CODE>PdfObject</CODE> as an array of * <CODE>byte</CODE>. */ protected PdfObject(int type, byte[] bytes) { this.bytes = bytes; this.type = type; } // methods dealing with the content of this object /** * Writes the PDF representation of this <CODE>PdfObject</CODE> as an * array of <CODE>byte</CODE>s to the writer. * * @param writer for backwards compatibility * @param os The <CODE>OutputStream</CODE> to write the bytes to. * @throws IOException */ public void toPdf(PdfWriter writer, OutputStream os) throws IOException { if (bytes != null) { PdfWriter.checkPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_OBJECT, this); os.write(bytes); } } /** * Returns the <CODE>String</CODE>-representation of this * <CODE>PdfObject</CODE>. * * @return a <CODE>String</CODE> */ public String toString() { if (bytes == null) return super.toString(); return PdfEncodings.convertToString(bytes, null); } /** * Gets the presentation of this object in a byte array * * @return a byte array */ public byte[] getBytes() { return bytes; } /** * Whether this object can be contained in an object stream. * * PdfObjects of type STREAM OR INDIRECT can not be contained in an * object stream. * * @return <CODE>true</CODE> if this object can be in an object stream. * Otherwise <CODE>false</CODE> */ public boolean canBeInObjStm() { switch (type) { case NULL: case BOOLEAN: case NUMBER: case STRING: case NAME: case ARRAY: case DICTIONARY: return true; case STREAM: case INDIRECT: default: return false; } } /** * Returns the length of the actual content of the <CODE>PdfObject</CODE>. * <P> * In some cases, namely for <CODE>PdfString</CODE> and <CODE>PdfStream</CODE>, * this method differs from the method <CODE>pdfLength</CODE> because <CODE>pdfLength</CODE> * returns the length of the PDF representation of the object, not of the actual content * as does the method <CODE>length</CODE>.</P> * <P> * Remark: the actual content of an object is in some cases identical to its representation. * The following statement is always true: length() &gt;= pdfLength().</P> * * @return The length as <CODE>int</CODE> */ public int length() { return toString().length(); } /** * Changes the content of this <CODE>PdfObject</CODE>. * * @param content the new content of this <CODE>PdfObject</CODE> */ protected void setContent(String content) { bytes = PdfEncodings.convertToBytes(content, null); } // methods dealing with the type of this object /** * Returns the type of this <CODE>PdfObject</CODE>. * * May be either of: * - <VAR>NULL</VAR>: A <CODE>PdfNull</CODE> * - <VAR>BOOLEAN</VAR>: A <CODE>PdfBoolean</CODE> * - <VAR>NUMBER</VAR>: A <CODE>PdfNumber</CODE> * - <VAR>STRING</VAR>: A <CODE>PdfString</CODE> * - <VAR>NAME</VAR>: A <CODE>PdfName</CODE> * - <VAR>ARRAY</VAR>: A <CODE>PdfArray</CODE> * - <VAR>DICTIONARY</VAR>: A <CODE>PdfDictionary</CODE> * - <VAR>STREAM</VAR>: A <CODE>PdfStream</CODE> * - <VAR>INDIRECT</VAR>: ><CODE>PdfIndirectObject</CODE> * * @return The type */ public int type() { return type; } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfNull</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isNull() { return (type == NULL); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfBoolean</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isBoolean() { return (type == BOOLEAN); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfNumber</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isNumber() { return (type == NUMBER); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfString</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isString() { return (type == STRING); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfName</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isName() { return (type == NAME); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfArray</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isArray() { return (type == ARRAY); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfDictionary</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isDictionary() { return (type == DICTIONARY); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfStream</CODE>. * * @return <CODE>true</CODE> or <CODE>false</CODE> */ public boolean isStream() { return (type == STREAM); } /** * Checks if this <CODE>PdfObject</CODE> is of the type * <CODE>PdfIndirectObject</CODE>. * * @return <CODE>true</CODE> if this is an indirect object, * otherwise <CODE>false</CODE> */ public boolean isIndirect() { return (type == INDIRECT); } /** * Get the indirect reference * * @return A <CODE>PdfIndirectReference</CODE> */ public PRIndirectReference getIndRef() { return indRef; } /** * Set the indirect reference * * @param indRef New value as a <CODE>PdfIndirectReference</CODE> */ public void setIndRef(PRIndirectReference indRef) { this.indRef = indRef; } }
4,751
495
/* * Copyright 2014-2016 Media for Mobile * * 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.m4m.samples; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import org.m4m.samples.controls.TimelineItem; import java.util.ArrayList; import java.util.List; public class ComposerVideoEffectActivity extends ActivityWithTimeline implements View.OnClickListener { TimelineItem mItem; Spinner mEffects; public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.composer_transcode_activity); ((Button)findViewById(R.id.action)).setText("Apply Video Effect"); ((Spinner)findViewById(R.id.effect)).setVisibility(View.VISIBLE); init(); } @Override public void onResume() { super.onResume(); if (mItem != null) { mItem.updateView(); } } private void init() { mItem = (TimelineItem) findViewById(R.id.timelineItem); mItem.setEventsListener(this); mItem.enableSegmentPicker(false); ((Button) findViewById(R.id.action)).setOnClickListener(this); mEffects = (Spinner) findViewById(R.id.effect); fillEffectsList(); } private void fillEffectsList() { List<String> list = new ArrayList<String>(); list.add("Sepia"); list.add("Grayscale"); list.add("Inverse"); list.add("Text Overlay"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mEffects.setAdapter(dataAdapter); } public void action() { String mediaFileName = mItem.getMediaFileName(); if (mediaFileName == null) { showToast("Please select a valid video file first"); return; } mItem.stopVideoView(); Intent intent = new Intent(); intent.setClass(this, ComposerVideoEffectCoreActivity.class); Bundle b = new Bundle(); b.putString("srcMediaName1", mItem.getMediaFileName()); intent.putExtras(b); b.putString("dstMediaPath", mItem.genDstPath(mItem.getMediaFileName(), mItem.getVideoEffectName(mEffects.getSelectedItemPosition()))); b.putInt("effectIndex", mEffects.getSelectedItemPosition()); intent.putExtras(b); b.putString("srcUri1", mItem.getUri().getString()); intent.putExtras(b); startActivity(intent); } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.action: { action(); } break; } } }
1,405
16,461
<filename>ios/versioned-react-native/ABI41_0_0/ReactNative/React/Base/ABI41_0_0RCTDefines.h /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #if __OBJC__ #import <Foundation/Foundation.h> #endif /** * Make global functions usable in C++ */ #if defined(__cplusplus) #define ABI41_0_0RCT_EXTERN extern "C" __attribute__((visibility("default"))) #define ABI41_0_0RCT_EXTERN_C_BEGIN extern "C" { #define ABI41_0_0RCT_EXTERN_C_END } #else #define ABI41_0_0RCT_EXTERN extern __attribute__((visibility("default"))) #define ABI41_0_0RCT_EXTERN_C_BEGIN #define ABI41_0_0RCT_EXTERN_C_END #endif /** * The ABI41_0_0RCT_DEBUG macro can be used to exclude error checking and logging code * from release builds to improve performance and reduce binary size. */ #ifndef ABI41_0_0RCT_DEBUG #if DEBUG #define ABI41_0_0RCT_DEBUG 1 #else #define ABI41_0_0RCT_DEBUG 0 #endif #endif /** * The ABI41_0_0RCT_DEV macro can be used to enable or disable development tools * such as the debug executors, dev menu, red box, etc. */ #ifndef ABI41_0_0RCT_DEV #if DEBUG #define ABI41_0_0RCT_DEV 1 #else #define ABI41_0_0RCT_DEV 0 #endif #endif /** * ABI41_0_0RCT_DEV_MENU can be used to toggle the dev menu separately from ABI41_0_0RCT_DEV. * By default though, it will inherit from ABI41_0_0RCT_DEV. */ #ifndef ABI41_0_0RCT_DEV_MENU #define ABI41_0_0RCT_DEV_MENU ABI41_0_0RCT_DEV #endif #ifndef ABI41_0_0RCT_ENABLE_INSPECTOR #if ABI41_0_0RCT_DEV && __has_include(<ABI41_0_0React/ABI41_0_0RCTInspectorDevServerHelper.h>) #define ABI41_0_0RCT_ENABLE_INSPECTOR 1 #else #define ABI41_0_0RCT_ENABLE_INSPECTOR 0 #endif #endif #ifndef ABI41_0_0ENABLE_PACKAGER_CONNECTION #if ABI41_0_0RCT_DEV && (__has_include("ABI41_0_0RCTPackagerConnection.h") || __has_include(<ABI41_0_0React/ABI41_0_0RCTPackagerConnection.h>)) #define ABI41_0_0ENABLE_PACKAGER_CONNECTION 1 #else #define ABI41_0_0ENABLE_PACKAGER_CONNECTION 0 #endif #endif #if ABI41_0_0RCT_DEV #define ABI41_0_0RCT_IF_DEV(...) __VA_ARGS__ #else #define ABI41_0_0RCT_IF_DEV(...) #endif #ifndef ABI41_0_0RCT_PROFILE #define ABI41_0_0RCT_PROFILE ABI41_0_0RCT_DEV #endif /** * Add the default Metro packager port number */ #ifndef ABI41_0_0RCT_METRO_PORT #define ABI41_0_0RCT_METRO_PORT 8081 #else // test if ABI41_0_0RCT_METRO_PORT is empty #define ABI41_0_0RCT_METRO_PORT_DO_EXPAND(VAL) VAL##1 #define ABI41_0_0RCT_METRO_PORT_EXPAND(VAL) ABI41_0_0RCT_METRO_PORT_DO_EXPAND(VAL) #if !defined(ABI41_0_0RCT_METRO_PORT) || (ABI41_0_0RCT_METRO_PORT_EXPAND(ABI41_0_0RCT_METRO_PORT) == 1) // Only here if ABI41_0_0RCT_METRO_PORT is not defined // OR ABI41_0_0RCT_METRO_PORT is the empty string #undef ABI41_0_0RCT_METRO_PORT #define ABI41_0_0RCT_METRO_PORT 8081 #endif #endif /** * Add the default packager name */ #ifndef ABI41_0_0RCT_PACKAGER_NAME #define ABI41_0_0RCT_PACKAGER_NAME @"Metro" #endif /** * By default, only raise an NSAssertion in debug mode * (custom assert functions will still be called). */ #ifndef ABI41_0_0RCT_NSASSERT #define ABI41_0_0RCT_NSASSERT ABI41_0_0RCT_DEBUG #endif /** * Concat two literals. Supports macro expansions, * e.g. ABI41_0_0RCT_CONCAT(foo, __FILE__). */ #define ABI41_0_0RCT_CONCAT2(A, B) A##B #define ABI41_0_0RCT_CONCAT(A, B) ABI41_0_0RCT_CONCAT2(A, B) /** * This attribute is used for static analysis. */ #if !defined ABI41_0_0RCT_DYNAMIC #if __has_attribute(objc_dynamic) #define ABI41_0_0RCT_DYNAMIC __attribute__((objc_dynamic)) #else #define ABI41_0_0RCT_DYNAMIC #endif #endif /** * Throw an assertion for unimplemented methods. */ #define ABI41_0_0RCT_NOT_IMPLEMENTED(method) \ _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wmissing-method-return-type\"") \ _Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \ ABI41_0_0RCT_EXTERN NSException *_ABI41_0_0RCTNotImplementedException(SEL, Class); \ method NS_UNAVAILABLE \ { \ @throw _ABI41_0_0RCTNotImplementedException(_cmd, [self class]); \ } \ _Pragma("clang diagnostic pop") /** * Check if WebKit iOS 10.0 APIs are available. */ #define WEBKIT_IOS_10_APIS_AVAILABLE __has_include(<WebKit/WKAudiovisualMediaTypes.h>) #define ABI41_0_0EX_REMOVE_VERSION(string) (([string hasPrefix:@"ABI41_0_0"]) ? [string stringByReplacingCharactersInRange:(NSRange){0,@"ABI41_0_0".length} withString:@""] : string)
2,430
4,121
<filename>source/rofi-icon-fetcher.c /* * rofi * * MIT/X11 License * Copyright © 2013-2022 <NAME> <<EMAIL>> * * 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. * */ /** The log domain of this Helper. */ #define G_LOG_DOMAIN "Helpers.IconFetcher" #include "config.h" #include <stdlib.h> #include <xcb/xproto.h> #include "helper.h" #include "rofi-icon-fetcher.h" #include "rofi-types.h" #include "settings.h" #include <cairo.h> #include <pango/pangocairo.h> #include "keyb.h" #include "view.h" #include "xcb.h" #include "nkutils-enum.h" #include "nkutils-xdg-theme.h" #include <stdint.h> #include "helper.h" #include <gdk-pixbuf/gdk-pixbuf.h> typedef struct { // Context for icon-themes. NkXdgThemeContext *xdg_context; // On name. GHashTable *icon_cache; // On uid. GHashTable *icon_cache_uid; // list extensions GList *supported_extensions; uint32_t last_uid; } IconFetcher; typedef struct { char *name; GList *sizes; } IconFetcherNameEntry; typedef struct { thread_state state; GCond *cond; GMutex *mutex; unsigned int *acount; uint32_t uid; int wsize; int hsize; cairo_surface_t *surface; IconFetcherNameEntry *entry; } IconFetcherEntry; /** * The icon fetcher internal state. */ IconFetcher *rofi_icon_fetcher_data = NULL; static void rofi_icon_fetch_entry_free(gpointer data) { IconFetcherNameEntry *entry = (IconFetcherNameEntry *)data; // Free name/key. g_free(entry->name); for (GList *iter = g_list_first(entry->sizes); iter; iter = g_list_next(iter)) { IconFetcherEntry *sentry = (IconFetcherEntry *)(iter->data); cairo_surface_destroy(sentry->surface); g_free(sentry); } g_list_free(entry->sizes); g_free(entry); } void rofi_icon_fetcher_init(void) { g_assert(rofi_icon_fetcher_data == NULL); static const gchar *const icon_fallback_themes[] = {"Adwaita", "gnome", NULL}; const char *themes[2] = {config.icon_theme, NULL}; rofi_icon_fetcher_data = g_malloc0(sizeof(IconFetcher)); rofi_icon_fetcher_data->xdg_context = nk_xdg_theme_context_new(icon_fallback_themes, NULL); nk_xdg_theme_preload_themes_icon(rofi_icon_fetcher_data->xdg_context, themes); rofi_icon_fetcher_data->icon_cache_uid = g_hash_table_new(g_direct_hash, g_direct_equal); rofi_icon_fetcher_data->icon_cache = g_hash_table_new_full( g_str_hash, g_str_equal, NULL, rofi_icon_fetch_entry_free); GSList *l = gdk_pixbuf_get_formats(); for (GSList *li = l; li != NULL; li = g_slist_next(li)) { gchar **exts = gdk_pixbuf_format_get_extensions((GdkPixbufFormat *)li->data); for (unsigned int i = 0; exts && exts[i]; i++) { rofi_icon_fetcher_data->supported_extensions = g_list_append(rofi_icon_fetcher_data->supported_extensions, exts[i]); g_info("Add image extension: %s", exts[i]); exts[i] = NULL; } g_free(exts); } g_slist_free(l); } static void free_wrapper(gpointer data, G_GNUC_UNUSED gpointer user_data) { g_free(data); } void rofi_icon_fetcher_destroy(void) { if (rofi_icon_fetcher_data == NULL) { return; } nk_xdg_theme_context_free(rofi_icon_fetcher_data->xdg_context); g_hash_table_unref(rofi_icon_fetcher_data->icon_cache_uid); g_hash_table_unref(rofi_icon_fetcher_data->icon_cache); g_list_foreach(rofi_icon_fetcher_data->supported_extensions, free_wrapper, NULL); g_list_free(rofi_icon_fetcher_data->supported_extensions); g_free(rofi_icon_fetcher_data); } /* * _rofi_icon_fetcher_get_icon_surface and alpha_mult * are inspired by gdk_cairo_set_source_pixbuf * GDK is: * Copyright (C) 2011-2018 Red Hat, Inc. */ #if G_BYTE_ORDER == G_LITTLE_ENDIAN /** Location of red byte */ #define RED_BYTE 2 /** Location of green byte */ #define GREEN_BYTE 1 /** Location of blue byte */ #define BLUE_BYTE 0 /** Location of alpha byte */ #define ALPHA_BYTE 3 #else /** Location of red byte */ #define RED_BYTE 1 /** Location of green byte */ #define GREEN_BYTE 2 /** Location of blue byte */ #define BLUE_BYTE 3 /** Location of alpha byte */ #define ALPHA_BYTE 0 #endif static inline guchar alpha_mult(guchar c, guchar a) { guint16 t; switch (a) { case 0xff: return c; case 0x00: return 0x00; default: t = c * a + 0x7f; return ((t >> 8) + t) >> 8; } } static cairo_surface_t * rofi_icon_fetcher_get_surface_from_pixbuf(GdkPixbuf *pixbuf) { gint width, height; const guchar *pixels; gint stride; gboolean alpha; if (pixbuf == NULL) { return NULL; } width = gdk_pixbuf_get_width(pixbuf); height = gdk_pixbuf_get_height(pixbuf); pixels = gdk_pixbuf_read_pixels(pixbuf); stride = gdk_pixbuf_get_rowstride(pixbuf); alpha = gdk_pixbuf_get_has_alpha(pixbuf); cairo_surface_t *surface = NULL; gint cstride; guint lo, o; guchar a = 0xff; const guchar *pixels_end, *line; guchar *cpixels; pixels_end = pixels + height * stride; o = alpha ? 4 : 3; lo = o * width; surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cpixels = cairo_image_surface_get_data(surface); cstride = cairo_image_surface_get_stride(surface); cairo_surface_flush(surface); while (pixels < pixels_end) { line = pixels; const guchar *line_end = line + lo; guchar *cline = cpixels; while (line < line_end) { if (alpha) { a = line[3]; } cline[RED_BYTE] = alpha_mult(line[0], a); cline[GREEN_BYTE] = alpha_mult(line[1], a); cline[BLUE_BYTE] = alpha_mult(line[2], a); cline[ALPHA_BYTE] = a; line += o; cline += 4; } pixels += stride; cpixels += cstride; } cairo_surface_mark_dirty(surface); cairo_surface_flush(surface); return surface; } gboolean rofi_icon_fetcher_file_is_image(const char *const path) { if (path == NULL) { return FALSE; } const char *suf = strrchr(path, '.'); if (suf == NULL) { return FALSE; } suf++; for (GList *iter = rofi_icon_fetcher_data->supported_extensions; iter != NULL; iter = g_list_next(iter)) { if (g_ascii_strcasecmp(iter->data, suf) == 0) { return TRUE; } } return FALSE; } static void rofi_icon_fetcher_worker(thread_state *sdata, G_GNUC_UNUSED gpointer user_data) { g_debug("starting up icon fetching thread."); // as long as dr->icon is updated atomicly.. (is a pointer write atomic?) // this should be fine running in another thread. IconFetcherEntry *sentry = (IconFetcherEntry *)sdata; const gchar *themes[] = {config.icon_theme, NULL}; const gchar *icon_path; gchar *icon_path_ = NULL; if (g_path_is_absolute(sentry->entry->name)) { icon_path = sentry->entry->name; } else if (g_str_has_prefix(sentry->entry->name, "font:")) { cairo_surface_t *surface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, sentry->wsize, sentry->hsize); cairo_t *cr = cairo_create(surface); PangoLayout *layout = pango_cairo_create_layout(cr); pango_layout_set_text(layout, &sentry->entry->name[5], -1); int width, height; pango_layout_get_size(layout, &width, &height); double ws = sentry->wsize / ((double)width / PANGO_SCALE); double wh = sentry->hsize / ((double)height / PANGO_SCALE); double scale = MIN(ws, wh); cairo_move_to( cr, (sentry->wsize - ((double)width / PANGO_SCALE) * scale) / 2.0, (sentry->hsize - ((double)height / PANGO_SCALE) * scale) / 2.0); cairo_scale(cr, scale, scale); pango_cairo_update_layout(cr, layout); pango_layout_get_size(layout, &width, &height); pango_cairo_show_layout(cr, layout); g_object_unref(layout); cairo_destroy(cr); sentry->surface = surface; rofi_view_reload(); return; } else { icon_path = icon_path_ = nk_xdg_theme_get_icon( rofi_icon_fetcher_data->xdg_context, themes, NULL, sentry->entry->name, MIN(sentry->wsize, sentry->hsize), 1, TRUE); if (icon_path_ == NULL) { g_debug("failed to get icon %s(%dx%d): n/a", sentry->entry->name, sentry->wsize, sentry->hsize); const char *ext = g_strrstr(sentry->entry->name, "."); if (ext) { icon_path = helper_get_theme_path(sentry->entry->name, ext); } if (icon_path == NULL) { return; } } else { g_debug("found icon %s(%dx%d): %s", sentry->entry->name, sentry->wsize, sentry->hsize, icon_path); } } cairo_surface_t *icon_surf = NULL; const char *suf = strrchr(icon_path, '.'); if (suf == NULL) { return; } GError *error = NULL; GdkPixbuf *pb = gdk_pixbuf_new_from_file_at_scale( icon_path, sentry->wsize, sentry->hsize, TRUE, &error); if (error != NULL) { g_warning("Failed to load image: %s", error->message); g_error_free(error); if (pb) { g_object_unref(pb); } } else { icon_surf = rofi_icon_fetcher_get_surface_from_pixbuf(pb); g_object_unref(pb); } sentry->surface = icon_surf; g_free(icon_path_); rofi_view_reload(); } uint32_t rofi_icon_fetcher_query_advanced(const char *name, const int wsize, const int hsize) { g_debug("Query: %s(%dx%d)", name, wsize, hsize); IconFetcherNameEntry *entry = g_hash_table_lookup(rofi_icon_fetcher_data->icon_cache, name); if (entry == NULL) { entry = g_new0(IconFetcherNameEntry, 1); entry->name = g_strdup(name); g_hash_table_insert(rofi_icon_fetcher_data->icon_cache, entry->name, entry); } IconFetcherEntry *sentry; for (GList *iter = g_list_first(entry->sizes); iter; iter = g_list_next(iter)) { sentry = iter->data; if (sentry->wsize == wsize && sentry->hsize == hsize) { return sentry->uid; } } // Not found. sentry = g_new0(IconFetcherEntry, 1); sentry->uid = ++(rofi_icon_fetcher_data->last_uid); sentry->wsize = wsize; sentry->hsize = hsize; sentry->entry = entry; sentry->surface = NULL; entry->sizes = g_list_prepend(entry->sizes, sentry); g_hash_table_insert(rofi_icon_fetcher_data->icon_cache_uid, GINT_TO_POINTER(sentry->uid), sentry); // Push into fetching queue. sentry->state.callback = rofi_icon_fetcher_worker; g_thread_pool_push(tpool, sentry, NULL); return sentry->uid; } uint32_t rofi_icon_fetcher_query(const char *name, const int size) { g_debug("Query: %s(%d)", name, size); IconFetcherNameEntry *entry = g_hash_table_lookup(rofi_icon_fetcher_data->icon_cache, name); if (entry == NULL) { entry = g_new0(IconFetcherNameEntry, 1); entry->name = g_strdup(name); g_hash_table_insert(rofi_icon_fetcher_data->icon_cache, entry->name, entry); } IconFetcherEntry *sentry; for (GList *iter = g_list_first(entry->sizes); iter; iter = g_list_next(iter)) { sentry = iter->data; if (sentry->wsize == size && sentry->hsize == size) { return sentry->uid; } } // Not found. sentry = g_new0(IconFetcherEntry, 1); sentry->uid = ++(rofi_icon_fetcher_data->last_uid); sentry->wsize = size; sentry->hsize = size; sentry->entry = entry; sentry->surface = NULL; entry->sizes = g_list_prepend(entry->sizes, sentry); g_hash_table_insert(rofi_icon_fetcher_data->icon_cache_uid, GINT_TO_POINTER(sentry->uid), sentry); // Push into fetching queue. sentry->state.callback = rofi_icon_fetcher_worker; g_thread_pool_push(tpool, sentry, NULL); return sentry->uid; } cairo_surface_t *rofi_icon_fetcher_get(const uint32_t uid) { IconFetcherEntry *sentry = g_hash_table_lookup( rofi_icon_fetcher_data->icon_cache_uid, GINT_TO_POINTER(uid)); if (sentry) { return sentry->surface; } return NULL; }
5,328
5,133
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.abstractclass.generics; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import org.mapstruct.ReportingPolicy; import org.mapstruct.factory.Mappers; /** * @author <NAME> * */ @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE) public abstract class GenericsHierarchyMapper { public static final GenericsHierarchyMapper INSTANCE = Mappers.getMapper( GenericsHierarchyMapper.class ); @Mapping(target = "animalKey", source = "key") public abstract Target toTarget(AbstractAnimal source); @Mapping(target = "keyOfAllBeings", source = "key") public abstract Target toTarget(AbstractHuman source); @Mapping(target = "key", source = "animalKey") public abstract void updateSourceWithAnimalKey(Target target, @MappingTarget AbstractAnimal bean); @Mapping(target = "key", source = "keyOfAllBeings") public abstract void updateSourceWithKeyOfAllBeings(Target target, @MappingTarget AbstractHuman bean); protected AnimalKey modifyAnimalKey(AnimalKey item) { item.setTypeParameterIsResolvedToAnimalKey( true ); return item; } protected KeyOfAllBeings modifyKeyOfAllBeings(KeyOfAllBeings item) { item.setTypeParameterIsResolvedToKeyOfAllBeings( true ); return item; } }
478
954
package com.jdon.container.access; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.jdon.bussinessproxy.TargetMetaDef; import com.jdon.container.pico.Startable; /** * 以service name为key, Service TargetMetaDef为value * * this class is registered in contain.xml every name has one TargetMetaDef * instance, if multi thread access same TargetMetaDef instance, they will * crash. * * @author banq * */ public class TargetMetaDefHolder implements Startable, Serializable { /** * */ private static final long serialVersionUID = 9184139922656648301L; /** * 以service name为key, Service TargetMetaDef为value */ private final Map<String, TargetMetaDef> metaDefs; public TargetMetaDefHolder() { this.metaDefs = new HashMap<String, TargetMetaDef>(); } public void add(Map<String, TargetMetaDef> maps) { metaDefs.putAll(maps); } public TargetMetaDef getTargetMetaDef(String name) { return metaDefs.get(name); } public void start() { } public void stop() { metaDefs.clear(); } public void add(String name, TargetMetaDef targetMetaDef) { metaDefs.put(name, targetMetaDef); } // for reister in container of DefaultContainerBuilder.registerUserService public Map<String, TargetMetaDef> loadMetaDefs() { return metaDefs; } public String lookupForName(String ClassName) { for (String name : metaDefs.keySet()) { TargetMetaDef tm = metaDefs.get(name); if (tm.getClassName().equals(ClassName)) { return name; } } return null; } }
612
3,102
<gh_stars>1000+ // RUN: c-index-test -index-file %s -target i686-pc-linux \ // RUN: | FileCheck %s -check-prefix CHECK -check-prefix CHECK-LINUX // RUN: c-index-test -index-file -Wno-unsupported-visibility %s -target i386-darwin \ // RUN: | FileCheck %s -check-prefix CHECK -check-prefix CHECK-DARWIN void __attribute__ (( visibility("default") )) default_visibility(); // CHECK: <attribute>: attribute(visibility)=default void __attribute__ (( visibility("hidden") )) hidden_visibility(); // CHECK: <attribute>: attribute(visibility)=hidden void __attribute__ (( visibility("protected") )) protected_visibility(); // CHECK-LINUX: <attribute>: attribute(visibility)=protected // CHECK-DARWIN: <attribute>: attribute(visibility)=default
247
583
#include <filesystem> #include <memory> #include <string> #include <vector> #include "base_test.hpp" #include "hyrise.hpp" #include "logical_query_plan/stored_table_node.hpp" #include "storage/table.hpp" #include "utils/meta_table_manager.hpp" namespace opossum { class StorageManagerTest : public BaseTest { protected: void SetUp() override { auto& sm = Hyrise::get().storage_manager; auto t1 = std::make_shared<Table>(TableColumnDefinitions{{"a", DataType::Int, false}}, TableType::Data); auto t2 = std::make_shared<Table>(TableColumnDefinitions{{"b", DataType::Int, false}}, TableType::Data, 4); sm.add_table("first_table", t1); sm.add_table("second_table", t2); const auto v1_lqp = StoredTableNode::make("first_table"); const auto v1 = std::make_shared<LQPView>(v1_lqp, std::unordered_map<ColumnID, std::string>{}); const auto v2_lqp = StoredTableNode::make("second_table"); const auto v2 = std::make_shared<LQPView>(v2_lqp, std::unordered_map<ColumnID, std::string>{}); sm.add_view("first_view", std::move(v1)); sm.add_view("second_view", std::move(v2)); const auto pp1_lqp = MockNode::make(MockNode::ColumnDefinitions{{DataType::Int, "a"}}, "a"); const auto pp1 = std::make_shared<PreparedPlan>(pp1_lqp, std::vector<ParameterID>{}); const auto pp2_lqp = MockNode::make(MockNode::ColumnDefinitions{{DataType::Float, "b"}}, "b"); const auto pp2 = std::make_shared<PreparedPlan>(pp2_lqp, std::vector<ParameterID>{}); sm.add_prepared_plan("first_prepared_plan", std::move(pp1)); sm.add_prepared_plan("second_prepared_plan", std::move(pp2)); } }; TEST_F(StorageManagerTest, AddTableTwice) { auto& sm = Hyrise::get().storage_manager; EXPECT_THROW(sm.add_table("first_table", std::make_shared<Table>(TableColumnDefinitions{}, TableType::Data)), std::exception); EXPECT_THROW(sm.add_table("first_view", std::make_shared<Table>(TableColumnDefinitions{}, TableType::Data)), std::exception); } TEST_F(StorageManagerTest, StatisticCreationOnAddTable) { auto& sm = Hyrise::get().storage_manager; sm.add_table("int_float", load_table("resources/test_data/tbl/int_float.tbl")); const auto table = sm.get_table("int_float"); EXPECT_EQ(table->table_statistics()->row_count, 3.0f); const auto chunk = table->get_chunk(ChunkID{0}); EXPECT_TRUE(chunk->pruning_statistics().has_value()); EXPECT_EQ(chunk->pruning_statistics()->at(0)->data_type, DataType::Int); EXPECT_EQ(chunk->pruning_statistics()->at(1)->data_type, DataType::Float); } TEST_F(StorageManagerTest, GetTable) { auto& sm = Hyrise::get().storage_manager; auto t3 = sm.get_table("first_table"); auto t4 = sm.get_table("second_table"); EXPECT_THROW(sm.get_table("third_table"), std::exception); auto names = std::vector<std::string>{"first_table", "second_table"}; auto sm_names = sm.table_names(); std::sort(sm_names.begin(), sm_names.end()); EXPECT_EQ(sm_names, names); } TEST_F(StorageManagerTest, DropTable) { auto& sm = Hyrise::get().storage_manager; sm.drop_table("first_table"); EXPECT_THROW(sm.get_table("first_table"), std::exception); EXPECT_THROW(sm.drop_table("first_table"), std::exception); const auto& tables = sm.tables(); EXPECT_EQ(tables.size(), 1); sm.add_table("first_table", std::make_shared<Table>(TableColumnDefinitions{}, TableType::Data)); EXPECT_TRUE(sm.has_table("first_table")); } TEST_F(StorageManagerTest, DoesNotHaveTable) { auto& sm = Hyrise::get().storage_manager; EXPECT_EQ(sm.has_table("third_table"), false); } TEST_F(StorageManagerTest, HasTable) { auto& sm = Hyrise::get().storage_manager; EXPECT_EQ(sm.has_table("first_table"), true); } TEST_F(StorageManagerTest, AddViewTwice) { const auto v1_lqp = StoredTableNode::make("first_table"); const auto v1 = std::make_shared<LQPView>(v1_lqp, std::unordered_map<ColumnID, std::string>{}); auto& sm = Hyrise::get().storage_manager; EXPECT_THROW(sm.add_view("first_table", v1), std::exception); EXPECT_THROW(sm.add_view("first_view", v1), std::exception); } TEST_F(StorageManagerTest, GetView) { auto& sm = Hyrise::get().storage_manager; auto v3 = sm.get_view("first_view"); auto v4 = sm.get_view("second_view"); EXPECT_THROW(sm.get_view("third_view"), std::exception); } TEST_F(StorageManagerTest, DropView) { auto& sm = Hyrise::get().storage_manager; sm.drop_view("first_view"); EXPECT_THROW(sm.get_view("first_view"), std::exception); EXPECT_THROW(sm.drop_view("first_view"), std::exception); const auto& views = sm.views(); EXPECT_EQ(views.size(), 1); const auto v1_lqp = StoredTableNode::make("first_table"); const auto v1 = std::make_shared<LQPView>(v1_lqp, std::unordered_map<ColumnID, std::string>{}); sm.add_view("first_view", v1); EXPECT_TRUE(sm.has_view("first_view")); } TEST_F(StorageManagerTest, ResetView) { Hyrise::reset(); auto& sm = Hyrise::get().storage_manager; EXPECT_THROW(sm.get_view("first_view"), std::exception); } TEST_F(StorageManagerTest, DoesNotHaveView) { auto& sm = Hyrise::get().storage_manager; EXPECT_EQ(sm.has_view("third_view"), false); } TEST_F(StorageManagerTest, HasView) { auto& sm = Hyrise::get().storage_manager; EXPECT_EQ(sm.has_view("first_view"), true); } TEST_F(StorageManagerTest, ListViewNames) { auto& sm = Hyrise::get().storage_manager; const auto view_names = sm.view_names(); EXPECT_EQ(view_names.size(), 2u); EXPECT_EQ(view_names[0], "first_view"); EXPECT_EQ(view_names[1], "second_view"); } TEST_F(StorageManagerTest, OutputToStream) { auto& sm = Hyrise::get().storage_manager; sm.add_table("third_table", load_table("resources/test_data/tbl/int_int2.tbl", 2)); std::ostringstream output; output << sm; auto output_string = output.str(); EXPECT_TRUE(output_string.find("===== Tables =====") != std::string::npos); EXPECT_TRUE(output_string.find("==== table >> first_table << (1 columns, 0 rows in 0 chunks)") != std::string::npos); EXPECT_TRUE(output_string.find("==== table >> second_table << (1 columns, 0 rows in 0 chunks)") != std::string::npos); EXPECT_TRUE(output_string.find("==== table >> third_table << (2 columns, 4 rows in 2 chunks)") != std::string::npos); EXPECT_TRUE(output_string.find("===== Views ======") != std::string::npos); EXPECT_TRUE(output_string.find("==== view >> first_view <<") != std::string::npos); EXPECT_TRUE(output_string.find("==== view >> second_view <<") != std::string::npos); } TEST_F(StorageManagerTest, ExportTables) { std::ostringstream output; auto& sm = Hyrise::get().storage_manager; // first, we remove empty test tables sm.drop_table("first_table"); sm.drop_table("second_table"); // add a non-empty table sm.add_table("third_table", load_table("resources/test_data/tbl/int_float.tbl")); sm.export_all_tables_as_csv(opossum::test_data_path); const std::string filename = opossum::test_data_path + "/third_table.csv"; EXPECT_TRUE(std::filesystem::exists(filename)); std::filesystem::remove(filename); } TEST_F(StorageManagerTest, AddPreparedPlanTwice) { auto& sm = Hyrise::get().storage_manager; const auto pp1_lqp = MockNode::make(MockNode::ColumnDefinitions{{DataType::Int, "a"}}, "a"); const auto pp1 = std::make_shared<PreparedPlan>(pp1_lqp, std::vector<ParameterID>{}); EXPECT_THROW(sm.add_prepared_plan("first_prepared_plan", pp1), std::exception); } TEST_F(StorageManagerTest, GetPreparedPlan) { auto& sm = Hyrise::get().storage_manager; auto pp3 = sm.get_prepared_plan("first_prepared_plan"); auto pp4 = sm.get_prepared_plan("second_prepared_plan"); EXPECT_THROW(sm.get_prepared_plan("third_prepared_plan"), std::exception); } TEST_F(StorageManagerTest, DropPreparedPlan) { auto& sm = Hyrise::get().storage_manager; sm.drop_prepared_plan("first_prepared_plan"); EXPECT_THROW(sm.get_prepared_plan("first_prepared_plan"), std::exception); EXPECT_THROW(sm.drop_prepared_plan("first_prepared_plan"), std::exception); const auto& prepared_plans = sm.prepared_plans(); EXPECT_EQ(prepared_plans.size(), 1); const auto pp_lqp = MockNode::make(MockNode::ColumnDefinitions{{DataType::Int, "a"}}, "a"); const auto pp = std::make_shared<PreparedPlan>(pp_lqp, std::vector<ParameterID>{}); sm.add_prepared_plan("first_prepared_plan", pp); EXPECT_TRUE(sm.has_prepared_plan("first_prepared_plan")); } TEST_F(StorageManagerTest, DoesNotHavePreparedPlan) { auto& sm = Hyrise::get().storage_manager; EXPECT_EQ(sm.has_prepared_plan("third_prepared_plan"), false); } TEST_F(StorageManagerTest, HasPreparedPlan) { auto& sm = Hyrise::get().storage_manager; EXPECT_EQ(sm.has_prepared_plan("first_prepared_plan"), true); } } // namespace opossum
3,339
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.storage.blob.changefeed.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * FOR INTERNAL USE ONLY. * Represents a cursor for a segment in BlobChangefeed. */ @Fluent public class SegmentCursor { @JsonProperty("ShardCursors") private List<ShardCursor> shardCursors; @JsonProperty("CurrentShardPath") private String currentShardPath; // 'log/00/2020/07/06/1600/' @JsonProperty("SegmentPath") private String segmentPath; // 'idx/segments/2020/07/06/1600/meta.json' /** * Default constructor (used to serialize and deserialize). */ public SegmentCursor() { } /** * Constructor for use by to*Cursor methods. */ public SegmentCursor(String segmentPath, List<ShardCursor> shardCursors, String currentShardPath) { this.segmentPath = segmentPath; this.shardCursors = shardCursors; this.currentShardPath = currentShardPath; } /** * Creates a new segment level cursor with the specified segment path. * * @param segmentPath The segment path. * @param userSegmentCursor The user segment cursor (Used to populate the list of shard cursors). */ public SegmentCursor(String segmentPath, SegmentCursor userSegmentCursor) { this.segmentPath = segmentPath; /* Deep copy the user segment cursor's list of shard cursors to make a new segment cursor. */ /* We need to do this since a shard cursor could sit at the end of a shard, in which case an event will not * be emitted, but we need to retain it in the list of shard cursors since the absence of a shard cursor * indicates we need to start from the beginning of a shard. */ List<ShardCursor> copy = new ArrayList<>(); if (userSegmentCursor != null) { userSegmentCursor.getShardCursors() .forEach(shardCursor -> copy.add(new ShardCursor(shardCursor.getCurrentChunkPath(), shardCursor.getBlockOffset(), shardCursor.getEventIndex()))); } this.shardCursors = copy; this.currentShardPath = null; } /** * Creates a new shard level cursor with the specified shard path. * * @param shardPath The shard path. * @return A new shard level {@link SegmentCursor cursor}. */ public SegmentCursor toShardCursor(String shardPath) { /* Not cloning shard cursors list so we save state within the segment level. */ return new SegmentCursor(this.segmentPath, this.shardCursors, shardPath); } /** * Creates a new event level cursor with the specified chunk path, block offset and event index. * * @param chunkPath The chunk path. * @param blockOffset The block offset. * @param eventIndex The event index. * @return A new event level {@link SegmentCursor cursor}. */ public SegmentCursor toEventCursor(String chunkPath, long blockOffset, long eventIndex) { /* Deep copy the list to attach to the event. */ List<ShardCursor> copy = new ArrayList<>(this.shardCursors.size() + 1); boolean found = false; /* Whether or not this shardPath exists in the list. */ for (ShardCursor cursor : this.shardCursors) { /* If we found a shard cursor for this shard, modify it. */ if (cursor.getCurrentChunkPath().contains(this.currentShardPath)) { found = true; cursor .setCurrentChunkPath(chunkPath) .setBlockOffset(blockOffset) .setEventIndex(eventIndex); } /* Add the cursor to the copied list after modifying it. */ copy.add(new ShardCursor(cursor.getCurrentChunkPath(), cursor.getBlockOffset(), cursor.getEventIndex())); } /* If a shard cursor for this shard does not exist in the list, add it, and add it to the copied list as well. */ if (!found) { this.shardCursors.add(new ShardCursor(chunkPath, blockOffset, eventIndex)); copy.add(new ShardCursor(chunkPath, blockOffset, eventIndex)); } return new SegmentCursor(this.segmentPath, copy, this.currentShardPath); } /** * @return the segment path. */ public String getSegmentPath() { return segmentPath; } /** * @return the shard cursors. */ public List<ShardCursor> getShardCursors() { return shardCursors; } /** * @return the shard path. */ public String getCurrentShardPath() { return currentShardPath; } /** * @param segmentPath the segment path. * @return the updated SegmentCursor */ public SegmentCursor setSegmentPath(String segmentPath) { this.segmentPath = segmentPath; return this; } /** * @param shardCursors the shard cursors. * @return the updated SegmentCursor */ public SegmentCursor setShardCursors(List<ShardCursor> shardCursors) { this.shardCursors = shardCursors; return this; } /** * @param currentShardPath the shard path. * @return the updated SegmentCursor */ public SegmentCursor setCurrentShardPath(String currentShardPath) { this.currentShardPath = currentShardPath; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof SegmentCursor)) { return false; } SegmentCursor that = (SegmentCursor) o; return Objects.equals(getShardCursors(), that.getShardCursors()) && Objects.equals(getCurrentShardPath(), that.getCurrentShardPath()) && Objects.equals(getSegmentPath(), that.getSegmentPath()); } @Override public int hashCode() { return Objects.hash(getShardCursors(), getCurrentShardPath(), getSegmentPath()); } }
2,504
716
<filename>src/OrbitGl/TrackHeaderTest.cpp // Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gmock/gmock.h> #include <gtest/gtest.h> #include "CaptureViewElementTester.h" #include "TrackControlInterface.h" #include "TrackHeader.h" namespace orbit_gl { using ::testing::Exactly; using testing::Return; class MockTrack : public TrackControlInterface { public: MOCK_METHOD(bool, IsPinned, (), (const override)); MOCK_METHOD(void, SetPinned, (bool), (override)); MOCK_METHOD(std ::string, GetLabel, (), (const override)); MOCK_METHOD(std::string, GetName, (), (const override)); MOCK_METHOD(int, GetNumberOfPrioritizedTrailingCharacters, (), (const override)); MOCK_METHOD(Color, GetTrackBackgroundColor, (), (const override)); MOCK_METHOD(uint32_t, GetIndentationLevel, (), (const override)); MOCK_METHOD(bool, IsCollapsible, (), (const override)); MOCK_METHOD(bool, Draggable, (), (override)); MOCK_METHOD(bool, IsTrackSelected, (), (const override)); MOCK_METHOD(void, SelectTrack, (), (override)); MOCK_METHOD(void, DragBy, (float), (override)); }; TEST(TrackHeader, TrackHeaderDragsTheTrack) { CaptureViewElementTester tester; MockTrack track; const int kDelta = 5; EXPECT_CALL(track, DragBy(kDelta)).Times(Exactly(2)); EXPECT_CALL(track, Draggable()).Times(Exactly(2)).WillRepeatedly(Return(true)); TrackHeader header(nullptr, tester.GetViewport(), tester.GetLayout(), &track); header.UpdateLayout(); header.OnPick(0, 0); header.OnDrag(0, kDelta); header.OnDrag(0, kDelta); header.OnRelease(); } TEST(TrackHeader, TrackHeaderDoesNotDragNonDraggableTracks) { CaptureViewElementTester tester; MockTrack track; const int kDelta = 5; EXPECT_CALL(track, DragBy(kDelta)).Times(Exactly(0)); EXPECT_CALL(track, Draggable()).Times(Exactly(2)).WillRepeatedly(Return(false)); TrackHeader header(nullptr, tester.GetViewport(), tester.GetLayout(), &track); header.UpdateLayout(); header.OnPick(0, 0); header.OnDrag(0, kDelta); header.OnDrag(0, kDelta); header.OnRelease(); } TEST(TrackHeader, ClickingTrackHeadersSelectsTheTrack) { CaptureViewElementTester tester; MockTrack track; EXPECT_CALL(track, SelectTrack()).Times(Exactly(1)); TrackHeader header(nullptr, tester.GetViewport(), tester.GetLayout(), &track); header.UpdateLayout(); header.OnPick(0, 0); header.OnRelease(); } TEST(TrackHeader, CollapseToggleWorksForCollapsibleTracks) { CaptureViewElementTester tester; MockTrack track; EXPECT_CALL(track, IsCollapsible()).WillRepeatedly(Return(true)); TrackHeader header(nullptr, tester.GetViewport(), tester.GetLayout(), &track); header.UpdateLayout(); TriangleToggle* toggle = header.GetCollapseToggle(); EXPECT_TRUE(toggle->IsCollapsible()); EXPECT_FALSE(toggle->IsCollapsed()); toggle->OnPick(0, 0); toggle->OnRelease(); EXPECT_TRUE(toggle->IsCollapsed()); } TEST(TrackHeader, CollapseToggleDoesNotWorkForNonCollapsibleTracks) { CaptureViewElementTester tester; MockTrack track; EXPECT_CALL(track, IsCollapsible()).WillRepeatedly(Return(false)); TrackHeader header(nullptr, tester.GetViewport(), tester.GetLayout(), &track); header.UpdateLayout(); TriangleToggle* toggle = header.GetCollapseToggle(); EXPECT_FALSE(toggle->IsCollapsible()); EXPECT_FALSE(toggle->IsCollapsed()); toggle->OnPick(0, 0); toggle->OnRelease(); EXPECT_FALSE(toggle->IsCollapsed()); } } // namespace orbit_gl
1,193
2,151
<gh_stars>1000+ #!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json from copy import deepcopy from cStringIO import StringIO from functools import partial from hashlib import sha1 from random import random import unittest from zipfile import ZipFile from caching_file_system import CachingFileSystem from file_system import FileNotFoundError, StatInfo from fake_url_fetcher import FakeURLFSFetcher, MockURLFetcher from local_file_system import LocalFileSystem from new_github_file_system import GithubFileSystem from object_store_creator import ObjectStoreCreator from test_file_system import TestFileSystem class _TestBundle(object): '''Bundles test file data with a GithubFileSystem and test utilites. Create GithubFileSystems via |CreateGfs()|, the Fetcher it uses as |fetcher|, randomly mutate its contents via |Mutate()|, and access the underlying zip data via |files|. ''' def __init__(self): self.files = { 'zipfile/': '', 'zipfile/hello.txt': 'world', 'zipfile/readme': 'test zip', 'zipfile/dir/file1': 'contents', 'zipfile/dir/file2': 'more contents' } self._test_files = { 'test_owner': { 'changing-repo': { 'commits': { 'HEAD': self._MakeShaJson(self._GenerateHash()) }, 'zipball': self._ZipFromFiles(self.files) } } } self._fake_fetcher = None def CreateGfsAndFetcher(self): fetchers = [] def create_mock_url_fetcher(base_path): assert not fetchers # Save this reference so we can replace the TestFileSystem in Mutate. self._fake_fetcher = FakeURLFSFetcher( TestFileSystem(self._test_files), base_path) fetchers.append(MockURLFetcher(self._fake_fetcher)) return fetchers[-1] # Constructing |gfs| will create a fetcher. gfs = GithubFileSystem.ForTest( 'changing-repo/', create_mock_url_fetcher, path='') assert len(fetchers) == 1 return gfs, fetchers[0] def Mutate(self): fake_version = self._GenerateHash() fake_data = self._GenerateHash() self.files['zipfile/hello.txt'] = fake_data self.files['zipfile/new-file'] = fake_data self.files['zipfile/dir/file1'] = fake_data self._test_files['test_owner']['changing-repo']['zipball'] = ( self._ZipFromFiles(self.files)) self._test_files['test_owner']['changing-repo']['commits']['HEAD'] = ( self._MakeShaJson(fake_version)) # Update the file_system used by FakeURLFSFetcher so the above mutations # propagate. self._fake_fetcher.UpdateFS(TestFileSystem(self._test_files)) return fake_version, fake_data def _GenerateHash(self): '''Generates an arbitrary SHA1 hash. ''' return sha1(str(random())).hexdigest() def _MakeShaJson(self, hash_value): commit_json = json.loads(deepcopy(LocalFileSystem('').ReadSingle( 'test_data/github_file_system/test_owner/repo/commits/HEAD').Get())) commit_json['sha'] = hash_value return json.dumps(commit_json) def _ZipFromFiles(self, file_dict): string = StringIO() zipfile = ZipFile(string, 'w') for filename, contents in file_dict.iteritems(): zipfile.writestr(filename, contents) zipfile.close() return string.getvalue() class TestGithubFileSystem(unittest.TestCase): def setUp(self): self._gfs = GithubFileSystem.ForTest( 'repo/', partial(FakeURLFSFetcher, LocalFileSystem(''))) # Start and finish the repository load. self._cgfs = CachingFileSystem(self._gfs, ObjectStoreCreator.ForTest()) def testReadDirectory(self): self._gfs.Refresh().Get() self.assertEqual( sorted(['requirements.txt', '.gitignore', 'README.md', 'src/']), sorted(self._gfs.ReadSingle('').Get())) self.assertEqual( sorted(['__init__.notpy', 'hello.notpy']), sorted(self._gfs.ReadSingle('src/').Get())) def testReadFile(self): self._gfs.Refresh().Get() expected = ( '# Compiled Python files\n' '*.pyc\n' ) self.assertEqual(expected, self._gfs.ReadSingle('.gitignore').Get()) def testMultipleReads(self): self._gfs.Refresh().Get() self.assertEqual( self._gfs.ReadSingle('requirements.txt').Get(), self._gfs.ReadSingle('requirements.txt').Get()) def testReads(self): self._gfs.Refresh().Get() expected = { 'src/': sorted(['hello.notpy', '__init__.notpy']), '': sorted(['requirements.txt', '.gitignore', 'README.md', 'src/']) } read = self._gfs.Read(['', 'src/']).Get() self.assertEqual(expected['src/'], sorted(read['src/'])) self.assertEqual(expected[''], sorted(read[''])) def testStat(self): # This is the hash value from the zip on disk. real_hash = 'c36fc23688a9ec9e264d3182905dc0151bfff7d7' self._gfs.Refresh().Get() dir_stat = StatInfo(real_hash, { 'hello.notpy': StatInfo(real_hash), '__init__.notpy': StatInfo(real_hash) }) self.assertEqual(StatInfo(real_hash), self._gfs.Stat('README.md')) self.assertEqual(StatInfo(real_hash), self._gfs.Stat('src/hello.notpy')) self.assertEqual(dir_stat, self._gfs.Stat('src/')) def testBadReads(self): self._gfs.Refresh().Get() self.assertRaises(FileNotFoundError, self._gfs.Stat, 'DONT_README.md') self.assertRaises(FileNotFoundError, self._gfs.ReadSingle('DONT_README.md').Get) def testCachingFileSystem(self): self._cgfs.Refresh().Get() initial_cgfs_read_one = self._cgfs.ReadSingle('src/hello.notpy').Get() self.assertEqual(initial_cgfs_read_one, self._gfs.ReadSingle('src/hello.notpy').Get()) self.assertEqual(initial_cgfs_read_one, self._cgfs.ReadSingle('src/hello.notpy').Get()) initial_cgfs_read_two = self._cgfs.Read( ['README.md', 'requirements.txt']).Get() self.assertEqual( initial_cgfs_read_two, self._gfs.Read(['README.md', 'requirements.txt']).Get()) self.assertEqual( initial_cgfs_read_two, self._cgfs.Read(['README.md', 'requirements.txt']).Get()) def testWithoutRefresh(self): # Without refreshing it will still read the content from blobstore, and it # does this via the magic of the FakeURLFSFetcher. self.assertEqual(['__init__.notpy', 'hello.notpy'], sorted(self._gfs.ReadSingle('src/').Get())) def testRefresh(self): test_bundle = _TestBundle() gfs, fetcher = test_bundle.CreateGfsAndFetcher() # It shouldn't fetch until Refresh does so; then it will do 2, one for the # stat, and another for the read. self.assertTrue(*fetcher.CheckAndReset()) gfs.Refresh().Get() self.assertTrue(*fetcher.CheckAndReset(fetch_count=1, fetch_async_count=1, fetch_resolve_count=1)) # Refresh is just an alias for Read(''). gfs.Refresh().Get() self.assertTrue(*fetcher.CheckAndReset()) initial_dir_read = sorted(gfs.ReadSingle('').Get()) initial_file_read = gfs.ReadSingle('dir/file1').Get() version, data = test_bundle.Mutate() # Check that changes have not effected the file system yet. self.assertEqual(initial_dir_read, sorted(gfs.ReadSingle('').Get())) self.assertEqual(initial_file_read, gfs.ReadSingle('dir/file1').Get()) self.assertNotEqual(StatInfo(version), gfs.Stat('')) gfs, fetcher = test_bundle.CreateGfsAndFetcher() gfs.Refresh().Get() self.assertTrue(*fetcher.CheckAndReset(fetch_count=1, fetch_async_count=1, fetch_resolve_count=1)) # Check that the changes have affected the file system. self.assertEqual(data, gfs.ReadSingle('new-file').Get()) self.assertEqual(test_bundle.files['zipfile/dir/file1'], gfs.ReadSingle('dir/file1').Get()) self.assertEqual(StatInfo(version), gfs.Stat('new-file')) # Regression test: ensure that reading the data after it's been mutated, # but before Refresh() has been realised, still returns the correct data. gfs, fetcher = test_bundle.CreateGfsAndFetcher() version, data = test_bundle.Mutate() refresh_future = gfs.Refresh() self.assertTrue(*fetcher.CheckAndReset(fetch_count=1, fetch_async_count=1)) self.assertEqual(data, gfs.ReadSingle('new-file').Get()) self.assertEqual(test_bundle.files['zipfile/dir/file1'], gfs.ReadSingle('dir/file1').Get()) self.assertEqual(StatInfo(version), gfs.Stat('new-file')) refresh_future.Get() self.assertTrue(*fetcher.CheckAndReset(fetch_resolve_count=1)) def testGetThenRefreshOnStartup(self): # Regression test: Test that calling Get() but never resolving the future, # then Refresh()ing the data, causes the data to be refreshed. test_bundle = _TestBundle() gfs, fetcher = test_bundle.CreateGfsAndFetcher() self.assertTrue(*fetcher.CheckAndReset()) # Get a predictable version. version, data = test_bundle.Mutate() read_future = gfs.ReadSingle('hello.txt') # Fetch for the Stat(), async-fetch for the Read(). self.assertTrue(*fetcher.CheckAndReset(fetch_count=1, fetch_async_count=1)) refresh_future = gfs.Refresh() self.assertTrue(*fetcher.CheckAndReset()) self.assertEqual(data, read_future.Get()) self.assertTrue(*fetcher.CheckAndReset(fetch_resolve_count=1)) self.assertEqual(StatInfo(version), gfs.Stat('hello.txt')) self.assertTrue(*fetcher.CheckAndReset()) # The fetch will already have been resolved, so resolving the Refresh won't # affect anything. refresh_future.Get() self.assertTrue(*fetcher.CheckAndReset()) # Read data should not have changed. self.assertEqual(data, gfs.ReadSingle('hello.txt').Get()) self.assertEqual(StatInfo(version), gfs.Stat('hello.txt')) self.assertTrue(*fetcher.CheckAndReset()) if __name__ == '__main__': unittest.main()
4,119
3,372
<reponame>rbalamohan/aws-sdk-java /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ec2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceResult; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RegisterTransitGatewayMulticastGroupSourcesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Information about the transit gateway multicast group sources. * </p> */ private TransitGatewayMulticastRegisteredGroupSources registeredMulticastGroupSources; /** * <p> * Information about the transit gateway multicast group sources. * </p> * * @param registeredMulticastGroupSources * Information about the transit gateway multicast group sources. */ public void setRegisteredMulticastGroupSources(TransitGatewayMulticastRegisteredGroupSources registeredMulticastGroupSources) { this.registeredMulticastGroupSources = registeredMulticastGroupSources; } /** * <p> * Information about the transit gateway multicast group sources. * </p> * * @return Information about the transit gateway multicast group sources. */ public TransitGatewayMulticastRegisteredGroupSources getRegisteredMulticastGroupSources() { return this.registeredMulticastGroupSources; } /** * <p> * Information about the transit gateway multicast group sources. * </p> * * @param registeredMulticastGroupSources * Information about the transit gateway multicast group sources. * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterTransitGatewayMulticastGroupSourcesResult withRegisteredMulticastGroupSources( TransitGatewayMulticastRegisteredGroupSources registeredMulticastGroupSources) { setRegisteredMulticastGroupSources(registeredMulticastGroupSources); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRegisteredMulticastGroupSources() != null) sb.append("RegisteredMulticastGroupSources: ").append(getRegisteredMulticastGroupSources()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RegisterTransitGatewayMulticastGroupSourcesResult == false) return false; RegisterTransitGatewayMulticastGroupSourcesResult other = (RegisterTransitGatewayMulticastGroupSourcesResult) obj; if (other.getRegisteredMulticastGroupSources() == null ^ this.getRegisteredMulticastGroupSources() == null) return false; if (other.getRegisteredMulticastGroupSources() != null && other.getRegisteredMulticastGroupSources().equals(this.getRegisteredMulticastGroupSources()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRegisteredMulticastGroupSources() == null) ? 0 : getRegisteredMulticastGroupSources().hashCode()); return hashCode; } @Override public RegisterTransitGatewayMulticastGroupSourcesResult clone() { try { return (RegisterTransitGatewayMulticastGroupSourcesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
1,613
17,481
<reponame>marcin-kozinski/dagger<gh_stars>1000+ /* * Copyright (C) 2021 The Dagger 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 dagger.internal.codegen; import static com.google.testing.compile.CompilationSubject.assertThat; import static dagger.internal.codegen.Compilers.daggerCompiler; import com.google.testing.compile.Compilation; import com.google.testing.compile.JavaFileObjects; import javax.tools.JavaFileObject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class RawTypeInjectionTest { @Test public void rawEntryPointTest() { JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component", "interface TestComponent {", " Foo foo();", // Fail: requesting raw type "}"); JavaFileObject foo = JavaFileObjects.forSourceLines( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "class Foo<T> {", " @Inject Foo() {}", "}"); Compilation compilation = daggerCompiler().compile(component, foo); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining("Foo cannot be provided without an @Provides-annotated method.") .inFile(component) .onLine(6); } @Test public void rawProvidesRequestTest() { JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component(modules = TestModule.class)", "interface TestComponent {", " int integer();", "}"); JavaFileObject foo = JavaFileObjects.forSourceLines( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "class Foo<T> {", " @Inject Foo() {}", "}"); JavaFileObject module = JavaFileObjects.forSourceLines( "test.TestModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "", "@Module", "class TestModule {", " @Provides", " int provideFoo(Foo foo) {", // Fail: requesting raw type " return 0;", " }", "}"); Compilation compilation = daggerCompiler().compile(component, foo, module); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining("Foo cannot be provided without an @Provides-annotated method.") .inFile(component) .onLine(6); } @Test public void rawInjectConstructorRequestTest() { JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component", "interface TestComponent {", " Foo foo();", "}"); JavaFileObject foo = JavaFileObjects.forSourceLines( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "class Foo<T> {", " @Inject Foo() {}", "}"); JavaFileObject bar = JavaFileObjects.forSourceLines( "test.Bar", "package test;", "", "import javax.inject.Inject;", "", "class Bar {", " @Inject Bar(Foo foo) {}", // Fail: requesting raw type "}"); Compilation compilation = daggerCompiler().compile(component, foo, bar); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining("Foo cannot be provided without an @Provides-annotated method.") .inFile(component) .onLine(6); } @Test public void rawProvidesReturnTest() { JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component(modules = TestModule.class)", "interface TestComponent {", // Test that we can request the raw type if it's provided by a module. " Foo foo();", "}"); JavaFileObject foo = JavaFileObjects.forSourceLines( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "class Foo<T> {", " @Inject Foo() {}", "}"); JavaFileObject module = JavaFileObjects.forSourceLines( "test.TestModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "", "@Module", "class TestModule {", // Test that Foo<T> can still be requested and is independent of Foo (otherwise we'd // get a cyclic dependency error). " @Provides", " Foo provideFoo(Foo<Integer> fooInteger) {", " return fooInteger;", " }", "", " @Provides", " int provideInt() {", " return 0;", " }", "}"); Compilation compilation = daggerCompiler().compile(component, foo, module); assertThat(compilation).succeeded(); } }
3,006
1,965
<filename>xbanner/src/main/java/com/stx/xhb/xbanner/transformers/CubePageTransformer.java package com.stx.xhb.xbanner.transformers; import android.support.v4.view.ViewCompat; import android.view.View; /** * Created by jxnk25 on 2016/10/18. * * link https://xiaohaibin.github.io/ * email: <EMAIL> * github: https://github.com/xiaohaibin * description:CubePageTransformer */ public class CubePageTransformer extends BasePageTransformer { private float mMaxRotation = 90.0f; public CubePageTransformer() { } public CubePageTransformer(float maxRotation) { setMaxRotation(maxRotation); } @Override public void handleInvisiblePage(View view, float position) { view.setPivotX(view.getMeasuredWidth()); view.setPivotY( view.getMeasuredHeight() * 0.5f); view.setRotationY(0); } @Override public void handleLeftPage(View view, float position) { view.setPivotX(view.getMeasuredWidth()); view.setPivotY( view.getMeasuredHeight() * 0.5f); view.setRotationY(mMaxRotation * position); } @Override public void handleRightPage(View view, float position) { view.setPivotX( 0); view.setPivotY(view.getMeasuredHeight() * 0.5f); view.setRotationY( mMaxRotation * position); } public void setMaxRotation(float maxRotation) { if (maxRotation >= 0.0f && maxRotation <= 90.0f) { mMaxRotation = maxRotation; } } }
606
332
<gh_stars>100-1000 # -*- coding: utf-8 -*- from django.http import HttpResponse def handle404(request): return HttpResponse('404') def handle500(request): return HttpResponse('500') handler404 = 'autofixture_tests.urls.handle404' handler500 = 'autofixture_tests.urls.handle500' urlpatterns = [ ]
115
321
<filename>Coins in a Line.py """ There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins. Could you please decide the first play will win or lose? Example n = 1, return true. n = 2, return true. n = 3, return false. n = 4, return true. n = 5, return true. Challenge O(1) time and O(1) memory """ __author__ = 'Daniel' class Solution: def firstWillWin(self, n): """ Starting from the easiest cases. Enumerate the cases and find the pattern :param n: an integer :return: a boolean which equals to True if the first player will win """ return not n%3 == 0
254
303
<gh_stars>100-1000 {"id":2377,"line-1":"New South Wales","line-2":"Australia","attribution":"©2014 CNES / Astrium, Cnes/Spot Image, DigitalGlobe, Landsat","url":"https://www.google.com/maps/@-33.422299,141.862517,13z/data=!3m1!1e3"}
92
1,805
<filename>glib-adv/tagcloud.h #ifndef tagcloud_h #define tagcloud_h ///////////////////////////////////////////////// // Includes #include "mine.h" #include "gks.h" ///////////////////////////////////////////////// // Tag-Cloud ClassTP(TTagCloud, PTagCloud)//{ private: TStrFltPrV WordStrWgtPrV; TFltQu RectV; UndefCopyAssign(TTagCloud); public: TTagCloud(): WordStrWgtPrV(){} static PTagCloud TTagCloud::New(){return new TTagCloud();} ~TTagCloud(){} TTagCloud(TSIn& SIn): WordStrWgtPrV(SIn){} static PTagCloud Load(TSIn& SIn){return new TTagCloud(SIn);} void Save(TSOut& SOut) const { WordStrWgtPrV.Save(SOut);} // create static PTagCloud GetFromDocStrWgtPrV(const TStrFltPrV& DocStrWgtPrV, const int& TopWords, const double& TopWordsWgtSumPrc); void PlaceWords(); // files static PTagCloud LoadBin(const TStr& FNm){ TFIn SIn(FNm); return Load(SIn);} void SaveBin(const TStr& FNm){ TFOut SOut(FNm); Save(SOut);} void Dump(); }; #endif
434
803
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <tchar.h> #include "os.hxx" #ifdef BUILD_ENV_IS_NT #include "esent_x.h" #else #include "jet.h" #endif #include "bfreqs.hxx" // requisite thunked out types #include "_bfconst.hxx" // BF constants and simple types we need #include "bfftl.hxx" // BF trace data and IDs #include "bfftldriver.hxx" // header for this library IOREASON g_iorThunk( (IOREASONPRIMARY) 1 ); // Terminates the FTL reader. void BFFTLITermFTLReader( __in BFFTLContext * const pbfftlc ) { Assert( !pbfftlc->pftlr || pbfftlc->pftl ); if ( pbfftlc->pftlr ) { // note FTLTerm destroys pbfftlc->pftlr as well pbfftlc->pftl->FTLTerm(); pbfftlc->pftlr = NULL; } if ( pbfftlc->pftl ) { delete pbfftlc->pftl; pbfftlc->pftl = NULL; } } class CFileSystemConfiguration : public CDefaultFileSystemConfiguration { public: CFileSystemConfiguration() { m_dtickAccessDeniedRetryPeriod = 2000; m_cbMaxReadSize = 512 * 1024; m_cbMaxWriteSize = 384 * 1024; } } g_fsconfigFTL; // Initializes the FTL reader. ERR ErrBFFTLIInitFTLReader( __in BFFTLContext * const pbfftlc, __in const WCHAR * const wszTraceLogFile ) { ERR err = JET_errSuccess; Assert( pbfftlc ); Assert( !pbfftlc->pftl ); Assert( !pbfftlc->pftlr ); Alloc( pbfftlc->pftl = new CFastTraceLog( NULL, &g_fsconfigFTL ) ); Call( pbfftlc->pftl->ErrFTLInitReader( wszTraceLogFile, &g_iorThunk, ( pbfftlc->grbit & fBFFTLDriverCollectFTLStats ) ? CFastTraceLog::ftlifKeepStats : CFastTraceLog::ftlifNone, &( pbfftlc->pftlr ) ) ); HandleError: if ( err < JET_errSuccess ) { BFFTLITermFTLReader( pbfftlc ); } return err; } // Initializes the BF trace driver's handle / context ERR ErrBFFTLInit( __in const void * const pvTraceDataLog, __in const DWORD grbit, __out BFFTLContext ** ppbfftlc ) { ERR err = JET_errSuccess; Alloc( *ppbfftlc = new BFFTLContext() ); BFFTLContext * const pbfftlc = *ppbfftlc; memset( pbfftlc, 0, sizeof(BFFTLContext) ); pbfftlc->grbit = grbit; if ( grbit & fBFFTLDriverTestMode ) { pbfftlc->rgFakeTraces = (BFTRACE*)pvTraceDataLog; } else { // Deal with real trace log(s) // // Count how many logs we need to process. ULONG cTraceLogFiles = 0; const WCHAR * wszTraceLogFiles = (WCHAR*)pvTraceDataLog; while ( ( wszTraceLogFiles != NULL ) && ( wszTraceLogFiles[0] != L'\0' ) ) { if ( wszTraceLogFiles[0] == L',' ) { wszTraceLogFiles++; continue; } cTraceLogFiles++; wszTraceLogFiles = wcsstr( wszTraceLogFiles, L"," ); } if ( cTraceLogFiles == 0 ) { Error( ErrERRCheck( JET_errInvalidPath ) ); } if ( ( grbit & fBFFTLDriverCollectFTLStats ) && ( cTraceLogFiles > 1 ) ) { // Not supported when working with multiple files. Error( ErrERRCheck( JET_errInvalidParameter ) ); } // Allocate space for all file paths. Alloc( pbfftlc->wszTraceLogFiles = new WCHAR*[ cTraceLogFiles ] ); memset( pbfftlc->wszTraceLogFiles, 0, cTraceLogFiles * sizeof( WCHAR* ) ); pbfftlc->cTraceLogFiles = cTraceLogFiles; pbfftlc->iTraceLogFile = 0; // Collect all paths to our array of paths. ULONG iTraceLogFile = 0; wszTraceLogFiles = (WCHAR*)pvTraceDataLog; while ( ( wszTraceLogFiles != NULL ) && ( wszTraceLogFiles[0] != L'\0' ) ) { if ( wszTraceLogFiles[0] == L',' ) { wszTraceLogFiles++; continue; } const WCHAR * const wszTraceLogFileBegin = wszTraceLogFiles; wszTraceLogFiles = wcsstr( wszTraceLogFiles, L"," ); const WCHAR * const wszTraceLogFileEnd = ( wszTraceLogFiles == NULL ) ? ( wszTraceLogFileBegin + wcslen( wszTraceLogFileBegin ) ) : wszTraceLogFiles; const ULONG cchTraceLogFile = (ULONG)( wszTraceLogFileEnd - wszTraceLogFileBegin ); Alloc( pbfftlc->wszTraceLogFiles[iTraceLogFile] = new WCHAR[cchTraceLogFile + 1] ); memcpy( pbfftlc->wszTraceLogFiles[iTraceLogFile], wszTraceLogFileBegin, cchTraceLogFile * sizeof(WCHAR) ); ( pbfftlc->wszTraceLogFiles[iTraceLogFile] )[cchTraceLogFile] = L'\0'; iTraceLogFile++; } Assert( cTraceLogFiles == iTraceLogFile ); // Collect max ifmp and pgnoMax from the multiple trace files. ULONG cifmpMin = ulMax, cifmpMax = 0; for ( iTraceLogFile = 0; iTraceLogFile < pbfftlc->cTraceLogFiles; iTraceLogFile++ ) { Call( ErrBFFTLIInitFTLReader( pbfftlc, pbfftlc->wszTraceLogFiles[iTraceLogFile] ) ); CFastTraceLog::BFFTLFilePostProcessHeader* const pPostProcessHeader = (CFastTraceLog::BFFTLFilePostProcessHeader *)( pbfftlc->pftl->PvFTLPrivatePostHeader() ); const ULONG cifmp = pPostProcessHeader->le_cifmp; Assert( cifmp <= ifmpMax ); cifmpMin = min( cifmpMin, cifmp ); cifmpMax = max( cifmpMax, cifmp ); BFFTLITermFTLReader( pbfftlc ); } // If any of the traces was not processed (0 ifmps), force the client to process them by // returning 0 in the IFMP count. Should we error out instead? if ( cifmpMin == 0 ) { pbfftlc->cIFMP = cifmpMin; } else { pbfftlc->cIFMP = cifmpMax; } // Max all pgnoMaxes. if ( pbfftlc->cIFMP != 0 ) { for ( iTraceLogFile = 0; iTraceLogFile < pbfftlc->cTraceLogFiles; iTraceLogFile++ ) { Call( ErrBFFTLIInitFTLReader( pbfftlc, pbfftlc->wszTraceLogFiles[iTraceLogFile] ) ); CFastTraceLog::BFFTLFilePostProcessHeader* const pPostProcessHeader = (CFastTraceLog::BFFTLFilePostProcessHeader *)( pbfftlc->pftl->PvFTLPrivatePostHeader() ); const ULONG cifmp = pPostProcessHeader->le_cifmp; Assert( cifmp != 0 ); for ( ULONG ifmp = 0; ifmp < cifmp; ifmp++ ) { pbfftlc->rgpgnoMax[ifmp] = max( (ULONG)pbfftlc->rgpgnoMax[ifmp], pPostProcessHeader->le_mpifmpcpg[ifmp] ); } BFFTLITermFTLReader( pbfftlc ); } } // FTL reader (open first file). Assert( pbfftlc->cTraceLogFiles > 0 ); Assert( pbfftlc->iTraceLogFile == 0 ); Call( ErrBFFTLIInitFTLReader( pbfftlc, pbfftlc->wszTraceLogFiles[pbfftlc->iTraceLogFile] ) ); } HandleError: return err; } // Shuts down and frees resources maintained by the BFFTLContext. void BFFTLTerm( __out BFFTLContext * pbfftlc ) { if ( !pbfftlc ) { return; } // FTL reader. BFFTLITermFTLReader( pbfftlc ); // Trace file path strings. if ( pbfftlc->wszTraceLogFiles ) { for ( ULONG iTraceLogFile = 0; iTraceLogFile < pbfftlc->cTraceLogFiles; iTraceLogFile++ ) { if ( !pbfftlc->wszTraceLogFiles[iTraceLogFile] ) { continue; } delete[] pbfftlc->wszTraceLogFiles[iTraceLogFile]; pbfftlc->wszTraceLogFiles[iTraceLogFile] = NULL; } delete[] pbfftlc->wszTraceLogFiles; pbfftlc->wszTraceLogFiles = NULL; } delete pbfftlc; } /* BOOL FBFFTLPostProcessed( __in const CFastTraceLog * pftl, const ULONG ulPostProcessVersionMajor ) { AssertSz( fFalse, "FBFFTLPostProcessed() NYI!" ); return fFalse; } ERR ErrBFFTLPostProcess( __inout CFastTraceLog * pftl ) { ERR err = JET_errSuccess; AssertSz( fFalse, "ErrBFFTLPostProcess() NYI!" ); return err; } PGNO CpgBFFTLHighPgnoRef( __in const IFMP ifmp ) { AssertSz( fFalse, "CpgBFFTLHighPgnoRef() NYI!" ); return -1; } */ ERR ErrBFFTLIUpdIfmpCpgStats( __inout BFFTLContext * pbfftlc, __in const IFMP ifmp, __in const PGNO pgno ) { if ( ifmp >= _countof( pbfftlc->rgpgnoMax ) ) { return ErrERRCheck( JET_errInvalidParameter ); } if ( ifmp >= pbfftlc->cIFMP ) { pbfftlc->cIFMP = ifmp + 1; } if ( (INT)pgno > pbfftlc->rgpgnoMax[ifmp] ) { pbfftlc->rgpgnoMax[ifmp] = pgno; } return JET_errSuccess; } ERR ErrBFFTLIAddSample( __inout BFFTLContext * pbfftlc, __out BFTRACE * pbftrace ) { ERR err = JET_errSuccess; switch( pbftrace->traceid ) { case bftidSysResMgrInit: pbfftlc->cSysResMgrInit++; break; case bftidSysResMgrTerm: pbfftlc->cSysResMgrTerm++; break; case bftidCache: CallR( ErrBFFTLIUpdIfmpCpgStats( pbfftlc, pbftrace->bfcache.ifmp, pbftrace->bfcache.pgno ) ); pbfftlc->cCache++; break; case bftidVerifyInfo: pbfftlc->cVerify++; break; case bftidTouchLong: case bftidTouch: CallR( ErrBFFTLIUpdIfmpCpgStats( pbfftlc, pbftrace->bftouch.ifmp, pbftrace->bftouch.pgno ) ); pbfftlc->cTouch++; break; case bftidDirty: CallR( ErrBFFTLIUpdIfmpCpgStats( pbfftlc, pbftrace->bfdirty.ifmp, pbftrace->bfdirty.pgno ) ); pbfftlc->cDirty++; break; case bftidWrite: CallR( ErrBFFTLIUpdIfmpCpgStats( pbfftlc, pbftrace->bfwrite.ifmp, pbftrace->bfwrite.pgno ) ); pbfftlc->cWrite++; break; case bftidSetLgposModify: CallR( ErrBFFTLIUpdIfmpCpgStats( pbfftlc, pbftrace->bfsetlgposmodify.ifmp, pbftrace->bfsetlgposmodify.pgno ) ); pbfftlc->cSetLgposModify++; break; case bftidEvict: CallR( ErrBFFTLIUpdIfmpCpgStats( pbfftlc, pbftrace->bfevict.ifmp, pbftrace->bfevict.pgno ) ); pbfftlc->cEvict++; break; case bftidSuperCold: pbfftlc->cSuperCold++; break; default: // test code uses bftidFTLReserved as discardable trace ... ugh AssertSz( pbftrace->traceid == bftidFTLReserved, "Unknown BF FTL Trace (%d)!\n", (ULONG)pbftrace->traceid ); wprintf( L"T:%08x { Unknown BF FTL Trace }\n", pbftrace->tick ); } return JET_errSuccess; } // Gets the next trace record in the Buffer Manager FTL trace log file, returning success if we were // able to get the trace, errNotFound if we're done with the trace file, and an a specific error in // any case. ERR ErrBFFTLGetNext( __inout BFFTLContext * pbfftlc, __out BFTRACE * pbftrace ) { ERR err = JET_errSuccess; if ( pbfftlc->grbit & fBFFTLDriverTestMode ) { if ( pbfftlc->rgFakeTraces[pbfftlc->iFake].traceid == bftidInvalid ) { Error( ErrERRCheck( errNotFound ) ); } *pbftrace = pbfftlc->rgFakeTraces[pbfftlc->iFake]; pbfftlc->iFake++; } else { // real traces: this loop will only normally execute once, unless we're switching files. while ( true ) { const ERR errGetNext = pbfftlc->pftlr->ErrFTLGetNextTrace( &(pbfftlc->ftltraceCurrent) ); if ( errGetNext == errNotFound ) { Assert( pbfftlc->cTraceLogFiles > 0 ); Assert( pbfftlc->iTraceLogFile < pbfftlc->cTraceLogFiles ); // switch to the next trace file, if any if ( ( pbfftlc->iTraceLogFile + 1 ) < pbfftlc->cTraceLogFiles ) { err = JET_errSuccess; BFFTLITermFTLReader( pbfftlc ); pbfftlc->iTraceLogFile++; Call( ErrBFFTLIInitFTLReader( pbfftlc, pbfftlc->wszTraceLogFiles[pbfftlc->iTraceLogFile] ) ); continue; } else { err = errGetNext; } } Call( errGetNext ); break; } pbftrace->traceid = pbfftlc->ftltraceCurrent.ftltid; pbftrace->tick = pbfftlc->ftltraceCurrent.tick; if ( ( sizeof(*pbftrace) - OffsetOf( BFTRACE_, bfinit ) ) < pbfftlc->ftltraceCurrent.cbTraceData ) { AssertSz( fFalse, "Hmmm, we have a data chunk that doesn't fit in the BFTRACE? Mismatched version?" ); Error( ErrERRCheck( JET_errInvalidParameter ) ); } memcpy( &(pbftrace->bfinit), pbfftlc->ftltraceCurrent.pbTraceData, pbfftlc->ftltraceCurrent.cbTraceData ); } Assert( pbftrace->traceid != 0 ); // accumulate statistics pbfftlc->cTracesProcessed++; (void)ErrBFFTLIAddSample( pbfftlc, pbftrace ); HandleError: // once empty returns errNotFound return err; } QWORD IbBFFTLBookmark( __out const BFFTLContext * pbfftlc ) { Assert( pbfftlc ); if ( pbfftlc == NULL ) { return 0; } return pbfftlc->ftltraceCurrent.ibBookmark; } ERR ErrBFFTLPostProcess( __in const BFFTLContext * pbfftlc ) { ERR err = JET_errSuccess; CFastTraceLog::BFFTLFilePostProcessHeader * pPostProcessHeader = (CFastTraceLog::BFFTLFilePostProcessHeader *) malloc( pbfftlc->pftl->CbPrivateHeader() ); C_ASSERT( sizeof(CFastTraceLog::BFFTLFilePostProcessHeader) <= 1024 ); Assert( sizeof(CFastTraceLog::BFFTLFilePostProcessHeader) <= pbfftlc->pftl->CbPrivateHeader() ); if ( 0 == ( pbfftlc->grbit & fBFFTLDriverCollectBFStats ) ) { // if stats weren't collected, impossible to update post proc header return ErrERRCheck( JET_errInvalidParameter ); } pPostProcessHeader->le_cifmp = (ULONG)pbfftlc->cIFMP; memcpy( pPostProcessHeader->le_mpifmpcpg, pbfftlc->rgpgnoMax, sizeof(CPG)*pbfftlc->cIFMP ); CallR( pbfftlc->pftl->ErrFTLSetPostProcessHeader( pPostProcessHeader ) ); return err; } #define DblPct( numerator, denominator ) ( ((double)numerator)/((double)denominator)*100.0 ) // Dumps stats about the trace file processed ERR ErrBFFTLDumpStats( __in const BFFTLContext * pbfftlc, __in const DWORD grbit ) { wprintf( L"Dumping pbfftlc = %p with grbit = 0x%x\n", pbfftlc, grbit ); wprintf( L"\n" ); // Dump the IFMP + cpgMax map // CFastTraceLog::BFFTLFilePostProcessHeader * pPostProcessHeader = (CFastTraceLog::BFFTLFilePostProcessHeader *)( pbfftlc->pftl->PvFTLPrivatePostHeader() ); wprintf( L" Processed file that has %d | %d ifmps\n", pbfftlc->cIFMP, pPostProcessHeader->le_cifmp ); ULONG ifmp; for ( ifmp = 0; ifmp < pbfftlc->cIFMP && ifmp < _countof(pPostProcessHeader->le_mpifmpcpg); ifmp++ ) { wprintf( L" [ifmp=%d].cpgMax = %d | %d\n", ifmp, pbfftlc->rgpgnoMax[ifmp], pPostProcessHeader->le_mpifmpcpg[ifmp] ); } if ( ifmp == _countof(pPostProcessHeader->le_mpifmpcpg) ) { wprintf( L" OVERFLOW of pPostProcessHeader->le_mpifmpcpg array!\n" ); } // Dump FTL-level stats // if ( grbit & fBFFTLDriverCollectFTLStats ) { CallS( pbfftlc->pftlr->ErrFTLDumpStats() ); wprintf( L"\n" ); } // Dump BF-level stats // if ( grbit & fBFFTLDriverCollectBFStats ) { wprintf( L"BF Stats:\n" ); wprintf( L" Traces: %8I64d\n", pbfftlc->cTracesProcessed ); wprintf( L" bftidSysResMgrInit: %8I64d\n", pbfftlc->cSysResMgrInit ); wprintf( L" bftidSysResMgrTerm: %8I64d\n", pbfftlc->cSysResMgrTerm ); wprintf( L" bftidCache: %8I64d (%6.3f%%)\n", pbfftlc->cCache, DblPct( pbfftlc->cCache, pbfftlc->cTracesProcessed ) ); wprintf( L" bftidVerify: %8I64d (%6.3f%%)\n", pbfftlc->cVerify, DblPct( pbfftlc->cVerify, pbfftlc->cTracesProcessed ) ); wprintf( L" bftidTouch[Long]: %8I64d (%6.3f%%, TC Ratio=%3.1f)\n", pbfftlc->cTouch, DblPct( pbfftlc->cTouch, pbfftlc->cTracesProcessed ), ( (double)pbfftlc->cTouch / (double)pbfftlc->cCache ) ); wprintf( L" bftidWrite: %8I64d (%6.3f%%)\n", pbfftlc->cWrite, DblPct( pbfftlc->cWrite, pbfftlc->cTracesProcessed ) ); wprintf( L" bftidDirty: %8I64d (%6.3f%%)\n", pbfftlc->cDirty, DblPct( pbfftlc->cDirty, pbfftlc->cTracesProcessed ) ); wprintf( L" bftidSetLgposModify: %8I64d (%6.3f%%)\n", pbfftlc->cSetLgposModify, DblPct( pbfftlc->cSetLgposModify, pbfftlc->cTracesProcessed ) ); wprintf( L" bftidEvict: %8I64d (%6.3f%%)\n", pbfftlc->cEvict, DblPct( pbfftlc->cEvict, pbfftlc->cTracesProcessed ) ); wprintf( L" bftidSuperCold: %8I64d (%6.3f%%)\n", pbfftlc->cSuperCold, DblPct( pbfftlc->cSuperCold, pbfftlc->cTracesProcessed ) ); } return JET_errSuccess; }
8,817
351
<reponame>sundogrd/tensorflow_end2end_speech_recognition #! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import sys import codecs from glob import glob import numpy as np import pandas as pd sys.path.append('../../../') from experiments.erato.data.load_dataset_ctc import Dataset def main(): results_paths = [path for path in glob( '/home/lab5/inaguma/asru2017/erato_results_0710/test/*.log')] # Julisu Rusults for path in results_paths: with codecs.open(path, 'r', 'euc_jp') as f: start_flag = False file_name = '' output, output_pos = '', '' result_dict = {} for line in f: line = line.strip() if line == '----------------------- System Information end -----------------------': start_flag = True if start_flag: if 'input MFCC file' in line: file_name = line.split(': ')[-1] file_name = '_'.join(file_name.split('/')[-2:]) file_name = re.sub('.wav', '', file_name) if 'sentence1' in line: output = line.split(': ')[-1] output = re.sub('<s>', '', output) output = re.sub('</s>', '', output) output = re.sub('<sp>', '', output) output = re.sub(r'[\sー]+', '', output) if 'wseq1' in line: output_pos = line.split(': ')[-1] output_pos = re.sub('<s>', '', output_pos) output_pos = re.sub('</s>', '', output_pos) output_pos = re.sub('<sp>', '', output_pos) output_pos = re.sub('感動詞', 'F', output_pos) output_pos = re.sub('言いよどみ', 'D', output_pos) result_dict[file_name] = [output, output_pos[1:]] output, output_pos = '', '' dataset = Dataset(data_type='test', label_type='kana', ss_type='insert_left', batch_size=1, max_epoch=1, shuffle=False, progressbar=True) tp_f, fp_f, fn_f = 0., 0., 0. tp_d, fp_d, fn_d = 0., 0., 0. for data, is_new_epoch in dataset: # Create feed dictionary for next mini batch inputs, labels_true, inputs_seq_len, input_names = data if input_names[0][0] not in result_dict.keys(): continue output, output_pos = result_dict[input_names[0][0]] detected_f_num = output_pos.count('F') detected_d_num = output_pos.count('D') if detected_f_num != 0 or detected_d_num != 0: print(output_pos) print(output) str_true = labels_true[0][0][0] print(str_true) print('-----') true_f_num = np.sum(labels_true[0][0][0].count('F')) true_d_num = np.sum(labels_true[0][0][0].count('D')) # Filler if detected_f_num <= true_f_num: tp_f += detected_f_num fn_f += true_f_num - detected_f_num else: tp_f += true_f_num fp_f += detected_f_num - true_f_num # Disfluency if detected_d_num <= true_d_num: tp_d += detected_d_num fn_d += true_d_num - detected_d_num else: tp_d += true_d_num fp_d += detected_d_num - true_d_num if is_new_epoch: break r_f = tp_f / (tp_f + fn_f) if (tp_f + fn_f) != 0 else 0 p_f = tp_f / (tp_f + fp_f) if (tp_f + fp_f) != 0 else 0 f_f = 2 * r_f * p_f / (r_f + p_f) if (r_f + p_f) != 0 else 0 r_d = tp_d / (tp_d + fn_d) if (tp_d + fn_d) != 0 else 0 p_d = tp_d / (tp_d + fp_d) if (tp_d + fp_d) != 0 else 0 f_d = 2 * r_d * p_d / (r_d + p_d) if (r_d + p_d) != 0 else 0 acc_f = [p_f, r_f, f_f] acc_d = [p_d, r_d, f_d] df_acc = pd.DataFrame({'Filler': acc_f, 'Disfluency': acc_d}, columns=['Filler', 'Disfluency'], index=['Precision', 'Recall', 'F-measure']) print(df_acc) if __name__ == '__main__': main()
2,479
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-455c-7cfq-wgff", "modified": "2022-05-01T07:41:09Z", "published": "2022-05-01T07:41:09Z", "aliases": [ "CVE-2006-6759" ], "details": "A certain ActiveX control in rpau3260.dll in RealNetworks RealPlayer 10.5 allows remote attackers to cause a denial of service (Internet Explorer crash) by invoking the RealPlayer.Initialize method with certain arguments.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-6759" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/31138" }, { "type": "WEB", "url": "https://www.exploit-db.com/exploits/2966" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/21689" }, { "type": "WEB", "url": "http://www.securityfocus.com/data/vulnerabilities/exploits/21689.html" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
518
1,337
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.cuba.web.widgets.client.treegrid; import com.google.gwt.dom.client.SpanElement; import com.google.gwt.dom.client.TableCellElement; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.vaadin.client.connectors.grid.TreeRendererConnector; import com.vaadin.client.renderers.HtmlRenderer; import com.vaadin.client.renderers.Renderer; import com.vaadin.client.widget.grid.RendererCellReference; import com.vaadin.shared.ui.Connect; import com.vaadin.ui.Tree; import elemental.json.JsonObject; import javax.annotation.Nullable; import java.util.Objects; @Connect(Tree.TreeRenderer.class) public class CubaTreeRendererConnector extends TreeRendererConnector { protected static final String V_CAPTIONTEXT_STYLENAME = "v-captiontext"; protected static final String ITEM_ICON = "itemIcon"; @Override public Renderer<String> createRenderer() { return new HtmlRenderer() { @Override public void render(RendererCellReference cell, String htmlString) { String content = getContentString(htmlString); Element icon = getIconElement(cell); Element span = findSpan(cell); if (span == null) { _render(cell, content, icon); } else { String oldContent = span.getInnerHTML(); if (!Objects.equals(content, oldContent)) { _render(cell, content, icon); } } } protected Element findSpan(RendererCellReference cell) { TableCellElement cellEl = cell.getElement(); int childCount = DOM.getChildCount(cellEl); for (int i = 0; i < childCount; i++) { Element child = DOM.getChild(cellEl, i); if (SpanElement.TAG.equalsIgnoreCase(child.getTagName())) { return child; } } return null; } protected Element getIconElement(RendererCellReference cell) { Element iconEl = null; JsonObject row = getParent().getParent().getDataSource() .getRow(cell.getRowIndex()); if (row != null && row.hasKey(ITEM_ICON)) { String resourceUrl = getResourceUrl(row.getString(ITEM_ICON)); iconEl = getConnection().getIcon(resourceUrl) .getElement(); } return iconEl; } protected void _render(RendererCellReference cell, String content, @Nullable Element icon) { Element span = DOM.createSpan(); span.addClassName(V_CAPTIONTEXT_STYLENAME); span.setInnerSafeHtml(SafeHtmlUtils.fromSafeConstant(content)); TableCellElement cellEl = cell.getElement(); cellEl.removeAllChildren(); if (icon != null) { cellEl.appendChild(icon); } cellEl.appendChild(span); } private String getContentString(String htmlString) { switch (getState().mode) { case HTML: return htmlString; case PREFORMATTED: return "<pre>" + SafeHtmlUtils.htmlEscape(htmlString) + "</pre>"; default: return SafeHtmlUtils.htmlEscape(htmlString); } } }; } }
2,025
451
<filename>test/monitoring/conftest.py import dataclasses import http import http.server import selectors import socket from concurrent.futures import ThreadPoolExecutor from types import TracebackType from typing import Callable, Iterator, Type import pytest @dataclasses.dataclass(frozen=True) class LoggedRequest: path: str body: bytes class LoggingServer(http.server.HTTPServer): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.requests: list[LoggedRequest] = [] class LoggingRequestHandler(http.server.BaseHTTPRequestHandler): server: LoggingServer def do_POST(self) -> None: request_body_size = int(self.headers["Content-Length"]) request_body = self.rfile.read(request_body_size) self.server.requests.append(LoggedRequest(path=self.path, body=request_body)) self.send_response(http.HTTPStatus.FOUND) self.end_headers() @pytest.fixture(scope="module", name="shared_logging_server") def fixture_shared_logging_server(get_available_port: Callable[[], int]) -> Iterator[LoggingServer]: server_address = ("localhost", get_available_port()) server = LoggingServer(server_address, RequestHandlerClass=LoggingRequestHandler, bind_and_activate=True) with ThreadPoolExecutor(max_workers=1) as executor: executor.submit(server.serve_forever) try: yield server finally: server.shutdown() @pytest.fixture(name="logging_server") def fixture_logging_server(shared_logging_server: LoggingServer) -> Iterator[LoggingServer]: try: yield shared_logging_server finally: shared_logging_server.requests.clear() class UdpServer: def __init__(self, port: int) -> None: self.port = port self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) def __enter__(self) -> "UdpServer": self.socket.bind(("localhost", self.port)) return self def __exit__(self, exc_type: Type, exc_val: BaseException, exc_tb: TracebackType) -> None: self.socket.close() def has_message(self) -> bool: selector = selectors.DefaultSelector() selector.register(self.socket, selectors.EVENT_READ) try: return len(selector.select(timeout=-1)) > 0 finally: selector.unregister(self.socket) def get_message(self) -> str: return self.socket.recv(2048).decode()
954
14,668
<filename>net/dns/public/util.h<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_DNS_PUBLIC_UTIL_H_ #define NET_DNS_PUBLIC_UTIL_H_ #include <string> #include "base/strings/string_piece.h" #include "net/base/address_family.h" #include "net/base/ip_endpoint.h" #include "net/base/net_export.h" namespace net { // Basic utility functions for interaction with MDNS and host resolution. namespace dns_util { // Returns true if the URI template is acceptable for sending requests. If so, // the |server_method| is set to "GET" if the template contains a "dns" variable // and to "POST" otherwise. Any "dns" variable may not be part of the hostname, // and the expanded template must parse to a valid HTTPS URL. NET_EXPORT_PRIVATE bool IsValidDohTemplate(base::StringPiece server_template, std::string* server_method); // Gets the endpoint for the multicast group a socket should join to receive // MDNS messages. Such sockets should also bind to the endpoint from // GetMDnsReceiveEndPoint(). // // This is also the endpoint messages should be sent to to send MDNS messages. NET_EXPORT IPEndPoint GetMdnsGroupEndPoint(AddressFamily address_family); // Gets the endpoint sockets should be bound to to receive MDNS messages. Such // sockets should also join the multicast group from GetMDnsGroupEndPoint(). NET_EXPORT IPEndPoint GetMdnsReceiveEndPoint(AddressFamily address_family); } // namespace dns_util } // namespace net #endif // NET_DNS_PUBLIC_UTIL_H_
525
335
<filename>T/Travertine_noun.json { "word": "Travertine", "definitions": [ "White or light-coloured calcareous rock deposited from mineral springs, used in building." ], "parts-of-speech": "Noun" }
86
12,895
/* * This file and its contents are licensed under the Apache License 2.0. * Please see the included NOTICE for copyright information and * LICENSE-APACHE for a copy of the license. */ #ifndef TIMESCALEDB_LOADER_LWLOCKS_H #define TIMESCALEDB_LOADER_LWLOCKS_H #define RENDEZVOUS_CHUNK_APPEND_LWLOCK "ts_chunk_append_lwlock" void ts_lwlocks_shmem_startup(void); void ts_lwlocks_shmem_alloc(void); #endif /* TIMESCALEDB_LOADER_LWLOCKS_H */
175
1,048
#coding:utf-8 import os import shutil from cactus.plugin.loader import CustomPluginsLoader from cactus.plugin.manager import PluginManager from cactus.tests import SiteTestCase class TestPluginLoader(SiteTestCase): def setUp(self): super(TestPluginLoader, self).setUp() self.site.plugin_manager = PluginManager(self.site, [CustomPluginsLoader(self.site.path)]) shutil.rmtree(self.site.plugin_path) os.makedirs(self.site.plugin_path) def _load_test_plugin(self, plugin, to_filename): src_path = os.path.join('cactus', 'tests', 'data', 'plugins', plugin) dst_path = os.path.join(self.site.plugin_path, to_filename) shutil.copy(src_path, dst_path) self.site.plugin_manager.reload() def test_ignore_disabled(self): self._load_test_plugin('test.py', 'test.disabled.py') self.assertEqual([], [p for p in self.site.plugin_manager.plugins if not p.builtin]) def test_load_plugin(self): self._load_test_plugin('test.py', 'test.py') plugins = self.site.plugin_manager.plugins self.assertEqual(1, len(plugins )) self.assertEqual('plugin_test', plugins[0].plugin_name) self.assertEqual(2, plugins[0].ORDER) def test_defaults(self): """ Check that defaults get initialized """ self._load_test_plugin('empty.py', 'empty.py') plugins = self.site.plugin_manager.plugins plugin = plugins[0] self.assert_(hasattr(plugin, 'preBuild')) self.assert_(hasattr(plugin, 'postBuild')) self.assertEqual(-1, plugin.ORDER) def test_call(self): """ Check that plugins get called """ self._load_test_plugin('test.py', 'call.py') plugins = self.site.plugin_manager.plugins plugin = plugins[0] self.assertEqual('plugin_call', plugin.plugin_name) # Just to check we're looking at the right one. self.site.build() # preBuild self.assertEqual(1, len(plugin.preBuild.calls)) self.assertEqual((self.site,), plugin.preBuild.calls[0]['args']) # preBuildPage self.assertEqual(len(self.site.pages()), len(plugin.preBuildPage.calls)) for call in plugin.preBuildPage.calls: self.assertIn(len(call['args']), (3, 4)) # postBuildPage self.assertEqual(len(self.site.pages()), len(plugin.postBuildPage.calls)) #postBuild self.assertEqual(1, len(plugin.postBuild.calls)) self.assertEqual((self.site,), plugin.postBuild.calls[0]['args'])
1,093
419
<gh_stars>100-1000 #include "ResourceLoader_PhysicsRagdoll.h" #include "Engine/Physics/PhysicsRagdoll.h" #include "Engine/Physics/PhysicsSystem.h" #include "System/Core/Serialization/BinaryArchive.h" //------------------------------------------------------------------------- using namespace physx; //------------------------------------------------------------------------- namespace KRG::Physics { RagdollLoader::RagdollLoader() { m_loadableTypes.push_back( RagdollDefinition::GetStaticResourceTypeID() ); } void RagdollLoader::SetPhysics( PhysicsSystem* pPhysicsSystem ) { KRG_ASSERT( pPhysicsSystem != nullptr && m_pPhysicsSystem == nullptr ); m_pPhysicsSystem = pPhysicsSystem; } bool RagdollLoader::LoadInternal( ResourceID const& resID, Resource::ResourceRecord* pResourceRecord, Serialization::BinaryMemoryArchive& archive ) const { KRG_ASSERT( archive.IsValid() ); RagdollDefinition* pRagdoll = KRG::New<RagdollDefinition>(); archive >> *pRagdoll; pResourceRecord->SetResourceData( pRagdoll ); return pRagdoll->IsValid(); } Resource::InstallResult RagdollLoader::Install( ResourceID const& resourceID, Resource::ResourceRecord* pResourceRecord, Resource::InstallDependencyList const& installDependencies ) const { RagdollDefinition* pRagdoll = pResourceRecord->GetResourceData<RagdollDefinition>(); pRagdoll->m_pSkeleton = GetInstallDependency( installDependencies, pRagdoll->m_pSkeleton.GetResourceID() ); pRagdoll->CreateRuntimeData(); return Resource::InstallResult::Succeeded; } }
578
1,542
""" Title: Guide to the Functional API Author: fchollet Date created: 2020/04/04 Last modified: 2020/04/04 Description: Complete guide to the functional API. """ """ ## Setup """ import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers tf.keras.backend.clear_session() # For easy reset of notebook state. """ ## Introduction The Keras *functional API* is a way to create models that is more flexible than the `tf.keras.Sequential` API. The functional API can handle models with non-linear topology, models with shared layers, and models with multiple inputs or outputs. The main idea that a deep learning model is usually a directed acyclic graph (DAG) of layers. So the functional API is a way to build *graphs of layers*. Consider the following model: ``` (input: 784-dimensional vectors) ↧ [Dense (64 units, relu activation)] ↧ [Dense (64 units, relu activation)] ↧ [Dense (10 units, softmax activation)] ↧ (output: logits of a probability distribution over 10 classes) ``` This is a basic graph with three layers. To build this model using the functional API, start by creating an input node: """ inputs = keras.Input(shape=(784,)) """ The shape of the data is set as a 784-dimensional vector. The batch size is always omitted since only the shape of each sample is specified. If, for example, you have an image input with a shape of `(32, 32, 3)`, you would use: """ # Just for demonstration purposes. img_inputs = keras.Input(shape=(32, 32, 3)) """ The `inputs` that is returned contains information about the shape and `dtype` of the input data that you feed to your model: """ inputs.shape inputs.dtype """ You create a new node in the graph of layers by calling a layer on this `inputs` object: """ dense = layers.Dense(64, activation="relu") x = dense(inputs) """ The "layer call" action is like drawing an arrow from "inputs" to this layer you created. You're "passing" the inputs to the `dense` layer, and out you get `x`. Let's add a few more layers to the graph of layers: """ x = layers.Dense(64, activation="relu")(x) outputs = layers.Dense(10)(x) """ At this point, you can create a `Model` by specifying its inputs and outputs in the graph of layers: """ model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model") """ Let's check out what the model summary looks like: """ model.summary() """ You can also plot the model as a graph: """ keras.utils.plot_model(model, "my_first_model.png") """ And, optionally, display the input and output shapes of each layer in the plotted graph: """ keras.utils.plot_model(model, "my_first_model_with_shape_info.png", show_shapes=True) """ This figure and the code are almost identical. In the code version, the connection arrows are replaced by the call operation. A "graph of layers" is an intuitive mental image for a deep learning model, and the functional API is a way to create models that closely mirror this. """ """ ## Training, evaluation, and inference Training, evaluation, and inference work exactly in the same way for models built using the functional API as for `Sequential` models. Here, load the MNIST image data, reshape it into vectors, fit the model on the data (while monitoring performance on a validation split), then evaluate the model on the test data: """ (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x_train.reshape(60000, 784).astype("float32") / 255 x_test = x_test.reshape(10000, 784).astype("float32") / 255 model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.RMSprop(), metrics=["accuracy"], ) history = model.fit(x_train, y_train, batch_size=64, epochs=1, validation_split=0.2) test_scores = model.evaluate(x_test, y_test, verbose=2) print("Test loss:", test_scores[0]) print("Test accuracy:", test_scores[1]) """ For further reading, see the [train and evaluate](./train_and_evaluate.ipynb) guide. """
1,255
1,861
<reponame>iamdarshshah/spectrum // Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "All.h" namespace facebook { namespace spectrum { namespace core { namespace matchers { namespace reasons { const folly::StringPiece CropUnsupported{ "characteristic_matcher_crop_unsupported"}; } namespace { bool _matchesCropRequirement( const Rule::CropSupport cropSupport, const spectrum::requirements::Crop& cropRequirement) { switch (cropSupport) { case Rule::CropSupport::None: return false; case Rule::CropSupport::Exact: return true; case Rule::CropSupport::Approximate: { return !cropRequirement.mustBeExact; } default: SPECTRUM_UNREACHABLE; } } } // namespace Result matchesCropRequirement( const Rule& rule, const Operation::Parameters& parameters) { const auto& cropRequirement = parameters.transformations.cropRequirement; if (cropRequirement.hasValue() && !_matchesCropRequirement(rule.cropSupport, *cropRequirement)) { return reasons::CropUnsupported; } return Result::ok(); } } // namespace matchers } // namespace core } // namespace spectrum } // namespace facebook
424
2,610
import itertools def tsp_action_go_from_a_to_b(a, b): # 0: Up, 1: Down, 2: Left, 3: Right action = None cur_x = a[0] cur_y = a[1] tar_x = b[0] tar_y = b[1] x_diff = tar_x - cur_x y_diff = tar_y - cur_y if abs(x_diff) >= abs(y_diff): # Move horizontally if x_diff > 0: action = 3 elif x_diff < 0: action = 2 else: # Move vertically if y_diff > 0: action = 0 elif y_diff < 0: action = 1 return action import numpy as np def create_dist_matrix(all_xy, num_stops): # D[i,j] is the cost of going from i to j D = {i: {} for i in range(num_stops)} # index 0 is the restaurant # Create distance matrix for i in range(num_stops): for j in range(i + 1, num_stops): dist = manhattan_dist(all_xy[i][0], all_xy[i][1], all_xy[j][0], all_xy[j][1]) D[i][j] = dist D[j][i] = dist return D def tsp_dp_approx_sol(res_xy, orders_xy): # This baseline is for the TSP problem, # a single agent traveling all orders starting and finishing at a single restaurant # assuming res_xy = (res_x, res_y), orders_xy = [(order1_x, order1_y), ...] all_xy = [res_xy] + orders_xy num_stops = len(all_xy) D = create_dist_matrix(all_xy, num_stops) # Best cost in stage i for each order DP = {i: {} for i in range(num_stops)} # Subsequent visits in the best route from stage i on for each order DP_will_visit = {i: {} for i in range(num_stops)} # DP solution, backwards for i in reversed(range(num_stops)): # This is the final visit to the restaurant if i == num_stops - 1: for o in range(1, num_stops): DP[i][o] = D[o][0] DP_will_visit[i][o] = [o] else: if i == 0: stop_list = [0] else: stop_list = range(1, num_stops) for o in stop_list: min_dist = np.inf min_o_next = None for o_next in range(1, num_stops): if o_next in DP_will_visit[i + 1].keys(): if o not in DP_will_visit[i + 1][o_next]: cost = D[o][o_next] + DP[i + 1][o_next] if cost < min_dist: min_o_next = o_next min_dist = cost if min_o_next: DP[i][o] = min_dist DP_will_visit[i][o] = [o] + DP_will_visit[i + 1][min_o_next] print(DP) print(DP_will_visit) return DP[0], DP_will_visit[0][0] + [0] def manhattan_dist(x1, y1, x2, y2): return np.abs(x1 - x2) + np.abs(y1 - y2) def tsp_dp_opt_sol(res_xy, orders_xy): all_xy = [res_xy] + orders_xy num_stops = len(all_xy) D = create_dist_matrix(all_xy, num_stops) C = {} # Subtour cost dictionary, (set of nodes in the subtour, last node) P = {} # Subtour path dictionary, (set of nodes in the subtour, last node) # Initialize C for o in range(1, num_stops): C[frozenset({o}), o] = D[0][o] P[frozenset({o}), o] = [0, o] for s in range(2, num_stops): for S in itertools.combinations(range(1, num_stops), s): for o in S: search_keys = [(frozenset(S) - {o}, m) for m in S if m != o] search_list = [C[S_o, m] + D[m][o] for S_o, m in search_keys] min_val = min(search_list) opt_key = search_keys[search_list.index(min_val)] C[frozenset(S), o] = min_val P[frozenset(S), o] = P[opt_key] + [o] final_set = frozenset(range(1, num_stops)) search_list = [C[final_set, o] + D[o][0] for o in final_set] best_cost = min(search_list) opt_final_order = search_list.index(best_cost) + 1 best_route = P[final_set, opt_final_order] + [0] return best_cost, best_route
2,120
892
<reponame>github/advisory-database { "schema_version": "1.2.0", "id": "GHSA-5pqm-hfmj-g8jg", "modified": "2022-05-13T01:32:20Z", "published": "2022-05-13T01:32:20Z", "aliases": [ "CVE-2018-3763" ], "details": "In Nextcloud Calendar before 1.5.8 and 1.6.1, a missing sanitization of search results for an autocomplete field could lead to a stored XSS requiring user-interaction. The missing sanitization only affected group names, hence malicious search results could only be crafted by privileged users like admins or group admins.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-3763" }, { "type": "WEB", "url": "https://nextcloud.com/security/advisory/?id=nc-sa-2018-004" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
470
340
<reponame>gajubadge11/HackerRank-1 #!/bin/python3 import sys def solve(n, bar, d, m): res = 0 for a_i in range(len(bar)-m+1): if sum(bar[a_i:a_i+m]) == d: res += 1 return res n = int(input().strip()) bar = list(map(int, input().strip().split(' '))) d, m = input().strip().split(' ') d, m = [int(d), int(m)] result = solve(n, bar, d, m) print(result)
197
349
<gh_stars>100-1000 package com.ray3k.skincomposer.dialog.scenecomposer.undoables; import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer; import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposerModel; public class SliderAnimationDurationUndoable implements SceneComposerUndoable { private DialogSceneComposerModel.SimSlider slider; private DialogSceneComposer dialog; private float animationDuration; private float previousAnimationDuration; public SliderAnimationDurationUndoable(float animationDuration) { this.animationDuration = animationDuration; dialog = DialogSceneComposer.dialog; slider = (DialogSceneComposerModel.SimSlider) dialog.simActor; previousAnimationDuration = slider.animationDuration; } @Override public void undo() { slider.animationDuration = previousAnimationDuration; if (dialog.simActor != slider) { dialog.simActor = slider; dialog.populateProperties(); dialog.populatePath(); } dialog.model.updatePreview(); } @Override public void redo() { slider.animationDuration = animationDuration; if (dialog.simActor != slider) { dialog.simActor = slider; dialog.populateProperties(); dialog.populatePath(); } dialog.model.updatePreview(); } @Override public String getRedoString() { return "Redo \"Slider animation duration " + animationDuration + "\""; } @Override public String getUndoString() { return "Undo \"Slider animation duration " + animationDuration + "\""; } }
685
2,291
<filename>issues/osmdroid_issue324.json<gh_stars>1000+ { "id" : 324, "status" : "Invalid", "summary" : "Download osmdroid.zip from android app.", "labels" : [ "Type-Other", "Priority-Medium" ], "stars" : 0, "commentCount" : 4, "comments" : [ { "id" : 0, "commenterId" : 4335488640438512661, "content" : "Is there any method to download map programatically i don't want to use MOBAC for download osmdroid.zip but download from my android application.\r\nIs it possible to do this?\r\n", "timestamp" : 1332153502, "attachments" : [ ] }, { "id" : 1, "commenterId" : 4335488640438512661, "content" : "http://stackoverflow.com/questions/9747765/how-can-download-map-in-osmdroid/9749861#9749861", "timestamp" : 1332153763, "attachments" : [ ] }, { "id" : 2, "commenterId" : 8937367184059112911, "content" : "There's also the packager - see the wiki HowToUsePackager. But if you want to write your own that's also possible.", "timestamp" : 1332162667, "attachments" : [ ] }, { "id" : 3, "commenterId" : 7646092065249173135, "content" : "There is no method to do this. You will have to write your own.\r\n\r\nStack Overflow is a more appropriate place for a question like this. Thank you.\r\n", "timestamp" : 1333746589, "attachments" : [ ] } ] }
540
708
<reponame>ethz-asl/Matterport #pragma once #include "mLibInclude.h" #include "keyPoint.h" #include "imageHelper.h" class MatchVisualization { public: static void visulizeMatches(const std::vector<SensorData*>& sds, const std::vector<KeyPointMatch>& matches, const std::vector<KeyPoint>& keypoints, size_t numPairs, size_t minMatches = 1) { size_t currMatch = 0; for (size_t i = 0; i < numPairs;) { std::vector<KeyPointMatch> curr; for (;; currMatch++) { if (currMatch >= matches.size()) break; if (curr.size() == 0) curr.push_back(matches[currMatch]); else if (curr.front().isSameImagePair(matches[currMatch], keypoints)) curr.push_back(matches[currMatch]); else break; } if (curr.size() >= minMatches) { const KeyPointMatch& r = curr.front(); ColorImageR8G8B8 img0 = sds[keypoints[r.m_kp0].m_sensorIdx]->computeColorImage(keypoints[r.m_kp0].m_imageIdx); ColorImageR8G8B8 img1 = sds[keypoints[r.m_kp1].m_sensorIdx]->computeColorImage(keypoints[r.m_kp1].m_imageIdx); ColorImageR8G8B8 m = match(img0, img1, curr, keypoints); const std::string filename = "matches_" + std::to_string(keypoints[r.m_kp0].m_imageIdx) + "_" + std::to_string(keypoints[r.m_kp1].m_imageIdx) + ".png"; std::cout << "creating debug file: " << filename << " ( " << curr.size() << " matches ) " << std::endl; FreeImageWrapper::saveImage(filename, m); i++; } if (currMatch >= matches.size()) break; } } static void visulizeMatches(const std::vector<std::vector<ColorImageR8G8B8>>& images, const std::vector<KeyPointMatch>& matches, const std::vector<KeyPoint>& keypoints, size_t numPairs, size_t minMatches = 1) { size_t currMatch = 0; for (size_t i = 0; i < numPairs;) { std::vector<KeyPointMatch> curr; for (;; currMatch++) { if (currMatch >= matches.size()) break; if (curr.size() == 0) curr.push_back(matches[currMatch]); else if (curr.front().isSameImagePair(matches[currMatch], keypoints)) curr.push_back(matches[currMatch]); else break; } if (curr.size() >= minMatches) { const KeyPointMatch& r = curr.front(); const ColorImageR8G8B8& img0 = images[keypoints[r.m_kp0].m_sensorIdx][keypoints[r.m_kp0].m_imageIdx]; const ColorImageR8G8B8& img1 = images[keypoints[r.m_kp1].m_sensorIdx][keypoints[r.m_kp1].m_imageIdx]; ColorImageR8G8B8 m = match(img0, img1, curr, keypoints); const std::string filename = "matches_" + std::to_string(keypoints[r.m_kp0].m_imageIdx) + "_" + std::to_string(keypoints[r.m_kp1].m_imageIdx) + ".png"; std::cout << "creating debug file: " << filename << " ( " << curr.size() << " matches ) " << std::endl; FreeImageWrapper::saveImage(filename, m); i++; } if (currMatch >= matches.size()) break; } } private: static ColorImageR8G8B8 match(const ColorImageR8G8B8& img0, const ColorImageR8G8B8& img1, const std::vector<KeyPointMatch>& matches, const std::vector<KeyPoint>& keypoints) { ColorImageR8G8B8 matchImage(img0.getWidth() * 2, img0.getHeight()); matchImage.copyIntoImage(img0, 0, 0); matchImage.copyIntoImage(img1, img1.getWidth(), 0); RGBColor lowColor = ml::RGBColor::Blue; RGBColor highColor = ml::RGBColor::Red; for (size_t i = 0; i < matches.size(); i++) { const KeyPointMatch& kp = matches[i]; //RGBColor c = RGBColor::interpolate(lowColor, highColor, 0.5f); RGBColor c = RGBColor::randomColor(); vec2i p0 = ml::math::round(ml::vec2f(keypoints[kp.m_kp0].m_pixelPos.x, keypoints[kp.m_kp0].m_pixelPos.y)); vec2i p1 = ml::math::round(ml::vec2f(keypoints[kp.m_kp1].m_pixelPos.x, keypoints[kp.m_kp1].m_pixelPos.y)); p1.x += img0.getWidth(); float size0 = keypoints[kp.m_kp0].m_size; float size1 = keypoints[kp.m_kp1].m_size; if (size0 == -std::numeric_limits<float>::infinity()) { size0 = 3.0f; std::cout << "warning: no key size available, using default size " << size0 << std::endl; } if (size1 == -std::numeric_limits<float>::infinity()) { size1 = 3.0f; std::cout << "warning: no key size available, using default size " << size1 << std::endl; } ImageHelper::drawCircle(matchImage, p0, ml::math::round(size0), c.getVec3()); ImageHelper::drawCircle(matchImage, p1, ml::math::round(size1), c.getVec3()); ImageHelper::drawLine(matchImage, p0, p1, c.getVec3()); } return matchImage; } };
1,927
650
/* * Copyright 2012-2021 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 * * https://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.springframework.data.rest.webmvc.json; import java.io.IOException; import java.lang.reflect.Field; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.CollectionFactory; import org.springframework.core.convert.TypeDescriptor; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.projection.TargetAware; import org.springframework.data.repository.support.Repositories; import org.springframework.data.repository.support.RepositoryInvoker; import org.springframework.data.repository.support.RepositoryInvokerFactory; import org.springframework.data.rest.core.UriToEntityConverter; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.core.mapping.ResourceMappings; import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.core.support.EntityLookup; import org.springframework.data.rest.core.support.SelfLinkProvider; import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler; import org.springframework.data.rest.webmvc.PersistentEntityResource; import org.springframework.data.rest.webmvc.mapping.Associations; import org.springframework.data.rest.webmvc.mapping.LinkCollector; import org.springframework.data.util.CastUtils; import org.springframework.data.util.TypeInformation; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.Links; import org.springframework.hateoas.UriTemplate; import org.springframework.hateoas.server.mvc.RepresentationModelProcessorInvoker; import org.springframework.plugin.core.PluginRegistry; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.deser.CreatorProperty; import com.fasterxml.jackson.databind.deser.SettableBeanProperty; import com.fasterxml.jackson.databind.deser.ValueInstantiator; import com.fasterxml.jackson.databind.deser.std.CollectionDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.JsonValueSerializer; import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.type.CollectionLikeType; import com.fasterxml.jackson.databind.util.NameTransformer; /** * Jackson 2 module to serialize and deserialize {@link PersistentEntityResource}s. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class PersistentEntityJackson2Module extends SimpleModule { private static final long serialVersionUID = -7289265674870906323L; private static final Logger LOG = LoggerFactory.getLogger(PersistentEntityJackson2Module.class); private static final TypeDescriptor URI_DESCRIPTOR = TypeDescriptor.valueOf(URI.class); /** * Creates a new {@link PersistentEntityJackson2Module} using the given {@link ResourceMappings}, {@link Repositories} * , {@link RepositoryRestConfiguration}, {@link UriToEntityConverter} and {@link SelfLinkProvider}. * * @param associations must not be {@literal null}. * @param entities must not be {@literal null}. * @param converter must not be {@literal null}. * @param collector must not be {@literal null}. * @param factory must not be {@literal null}. * @param lookupObjectSerializer must not be {@literal null}. * @param invoker must not be {@literal null}. * @param assembler must not be {@literal null}. */ public PersistentEntityJackson2Module(Associations associations, PersistentEntities entities, UriToEntityConverter converter, LinkCollector collector, RepositoryInvokerFactory factory, LookupObjectSerializer lookupObjectSerializer, RepresentationModelProcessorInvoker invoker, EmbeddedResourcesAssembler assembler) { super("persistent-entity-resource", new Version(2, 0, 0, null, "org.springframework.data.rest", "jackson-module")); Assert.notNull(associations, "AssociationLinks must not be null!"); Assert.notNull(entities, "Repositories must not be null!"); Assert.notNull(converter, "UriToEntityConverter must not be null!"); Assert.notNull(collector, "LinkCollector must not be null!"); NestedEntitySerializer serializer = new NestedEntitySerializer(entities, assembler, invoker); addSerializer(new PersistentEntityResourceSerializer(collector)); addSerializer(new ProjectionSerializer(collector, associations, invoker, false)); addSerializer(new ProjectionResourceContentSerializer(false)); setSerializerModifier( new AssociationOmittingSerializerModifier(entities, associations, serializer, lookupObjectSerializer)); setDeserializerModifier( new AssociationUriResolvingDeserializerModifier(entities, associations, converter, factory)); } /** * Custom {@link JsonSerializer} for {@link PersistentEntityResource}s to turn associations into {@link Link}s. * Delegates to standard {@link EntityModel} serialization afterwards. * * @author <NAME> */ @SuppressWarnings("serial") private static class PersistentEntityResourceSerializer extends StdSerializer<PersistentEntityResource> { private final LinkCollector collector; /** * Creates a new {@link PersistentEntityResourceSerializer} using the given {@link PersistentEntities} and * {@link Associations}. * * @param entities must not be {@literal null}. */ private PersistentEntityResourceSerializer(LinkCollector collector) { super(PersistentEntityResource.class); this.collector = collector; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(final PersistentEntityResource resource, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonGenerationException { LOG.debug("Serializing PersistentEntity {}.", resource.getPersistentEntity()); Object content = resource.getContent(); if (hasScalarSerializer(content, provider)) { provider.defaultSerializeValue(content, jgen); return; } Links links = getLinks(resource); if (TargetAware.class.isInstance(content)) { TargetAware targetAware = (TargetAware) content; provider.defaultSerializeValue(new ProjectionResource(targetAware, links), jgen); return; } @SuppressWarnings("deprecation") EntityModel<Object> resourceToRender = new EntityModel<Object>(resource.getContent(), links) { @JsonUnwrapped public Iterable<?> getEmbedded() { return resource.getEmbeddeds(); } }; provider.defaultSerializeValue(resourceToRender, jgen); } private Links getLinks(PersistentEntityResource resource) { Object source = getLinkSource(resource.getContent()); return resource.isNested() ? collector.getLinksForNested(source, resource.getLinks()) : collector.getLinksFor(source, resource.getLinks()); } private Object getLinkSource(Object object) { return TargetAware.class.isInstance(object) ? ((TargetAware) object).getTarget() : object; } private static boolean hasScalarSerializer(Object source, SerializerProvider provider) throws JsonMappingException { JsonSerializer<Object> serializer = provider.findValueSerializer(source.getClass()); return serializer instanceof ToStringSerializer || serializer instanceof StdScalarSerializer; } } /** * {@link BeanSerializerModifier} to drop the property descriptors for associations. * * @author <NAME> */ static class AssociationOmittingSerializerModifier extends BeanSerializerModifier { private final PersistentEntities entities; private final Associations associations; private final NestedEntitySerializer nestedEntitySerializer; private final LookupObjectSerializer lookupObjectSerializer; public AssociationOmittingSerializerModifier(PersistentEntities entities, Associations associations, NestedEntitySerializer nestedEntitySerializer, LookupObjectSerializer lookupObjectSerializer) { Assert.notNull(entities, "PersistentEntities must not be null!"); Assert.notNull(associations, "Associations must not be null!"); Assert.notNull(nestedEntitySerializer, "NestedEntitySerializer must not be null!"); Assert.notNull(lookupObjectSerializer, "LookupObjectSerializer must not be null!"); this.entities = entities; this.associations = associations; this.nestedEntitySerializer = nestedEntitySerializer; this.lookupObjectSerializer = lookupObjectSerializer; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.ser.BeanSerializerModifier#changeProperties(com.fasterxml.jackson.databind.SerializationConfig, com.fasterxml.jackson.databind.BeanDescription, java.util.List) */ @Override public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) { return entities.getPersistentEntity(beanDesc.getBeanClass()).map(entity -> { List<BeanPropertyWriter> result = new ArrayList<BeanPropertyWriter>(); for (BeanPropertyWriter writer : beanProperties) { Optional<? extends PersistentProperty<?>> findProperty = findProperty(writer.getName(), entity, beanDesc); if (!findProperty.isPresent()) { result.add(writer); continue; } findProperty.flatMap(it -> { if (associations.isLookupType(it)) { LOG.debug("Assigning lookup object serializer for {}.", it); writer.assignSerializer(lookupObjectSerializer); return Optional.of(writer); } // Is there a default projection? if (associations.isLinkableAssociation(it)) { return Optional.empty(); } // Skip ids unless explicitly configured to expose if (it.isIdProperty() && !associations.isIdExposed(entity)) { return Optional.empty(); } if (it.isVersionProperty()) { return Optional.empty(); } if (it.isEntity() && !writer.isUnwrapping()) { LOG.debug("Assigning nested entity serializer for {}.", it); writer.assignSerializer(nestedEntitySerializer); } return Optional.of(writer); }).ifPresent(result::add); } return result; }).orElse(beanProperties); } /** * Returns the {@link PersistentProperty} for the property with the given final name (the name that it will be * rendered under eventually). * * @param finalName the output name the property will be rendered under. * @param entity the {@link PersistentEntity} to find the property on. * @param description the Jackson {@link BeanDescription}. * @return */ private Optional<? extends PersistentProperty<?>> findProperty(String finalName, PersistentEntity<?, ? extends PersistentProperty<?>> entity, BeanDescription description) { return description.findProperties().stream()// .filter(it -> it.getName().equals(finalName))// .findFirst().map(it -> entity.getPersistentProperty(it.getInternalName())); } } /** * Serializer to wrap values into an {@link EntityModel} instance and collecting all association links. * * @author <NAME> * @author <NAME> * @since 2.5 */ static class NestedEntitySerializer extends StdSerializer<Object> { private static final long serialVersionUID = -2327469118972125954L; private final PersistentEntities entities; private final EmbeddedResourcesAssembler assembler; private final RepresentationModelProcessorInvoker invoker; public NestedEntitySerializer(PersistentEntities entities, EmbeddedResourcesAssembler assembler, RepresentationModelProcessorInvoker invoker) { super(Object.class); this.entities = entities; this.assembler = assembler; this.invoker = invoker; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (value instanceof Collection) { Collection<?> source = (Collection<?>) value; List<Object> resources = new ArrayList<Object>(); for (Object element : source) { resources.add(toModel(element, provider)); } provider.defaultSerializeValue(resources, gen); } else if (value instanceof Map) { Map<?, ?> source = (Map<?, ?>) value; Map<Object, Object> resources = CollectionFactory.createApproximateMap(value.getClass(), source.size()); for (Entry<?, ?> entry : source.entrySet()) { resources.put(entry.getKey(), toModel(entry.getValue(), provider)); } provider.defaultSerializeValue(resources, gen); } else { provider.defaultSerializeValue(toModel(value, provider), gen); } } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonSerializer#serializeWithType(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider, com.fasterxml.jackson.databind.jsontype.TypeSerializer) */ @Override public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSerializer) throws IOException { serialize(value, gen, provider); } private Object toModel(Object value, SerializerProvider provider) throws JsonMappingException { JsonSerializer<Object> serializer = provider.findValueSerializer(value.getClass()); if (JsonValueSerializer.class.isInstance(serializer)) { return value; } JsonSerializer<Object> unwrappingSerializer = serializer.unwrappingSerializer(NameTransformer.NOP); if (!unwrappingSerializer.isUnwrappingSerializer()) { return value; } PersistentEntity<?, ?> entity = entities.getRequiredPersistentEntity(value.getClass()); return invoker.invokeProcessorsFor(PersistentEntityResource.build(value, entity).// withEmbedded(assembler.getEmbeddedResources(value)).// buildNested()); } } /** * A {@link BeanDeserializerModifier} that registers a custom {@link UriStringDeserializer} for association properties * of {@link PersistentEntity}s. This allows to submit URIs for those properties in request payloads, so that * non-optional associations can be populated on resource creation. * * @author <NAME> */ public static class AssociationUriResolvingDeserializerModifier extends BeanDeserializerModifier { private final PersistentEntities entities; private final Associations associationLinks; private final UriToEntityConverter converter; private final RepositoryInvokerFactory factory; public AssociationUriResolvingDeserializerModifier(PersistentEntities entities, Associations associations, UriToEntityConverter converter, RepositoryInvokerFactory factory) { Assert.notNull(entities, "PersistentEntities must not be null!"); Assert.notNull(associations, "Associations must not be null!"); Assert.notNull(converter, "UriToEntityConverter must not be null!"); Assert.notNull(factory, "RepositoryInvokerFactory must not be null!"); this.entities = entities; this.associationLinks = associations; this.converter = converter; this.factory = factory; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.deser.BeanDeserializerModifier#updateBuilder(com.fasterxml.jackson.databind.DeserializationConfig, com.fasterxml.jackson.databind.BeanDescription, com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder) */ @Override public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BeanDescription beanDesc, BeanDeserializerBuilder builder) { ValueInstantiatorCustomizer customizer = new ValueInstantiatorCustomizer(builder.getValueInstantiator(), config); Iterator<SettableBeanProperty> properties = builder.getProperties(); entities.getPersistentEntity(beanDesc.getBeanClass()).ifPresent(entity -> { while (properties.hasNext()) { SettableBeanProperty property = properties.next(); PersistentProperty<?> persistentProperty = entity.getPersistentProperty(property.getName()); if (persistentProperty == null) { continue; } TypeInformation<?> propertyType = persistentProperty.getTypeInformation(); if (associationLinks.isLookupType(persistentProperty)) { RepositoryInvokingDeserializer repositoryInvokingDeserializer = new RepositoryInvokingDeserializer(factory, persistentProperty); JsonDeserializer<?> deserializer = wrapIfCollection(propertyType, repositoryInvokingDeserializer, config); builder.addOrReplaceProperty(property.withValueDeserializer(deserializer), false); continue; } if (!associationLinks.isLinkableAssociation(persistentProperty)) { continue; } Class<?> actualPropertyType = persistentProperty.getActualType(); UriStringDeserializer uriStringDeserializer = new UriStringDeserializer(actualPropertyType, converter); JsonDeserializer<?> deserializer = wrapIfCollection(propertyType, uriStringDeserializer, config); customizer.replacePropertyIfNeeded(builder, property.withValueDeserializer(deserializer)); } }); return customizer.conclude(builder); } /** * Advanced customization of the {@link CreatorProperty} instances customized to additionally register them with the * {@link ValueInstantiator} backing the {@link BeanDeserializerModifier}. This is necessary as the standard * customization does not propagate into the initial object construction as the {@link CreatorProperty} instances * for that are looked up via the {@link ValueInstantiator} and the property model behind those is not undergoing * the customization currently (Jackson 2.9.9). * * @author <NAME> * @see https://github.com/FasterXML/jackson-databind/issues/2367 */ static class ValueInstantiatorCustomizer { private final SettableBeanProperty[] properties; private final StdValueInstantiator instantiator; ValueInstantiatorCustomizer(ValueInstantiator instantiator, DeserializationConfig config) { this.instantiator = StdValueInstantiator.class.isInstance(instantiator) // ? StdValueInstantiator.class.cast(instantiator) // : null; this.properties = this.instantiator == null || this.instantiator.getFromObjectArguments(config) == null // ? new SettableBeanProperty[0] // : this.instantiator.getFromObjectArguments(config).clone(); // } /** * Replaces the logically same property with the given {@link SettableBeanProperty} on the given * {@link BeanDeserializerBuilder}. In case we get a {@link CreatorProperty} we also register that one to be later * exposed via the {@link ValueInstantiator} backing the {@link BeanDeserializerBuilder}. * * @param builder must not be {@literal null}. * @param property must not be {@literal null}. */ void replacePropertyIfNeeded(BeanDeserializerBuilder builder, SettableBeanProperty property) { builder.addOrReplaceProperty(property, false); if (!CreatorProperty.class.isInstance(property)) { return; } properties[((CreatorProperty) property).getCreatorIndex()] = property; } /** * Concludes the setup of the given {@link BeanDeserializerBuilder} by reflectively registering the potentially * customized {@link SettableBeanProperty} instances in the {@link ValueInstantiator} backing the builder. * * @param builder must not be {@literal null}. * @return */ BeanDeserializerBuilder conclude(BeanDeserializerBuilder builder) { if (instantiator == null) { return builder; } Field field = ReflectionUtils.findField(StdValueInstantiator.class, "_constructorArguments"); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, instantiator, properties); builder.setValueInstantiator(instantiator); return builder; } } private static JsonDeserializer<?> wrapIfCollection(TypeInformation<?> property, JsonDeserializer<Object> elementDeserializer, DeserializationConfig config) { if (!property.isCollectionLike()) { return elementDeserializer; } CollectionLikeType collectionType = config.getTypeFactory().constructCollectionLikeType(property.getType(), property.getActualType().getType()); CollectionValueInstantiator instantiator = new CollectionValueInstantiator(property); return new CollectionDeserializer(collectionType, elementDeserializer, null, instantiator); } } /** * Custom {@link JsonDeserializer} to interpret {@link String} values as URIs and resolve them using a * {@link UriToEntityConverter}. * * @author <NAME> * @author <NAME> */ public static class UriStringDeserializer extends StdDeserializer<Object> { private static final long serialVersionUID = -2175900204153350125L; private static final String UNEXPECTED_VALUE = "Expected URI cause property %s points to the managed domain type!"; private final Class<?> type; private final UriToEntityConverter converter; /** * Creates a new {@link UriStringDeserializer} for the given {@link PersistentProperty} using the given * {@link UriToEntityConverter}. * * @param type must not be {@literal null}. * @param converter must not be {@literal null}. */ public UriStringDeserializer(Class<?> type, UriToEntityConverter converter) { super(type); this.type = type; this.converter = converter; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) */ @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String source = jp.getValueAsString(); if (!StringUtils.hasText(source)) { return null; } try { URI uri = UriTemplate.of(source).expand(); TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(type); return converter.convert(uri, URI_DESCRIPTOR, typeDescriptor); } catch (IllegalArgumentException o_O) { throw ctxt.weirdStringException(source, URI.class, String.format(UNEXPECTED_VALUE, type)); } } /** * Deserialize by ignoring the {@link TypeDeserializer}, as URIs will either resolve to {@literal null} or a * concrete instance anyway. * * @see com.fasterxml.jackson.databind.deser.std.StdDeserializer#deserializeWithType(com.fasterxml.jackson.core.JsonParser, * com.fasterxml.jackson.databind.DeserializationContext, * com.fasterxml.jackson.databind.jsontype.TypeDeserializer) */ @Override public Object deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException { return deserialize(jp, ctxt); } } @SuppressWarnings("serial") static class ProjectionSerializer extends StdSerializer<TargetAware> { private final LinkCollector collector; private final Associations associations; private final RepresentationModelProcessorInvoker invoker; private final boolean unwrapping; /** * Creates a new {@link ProjectionSerializer} for the given {@link LinkCollector}, {@link ResourceMappings} whether * to be in unwrapping mode or not. * * @param collector must not be {@literal null}. * @param mappings must not be {@literal null}. * @param invoker must not be {@literal null}. * @param unwrapping */ private ProjectionSerializer(LinkCollector collector, Associations mappings, RepresentationModelProcessorInvoker invoker, boolean unwrapping) { super(TargetAware.class); this.collector = collector; this.associations = mappings; this.invoker = invoker; this.unwrapping = unwrapping; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(TargetAware value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { if (!unwrapping) { jgen.writeStartObject(); } provider.// findValueSerializer(ProjectionResource.class, null).// unwrappingSerializer(null).// serialize(toModel(value), jgen, provider); if (!unwrapping) { jgen.writeEndObject(); } } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonSerializer#isUnwrappingSerializer() */ @Override public boolean isUnwrappingSerializer() { return unwrapping; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonSerializer#unwrappingSerializer(com.fasterxml.jackson.databind.util.NameTransformer) */ @Override public JsonSerializer<TargetAware> unwrappingSerializer(NameTransformer unwrapper) { return new ProjectionSerializer(collector, associations, invoker, true); } /** * Creates a {@link ProjectionResource} for the given {@link TargetAware}. * * @param value must not be {@literal null}. * @return */ private ProjectionResource toModel(TargetAware value) { Object target = value.getTarget(); ResourceMetadata metadata = associations.getMetadataFor(value.getTargetClass()); Links links = metadata.isExported() ? collector.getLinksFor(target) : Links.NONE; EntityModel<TargetAware> resource = invoker.invokeProcessorsFor(EntityModel.of(value, links)); return new ProjectionResource(resource.getContent(), resource.getLinks()); } } static class ProjectionResource extends EntityModel<ProjectionResourceContent> { @SuppressWarnings("deprecation") ProjectionResource(TargetAware projection, Iterable<Link> links) { super(new ProjectionResourceContent(projection, projection.getClass().getInterfaces()[0]), links); } } static class ProjectionResourceContent { private final Object projection; private final Class<?> projectionInterface; /** * @param projection * @param projectionInterface */ public ProjectionResourceContent(Object projection, Class<?> projectionInterface) { this.projection = projection; this.projectionInterface = projectionInterface; } public Object getProjection() { return projection; } public Class<?> getProjectionInterface() { return projectionInterface; } } @SuppressWarnings("serial") private static class ProjectionResourceContentSerializer extends StdSerializer<ProjectionResourceContent> { private final boolean unwrapping; /** * Creates a new {@link ProjectionResourceContentSerializer}. * * @param unwrapping whether to expose the unwrapping state. */ public ProjectionResourceContentSerializer(boolean unwrapping) { super(ProjectionResourceContent.class); this.unwrapping = unwrapping; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(ProjectionResourceContent value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { provider.// findValueSerializer(value.getProjectionInterface(), null).// unwrappingSerializer(null).// serialize(value.getProjection(), jgen, provider); } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonSerializer#isUnwrappingSerializer() */ @Override public boolean isUnwrappingSerializer() { return unwrapping; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonSerializer#unwrappingSerializer(com.fasterxml.jackson.databind.util.NameTransformer) */ @Override public JsonSerializer<ProjectionResourceContent> unwrappingSerializer(NameTransformer unwrapper) { return new ProjectionResourceContentSerializer(true); } } /** * {@link ValueInstantiator} to create collection or map instances based on the type of the configured * {@link PersistentProperty}. * * @author <NAME> */ static class CollectionValueInstantiator extends ValueInstantiator { private final TypeInformation<?> property; /** * Creates a new {@link CollectionValueInstantiator} for the given {@link PersistentProperty}. * * @param property must not be {@literal null} and must be a collection. */ public CollectionValueInstantiator(TypeInformation<?> property) { Assert.notNull(property, "Property must not be null!"); Assert.isTrue(property.isCollectionLike() || property.isMap(), "Property must be a collection or map property!"); this.property = property; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.deser.ValueInstantiator#getValueTypeDesc() */ @Override public String getValueTypeDesc() { return property.getType().getName(); } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.deser.ValueInstantiator#createUsingDefault(com.fasterxml.jackson.databind.DeserializationContext) */ @Override public Object createUsingDefault(DeserializationContext ctxt) throws IOException, JsonProcessingException { Class<?> collectionOrMapType = property.getType(); return property.isMap() ? CollectionFactory.createMap(collectionOrMapType, 0) : CollectionFactory.createCollection(collectionOrMapType, 0); } } private static class RepositoryInvokingDeserializer extends StdScalarDeserializer<Object> { private static final long serialVersionUID = -3033458643050330913L; private final RepositoryInvoker invoker; private RepositoryInvokingDeserializer(RepositoryInvokerFactory factory, PersistentProperty<?> property) { super(property.getActualType()); this.invoker = factory.getInvokerFor(_valueClass); } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) */ @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { Object id = p.getCurrentToken().isNumeric() ? p.getValueAsLong() : p.getValueAsString(); return invoker.invokeFindById(id).orElse(null); } } public static class LookupObjectSerializer extends ToStringSerializer { private static final long serialVersionUID = -3033458643050330913L; private final PluginRegistry<EntityLookup<?>, Class<?>> lookups; public LookupObjectSerializer(PluginRegistry<EntityLookup<?>, Class<?>> lookups) { Assert.notNull(lookups, "EntityLookups must not be null!"); this.lookups = lookups; } /* * (non-Javadoc) * @see com.fasterxml.jackson.databind.ser.std.ToStringSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (value instanceof Collection) { gen.writeStartArray(); for (Object element : (Collection<?>) value) { gen.writeObject(getLookupKey(element)); } gen.writeEndArray(); } else { gen.writeObject(getLookupKey(value)); } } private Object getLookupKey(Object value) { return lookups.getPluginFor(value.getClass()) // .<EntityLookup<Object>> map(CastUtils::cast) .orElseThrow(() -> new IllegalArgumentException("No EntityLookup found for " + value.getClass().getName())) .getResourceIdentifier(value); } } }
11,272
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/animation/scheduler.hxx> #include <vector> ////////////////////////////////////////////////////////////////////////////// // event class namespace sdr { namespace animation { Event::Event(sal_uInt32 nTime) : mnTime(nTime), mpNext(0L) { } Event::~Event() { } Event* Event::GetNext() const { return mpNext; } void Event::SetNext(Event* pNew) { if(pNew != mpNext) { mpNext = pNew; } } sal_uInt32 Event::GetTime() const { return mnTime; } void Event::SetTime(sal_uInt32 nNew) { if(mnTime != nNew) { mnTime = nNew; } } } // end of namespace animation } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eventlist class namespace sdr { namespace animation { EventList::EventList() : mpHead(0L) { } EventList::~EventList() { Clear(); } void EventList::Insert(Event* pNew) { if(pNew) { Event* pCurrent = mpHead; Event* pPrev = 0L; while(pCurrent && pCurrent->GetTime() < pNew->GetTime()) { pPrev = pCurrent; pCurrent = pCurrent->GetNext(); } if(pPrev) { pNew->SetNext(pPrev->GetNext()); pPrev->SetNext(pNew); } else { pNew->SetNext(mpHead); mpHead = pNew; } } } void EventList::Remove(Event* pOld) { if(pOld && mpHead) { Event* pCurrent = mpHead; Event* pPrev = 0L; while(pCurrent && pCurrent != pOld) { pPrev = pCurrent; pCurrent = pCurrent->GetNext(); } if(pPrev) { pPrev->SetNext(pOld->GetNext()); } else { mpHead = pOld->GetNext(); } pOld->SetNext(0L); } } void EventList::Clear() { while(mpHead) { Event* pNext = mpHead->GetNext(); mpHead->SetNext(0L); mpHead = pNext; } } Event* EventList::GetFirst() { return mpHead; } } // end of namespace animation } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // scheduler class namespace sdr { namespace animation { Scheduler::Scheduler() : mnTime(0L), mnDeltaTime(0L), mbIsPaused(false) { } Scheduler::~Scheduler() { Stop(); } void Scheduler::Timeout() { // stop timer and add time Stop(); mnTime += mnDeltaTime; // execute events triggerEvents(); // re-start or stop timer according to event list checkTimeout(); } void Scheduler::triggerEvents() { Event* pNextEvent = maList.GetFirst(); if(pNextEvent) { // copy events which need to be executed to a vector. Remove them from // the scheduler ::std::vector< Event* > EventPointerVector; while(pNextEvent && pNextEvent->GetTime() <= mnTime) { maList.Remove(pNextEvent); EventPointerVector.push_back(pNextEvent); pNextEvent = maList.GetFirst(); } // execute events from the vector for(::std::vector< Event* >::iterator aCandidate = EventPointerVector.begin(); aCandidate != EventPointerVector.end(); aCandidate++) { // trigger event. This may re-insert the event to the scheduler again (*aCandidate)->Trigger(mnTime); } } } void Scheduler::checkTimeout() { // re-start or stop timer according to event list if(!IsPaused() && maList.GetFirst()) { mnDeltaTime = maList.GetFirst()->GetTime() - mnTime; if(0L != mnDeltaTime) { SetTimeout(mnDeltaTime); Start(); } } else { Stop(); } } sal_uInt32 Scheduler::GetTime() { return mnTime; } // #i38135# void Scheduler::SetTime(sal_uInt32 nTime) { // reset time Stop(); mnTime = nTime; // get event pointer Event* pEvent = maList.GetFirst(); if(pEvent) { // retet event time points while(pEvent) { pEvent->SetTime(nTime); pEvent = pEvent->GetNext(); } if(!IsPaused()) { // without delta time, init events by triggering them. This will invalidate // painted objects and add them to the scheduler again mnDeltaTime = 0L; triggerEvents(); checkTimeout(); } } } void Scheduler::Reset(sal_uInt32 nTime) { mnTime = nTime; mnDeltaTime = 0L; maList.Clear(); } void Scheduler::InsertEvent(Event* pNew) { if(pNew) { maList.Insert(pNew); checkTimeout(); } } void Scheduler::RemoveEvent(Event* pOld) { if(pOld && maList.GetFirst()) { maList.Remove(pOld); checkTimeout(); } } void Scheduler::SetPaused(bool bNew) { if(bNew != mbIsPaused) { mbIsPaused = bNew; checkTimeout(); } } } // end of namespace animation } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof
2,412
348
{"nom":"Aix-en-Ergny","circ":"4ème circonscription","dpt":"Pas-de-Calais","inscrits":114,"abs":51,"votants":63,"blancs":2,"nuls":5,"exp":56,"res":[{"nuance":"LR","nom":"<NAME>","voix":34},{"nuance":"REM","nom":"<NAME>","voix":22}]}
99
1,744
<gh_stars>1000+ /* * Copyright 2014 The Embulk 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 org.embulk.spi; import java.util.List; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigSource; import org.embulk.config.TaskReport; import org.embulk.config.TaskSource; /** * The main class that an Output Plugin implements. * * <p>An Output Plugin writes a sequence of data records in {@link org.embulk.spi.Page}s read from an Input Plugin, or a Filter * Plugin, into the configured destination. * * @since 0.4.0 */ public interface OutputPlugin { /** * A controller of the following tasks provided from the Embulk core. * * @since 0.4.0 */ interface Control { /** * Runs the following tasks of the Output Plugin. * * <p>It would be executed at the end of * {@link #transaction(org.embulk.config.ConfigSource, org.embulk.spi.Schema, int, OutputPlugin.Control)}. * * @param taskSource {@link org.embulk.config.TaskSource} processed for tasks from {@link org.embulk.config.ConfigSource} * @return reports of tasks * * @since 0.7.0 */ List<TaskReport> run(TaskSource taskSource); } /** * Processes the entire output transaction. * * @param config a configuration for the Output Plugin given from a user * @param schema {@link org.embulk.spi.Schema} of the output * @param taskCount the number of tasks * @param control a controller of the following tasks provided from the Embulk core * @return {@link org.embulk.config.ConfigDiff} to represent the difference the next incremental run * * @since 0.4.0 */ ConfigDiff transaction(ConfigSource config, Schema schema, int taskCount, OutputPlugin.Control control); /** * Resumes an output transaction. * * @param taskSource a configuration processed for the task from {@link org.embulk.config.ConfigSource} * @param schema {@link org.embulk.spi.Schema} of the output * @param taskCount the number of tasks * @param control a controller of the following tasks provided from the Embulk core * @return {@link org.embulk.config.ConfigDiff} to represent the difference the next incremental run * * @since 0.4.0 */ ConfigDiff resume(TaskSource taskSource, Schema schema, int taskCount, OutputPlugin.Control control); /** * Cleans up resources used in the transaction. * * @param taskSource a configuration processed for the task from {@link org.embulk.config.ConfigSource} * @param schema {@link org.embulk.spi.Schema} of the output * @param taskCount the number of tasks * @param successTaskReports reports of successful tasks * * @since 0.7.0 */ void cleanup(TaskSource taskSource, Schema schema, int taskCount, List<TaskReport> successTaskReports); /** * Opens a {@link org.embulk.spi.TransactionalPageOutput} instance that receives {@link org.embulk.spi.Page}s from an Input * Plugin, or a Filter Plugin, and writes them into the configured destination. * * <p>It processes each output task. * * @param taskSource a configuration processed for the task from {@link org.embulk.config.ConfigSource} * @param schema {@link org.embulk.spi.Schema} of the output * @param taskIndex the index number of the task * @return an implementation of {@link org.embulk.spi.TransactionalPageOutput} that receives {@link org.embulk.spi.Page}s * from an Input Plugin, or a Filter Plugin, and writes them into the configured destination * * @since 0.4.0 */ TransactionalPageOutput open(TaskSource taskSource, Schema schema, int taskIndex); }
1,457
1,083
/* * 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.carbondata.core.util; import org.apache.carbondata.core.memory.CarbonUnsafe; import org.apache.carbondata.core.metadata.datatype.DataType; import org.apache.carbondata.core.metadata.datatype.DataTypes; public class CarbonUnsafeUtil { /** * Put the data to unsafe memory * * @param dataType * @param data * @param baseObject * @param address * @param size * @param sizeInBytes */ public static void putDataToUnsafe(DataType dataType, Object data, Object baseObject, long address, int size, int sizeInBytes) { dataType = DataTypeUtil.valueOf(dataType.getName()); if (dataType == DataTypes.BOOLEAN) { CarbonUnsafe.getUnsafe().putBoolean(baseObject, address + size, (boolean) data); } else if (dataType == DataTypes.BYTE) { CarbonUnsafe.getUnsafe().putByte(baseObject, address + size, (byte) data); } else if (dataType == DataTypes.SHORT) { CarbonUnsafe.getUnsafe().putShort(baseObject, address + size, (short) data); } else if (dataType == DataTypes.INT) { CarbonUnsafe.getUnsafe().putInt(baseObject, address + size, (int) data); } else if (dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { CarbonUnsafe.getUnsafe().putLong(baseObject, address + size, (long) data); } else if (DataTypes.isDecimal(dataType) || dataType == DataTypes.DOUBLE) { CarbonUnsafe.getUnsafe().putDouble(baseObject, address + size, (double) data); } else if (dataType == DataTypes.FLOAT) { CarbonUnsafe.getUnsafe().putFloat(baseObject, address + size, (float) data); } else if (dataType == DataTypes.BYTE_ARRAY) { CarbonUnsafe.getUnsafe() .copyMemory(data, CarbonUnsafe.BYTE_ARRAY_OFFSET, baseObject, address + size, sizeInBytes); } } /** * Retrieve/Get the data from unsafe memory * * @param dataType * @param baseObject * @param address * @param size * @param sizeInBytes * @return */ public static Object getDataFromUnsafe(DataType dataType, Object baseObject, long address, int size, int sizeInBytes) { dataType = DataTypeUtil.valueOf(dataType.getName()); Object data = new Object(); if (dataType == DataTypes.BOOLEAN) { data = CarbonUnsafe.getUnsafe().getBoolean(baseObject, address + size); } else if (dataType == DataTypes.BYTE) { data = CarbonUnsafe.getUnsafe().getByte(baseObject, address + size); } else if (dataType == DataTypes.SHORT) { data = CarbonUnsafe.getUnsafe().getShort(baseObject, address + size); } else if (dataType == DataTypes.INT) { data = CarbonUnsafe.getUnsafe().getInt(baseObject, address + size); } else if (dataType == DataTypes.LONG || dataType == DataTypes.TIMESTAMP) { data = CarbonUnsafe.getUnsafe().getLong(baseObject, address + size); } else if (DataTypes.isDecimal(dataType) || dataType == DataTypes.DOUBLE) { data = CarbonUnsafe.getUnsafe().getDouble(baseObject, address + size); } else if (dataType == DataTypes.FLOAT) { data = CarbonUnsafe.getUnsafe().getFloat(baseObject, address + size); } else if (dataType == DataTypes.BYTE_ARRAY) { CarbonUnsafe.getUnsafe() .copyMemory(baseObject, address + size, data, CarbonUnsafe.BYTE_ARRAY_OFFSET, sizeInBytes); } return data; } }
1,434
1,574
<reponame>LaudateCorpus1/FirebaseUI-iOS // // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <FirebaseAuthUI/FirebaseAuthUI.h> NS_ASSUME_NONNULL_BEGIN /** @var kGoogleGamesScope @brief The OAuth scope string for the "Games" scope. */ static NSString *const kGoogleGamesScope = @"https://www.googleapis.com/auth/games"; /** @var kGooglePlusMeScope @brief The OAuth scope string for the "plus.me" scope. */ static NSString *const kGooglePlusMeScope = @"https://www.googleapis.com/auth/plus.me"; /** @var kGooglePlusMeScope @brief The OAuth scope string for the user's email scope. */ static NSString *const kGoogleUserInfoEmailScope = @"https://www.googleapis.com/auth/userinfo.email"; /** @var kGooglePlusMeScope @brief The OAuth scope string for the basic G+ profile information scope. */ static NSString *const kGoogleUserInfoProfileScope = @"https://www.googleapis.com/auth/userinfo.profile"; /** @class FUIGoogleAuth @brief AuthUI components for Google Sign In. */ @interface FUIGoogleAuth : NSObject <FUIAuthProvider> /** @property scopes @brief The scopes to use with Google Sign In. @remarks Defaults to using email and profile scopes. For a list of all scopes see https://developers.google.com/identity/protocols/googlescopes. Starting with GoogleSignIn 6.0, scopes are no longer granted upon first authentication and should be requested lazily. */ @property(nonatomic, copy, readonly) NSArray<NSString *> *scopes; /** @property buttonAlignment @brief The alignment of the icon and text of the button. */ @property(nonatomic, readwrite) FUIButtonAlignment buttonAlignment; /** @fn initWithAuthUI @brief Convenience initializer. Calls designated init with default scopes of "email" and "profile". @param authUI The @c FUIAuth instance that manages this provider. */ - (instancetype)initWithAuthUI:(FUIAuth *)authUI; /** @fn initWithAuthUI:scopes: @brief Designated initializer. @param authUI The @c FUIAuth instance that manages this provider. @param scopes The user account scopes required by the app. A list of possible scopes can be found at https://developers.google.com/identity/protocols/googlescopes. Starting with GoogleSignIn 6.0, scopes are no longer granted upon first authentication and should be requested lazily. */ - (instancetype)initWithAuthUI:(FUIAuth *)authUI scopes:(NSArray <NSString *> *)scopes NS_DESIGNATED_INITIALIZER; /** @fn init @brief Convenience initializer. Calls designated init with default scopes of "email" and "profile". */ - (instancetype)init __attribute__((deprecated("Instead use initWithAuthUI:"))); /** @fn initWithScopes: @param scopes The user account scopes required by the app. A list of possible scopes can be found at https://developers.google.com/identity/protocols/googlescopes */ - (instancetype)initWithScopes:(NSArray <NSString *> *)scopes __attribute__((deprecated("Instead use initWithAuthUI:permissions:"))) NS_DESIGNATED_INITIALIZER; /** @fn requestScopesWithPresentingViewController:completion: @brief Requests the scopes in the `scopes` array. */ - (void)requestScopesWithPresentingViewController:(UIViewController *)presentingViewController completion:(FUIAuthProviderSignInCompletionBlock)completion; @end NS_ASSUME_NONNULL_END
1,328
482
package org.surus.pig; import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBException; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.junit.*; import org.surus.pig.ScorePMML; import org.xml.sax.SAXException; public class ScorePMML_AuditTest { // Audit Models private String ensembleAuditModelPath = "./resources/examples/models/ensemble_audit_dectree.xml"; // Tuple Factory private TupleFactory tf = TupleFactory.getInstance(); // -------------------------- // Audit Test Functions // -------------------------- @Test public void ensembleScoringTest_Audit_1() throws IOException, SAXException, JAXBException { Schema inputSchema = buildAuditInputSchema(); // Input/Output Bag Tuple inputTuple = tf.newTuple(); Tuple expected = tf.newTuple(); { // Visit 1, Input: Implicit Signout inputTuple = this.buildAuditInputEvent(1038288L,45,"Private","Bachelor","Married","Repair",27743.82,"Male",0,55,"UnitedStates",7298,1); // Visit 1, Output expected = this.buildAuditOutputEvent(1038288L,45,"Private","Bachelor","Married","Repair",27743.82,"Male",0,55,"UnitedStates",7298,1,"0"); } // Initialize Class ScorePMML evalPMML = new ScorePMML(this.ensembleAuditModelPath); Schema outputScheam = evalPMML.outputSchema(inputSchema); Tuple observed = evalPMML.exec(inputTuple); // Test if (expected.equals(observed)) { System.out.println("ensembleScoringTest_Audit_1: PASS"); } else { System.out.println("---------- EPIC FAIL: ensembleScoringTest_Audit_1 ----------"); System.out.println("Expected: " + expected.toString()); System.out.println("Observed: " + observed.toString()); System.out.println("-------- END EPIC FAIL --------"); } assertEquals(expected,observed); } // -------------------------- // Audit Helper Functions // -------------------------- private Schema buildAuditInputSchema() throws FrontendException { // Build Field Schema List<FieldSchema> fieldSchemas = new ArrayList<FieldSchema>(); fieldSchemas.add(new Schema.FieldSchema("id" , DataType.LONG)); fieldSchemas.add(new Schema.FieldSchema("age" , DataType.INTEGER)); fieldSchemas.add(new Schema.FieldSchema("employment" , DataType.CHARARRAY)); fieldSchemas.add(new Schema.FieldSchema("education" , DataType.CHARARRAY)); fieldSchemas.add(new Schema.FieldSchema("marital" , DataType.CHARARRAY)); fieldSchemas.add(new Schema.FieldSchema("occupation" , DataType.CHARARRAY)); fieldSchemas.add(new Schema.FieldSchema("income" , DataType.DOUBLE)); fieldSchemas.add(new Schema.FieldSchema("gender" , DataType.CHARARRAY)); fieldSchemas.add(new Schema.FieldSchema("deductions" , DataType.DOUBLE)); fieldSchemas.add(new Schema.FieldSchema("hours" , DataType.INTEGER)); fieldSchemas.add(new Schema.FieldSchema("ignore_accounts", DataType.CHARARRAY)); fieldSchemas.add(new Schema.FieldSchema("risk_adjustment", DataType.INTEGER)); fieldSchemas.add(new Schema.FieldSchema("target_adjusted", DataType.INTEGER)); return new Schema(fieldSchemas); } private Tuple buildAuditInputEvent( Long ID , Integer Age , String Employment , String Education , String Marital , String Occupation , Double Income , String Gender , Integer Deductions , Integer Hours , String IGNORE_Accounts , Integer RISK_Adjustment , Integer TARGET_Adjusted) { Tuple newTuple = tf.newTuple(); newTuple.append(ID ); newTuple.append(Age ); newTuple.append(Employment ); newTuple.append(Education ); newTuple.append(Marital ); newTuple.append(Occupation ); newTuple.append(Income ); newTuple.append(Gender ); newTuple.append(Deductions ); newTuple.append(Hours ); newTuple.append(IGNORE_Accounts); newTuple.append(RISK_Adjustment); newTuple.append(TARGET_Adjusted); return newTuple; } private Tuple buildAuditOutputEvent( Long ID , Integer Age , String Employment , String Education , String Marital , String Occupation , Double Income , String Gender , Integer Deductions , Integer Hours , String IGNORE_Accounts , Integer RISK_Adjustment , Integer TARGET_Adjusted , String TARGET_Adjusted_predicted) { Tuple newTuple = tf.newTuple(); newTuple.append(TARGET_Adjusted_predicted); return newTuple; } }
3,157
1,353
package net.lingala.zip4j.util; import net.lingala.zip4j.AbstractIT; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.progress.ProgressMonitor; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.CRC32; import static net.lingala.zip4j.testutils.TestUtils.getTestFileFromResources; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CrcUtilIT extends AbstractIT { @Rule public ExpectedException expectedException = ExpectedException.none(); private ProgressMonitor progressMonitor = new ProgressMonitor(); @Test public void testComputeFileCrcThrowsExceptionWhenFileIsNull() throws IOException { expectedException.expectMessage("input file is null or does not exist or cannot read. " + "Cannot calculate CRC for the file"); expectedException.expect(ZipException.class); CrcUtil.computeFileCrc(null, progressMonitor); } @Test public void testComputeFileCrcThrowsExceptionWhenCannotReadFile() throws IOException { expectedException.expectMessage("input file is null or does not exist or cannot read. " + "Cannot calculate CRC for the file"); expectedException.expect(ZipException.class); File unreadableFile = mock(File.class); when(unreadableFile.exists()).thenReturn(true); when(unreadableFile.canRead()).thenReturn(false); CrcUtil.computeFileCrc(unreadableFile, progressMonitor); } @Test public void testComputeFileCrcThrowsExceptionWhenFileDoesNotExist() throws IOException { expectedException.expectMessage("input file is null or does not exist or cannot read. " + "Cannot calculate CRC for the file"); expectedException.expect(ZipException.class); CrcUtil.computeFileCrc(new File("DoesNotExist"), progressMonitor); } @Test public void testComputeFileCrcGetsValueSuccessfully() throws IOException { testComputeFileCrcForFile(getTestFileFromResources("sample.pdf")); testComputeFileCrcForFile(getTestFileFromResources("sample_text1.txt")); testComputeFileCrcForFile(getTestFileFromResources("sample_text_large.txt")); } private void testComputeFileCrcForFile(File file) throws IOException { long actualFileCrc = calculateFileCrc(file); assertThat(CrcUtil.computeFileCrc(file, progressMonitor)).isEqualTo(actualFileCrc); } private long calculateFileCrc(File file) throws IOException { try(InputStream inputStream = new FileInputStream(file)) { byte[] buffer = new byte[InternalZipConstants.BUFF_SIZE]; int readLen = -1; CRC32 crc32 = new CRC32(); while((readLen = inputStream.read(buffer)) != -1) { crc32.update(buffer, 0, readLen); } return crc32.getValue(); } } }
983
3,428
<gh_stars>1000+ {"id":"01267","group":"easy-ham-1","checksum":{"type":"MD5","value":"88686fe91228476214e39e736ef35838"},"text":"From <EMAIL> Mon Oct 7 12:04:42 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 7476B16F1A\n\tfor <jm@localhost>; Mon, 7 Oct 2002 12:03:22 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 07 Oct 2002 12:03:22 +0100 (IST)\nReceived: from egwn.net (ns2.egwn.net [192.168.3.11]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g9766DK20698 for\n <<EMAIL>>; Mon, 7 Oct 2002 07:06:13 +0100\nReceived: from auth02.nl.egwn.net (localhost [127.0.0.1]) by egwn.net\n (8.11.6/8.11.6/EGWN) with ESMTP id g97602f16257; Mon, 7 Oct 2002 08:00:02\n +0200\nReceived: from snickers.hotpop.com (snickers.hotpop.com [204.57.55.49]) by\n egwn.net (8.11.6/8.11.6/EGWN) with ESMTP id g975xRf15813 for\n <<EMAIL>>; Mon, 7 Oct 2002 07:59:27 +0200\nReceived: from punkass.com (kubrick.hotpop.com [204.57.55.16]) by\n snickers.hotpop.com (Postfix) with SMTP id B035B700A6 for\n <<EMAIL>>; Mon, 7 Oct 2002 05:59:11 +0000 (UTC)\nReceived: from punkass.com (unknown [80.178.1.203]) by smtp-1.hotpop.com\n (Postfix) with ESMTP id B78CF2F813E for <<EMAIL>>;\n Mon, 7 Oct 2002 05:58:30 +0000 (UTC)\nMessage-Id: <<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.1) Gecko/20020830\nX-Accept-Language: en-us, en, he\nMIME-Version: 1.0\nTo: <EMAIL>-zzzlist@<EMAIL>.net\nSubject: apt-get problem ?\nReferences: <<EMAIL>>\n <<EMAIL>>\nContent-Type: text/plain; charset=us-ascii; format=flowed\nContent-Transfer-Encoding: 7bit\nX-Hotpop: ----------------------------------------------- Sent By\n HotPOP.com FREE Email Get your FREE POP email at www.HotPOP.com\n -----------------------------------------------\nX-Mailscanner: Found to be clean, Found to be clean\nSender: [email protected]\nErrors-To: rpm-zz<EMAIL>.net\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nReply-To: <EMAIL>\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Freshrpms RPM discussion list <rpm-zzzlist.freshrpms.net>\nList-Unsubscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://lists.freshrpms.net/pipermail/rpm-zzzlist/>\nX-Original-Date: Mon, 07 Oct 2002 08:01:24 +0200\nDate: Mon, 07 Oct 2002 08:01:24 +0200\n\nWhen I try to use apt-get upgrade\nit wants to install libusb while I got it\n(same version)\nand all collapse because of this.\n\nRoi\n\n\n\n\n\n_______________________________________________\nRPM-List mailing list <<EMAIL>>\nhttp://lists.freshrpms.net/mailman/listinfo/rpm-list\n\n\n"}
1,289
1,405
<filename>sample5/recompiled_java/sources/com/network/android/g.java<gh_stars>1000+ package com.network.android; import android.content.Context; import android.util.Xml; import com.network.android.a.c; import com.network.android.c.a.a; import com.network.b.b; import java.io.ByteArrayOutputStream; import java.io.StringWriter; import java.net.HttpURLConnection; import java.util.Iterator; import java.util.Vector; import java.util.zip.GZIPOutputStream; import org.xmlpull.v1.XmlSerializer; public final class g { public static final byte[] b = "0".getBytes(); private static long c; private static HttpURLConnection d; private static final byte[] e = "\r\n".getBytes(); private static final byte[] f = "\"; filename=\"".getBytes(); private static final byte[] g = "\"\r\nContent-Type: ".getBytes(); private static final byte[] h = "--__ANDROID_BOUNDARY__--\r\n".getBytes(); private static final byte[] i = "--__ANDROID_BOUNDARY__\r\nContent-Disposition: form-data; name=\"".getBytes(); private static final byte[] j = "\r\n\r\n".getBytes(); private static final byte[] k = "text/xml".getBytes(); private static final byte[] l = "header".getBytes(); private static final byte[] m = "data".getBytes(); private static final byte[] n = "application/zip".getBytes(); private static final byte[] o = "image/jpeg".getBytes(); private static final String p = null; private static final String q = null; private static int r = 0; /* renamed from: a reason: collision with root package name */ byte[] f78a = k; public static ByteArrayOutputStream a(byte[] bArr) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream); gZIPOutputStream.write(bArr); gZIPOutputStream.close(); return byteArrayOutputStream; } private static void a(Context context, byte[] bArr, byte[] bArr2, StringWriter stringWriter, String str, Vector vector) { XmlSerializer newSerializer = Xml.newSerializer(); SmsReceiver.a(newSerializer, stringWriter, context); if (!vector.isEmpty()) { newSerializer.startTag("", "ackList"); Iterator it = vector.iterator(); while (it.hasNext()) { String str2 = (String) it.next(); a.a("add to header commandId - " + str2); newSerializer.startTag("", "ack"); newSerializer.attribute("", "id", str2); newSerializer.endTag("", "ack"); } newSerializer.endTag("", "ackList"); c.b = null; } if (c.i) { newSerializer.startTag("", "unkey"); newSerializer.text(b.e); newSerializer.endTag("", "unkey"); } newSerializer.startTag("", "telemetry"); newSerializer.text(c.c()); newSerializer.endTag("", "telemetry"); newSerializer.startTag("", "dataCollectionFiles"); a(bArr, newSerializer, "data", "datacollection", str); if (bArr2 != null) { a.a("add log file Header"); a(bArr, newSerializer, "log", "log", str); } newSerializer.endTag("", "dataCollectionFiles"); SmsReceiver.b(newSerializer); } /* JADX WARNING: Removed duplicated region for block: B:11:0x0034 A[Catch:{ all -> 0x00e4 }] */ /* JADX WARNING: Removed duplicated region for block: B:14:0x0040 A[SYNTHETIC, Splitter:B:14:0x0040] */ /* JADX WARNING: Removed duplicated region for block: B:27:0x00e7 A[SYNTHETIC, Splitter:B:27:0x00e7] */ /* Code decompiled incorrectly, please refer to instructions dump. */ private static void a(com.network.android.x r4, java.net.HttpURLConnection r5, java.lang.String r6) { /* // Method dump skipped, instructions count: 294 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.g.a(com.network.android.x, java.net.HttpURLConnection, java.lang.String):void"); } private static void a(ByteArrayOutputStream byteArrayOutputStream, byte[] bArr, byte[] bArr2, byte[] bArr3) { byteArrayOutputStream.write(i); byteArrayOutputStream.write(bArr); byteArrayOutputStream.write(f); byteArrayOutputStream.write(bArr); byteArrayOutputStream.write(g); byteArrayOutputStream.write(bArr2); byteArrayOutputStream.write(j); byteArrayOutputStream.write(bArr3); byteArrayOutputStream.write(e); } public static void a(String str) { try { a.a(str + "disconectBadConection"); if (d != null) { a.a(str + "disconectBadConection (connection != null)"); if (c != 0) { long currentTimeMillis = System.currentTimeMillis() - c; a.a(str + "disconectBadConection timeElapsed: " + currentTimeMillis); if (currentTimeMillis > 300000) { a.a(str + "disconectBadConection- connection Disconnect!!!! "); d.disconnect(); d = null; } } } } catch (Throwable th) { a.a("printConectionStatus: " + th.getMessage(), th); } } /* JADX WARNING: Code restructure failed: missing block: B:105:?, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:26:0x01be, code lost: r1 = th; */ /* JADX WARNING: Code restructure failed: missing block: B:27:0x01bf, code lost: r2 = r8; r3 = r9; */ /* JADX WARNING: Code restructure failed: missing block: B:31:0x01ca, code lost: com.network.android.c.a.b.a(1, 34, ""); com.network.android.c.a.a.a("sentData - LOG_HTTP_ERROR_OCCURRED: " + r1.getMessage(), r1); */ /* JADX WARNING: Code restructure failed: missing block: B:34:?, code lost: r2.close(); */ /* JADX WARNING: Code restructure failed: missing block: B:36:0x01ef, code lost: r3.close(); */ /* JADX WARNING: Code restructure failed: missing block: B:43:0x023a, code lost: r1 = th; */ /* JADX WARNING: Code restructure failed: missing block: B:46:?, code lost: r8.close(); */ /* JADX WARNING: Code restructure failed: missing block: B:48:0x0242, code lost: r9.close(); */ /* JADX WARNING: Code restructure failed: missing block: B:85:0x041d, code lost: r1 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:86:0x041e, code lost: com.network.android.c.a.a.a("sentData - close connection: " + r1.getMessage(), r1); */ /* JADX WARNING: Code restructure failed: missing block: B:87:0x0436, code lost: r2 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:88:0x0437, code lost: com.network.android.c.a.a.a("sentData - close connection: " + r2.getMessage(), r2); */ /* JADX WARNING: Failed to process nested try/catch */ /* JADX WARNING: Removed duplicated region for block: B:31:0x01ca A[Catch:{ all -> 0x0458 }] */ /* JADX WARNING: Removed duplicated region for block: B:33:0x01ea A[SYNTHETIC, Splitter:B:33:0x01ea] */ /* JADX WARNING: Removed duplicated region for block: B:36:0x01ef A[Catch:{ Throwable -> 0x041d }] */ /* JADX WARNING: Removed duplicated region for block: B:43:0x023a A[ExcHandler: all (th java.lang.Throwable), Splitter:B:5:0x007b] */ /* JADX WARNING: Removed duplicated region for block: B:45:0x023d A[SYNTHETIC, Splitter:B:45:0x023d] */ /* JADX WARNING: Removed duplicated region for block: B:48:0x0242 A[Catch:{ Throwable -> 0x0436 }] */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static void a(java.lang.String r13, java.lang.String r14, com.network.android.x r15, java.lang.String[] r16, byte[][] r17, android.content.Context r18, byte[] r19) { /* // Method dump skipped, instructions count: 1128 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.g.a(java.lang.String, java.lang.String, com.network.android.x, java.lang.String[], byte[][], android.content.Context, byte[]):void"); } private static void a(Vector vector) { if (vector != null) { try { Iterator it = vector.iterator(); while (it.hasNext()) { String str = (String) it.next(); c.f44a.remove(str); a.a("commandAckIdsVector removed: " + str); } a.a("commandAckIdsVector size: " + c.f44a.size()); } catch (Throwable th) { a.a("removeAcks: " + th.getMessage(), th); c.f44a.removeAllElements(); vector.removeAllElements(); } } } /* JADX WARNING: Removed duplicated region for block: B:14:0x0056 A[SYNTHETIC, Splitter:B:14:0x0056] */ /* JADX WARNING: Removed duplicated region for block: B:21:0x0080 A[SYNTHETIC, Splitter:B:21:0x0080] */ /* JADX WARNING: Removed duplicated region for block: B:30:? A[RETURN, SYNTHETIC] */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static void a(byte[] r4, java.lang.String r5) { /* // Method dump skipped, instructions count: 170 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.g.a(byte[], java.lang.String):void"); } private static void a(byte[] bArr, XmlSerializer xmlSerializer, String str, String str2, String str3) { xmlSerializer.startTag("", "dataCollectionFile"); xmlSerializer.attribute("", "name", str); xmlSerializer.attribute("", "filename", str); xmlSerializer.attribute("", "length", String.valueOf(bArr.length + 1)); xmlSerializer.attribute("", "isCompressed", "true"); xmlSerializer.attribute("", "type", str2); xmlSerializer.attribute("", "key", str3); xmlSerializer.endTag("", "dataCollectionFile"); } public static boolean a() { return d != null; } private static void b() { try { if (d != null) { d.disconnect(); } } catch (Throwable th) { a.a("sentData - disconnect: " + th.getMessage(), th); } a.a("!url! disconnect setting connection to null"); d = null; c = 0; } }
4,569
13,885
<filename>third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.h // Copyright (c) 2020 <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. #ifndef SOURCE_FUZZ_FUZZER_PASS_INLINE_FUNCTIONS_H_ #define SOURCE_FUZZ_FUZZER_PASS_INLINE_FUNCTIONS_H_ #include "source/fuzz/fuzzer_pass.h" namespace spvtools { namespace fuzz { // Looks for OpFunctionCall instructions and randomly decides which ones to // inline. If the instructions of the called function are going to be inlined, // then a mapping, between their result ids and suitable ids, is done. class FuzzerPassInlineFunctions : public FuzzerPass { public: FuzzerPassInlineFunctions(opt::IRContext* ir_context, TransformationContext* transformation_context, FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations, bool ignore_inapplicable_transformations); void Apply() override; }; } // namespace fuzz } // namespace spvtools #endif // SOURCE_FUZZ_FUZZER_PASS_INLINE_FUNCTIONS_H_
559
458
<gh_stars>100-1000 package com.mousebird.maply; import android.os.Handler; /** * The Maply Quad Image Frame Loader is for paging individual frames of image pyramids. * <br> * This works much like the Quad Image Loader, but handles more than one frame. You can animate * between the frames with the QuadImageFrameAnimator. */ public class QuadImageFrameLoader extends QuadImageLoaderBase { protected boolean valid = false; protected QuadImageFrameLoader() { } public QuadImageFrameLoader(BaseController control) { super(control); valid = true; } public QuadImageFrameLoader(final SamplingParams params,TileInfoNew inTileInfos[],BaseController control) { super(control, params, inTileInfos.length); tileInfos = inTileInfos; valid = true; Handler handler = new Handler(control.getActivity().getMainLooper()); handler.post(new Runnable() { @Override public void run() { if (!valid) return; delayedInit(params); } }); } public enum FrameLoadMode {Broad,Narrow}; /** * How frames are loaded (top down vs broad). Top down is the default. */ public void setLoadFrameMode(FrameLoadMode mode) { if (setLoadFrameModeNative(mode.ordinal()) && samplingLayer != null) { // If we changed the frame mode we may need to refresh the priorities QuadSamplingLayer layer = samplingLayer.get(); if (layer == null || layer.layerThread == null) return; layer.layerThread.addTask(new Runnable() { @Override public void run() { updatePriorities(); } }); } } protected native boolean setLoadFrameModeNative(int mode); protected native void updatePriorities(); /** * Add another rendering focus to the frame loader. * * Normally you'd have one point of focus for a frame loader resulting in one image * to be displayed. But if you're using render targets, you may want to have two * and combine them in some way yourself. Or more. No idea why you'd do that. * * If you're going to do this, call addFocus right after you create the FrameLoader. */ public native void addFocus(); /** * Return the number of focii. Normally it's 1. * * See addFocus for what these are. You probably don't need to be using them. */ public native int getNumFocus(); /** * Set the interpolated location within the array of frames. * <br> * Each set of frames can be accessed from [0.0,numFrames]. Images will be interpolated between * those values and may be snapped if data has not yet loaded. * <br> * This value is used once per frame, so feel free to call this as much as you'd like. */ public void setCurrentImage(double where) { setCurrentImage(0,where); } /** * Set the currentImage for the given focus. See addFocus for what those are. * @param focusID Which focus to use. Only use this method if you've got more than one. * @param where What to set the currentImage to. */ public void setCurrentImage(int focusID,double where) { // double curFrame = std::min(std::max(where,0.0),(double)([loader->frameInfos count]-1)); double curFrame = Math.min(Math.max(where,0.0),(double)(tileInfos.length-1)); if (setCurrentImageNative(focusID,where) && samplingLayer != null) { // setCurrentImage tells us if we changed the actual image QuadSamplingLayer layer = samplingLayer.get(); if (layer == null || layer.layerThread == null) return; layer.layerThread.addTask(new Runnable() { @Override public void run() { updatePriorities(); } }); } } protected native boolean setCurrentImageNative(int focusID,double where); /** * Return the interpolated location within the array of frames. */ public double getCurrentImage() { return getCurrentImage(0); } /** * Return the interpolated location for a given focus within the array of frames. */ public native double getCurrentImage(int focusID); /** * Set whether we require the top tiles to be loaded before a frame can be displayed. * * Normally the system wants all the top level tiles to be loaded (just one at level 0) * to be in memory before it will display a frame at all. You can turn this off. */ public native void setRequireTopTiles(boolean newVal); /** * An optional render target for this loader. * * The loader can draw to a render target rather than to the screen. * You use this in a multi-pass rendering setup. * * This version takes a specific focus. See addFocus for what that means. */ public void setRenderTarget(int focusID,RenderTarget renderTarget) { setRenderTargetIDNative(focusID,renderTarget.renderTargetID); } protected native void setRenderTargetIDNative(int focusID,long renderTargetID); /** * In special cases we may have tiles that already have borders baked in. In that case, call this * method to set both the total textures size and the number of border pixels around the outside. * * By default this functionality is off. */ public native void setTextureSize(int tileSize,int borderSize); /** * Shader to use for rendering the image frames for a particular focus. * * Consult addFocus for what this means. */ public void setShader(int focusID,Shader shader) { setShaderIDNative(focusID,(shader != null) ? shader.getID() : 0); } protected native void setShaderIDNative(int focusID,long renderTargetID); /** * Number of tile sources passed in as individual frames. */ public int getNumFrames() { return tileInfos.length; } /** * Change the tile sources all at once. This also forces a reload. */ public void changeTileInfo(final TileInfoNew[] newTileInfo) { super.changeTileInfo(newTileInfo); } @Override public void shutdown() { valid = false; super.shutdown(); } /** * The Maply Quad Image Frame Loader can generation per-frame stats. These are them. */ public class FrameStats { /** * Number of tiles this frame is in (loading and loaded) */ public int totalTiles; /** * Number of tiles this frame has yet to load */ public int tilesToLoad; } /** * Stats generated by the Maply Quad Image Frame Loader. */ public class Stats { /** * Total number of tiles managed by the loader */ public int numTiles = 0; /** * Per frame stats for current loading state */ public FrameStats[] frameStats = null; } /** * Pull out the per-frame instantaneous stats. */ public Stats getStats() { int numFrames = getNumFrames(); if (numFrames == 0) return null; Stats stats = new Stats(); stats.frameStats = new FrameStats[numFrames]; int totalTiles[] = new int[numFrames]; int tilesToLoad[] = new int[numFrames]; // Fetch the data like this because I'm lazy stats.numTiles = getStatsNative(totalTiles, tilesToLoad); for (int ii=0;ii<numFrames;ii++) { FrameStats frameStats = new FrameStats(); frameStats.tilesToLoad = tilesToLoad[ii]; frameStats.totalTiles = totalTiles[ii]; stats.frameStats[ii] = frameStats; } return stats; } private native int getStatsNative(int[] totalTiles,int[] tilesToLoad); }
3,131
571
<reponame>ufora/ufora<gh_stars>100-1000 /*************************************************************************** Copyright 2015 Ufora 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. ****************************************************************************/ #pragma once #include <unordered_map> #include <boost/enable_shared_from_this.hpp> #include "../../../core/containers/MapWithIndex.hpp" #include <boost/thread.hpp> namespace ChecksummedFile { class ChecksummedWriter; }; namespace SharedState { class OpenFilesInterface : public boost::enable_shared_from_this<OpenFilesInterface> { public: virtual ~OpenFilesInterface() {}; virtual void append(const std::string& path, const std::string& contents) = 0; virtual uint64_t written(const std::string& path) const = 0; virtual void flush(const std::string& path) = 0; virtual void shutdown() = 0; virtual void closeFile(const std::string& path) = 0; virtual bool readFileAsStringVector(const std::string& path, std::vector<std::string>& out) const = 0; }; class OpenFiles : public OpenFilesInterface { public: typedef ChecksummedFile::ChecksummedWriter writer_type; typedef boost::shared_ptr<writer_type> writer_ptr_type; typedef boost::shared_ptr<const writer_type> const_writer_ptr_type; OpenFiles(uint32_t); virtual ~OpenFiles(); // disable copy sematics OpenFiles(const OpenFiles&) = delete; OpenFiles operator=(const OpenFiles&) = delete; virtual void append(const std::string& path, const std::string& contents); virtual uint64_t written(const std::string& path) const; virtual void flush(const std::string& path); virtual void shutdown(); virtual void closeFile(const std::string& path); virtual bool readFileAsStringVector(const std::string& path, std::vector<std::string>& out) const; private: bool isFlushLoopRunning() const; void flushLoop(); void flushFiles(uint64_t fromAccess, uint64_t toAccess); void recordFileAccess(const std::string& filename); void closeFilesIfNecessary(); std::string getFileNameFromAccessId(uint64_t accessId) const; writer_ptr_type getFile(const std::string& filename); const_writer_ptr_type getFile(const std::string& filename) const; writer_ptr_type openFile(const std::string& path); void closeAFile(); mutable boost::recursive_mutex mMutex; boost::thread mFlushLoopThread; boost::condition_variable_any mShutdownCondition; bool mIsShutdown; std::unordered_map<std::string, writer_ptr_type> mOpenFiles; uint32_t mMaxOpenFiles; uint64_t mFileAccessCount; MapWithIndex<std::string, uint64_t> mFileAccesses; }; }
950
3,227
#include "test_dependencies.h" // and additionally #define CGAL_SPATIAL_SEARCHING_COMMERCIAL_LICENSE 22222222 #define CGAL_APOLLONIUS_GRAPH_2_COMMERCIAL_LICENSE 22222222 #include <CGAL/config.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Constrained_Delaunay_triangulation_2.h> #include <CGAL/Delaunay_mesh_vertex_base_2.h> #include <CGAL/Delaunay_mesh_face_base_2.h> #include <CGAL/Mesh_2/Lipschitz_sizing_field_2.h> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Delaunay_mesh_vertex_base_2<K> Vb; typedef CGAL::Delaunay_mesh_face_base_2<K> Fb; typedef CGAL::Triangulation_data_structure_2<Vb, Fb> TDS; typedef CGAL::Exact_predicates_tag Itag; typedef CGAL::Constrained_Delaunay_triangulation_2<K, TDS, Itag> CDT; int main() { CDT cdt; CGAL::Lipschitz_sizing_field_2<CDT> lip_size(cdt); lip_size.set_K(2.); CGAL_assertion(lip_size.get_K() == 2.); }
453
6,992
/* * Copyright 2002-2020 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 * * https://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.springframework.security.oauth2.client.jackson2; import java.util.Collections; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.module.SimpleModule; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2RefreshToken; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcUserInfo; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; /** * Jackson {@code Module} for {@code spring-security-oauth2-client}, that registers the * following mix-in annotations: * * <ul> * <li>{@link OAuth2AuthorizationRequestMixin}</li> * <li>{@link ClientRegistrationMixin}</li> * <li>{@link OAuth2AccessTokenMixin}</li> * <li>{@link OAuth2RefreshTokenMixin}</li> * <li>{@link OAuth2AuthorizedClientMixin}</li> * <li>{@link OAuth2UserAuthorityMixin}</li> * <li>{@link DefaultOAuth2UserMixin}</li> * <li>{@link OidcIdTokenMixin}</li> * <li>{@link OidcUserInfoMixin}</li> * <li>{@link OidcUserAuthorityMixin}</li> * <li>{@link DefaultOidcUserMixin}</li> * <li>{@link OAuth2AuthenticationTokenMixin}</li> * <li>{@link OAuth2AuthenticationExceptionMixin}</li> * <li>{@link OAuth2ErrorMixin}</li> * </ul> * * If not already enabled, default typing will be automatically enabled as type info is * required to properly serialize/deserialize objects. In order to use this module just * add it to your {@code ObjectMapper} configuration. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new OAuth2ClientJackson2Module()); * </pre> * * <b>NOTE:</b> Use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get a list * of all security modules. * * @author <NAME> * @since 5.3 * @see SecurityJackson2Modules * @see OAuth2AuthorizationRequestMixin * @see ClientRegistrationMixin * @see OAuth2AccessTokenMixin * @see OAuth2RefreshTokenMixin * @see OAuth2AuthorizedClientMixin * @see OAuth2UserAuthorityMixin * @see DefaultOAuth2UserMixin * @see OidcIdTokenMixin * @see OidcUserInfoMixin * @see OidcUserAuthorityMixin * @see DefaultOidcUserMixin * @see OAuth2AuthenticationTokenMixin * @see OAuth2AuthenticationExceptionMixin * @see OAuth2ErrorMixin */ public class OAuth2ClientJackson2Module extends SimpleModule { public OAuth2ClientJackson2Module() { super(OAuth2ClientJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); } @Override public void setupModule(SetupContext context) { SecurityJackson2Modules.enableDefaultTyping(context.getOwner()); context.setMixInAnnotations(Collections.unmodifiableMap(Collections.emptyMap()).getClass(), UnmodifiableMapMixin.class); context.setMixInAnnotations(OAuth2AuthorizationRequest.class, OAuth2AuthorizationRequestMixin.class); context.setMixInAnnotations(ClientRegistration.class, ClientRegistrationMixin.class); context.setMixInAnnotations(OAuth2AccessToken.class, OAuth2AccessTokenMixin.class); context.setMixInAnnotations(OAuth2RefreshToken.class, OAuth2RefreshTokenMixin.class); context.setMixInAnnotations(OAuth2AuthorizedClient.class, OAuth2AuthorizedClientMixin.class); context.setMixInAnnotations(OAuth2UserAuthority.class, OAuth2UserAuthorityMixin.class); context.setMixInAnnotations(DefaultOAuth2User.class, DefaultOAuth2UserMixin.class); context.setMixInAnnotations(OidcIdToken.class, OidcIdTokenMixin.class); context.setMixInAnnotations(OidcUserInfo.class, OidcUserInfoMixin.class); context.setMixInAnnotations(OidcUserAuthority.class, OidcUserAuthorityMixin.class); context.setMixInAnnotations(DefaultOidcUser.class, DefaultOidcUserMixin.class); context.setMixInAnnotations(OAuth2AuthenticationToken.class, OAuth2AuthenticationTokenMixin.class); context.setMixInAnnotations(OAuth2AuthenticationException.class, OAuth2AuthenticationExceptionMixin.class); context.setMixInAnnotations(OAuth2Error.class, OAuth2ErrorMixin.class); } }
1,774
523
package moonbox.jdbc; import java.sql.*; import java.util.Properties; import java.util.logging.Logger; public class MbDriver implements Driver { public static final String OS = getOSName(); public static final String PLATFORM = getPlatform(); public static final String LICENSE = "APACHE 2"; public static final String VERSION = "0.4.0"; public static final String NAME = "Moonbox Connector Java"; public static final String URL_PREFIX = "jdbc:moonbox://"; static { try { DriverManager.registerDriver(new MbDriver()); } catch (SQLException e) { throw new RuntimeException("Can't register MbDriver!"); } } @Override public Connection connect(String url, Properties info) throws SQLException { if (!acceptsURL(url)) { return null; } return new MoonboxConnection(url, info); } @Override public boolean acceptsURL(String url) throws SQLException { return url != null && url.toLowerCase().startsWith(URL_PREFIX); } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } public static String getOSName() { return System.getProperty("os.name"); } public static String getPlatform() { return System.getProperty("os.arch"); } }
519
634
<filename>modules/base/platform-api/src/main/java/com/intellij/ui/components/JBPanelWithEmptyText.java /* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.ui.components; import com.intellij.util.ui.ComponentWithEmptyText; import com.intellij.util.ui.JBSwingUtilities; import com.intellij.util.ui.StatusText; import com.intellij.util.ui.UIUtil; import javax.annotation.Nonnull; import java.awt.*; /** * @author gregsh */ public class JBPanelWithEmptyText extends JBPanel<JBPanelWithEmptyText> implements ComponentWithEmptyText { private final StatusText myEmptyText = new StatusText() { @Override protected boolean isStatusVisible() { return UIUtil.uiChildren(JBPanelWithEmptyText.this).filter(Component::isVisible).isEmpty(); } }; public JBPanelWithEmptyText() { super(); } public JBPanelWithEmptyText(LayoutManager layout) { super(layout); } @Nonnull @Override public StatusText getEmptyText() { return myEmptyText; } @Nonnull public JBPanelWithEmptyText withEmptyText(String str) { myEmptyText.setText(str); return this; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); myEmptyText.paint(this, g); } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } }
621
1,511
/* * Copyright 2008, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); if (c == -1) { break; } switch (c) { case 0: break;
115
1,253
#include<iostream> #include<vector> using namespace std; int hammingDistance(const vector<int> &A) { long long int sol = 0; int n = A.size(); int M = 1000000007; int b = 1; for(int i = 0; i < 32; i++) { int setBits = 0; for(int j = 0; j < A.size(); j++) { int t = A[j] & b; if(t > 0){ setBits++; } } b *= 2; sol = (sol + (setBits * ((n - setBits) * 2)%M))%M ; } sol = sol%M; return (int)sol; } int main() { vector<int> A = {4,5,63,2,5,3,6,8,5,4,9}; int distance = hammingDistance(A); cout << "Sum of pairwise hamming distance : " << distance << endl; }
366
2,151
// Copyright (c) 2012, Google Inc. // 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 Google Inc. 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. #ifndef COMMON_MAC_BOOTSTRAP_COMPAT_H_ #define COMMON_MAC_BOOTSTRAP_COMPAT_H_ #include <servers/bootstrap.h> namespace breakpad { // Wrapper for bootstrap_register to avoid deprecation warnings. // // In 10.6, it's possible to call bootstrap_check_in as the one-stop-shop for // handling what bootstrap_register is used for. In 10.5, bootstrap_check_in // can't check in a service whose name has not yet been registered, despite // bootstrap_register being marked as deprecated in that OS release. Breakpad // needs to register new service names, and in 10.5, calling // bootstrap_register is the only way to achieve that. Attempts to call // bootstrap_check_in for a new service name on 10.5 will result in // BOOTSTRAP_UNKNOWN_SERVICE being returned rather than registration of the // new service name. kern_return_t BootstrapRegister(mach_port_t bp, name_t service_name, mach_port_t sp); } // namespace breakpad #endif // COMMON_MAC_BOOTSTRAP_COMPAT_H_
798