repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
dBucik/OpenID-Connect-Java-Spring-Server
perun-oidc-server/src/main/java/cz/muni/ics/oidc/server/claims/PerunCustomClaimDefinition.java
package cz.muni.ics.oidc.server.claims; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; /** * Keeps definition of a custom user claim. * * Configuration declaring custom claims: * <ul> * <li><b>custom.claims</b> - coma separated list of names of the claims</li> * </ul> * * Configuration for claim(replace [claimName] with name of the claim): * * <ul> * <li><b>custom.claim.[claimName].claim</b> - name of the claim</li> * <li><b>custom.claim.[claimName].scope</b> - scope that needs to be granted to include the claim</li> * <li><b>custom.claim.[claimName].source.class</b> instance of a class implementing {@link ClaimSource}</li> * <li><b>custom.claim.[claimName].modifier.class</b> instance of a class implementing {@link ClaimModifier}</li> * </ul> * * * @see ClaimSource * @see ClaimModifier * @author <NAME> <<EMAIL>> */ @Slf4j public class PerunCustomClaimDefinition { private final String scope; private final String claim; private final ClaimSource claimSource; private final List<ClaimModifier> claimModifiers = new ArrayList<>(); public PerunCustomClaimDefinition(String scope, String claim, ClaimSource claimSource, List<ClaimModifier> claimModifiers) { this.scope = scope; this.claim = claim; this.claimSource = claimSource; this.claimModifiers.addAll(claimModifiers); log.debug("initialized scope '{}' with claim '{}', claimSource '{}' and modifiers '{}", scope, claim, (claimSource != null ? claimSource.getClass().getSimpleName() : "none"), (!claimModifiers.isEmpty() ? claimModifiers.stream() .map(cm -> cm.getClass().getSimpleName()) .collect(Collectors.joining(",")) : "none") ); } public String getScope() { return scope; } public String getClaim() { return claim; } public ClaimSource getClaimSource() { return claimSource; } public List<ClaimModifier> getClaimModifiers() { return claimModifiers; } }
mikelandy/HIPS
lib/sources/read_image.c
/* * Copyright (c) 1991 <NAME> * * Disclaimer: No guarantees of performance accompany this software, * nor is any responsibility assumed on the part of the authors. All the * software has been tested extensively and every effort has been made to * insure its reliability. */ /* * read_image.c - read an image frame * * <NAME> - 1/4/91 */ #include <stdio.h> #include <hipl_format.h> int read_image(hd,fr) struct header *hd; int fr; { return(fread_image(stdin,hd,fr,"<stdin>")); } int fread_image(fp,hd,fr,fname) FILE *fp; struct header *hd; int fr; Filename fname; { if (fread(hd->image,hd->sizeimage,1,fp) != 1) return(perr(HE_READFRFILE,fr,fname)); return(HIPS_OK); }
Kyle9021/trireme-lib
controller/internal/enforcer/applicationproxy/markedconn/mark_windows.go
// +build windows package markedconn import ( "net" "syscall" "go.aporeto.io/enforcerd/trireme-lib/utils/frontman" "go.uber.org/zap" ) func makeListenerConfig(mark int) net.ListenConfig { return net.ListenConfig{} } // ControlFunc used in the dialer. func ControlFunc(mark int, block bool, platformData *PlatformData) Control { return func(_, _ string, c syscall.RawConn) error { return c.Control(func(fd uintptr) { if platformData == nil { return } // call FrontmanApplyDestHandle to update WFP redirect data before the connect() call on the new socket if err := frontman.Wrapper.ApplyDestHandle(fd, platformData.handle); err != nil { zap.L().Error("could not update proxy redirect", zap.Error(err)) } }) } }
marko-hudomal/MJComipler
Final/MJCompiler/src/rs/ac/bg/etf/pp1/ast/MethodDeclarations.java
// generated with ast extension for cup // version 0.8 // 6/1/2019 3:51:16 package rs.ac.bg.etf.pp1.ast; public class MethodDeclarations extends MethodDeclList { private MethodDeclList MethodDeclList; private MethodDecl MethodDecl; public MethodDeclarations (MethodDeclList MethodDeclList, MethodDecl MethodDecl) { this.MethodDeclList=MethodDeclList; if(MethodDeclList!=null) MethodDeclList.setParent(this); this.MethodDecl=MethodDecl; if(MethodDecl!=null) MethodDecl.setParent(this); } public MethodDeclList getMethodDeclList() { return MethodDeclList; } public void setMethodDeclList(MethodDeclList MethodDeclList) { this.MethodDeclList=MethodDeclList; } public MethodDecl getMethodDecl() { return MethodDecl; } public void setMethodDecl(MethodDecl MethodDecl) { this.MethodDecl=MethodDecl; } public void accept(Visitor visitor) { visitor.visit(this); } public void childrenAccept(Visitor visitor) { if(MethodDeclList!=null) MethodDeclList.accept(visitor); if(MethodDecl!=null) MethodDecl.accept(visitor); } public void traverseTopDown(Visitor visitor) { accept(visitor); if(MethodDeclList!=null) MethodDeclList.traverseTopDown(visitor); if(MethodDecl!=null) MethodDecl.traverseTopDown(visitor); } public void traverseBottomUp(Visitor visitor) { if(MethodDeclList!=null) MethodDeclList.traverseBottomUp(visitor); if(MethodDecl!=null) MethodDecl.traverseBottomUp(visitor); accept(visitor); } public String toString(String tab) { StringBuffer buffer=new StringBuffer(); buffer.append(tab); buffer.append("MethodDeclarations(\n"); if(MethodDeclList!=null) buffer.append(MethodDeclList.toString(" "+tab)); else buffer.append(tab+" null"); buffer.append("\n"); if(MethodDecl!=null) buffer.append(MethodDecl.toString(" "+tab)); else buffer.append(tab+" null"); buffer.append("\n"); buffer.append(tab); buffer.append(") [MethodDeclarations]"); return buffer.toString(); } }
picacure/adc-tmd
server/node_modules/socket.io/node_modules/socket.io-client/node_modules/uglify-js/test/unit/compress/expected/issue16.js
var a = 3250441966
anruky/Zeta
zds-server/src/main/java/com/ebay/dss/zds/rest/FooController.java
<gh_stars>10-100 package com.ebay.dss.zds.rest; import com.ebay.dss.zds.exception.ErrorCode; import com.ebay.dss.zds.exception.IllegalStatusException; import com.ebay.dss.zds.exception.InvalidInputException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * This controller is for testing purpose. */ @RestController @RequestMapping("foo") public class FooController { @RequestMapping(path = "/exception", method = RequestMethod.GET) public ResponseEntity<String> exception(@RequestParam(name = "type", defaultValue = "0") String type) { switch (type) { case "0": throw new IllegalStatusException("Exception 0 is thrown."); case "1": throw new IllegalStateException("Exception 1 is thrown."); case "2": try { String s = "" + 100 / 0; }catch(Throwable t){ throw new InvalidInputException(ErrorCode.INVALID_INPUT, "Invalid input - 2 is not a good input, this is to test nested cause in exception.", t); } default: return ResponseEntity.badRequest().body("Unknown type"); } } }
anddorua/biblio
js/views/bookAdd.js
/** * Created by Такси on 16.07.15. */ window.biblio = window.biblio || {}; window.biblio.views = window.biblio.views || {}; window.biblio.views.bookAdd = (function(){ var controller; var vmBook = {}; var bookHoldersTableSection; var submitHandler = function(){ controller.onSubmitBtnPressed() }; var cancelHandler = function(){ controller.onCancelBtnPressed() }; var show = function(isShow) { document.getElementById("book-form").style.display = isShow ? "block" : "none"; }; var handlers = [ {selector: "#bf-submit", event: "click", handler: submitHandler}, {selector: "#bf-cancel", event: "click", handler: cancelHandler}, {selector: "#book-form-form", event: "submit", handler: submitHandler} ]; var getViewModel = function(){ return { book: biblio.services.html.extendStrict(new biblio.models.BookItem(), vmBook), parameters: { adding: vmBook.adding, comment: vmBook.comment } }; }; var setViewModel = function(vm){ if (vm) { biblio.services.html.extendStrict(vmBook, vm.book); biblio.services.html.extendStrict(vmBook, vm.parameters); vmBook.adding = ""; renderHoldersSection(vm.holders || []); } else { biblio.services.html.emptyObject(vmBook); } }; var init = function(aController){ controller = aController; show(true); bookHoldersTableSection = document.getElementById("book-holders-table"); biblio.services.html.viewModelBind("#book-form-form input", vmBook); biblio.services.html.eventBind(handlers); }; var renderHoldersSection = function(holderList){ if (holderList.length > 0) { var innerListText = ""; holderList.forEach(function(holderEntry){ var data = {}; data.userId = holderEntry.userId; data.issueDate = holderEntry.when; data.when = holderEntry.when; data.amount = holderEntry.amount; data.reader = holderEntry.user.getFullName(); var itemText = biblio.services.html.parseTemplate("book-holder-item-template", data); innerListText += itemText; }); bookHoldersTableSection.innerHTML = innerListText; } else { bookHoldersTableSection.innerHTML = ""; } }; return { init: init, show: show, getViewModel: getViewModel, setViewModel: setViewModel } })();
FogInTheFrog/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/testingSupport/utest/scala2_12/utest_0_7_4/UTestSimpleTest_2_12_0_7_4.scala
<gh_stars>100-1000 package org.jetbrains.plugins.scala.testingSupport.utest.scala2_12.utest_0_7_4 import org.jetbrains.plugins.scala.testingSupport.utest.UTestNewSyntaxSimpleTest class UTestSimpleTest_2_12_0_7_4 extends UTestTestBase_2_12_0_7_4 with UTestNewSyntaxSimpleTest
biantiange/Treasure
Treasure/Java/src/Comment/controller/CommentAddServlet.java
<gh_stars>1-10 package Comment.controller; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Timestamp; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import Comment.dao.CommentDao; import entity.Comment; /** * Servlet implementation class CommentAddServlet */ @WebServlet("/CommentAddServlet") public class CommentAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CommentAddServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); OutputStream out = response.getOutputStream(); //获得数据 InputStream inputStream = request.getInputStream(); byte[] bs = new byte[255]; int len = inputStream.read(bs); String param = new String(bs,0,len); JSONObject object = new JSONObject(param); int postId = object.getInt("postId"); int commentatorId = object.getInt("commentatorId"); int responderId = object.getInt("responderId"); String content = object.getString("content"); String time = object.getString("time"); Comment comment = new Comment(); comment.setResComId(0); comment.setCommentatorId(commentatorId); comment.setContent(content); comment.setPostId(postId); comment.setResponderId(responderId); comment.setTime(Timestamp.valueOf(time)); System.out.println(Timestamp.valueOf(time));//打印传过来的时间 int add = new CommentDao().AddComment(comment); if (add>0) { System.out.println("succeed!"); } out.close(); inputStream.close(); } }
alliance-genome/agr_archive_initial_prototype
webapp/src/components/dataTable/index.js
<reponame>alliance-genome/agr_archive_initial_prototype<gh_stars>1-10 import LocalDataTable from './localDataTable'; import RemoteDataTable from './remoteDataTable'; export { LocalDataTable, RemoteDataTable };
icml2020submission6857/metarl
src/metarl/tf/policies/__init__.py
<gh_stars>1-10 """Policies for TensorFlow-based algorithms.""" from metarl.tf.policies.base import Policy from metarl.tf.policies.base import StochasticPolicy from metarl.tf.policies.categorical_cnn_policy import CategoricalCNNPolicy from metarl.tf.policies.categorical_gru_policy import CategoricalGRUPolicy from metarl.tf.policies.categorical_lstm_policy import CategoricalLSTMPolicy from metarl.tf.policies.categorical_mlp_policy import CategoricalMLPPolicy from metarl.tf.policies.continuous_mlp_policy import ContinuousMLPPolicy from metarl.tf.policies.discrete_qf_derived_policy import ( DiscreteQfDerivedPolicy) from metarl.tf.policies.gaussian_gru_policy import GaussianGRUPolicy from metarl.tf.policies.gaussian_lstm_policy import GaussianLSTMPolicy from metarl.tf.policies.gaussian_mlp_multitask_policy import GaussianMLPMultitaskPolicy from metarl.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy from metarl.tf.policies.multitask_policy import StochasticMultitaskPolicy __all__ = [ 'Policy', 'StochasticPolicy', 'CategoricalCNNPolicy', 'CategoricalGRUPolicy', 'CategoricalLSTMPolicy', 'CategoricalMLPPolicy', 'ContinuousMLPPolicy', 'DiscreteQfDerivedPolicy', 'GaussianGRUPolicy', 'GaussianLSTMPolicy', 'GaussianMLPPolicy', 'StochasticMultitaskPolicy', 'GaussianMLPMultitaskPolicy' ]
dongkap/satpol-api-activity
satpol-activity/src/main/java/com/dongkap/activity/dao/ParameterI18nRepo.java
<gh_stars>0 package com.dongkap.activity.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.dongkap.activity.entity.ParameterI18nEntity; public interface ParameterI18nRepo extends JpaRepository<ParameterI18nEntity, String>, JpaSpecificationExecutor<ParameterI18nEntity> { List<ParameterI18nEntity> findByParameter_ParameterCode(String parameterCode); ParameterI18nEntity findByParameter_ParameterCodeAndLocaleCode(String parameterCode, String localeCode); }
yakuizhao/intel-vaapi-driver
android/android_9/hardware/intel/img/hwcomposer/merrifield/common/base/Drm.h
/* // Copyright (c) 2014 Intel Corporation  // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //      http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #ifndef __DRM_H__ #define __DRM_H__ #include <utils/Mutex.h> #include <hardware/hwcomposer.h> // TODO: psb_drm.h is IP specific defintion #include <linux/psb_drm.h> extern "C" { #include "xf86drm.h" #include "xf86drmMode.h" } namespace android { namespace intel { enum { PANEL_ORIENTATION_0 = 0, PANEL_ORIENTATION_180 }; class Drm { public: Drm(); virtual ~Drm(); public: bool initialize(); void deinitialize(); bool detect(int device); bool setDrmMode(int device, drmModeModeInfo& value); bool setRefreshRate(int device, int hz); bool writeReadIoctl(unsigned long cmd, void *data, unsigned long size); bool writeIoctl(unsigned long cmd, void *data, unsigned long size); bool readIoctl(unsigned long cmd, void *data, unsigned long size); bool isConnected(int device); bool setDpmsMode(int device, int mode); int getDrmFd() const; bool getModeInfo(int device, drmModeModeInfo& mode); bool getPhysicalSize(int device, uint32_t& width, uint32_t& height); bool isSameDrmMode(drmModeModeInfoPtr mode, drmModeModeInfoPtr base) const; int getPanelOrientation(int device); drmModeModeInfoPtr detectAllConfigs(int device, int *modeCount); private: bool initDrmMode(int index); bool setDrmMode(int index, drmModeModeInfoPtr mode); void resetOutput(int index); // map device type to output index, return -1 if not mapped inline int getOutputIndex(int device); private: // DRM object index enum { OUTPUT_PRIMARY = 0, OUTPUT_EXTERNAL, OUTPUT_MAX, }; struct DrmOutput { drmModeConnectorPtr connector; drmModeEncoderPtr encoder; drmModeCrtcPtr crtc; drmModeModeInfo mode; buffer_handle_t fbHandle; uint32_t fbId; int connected; int panelOrientation; } mOutputs[OUTPUT_MAX]; int mDrmFd; Mutex mLock; bool mInitialized; }; } // namespace intel } // namespace android #endif /* __DRM_H__ */
zengLH1981/mockneat
src/main/java/net/andreinc/mockneat/unit/misc/Creatures.java
<gh_stars>100-1000 package net.andreinc.mockneat.unit.misc; import net.andreinc.mockneat.MockNeat; import net.andreinc.mockneat.abstraction.MockUnitBase; import net.andreinc.mockneat.abstraction.MockUnitString; import net.andreinc.mockneat.types.enums.DictType; import java.util.function.Supplier; public class Creatures extends MockUnitBase implements MockUnitString { /** * <p> Returns a {@code Creatures} object that can be used to generate arbitrary creature names.</p> * * @return A re-usable {@code Creatures} instance. The class implements {@code MockUnitString}. */ public static Creatures creatures() { return MockNeat.threadLocal().creatures(); } public Creatures(MockNeat mockNeat) { super(mockNeat); } @Override public Supplier<String> supplier() { return mockNeat.dicts().type(DictType.CREATURES).supplier(); } }
SyedThaseemuddin/MPLAB-Harmony-Reference-Apps
apps/sam_e54_cult/same54_sdcard_usb_audio_player/firmware/src/config/same54_cult/gfx/legato/generated/image/le_gen_image_music_icon2.c
<gh_stars>1-10 #include "gfx/legato/generated/le_gen_assets.h" /********************************* * Legato Image Asset * Name: music_icon2 * Size: 20x24 pixels * Mode: ARGB_8888 * Format: Raw ***********************************/ const uint8_t music_icon2_data[1920] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x10,0x10,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xCF,0xCF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x40,0x40,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8F,0x8F,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x9F,0x9F,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xEF,0xEF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x70,0x70,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x50,0x50,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0xAF,0xAF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x9F,0x9F,0xFF,0xFF,0x70,0x70,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x00,0x00,0xFF,0xFF,0xEF,0xEF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0x40,0x40,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0x00,0x00,0xFF,0xFF, 0x40,0x40,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, }; leImage music_icon2 = { { LE_STREAM_LOCATION_ID_INTERNAL, // data location id (void*)music_icon2_data, // data address pointer 1920, // data size }, LE_IMAGE_FORMAT_RAW, { LE_COLOR_MODE_ARGB_8888, { 20, 24 }, 480, 1920, (void*)music_icon2_data }, 0, // image flags { 0xFF000000, // color mask }, NULL, // alpha mask NULL, // palette };
xiehuanx/learn-cloud
learn-upms-model/src/main/java/com/icedevcloud/miniapp/dto/user/NormalAndVipUserReqDto.java
<reponame>xiehuanx/learn-cloud<filename>learn-upms-model/src/main/java/com/icedevcloud/miniapp/dto/user/NormalAndVipUserReqDto.java package com.icedevcloud.miniapp.dto.user; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.util.Date; /** * author :xiehuan * Email: <EMAIL> * Date: 2020/12/26 * Describe: */ @Data public class NormalAndVipUserReqDto { @ApiModelProperty(value = "id") private Long id; @ApiModelProperty(value = "用户昵称") private String nickName; @ApiModelProperty(value = "用户头像") private String avatarUrl; @ApiModelProperty(value = "创建时间") private Date gmtCreate; @ApiModelProperty(value = "vip生效时间") private Date vipEffDate; @ApiModelProperty(value = "vip失效时间") private Date vipExpDate; @ApiModelProperty(value = "VIP 用户类型 MC-月会员 QC-季会员 YC-年会员") private String vipUserType; }
tockri/hello-next
infra/src/main/scala/infra/jdbc/ExtraworkApplicationRepositoryOnDB.scala
<reponame>tockri/hello-next package infra.jdbc import domain.ExtraworkApplicationRepository import domain.model.{ExtraworkApplication, ExtraworkApplicationId, UserId} import org.joda.time.DateTime import scalikejdbc._ /** * */ class ExtraworkApplicationRepositoryOnDB extends RepositoryOnDB[ExtraworkApplication, ExtraworkApplicationId] with ExtraworkApplicationRepository { override val tableName = "extrawork_application" override val columns = Seq("id", "start_time", "end_time", "status", "applier_id", "approver_id", "reason", "comment", "creator_id", "created", "updator_id", "updated") override def entityMap(e:ExtraworkApplication):Map[SQLSyntax, ParameterBinder] = Map( column.startTime -> e.startTime, column.endTime -> e.endTime, column.status -> e.status, column.applierId -> e.applierId, column.approverId -> e.approverId, column.reason -> e.reason, column.comment -> e.comment, column.creatorId -> e.creatorId, column.updatorId -> e.updatorId ) override def entity(ea: ResultName[ExtraworkApplication])(rs: WrappedResultSet) = new ExtraworkApplication( id = new ExtraworkApplicationId(rs.get(ea.id)), startTime = rs.get(ea.startTime), endTime = rs.get(ea.endTime), status = rs.get(ea.status), applierId = UserId(rs.get(ea.applierId)), approverId = UserId(rs.get(ea.approverId)), reason = rs.get(ea.reason), comment = rs.get(ea.comment), creatorId = UserId(rs.get(ea.creatorId)), created = rs.get(ea.created), updatorId = UserId(rs.get(ea.updatorId)), updated = rs.get(ea.updated) ) override def createdEntity(e: ExtraworkApplication, newId: Long) = e.copy(id = new ExtraworkApplicationId(newId), updated = DateTime.now(), created = DateTime.now()) override val stx = syntax("ea") }
nilsthamm/hyrise
src/test/operators/operator_join_predicate_test.cpp
<filename>src/test/operators/operator_join_predicate_test.cpp #include "gtest/gtest.h" #include "expression/expression_functional.hpp" #include "logical_query_plan/mock_node.hpp" #include "operators/operator_join_predicate.hpp" using namespace opossum::expression_functional; // NOLINT namespace opossum { class OperatorJoinPredicateTest : public ::testing::Test { public: void SetUp() override { node_a = MockNode::make(MockNode::ColumnDefinitions{{DataType::Int, "a"}, {DataType::Float, "b"}}); a_a = node_a->get_column("a"); a_b = node_a->get_column("b"); node_b = MockNode::make(MockNode::ColumnDefinitions{{DataType::Int, "a"}, {DataType::Float, "b"}}); b_a = node_b->get_column("a"); b_b = node_b->get_column("b"); } std::shared_ptr<MockNode> node_a, node_b; LQPColumnReference a_a, a_b, b_a, b_b; }; TEST_F(OperatorJoinPredicateTest, Conversion) { const auto predicate_a = OperatorJoinPredicate::from_expression(*equals_(a_a, b_b), *node_a, *node_b); ASSERT_TRUE(predicate_a); EXPECT_EQ(predicate_a->column_ids.first, ColumnID{0}); EXPECT_EQ(predicate_a->column_ids.second, ColumnID{1}); EXPECT_EQ(predicate_a->predicate_condition, PredicateCondition::Equals); const auto predicate_b = OperatorJoinPredicate::from_expression(*less_than_(b_a, a_b), *node_a, *node_b); ASSERT_TRUE(predicate_b); EXPECT_EQ(predicate_b->column_ids.first, ColumnID{1}); EXPECT_EQ(predicate_b->column_ids.second, ColumnID{0}); EXPECT_EQ(predicate_b->predicate_condition, PredicateCondition::GreaterThan); } TEST_F(OperatorJoinPredicateTest, ConversionImpossible) { const auto predicate_a = OperatorJoinPredicate::from_expression(*equals_(a_a, a_b), *node_a, *node_b); ASSERT_FALSE(predicate_a); const auto predicate_b = OperatorJoinPredicate::from_expression(*less_than_(add_(b_a, 5), a_b), *node_a, *node_b); ASSERT_FALSE(predicate_b); } } // namespace opossum
navono/MethaneKit
Modules/Graphics/Core/Sources/Methane/Graphics/Vulkan/ShaderVK.cpp
<reponame>navono/MethaneKit /****************************************************************************** Copyright 2019-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. ******************************************************************************* FILE: Methane/Graphics/Vulkan/ShaderVK.mm Vulkan implementation of the shader interface. ******************************************************************************/ #include "ShaderVK.h" #include "ContextVK.h" #include <Methane/Graphics/ContextBase.h> #include <Methane/Instrumentation.h> namespace Methane::Graphics { Ptr<Shader> Shader::Create(Shader::Type shader_type, const Context& context, const Settings& settings) { META_FUNCTION_TASK(); return std::make_shared<ShaderVK>(shader_type, dynamic_cast<const ContextBase&>(context), settings); } ShaderVK::ShaderVK(Shader::Type shader_type, const ContextBase& context, const Settings& settings) : ShaderBase(shader_type, context, settings) { META_FUNCTION_TASK(); } ShaderBase::ArgumentBindings ShaderVK::GetArgumentBindings(const Program::ArgumentAccessors&) const { META_FUNCTION_TASK(); ArgumentBindings argument_bindings; return argument_bindings; } const IContextVK& ShaderVK::GetContextVK() const noexcept { META_FUNCTION_TASK(); return static_cast<const IContextVK&>(GetContext()); } } // namespace Methane::Graphics
TREGS4/Tek
Projet/Tools/queue/queue.h
#ifndef QUEUE #define QUEUE #include <stdlib.h> #include <err.h> typedef struct queue { // Value of an element. void *ptr; // Pointer to the next element. struct queue *next; } queue; // Pushes a new value onto a queue. // start = Starting address of the queue. // val = Value to push. // Returns the new starting address of the queue. queue *queue_push(queue *start, void *ptr); // Pops a value off a queue. // start = Starting address of the queue. // pval = Pointer used to return the value. // Returns the new starting address of the queue. queue *queue_pop(queue *start, void **ptr); //BE CAREFUL DOESN'T FREE THE POINTER SO USE IT ONLY IF YOU ARE SURE //THERE IS NOTHING TO FREE !!!!! // Removes all the elements of a queue. // pstart = Address that contains the starting address of the queue. // Must set the starting address to NULL. void queue_empty(queue **pstart); #endif
RobertClay/Paper1
minos/modules/depression.py
<reponame>RobertClay/Paper1 """ Module for implementation of BHPS depression data to daedalus frame. """ import pandas as pd import numpy as np import subprocess import os from pathlib import Path from vivarium.framework.utilities import rate_to_probability #from minos.RateTables.DepressionRateTable import DepressionRateTable class Depression: """ Main class for application of depression data to BHPS.""" @property def name(self): return "depression" def __repr__(self): return "Depression()" def write_config(self, config): """ Update config file with what this module needs to run. Parameters ---------- config : vivarium.config_tree.ConfigTree Config yaml tree for AngryMob. Returns ------- config : vivarium.config_tree.ConfigTree Config yaml tree for AngryMob with added items needed for this module to run. """ # config.update({ # "path_to_depression_files": { # "tier0": "{}/{}".format(config.persistent_data_dir, config.depression_files.tier0), # }, # }, # minos=str(Path(__file__).resolve())) return config def pre_setup(self, config, simulation): """ Load in anything required for the module to run. Parameters ---------- config : vivarium.config_tree.ConfigTree Config yaml tree for vivarium with the items needed for this module to run simulation : vivarium.interface.interactive.InteractiveContext The initiated vivarium simulation object before simulation.setup() is run. Returns ------- simulation : vivarium.interface.interactive.InteractiveContext The initiated vivarium simulation object with anything needed to run the module. E.g. rate tables. """ return simulation def setup(self, builder): """ Method for initialising the depression module. Parameters ---------- builder : vivarium.builder Vivarium's control object. Stores all simulation metadata and allows modules to use it. """ # Rate producer for individual states. Given a population calculate depression probabilities using # self.calculate_depression_transitions. # Name depre #self.depression_tier0_rate_producer = builder.value.register_rate_producer('depression_transitions', # minos=self.calculate_depression_transitions, # requires_columns=['sex', 'ethnicity']) # CRN stream for depression states. maybe need one per state? self.random = builder.randomness.get_stream('depression_handler') # Add columns for depression module to alter to population data frame. columns_created = ["depression_duration"] view_columns = columns_created + ['alive', 'age', 'sex', 'ethnicity', 'labour_state', "depression_state", "education_state", "pidp"] self.population_view = builder.population.get_view(view_columns) builder.population.initializes_simulants(self.on_initialize_simulants, creates_columns=columns_created) # Register modifier for mortality based on depression state. # Adjust death rate dependent on self.depression_mortality_modifier function. # TODO: how to adjust rates? mortality_modifier = builder.value.register_value_modifier("mortality_rate", self.depression_mortality_modifier) # Register time step event for transition of depression on time_step. # Priority 1 due so no action if a patient dies on priority 0. Can't be anxious if you're dead. # TODO: more formal definition of priority. Ordering of the modules.. depression_time_step = builder.event.register_listener("time_step", self.on_time_step, priority=1) # Load in vivarium clock. self.clock = builder.time.clock() def on_initialize_simulants(self, pop_data): """ Module for adding required module columns to population data frame when vivarium simulation.setup() is run. Parameters ---------- pop_data: vivarium.framework.population.SimulantData `pop_data` is a custom vivarium class for interacting with the population data frame. It is essentially a pandas DataFrame with a few extra attributes such as the creation_time, creation_window, and current simulation state (setup/running/etc.). """ # Create new columns and add them to the population frame. # Default states here are simply the 0 state. # Default depression columns across all 3 init types. # TODO naive depression duration. No data in US? not sure what else can be done. pop_update = pd.DataFrame({'depression_duration': 0.}, index=pop_data.index) # On initial wave do nothing. Depression state already in data. if pop_data.user_data["sim_state"] == "setup": pass # On replenishment also do nothing. elif pop_data.user_data["cohort_type"] == "replenishment": # For initial and cohorts import depression state. pass elif pop_data.user_data["cohort_type"] == "births": # Default newborns to have normal levels of depression. # Assuming babies cant be depressed. pop_update["depression_state"] = 2. self.population_view.update(pop_update) def on_time_step(self, event): """ What happens in the depression module on every simulation timestep. Parameters ---------- event : vivarium.builder.event The event time_step that called this function. """ # Get anyone alive. pop = self.population_view.get(event.index, query="alive =='alive'") prob_df = pd.DataFrame(index = pop.index) prob_df["increase"] = rate_to_probability(pd.DataFrame(self.calculate_depression_transitions(pop.index))) prob_df["decrease"] = 1 - prob_df["increase"] # Choose a new state with bernoulli variables. Probs dont need normalising to 1 which is nice. prob_df['depression_state'] = self.random.choice(prob_df.index, prob_df.columns, prob_df) # Map states to 0/1 to match existing states. # TODO fix this dumb approach so empoyment nnet works properly. Should be true and false. prob_df["depression_state"] = prob_df["depression_state"].map({"increase":1., "decrease":0.}) # Add 1 to duration if they remain in their previous state. Otherwise reset to 0. same_state_index = pop.loc[pop["depression_state"] == prob_df["depression_state"]].index not_same_state_index = set(pop.index) - set(same_state_index) pop.loc[same_state_index, "depression_duration"] += 1. pop.loc[not_same_state_index, "depression_duration"] = 0. pop["depression_state"] = prob_df["depression_state"] self.population_view.update(pop[['depression_state', "depression_duration"]]) def calculate_depression_transitions(self, index): """ Calculate rates of transition between depression into state 0. Parameters ---------- index : pandas.DataFrame.index `index` series indicating which agents to calculate the death rates of. Returns ------- depression_transitions: pd.DataFrame `final_mortality_rates` indicates the rate of death for each agent specified in index between the previous and current time step events. """ pop = self.population_view.get(index, "alive=='alive'") pop_file_name = "data/depression_transition_frame.csv" pop.to_csv(pop_file_name, index=False) # input arguments for depression transitions R file. arg1 = "logistic_normal" arg2 = pop_file_name # Run R script with given parameters. Will return labour transition probabilities for each sim. # Return this to a csv for on_time_step to use random.choice and choose the new labour state. process = subprocess.call(f'Rscript transitions/depression_in_python.R {arg1} {arg2}', shell=True) # Pull labour transition probabilities from the csv and delete the csv for privacy/storage reasons. depression_transitions = pd.read_csv("data/depression_state_transitions.csv") depression_transitions.index = index # replace index to align with main population dataframe. os.remove(pop_file_name) os.remove("data/depression_state_transitions.csv") # Dummy safety for debugging. Set all to 0.1 prob. # depression_transitions = pd.DataFrame({'all_causes': 0.1}, index=index) return depression_transitions def depression_mortality_modifier(self, index, values): """ Adjust mortality rate based on depression states Note this function requires arguments that match those of mortality.calculate_mortality_rate and an addition values argument (not name dependent) that gives the current values output by the mortality rate producer. Parameters ---------- index : pandas.core.indexes.numeric.Int64Index `index` which rows of population frame apply rate modification to. values : pandas.core.frame.DataFrame the previous `values` output by the mortality_rate value producer. More generally the producer defined in the register_value_modifier method with this as its minos. Returns ------- values : pandas.core.frame.DataFrame The modified `values` handed back to the builder for application in mortality's on_time_step. In theory, those with higher depression states are at higher risk of dying. """ # get depression states from population. pop = self.population_view.get(index, query="alive =='alive' and sex != 'nan'") # Adjust depression rates accordingly. # TODO: actual values for these. values.loc[pop["depression_state"] == 1] *= 0.5 values.loc[pop["depression_state"] == 2] *= 1 values.loc[pop["depression_state"] == 3] *= 2 values.loc[pop["depression_state"] == 4] *= 10 return values
gitskarios/Gitskarios
app/src/main/java/com/alorma/github/presenter/notifications/NotificationsPresenter.java
package com.alorma.github.presenter.notifications; import com.alorma.github.bean.NotificationsParent; import com.alorma.github.presenter.BaseRxPresenter; import com.alorma.github.presenter.View; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import core.datasource.SdkItem; import core.notifications.Notification; import core.notifications.NotificationsRequest; import core.repository.GenericRepository; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class NotificationsPresenter extends BaseRxPresenter<NotificationsRequest, List<NotificationsParent>, View<List<NotificationsParent>>> { private GenericRepository<NotificationsRequest, List<Notification>> repository; public NotificationsPresenter( Scheduler mainScheduler, Scheduler ioScheduler, GenericRepository<NotificationsRequest, List<Notification>> repository) { super(mainScheduler, ioScheduler, null); this.repository = repository; } @Override public void execute(final NotificationsRequest request) { if(!isViewAttached()) return; repository.execute(new SdkItem<>(request)).map(SdkItem::getK).map(notifications -> { Map<Long, NotificationsParent> parents = new HashMap<>(); for (Notification notification : notifications) { if (parents.get(notification.repository.getId()) == null) { NotificationsParent notificationsParent = new NotificationsParent(); parents.put(notification.repository.getId(), notificationsParent); notificationsParent.repo = notification.repository; notificationsParent.notifications = new ArrayList<>(); } parents.get(notification.repository.getId()).notifications.add(notification); } Collection<NotificationsParent> values = parents.values(); ArrayList<NotificationsParent> notificationsParents = new ArrayList<>(values); Collections.reverse(notificationsParents); return notificationsParents; }).subscribeOn(ioScheduler).observeOn(mainScheduler).doOnSubscribe(() -> { if (isViewAttached()) { getView().showLoading(); } }).subscribe(notifications -> { if (isViewAttached()) { getView().hideLoading(); getView().onDataReceived(notifications, false); } }, throwable -> { if (isViewAttached()) { getView().showError(throwable); } }); } }
sourceperl/sandbox
plot/cv_valve_check/show_cv.py
import csv import matplotlib.pyplot as plt import math # some functions def celsius_to_kelvin(deg_c): return deg_c + 273.15 def is_subsonic(p_up_bara, p_down_bara): return p_down_bara > p_up_bara / 2 def valve_flow(cv, p_up_bara, p_down_bara, position=100.0, t_deg_c=8.0, sg=0.64): # compute flow in linear process valve t_deg_k = celsius_to_kelvin(t_deg_c) kv = 0.857 * cv # circulation below or over critical point if is_subsonic(p_up_bara, p_down_bara): delta_p_bar = p_up_bara - p_down_bara q_nm3_h = 514 * kv * (position / 100.0) * math.sqrt((delta_p_bar * p_down_bara) / (sg * t_deg_k)) else: q_nm3_h = 257 * kv * (position / 100.0) * p_up_bara * 1 / math.sqrt(sg * t_deg_k) return q_nm3_h def valve_cv(q_nm3_h, p_up_bara, p_down_bara, position=100.0, t_deg_c=8.0, sg=0.64): # compute cv for a linear process valve t_deg_k = celsius_to_kelvin(t_deg_c) delta_p_bar = p_up_bara - p_down_bara # circulation below or over critical point if is_subsonic(p_up_bara, p_down_bara): kv = q_nm3_h * (100.0 / (514 * position)) * math.sqrt((sg * t_deg_k) / (delta_p_bar * p_down_bara)) else: kv = q_nm3_h * (100.0 / (257 * p_up_bara * position)) * math.sqrt(sg * t_deg_k) cv = kv / 0.857 return cv if __name__ == '__main__': # load csv data pos_l, qi_l, qt_l = [], [], [] with open('valve_data.csv', 'r') as f: for row in csv.DictReader(f, delimiter=';'): pos = float(row['Position VL']) / 10 pos_l.append(pos) qi = float(row['Qi']) qi_l.append(qi) dp = (float(row['P amont']) / 10) - (float(row['P aval']) / 10) p_amt = float(row['P amont']) / 10 p_avl = float(row['P aval']) / 10 qt = valve_flow(cv=48, p_up_bara=p_amt, p_down_bara=p_avl, position=pos) qt_l.append(qt) # plot it plt.scatter(pos_l, qi_l, marker='o', label='Qi') plt.scatter(pos_l, qt_l, marker='^', label='Qt') plt.xlabel('Position (%)') plt.ylabel('Q (nm3/h)') plt.legend() plt.grid() plt.show()
MrWOLFF24/expensa
backend-nodejs/api/models/tasksModel.js
'use strict' const moment = require('moment') const mysql = require('./../util/mysql') // get all tasks per user const getTasks = (clbk, id) => { const q = `SELECT task_id, task_name, task_description, task_done, task_date FROM tasks WHERE fk_user_id = ${mysql.escape(id)}` mysql.query(q, (error, results, fields) => { if (error) throw error // in case of query error, an exception is thrown clbk(results) // result is send in calback }) } // create new task const createTask = (clbk, data, id) => { const todayDate = moment().format('YYYY-MM-DD HH:mm:ss') console.log(todayDate) const q = `INSERT INTO tasks (task_name, task_description, task_date, fk_user_id) VALUES ( ${mysql.escape(data.taskName)}, ${mysql.escape(data.taskDescription)}, ${mysql.escape(todayDate)}, ${mysql.escape(id)} )` mysql.query(q, (error, results, fields) => { if (error) throw error results.message = 'Tâche ajoutée avec succès' clbk(results) }) } // update a task const updateTask = (clbk, data, id) => { const q = `UPDATE tasks SET task_name = ${mysql.escape(data.taskName)}, task_description = ${mysql.escape(data.taskDescription)} WHERE task_id = ${mysql.escape(id)}` mysql.query(q, (error, results, fields) => { if (error) throw error results.message = 'Tâche mise à jour avec succès' clbk(results) }) } // update task status const updateTaskStatus = (clbk, data, id) => { const q = `UPDATE tasks SET task_done = ${mysql.escape(data.taskDone)} WHERE task_id = ${mysql.escape(id)}` mysql.query(q, (error, results, fields) => { if (error) throw error results.message = 'Le statut à bien été modifié' clbk(results) }) } // remove a task const removeTask = (clbk, id) => { const q = `DELETE FROM tasks WHERE task_id = ${mysql.escape(id)}` mysql.query(q, (error, results, fields) => { if (error) throw error results.message = 'Tâche supprimée avec succès' clbk(results) }) } module.exports = { getTasks, createTask, updateTask, updateTaskStatus, removeTask, }
mises-iscte/ES-LIGE-2Sem-2022-Grupo-31
jfreechart-master/src/main/java/org/jfree/chart/swing/Overlay.java
<gh_stars>1-10 /* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2022, by <NAME> and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------ * Overlay.java * ------------ * (C) Copyright 2009-2022, by <NAME>. * * Original Author: <NAME>; * Contributor(s): -; * */ package org.jfree.chart.swing; import java.awt.Graphics2D; /** * An {@code Overlay} is anything that can be drawn over top of a chart to add * additional information to the chart. This interface defines the operations * that must be supported for an overlay that can be added to a * {@link ChartPanel} in Swing. * <br><br> * Note: if you are using JavaFX rather than Swing, then you need to look at * the {@code OverlayFX} interface in the <b>JFreeChart-FX</b> project. */ public interface Overlay { /** * Paints the visual representation of the overlay. This method will be * called by the {@link ChartPanel} after the underlying chart has been * fully rendered. When implementing this method, the {@code chartPanel} * argument can be used to get state information from the chart (you can, * for example, extract the axis ranges for the chart). * * @param g2 the graphics target (never {@code null}). * @param chartPanel the chart panel (never {@code null}). */ void paintOverlay(Graphics2D g2, ChartPanel chartPanel); /** * Registers a change listener with the overlay. Typically this method * not be called by user code, it exists so that the {@link ChartPanel} * can register and receive notification of changes to the overlay (such * changes will trigger an automatic repaint of the chart). * * @param listener the listener ({@code null} not permitted). * * @see #removeChangeListener(org.jfree.chart.event.OverlayChangeListener) */ void addChangeListener(OverlayChangeListener listener); /** * Deregisters a listener from the overlay. * * @param listener the listener ({@code null} not permitted). * * @see #addChangeListener(org.jfree.chart.event.OverlayChangeListener) */ void removeChangeListener(OverlayChangeListener listener); }
zippy1978/stark
lang/codeGen/CodeGenBitcode.cpp
<reponame>zippy1978/stark<gh_stars>0 #include <llvm/Bitcode/BitcodeWriter.h> #include <llvm/Support/SourceMgr.h> #include <llvm/IRReader/IRReader.h> #include <llvm/Support/FormatVariadic.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetOptions.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Host.h> #include <llvm/Support/raw_ostream.h> #include <llvm/IR/LegacyPassManager.h> #include <iostream> #include "CodeGenBitcode.h" using namespace llvm; namespace stark { std::string CodeGenBitcode::getHostTargetTriple() { return sys::getDefaultTargetTriple(); } void CodeGenBitcode::load(std::string filename) { SMDiagnostic error; llvmModule = parseIRFile(filename, error, context).release(); // LLVM module was not loaded if (llvmModule == nullptr) { logger.setFilename(error.getFilename().str()); logger.logError(formatv("{0} {1}", error.getMessage(), error.getLineContents())); } } void CodeGenBitcode::write(std::string filename) { // TODO : hande error std::error_code errorCode; //raw_ostream output = outs(); raw_fd_ostream output(filename, errorCode); WriteBitcodeToFile(*llvmModule, output); } void CodeGenBitcode::writeObjectCode(std::string filename, std::string targetString) { logger.setFilename(filename); InitializeAllTargetInfos(); InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllAsmPrinters(); // Parse target string std::vector<std::string> targetParts = split(targetString, ':'); std::string targetTriple = sys::getDefaultTargetTriple(); if (targetParts[0].size() > 0) { targetTriple = targetParts[0]; } // Features: add options support here for tuning ! std::string cpu = "generic"; if (targetParts.size() > 1 && targetParts[1].size() > 0) { cpu = targetParts[1]; } std::string features = ""; //+vfp2,+... if (targetParts.size() > 2 && targetParts[2].size() > 0) { features = targetParts[2]; } std::string error; auto target = TargetRegistry::lookupTarget(targetTriple, error); // Target not found if (!target) { logger.logError(error); } TargetOptions opt; auto rm = Optional<Reloc::Model>(); auto targetMachine = target->createTargetMachine(targetTriple, cpu, features, opt, rm); // Configure module llvmModule->setDataLayout(targetMachine->createDataLayout()); llvmModule->setTargetTriple(targetTriple); // Prepare output file std::error_code errorCode; raw_fd_ostream dest(filename, errorCode, sys::fs::OF_None); if (errorCode) { logger.logError(errorCode.message()); } // Run pass manager to write output legacy::PassManager pass; auto fileType = CGFT_ObjectFile; if (targetMachine->addPassesToEmitFile(pass, dest, nullptr, fileType)) { logger.logError("target machine can't emit a file of this type"); } pass.run(*llvmModule); dest.flush(); } void CodeGenBitcode::writeObjectCode(std::string filename) { this->writeObjectCode(filename, sys::getDefaultTargetTriple()); } } // namespace stark
Joseph295/Coorabie
src/main/java/model/sinker/HttpSinker.java
<gh_stars>0 package model.sinker; import config.HttpConfig; public class HttpSinker implements Sinker<String> { private HttpConfig httpConfig; public HttpSinker(String path) { httpConfig = new HttpConfig(path); } @Override public boolean sink(String content) { return true; } }
fabsgc/TweedeFramework
Source/Framework/Core/Manager/TeRenderAPIManager.h
<reponame>fabsgc/TweedeFramework #pragma once #include "TeCorePrerequisites.h" #include "Utility/TeModule.h" #include "RenderAPI/TeRenderAPI.h" #include "RenderAPI/TeRenderAPIFactory.h" namespace te { /** Manager that handles render system start up. */ class TE_CORE_EXPORT RenderAPIManager : public Module<RenderAPIManager> { public: RenderAPIManager(); ~RenderAPIManager(); /** * Starts the render API with the provided name and creates the primary render window. * * @param[in] name Name of the render system to start. Factory for this render system must be * previously registered. * @param[in] primaryWindowDesc Contains options used for creating the primary window. */ void Initialize(const String& name, const RENDER_WINDOW_DESC& windowDesc); /** Registers a new render API factory responsible for creating a specific render system type. */ void RegisterFactory(SPtr<RenderAPIFactory> factory); private: Vector<SPtr<RenderAPIFactory>> _availableFactories; bool _renderAPIInitialized; }; /** @} */ }
sourav025/algorithms-practices
UVA/IsItTree2.cpp
<gh_stars>0 #include<iostream> #include<cstdio> #include<set> #include<utility> using namespace std; set< pair<int,int> > st; int cnt; set<int> nodes; int main() { int cas=1,u,v; while( scanf("%d%d",&u,&v)==2&&v>=0&&u>=0 ) { if(u==0&&v==0){ printf("Case %d is not a tree.\n",cas++);continue; } nodes.clear(),st.clear(); nodes.insert(u);nodes.insert(v); if(u!=v) st.insert(make_pair(u,v)); while(scanf("%d%d",&u,&v)==2&&v>0&&u>0) { if(u!=v){ nodes.insert(u);nodes.insert(v); st.insert(make_pair(u,v)); } } int nn=nodes.size(); int edges=st.size(); if(nn-1==edges) { printf("Case %d is a tree.\n",cas++); } else printf("Case %d is not a tree.\n",cas++); } return 0; }
sm453/MOpS
src/sweepc/include/swp_aggmodel_type.h
<filename>src/sweepc/include/swp_aggmodel_type.h /* Author(s): <NAME> (msc37) Project: sweep (population balance solver) Sourceforge: http://sourceforge.net/projects/mopssuite Copyright (C) 2008 <NAME>. File purpose: The AggModelType enumeration gives ID number for all the different possible aggregation models implemented in sweep for primary particles. Each model defines rules for how a primary particle is stored in memory and how they are modified by particle processes. Licence: This file is part of "sweepc". sweepc is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Contact: Dr <NAME> Dept of Chemical Engineering University of Cambridge New Museums Site Pembroke Street Cambridge CB2 3RA UK Email: <EMAIL> Website: http://como.cheng.cam.ac.uk */ #ifndef SWEEP_AGGMODEL_TYPE_H #define SWEEP_AGGMODEL_TYPE_H namespace Sweep { namespace AggModels { // IMPORTANT: DO NOT CHANGE THE VALUES HERE. IT WILL INVALIDATE // PREVIOUSLY GENERATED INPUT FILES. enum AggModelType { Spherical_ID = 10000, // Spherical particle model. SurfVol_ID = 10001, // Surface-volume model (Patterson et al., Combust. Flame, 151, 160-172, 2007). //PriPartList_ID = 10002, // Primary-particle list (West et al., Ind. Eng. Chem. Res., 46, 6147-6156, 2007). //PAH_ID = 10003, // A particle storing multiple PAHs (Markus et al., Proceedings of the Combustion Institute, 33, 675-683, 2011) PAH_KMC_ID = 10004, // coupled PAH-PP model (ms785) with KMC-ARS model (zz260 and ar447) Silica_ID = 10005, // Silica particle model (ms785 & ss663, integrated with git repository by wjm34) SurfVolHydrogen_ID = 10006, //! (Blanquart & Pitsch., Combust. Flame, 156, 1614-1626, 2009). BinTree_ID = 10007, // Generalised form of silica and PAH-PP models for multicomponent systems (wjm34) SurfVolSilica_ID = 10008, // Surfvol implementation of the silica model BinTreeSilica_ID = 10009, // Binary tree implementation of the silica model SurfVolCubic_ID = 10010, //! Surface volume approximation for cuboidal crystals }; } } #endif
Pratham82/Java-Programming
Practice_Problems/Edabit_Practice_problems/Question_46.java
<reponame>Pratham82/Java-Programming<gh_stars>1-10 package Practice_Problems.Edabit_Practice_problems; /* Write a function that accepts base (decimal), height (decimal) and shape ("triangle", "parallelogram") as input and calculates the area of that shape. */ public class Question_46 { public static void main(String[] args) { System.out.println(areaShape(2, 3, "triangle")); System.out.println(areaShape(8, 6, "parallelogram")); System.out.println(areaShape(2.9, 1.3, "parallelogram")); } public static double areaShape(double base,double height, String shape){ return shape.equals("triangle")? Math.floor(base*height*0.5): base*height; } }
kimjuyounglisa/radeon_compute_profiler
Src/sanalyze/CLAPIAnalyzer.h
<reponame>kimjuyounglisa/radeon_compute_profiler //============================================================================== // Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief This file defines the CLAPIAnalyzer and CLAPIAnalyzerManager specialization classes //============================================================================== #ifndef _CL_API_ANALYZER_H_ #define _CL_API_ANALYZER_H_ #include "APIAnalyzer.h" #include "../CLTraceAgent/CLAPIInfo.h" #define NUM_ARG_CL_SET_KERNEL_ARG 4 #define NUM_ARG_CL_CREATE_KERNELS_IN_PROGRAM 4 #define NUM_ARG_CL_CREATE_SUB_DEVICES_EXT 5 #define NUM_ARG_CL_WAIT_FOR_EVENTS 2 class CLAPIAnalyzerManager; typedef std::map<unsigned int, std::string> CLKernelArgsSetup; //------------------------------------------------------------------------------------ /// CL Kernel Info //------------------------------------------------------------------------------------ struct CLKernelInfo { unsigned int uiRefCount; ///< Kernel handle reference count CLKernelArgsSetup kernelArgsSetup; ///< Kernel arguments setup table }; typedef std::map<std::string, CLKernelInfo> CLKernelArgsSetupMap; //------------------------------------------------------------------------------------ /// OpenCL API Analyzer base class //------------------------------------------------------------------------------------ class CLAPIAnalyzer : public APIAnalyzer<CL_FUNC_TYPE> { public: /// Constructor /// \param pManager CLAPIAnalyzerManager object CLAPIAnalyzer(CLAPIAnalyzerManager* pManager); protected: CLAPIAnalyzerManager* m_pParent; ///< CLAPIAnalyzerManager pointer }; class CLAPIAnalyzerManager : public APIAnalyzerManager <CLAPIAnalyzer, CL_FUNC_TYPE>, public IParserListener<CLAPIInfo> { public: /// Constructor CLAPIAnalyzerManager(); /// KernelArgsSetupMap getter /// \return reference to CLKernelArgsSetupMap const CLKernelArgsSetupMap& GetKernelArgsSetupMap() const; /// Enable kernel args setup analyzer /// It's used by DataTransferAnalyzer. If DataTransferAnalyzer is disabled, /// We can disable kernel args setup as well. void EnableKernelArgsSetupAnalyzer(); /// Analyze kernel arg setup /// \param pAPIInfo API Info object void AnalyzeKernelArgSetup(CLAPIInfo* pAPIInfo); /// Listener function /// \param pAPIInfo API Info object /// \param[out] stopParsing flag indicating if parsing should stop after this item void OnParse(CLAPIInfo* pAPIInfo, bool& stopParsing); protected: /// Overridden virtual fnuction see base class for description virtual bool DoEnableAnalyzer(); /// Overridden virtual fnuction see base class for description virtual bool DoEndAnalyze(APIInfo* pAPIInfo); private: CLKernelArgsSetupMap m_KernelArgsSetupMap; ///< Kernel args setup map bool m_bEnableKernelArgsAnalyzer; ///< A flag indicating whether or not kernel args setup are parsed. }; #endif //_CL_API_ANALYZER_H_
ajayns/zulip-mobile
src/topics/__tests__/topicsSelectors-test.js
import deepFreeze from 'deep-freeze'; import { getTopicsInActiveNarrow, getLastMessageTopic } from '../topicSelectors'; import { homeNarrow, streamNarrow } from '../../utils/narrow'; describe('getTopicsInActiveNarrow', () => { test('when no topics return an empty list', () => { const state = deepFreeze({ chat: { narrow: homeNarrow, }, }); const topics = getTopicsInActiveNarrow(state); expect(topics).toEqual([]); }); test('when there are topics in the active narrow, return them as string array', () => { const state = deepFreeze({ chat: { narrow: streamNarrow('hello'), }, streams: [{ stream_id: 123, name: 'hello' }], topics: { 123: [{ name: 'hi' }, { name: 'wow' }], }, }); const topics = getTopicsInActiveNarrow(state); expect(topics).toEqual(['hi', 'wow']); }); }); describe('getLastMessageTopic', () => { test('when no messages in narrow return an empty string', () => { const state = deepFreeze({ chat: { narrow: homeNarrow, messages: {}, }, }); const topic = getLastMessageTopic(state); expect(topic).toEqual(''); }); test('when one or more messages return the topic of the last one', () => { const narrow = streamNarrow('hello'); const state = deepFreeze({ chat: { narrow, messages: { [JSON.stringify(narrow)]: [{ id: 1 }, { id: 2, subject: 'some topic' }], }, }, }); const topic = getLastMessageTopic(state); expect(topic).toEqual('some topic'); }); });
misery/AusweisApp2
test/qt/core/paos/test_PaosMessage.cpp
<reponame>misery/AusweisApp2 /*! * \brief Unit tests for \ref PaosMessage * * \copyright Copyright (c) 2015-2018 Governikus GmbH & Co. KG, Germany */ #include "paos/PaosMessage.h" #include <QtCore> #include <QtTest> using namespace governikus; class test_PaosMessage : public QObject { Q_OBJECT private Q_SLOTS: void type() { PaosMessage msg(PaosType::UNKNOWN); QCOMPARE(msg.mType, PaosType::UNKNOWN); PaosMessage msg2(PaosType::DID_AUTHENTICATE_EAC_ADDITIONAL_INPUT_TYPE); QCOMPARE(msg2.mType, PaosType::DID_AUTHENTICATE_EAC_ADDITIONAL_INPUT_TYPE); } void emptyMembers() { PaosMessage msg(PaosType::UNKNOWN); QCOMPARE(msg.getMessageId(), QString()); QCOMPARE(msg.getRelatesTo(), QString()); } void handleWSAddressingHeaders() { PaosMessage msg(PaosType::UNKNOWN); QCOMPARE(msg.handleWSAddressingHeaders(QStringLiteral("elem name"), QStringLiteral("some value"), QXmlStreamAttributes()), false); QCOMPARE(msg.getMessageId(), QString()); QCOMPARE(msg.getRelatesTo(), QString()); QCOMPARE(msg.handleWSAddressingHeaders(QStringLiteral("MessageID"), QStringLiteral("msg value"), QXmlStreamAttributes()), true); QCOMPARE(msg.getMessageId(), QStringLiteral("msg value")); QCOMPARE(msg.getRelatesTo(), QString()); QCOMPARE(msg.handleWSAddressingHeaders(QStringLiteral("RelatesTo"), QStringLiteral("relates value"), QXmlStreamAttributes()), true); QCOMPARE(msg.getMessageId(), QStringLiteral("msg value")); QCOMPARE(msg.getRelatesTo(), QStringLiteral("relates value")); } }; QTEST_GUILESS_MAIN(test_PaosMessage) #include "test_PaosMessage.moc"
alvaroreis/xti
src/br/com/xti/poo/Funcionario.java
package br.com.xti.poo; public class Funcionario { private String nome; private double salario; private boolean ativo; public String getNome() { return this.nome; } public void setNome(final String nome) { this.nome = nome; } public boolean isAtivo() { return this.ativo; } public void setAtivo(final boolean ativo) { this.ativo = ativo; } }
martianworm17/java-codingbat
src/com/codingbat/warmup2/arraycount9/ArrayCount9.java
package com.codingbat.warmup2.arraycount9; public class ArrayCount9 { public static void main(String[] args) { System.out.println(arrayCount9(new int[]{1, 2, 9})); System.out.println(arrayCount9(new int[]{1, 9, 9})); System.out.println(arrayCount9(new int[]{1, 9, 9, 3, 9})); } private static int arrayCount9(int[] nums) { int count9 = 0; for (int x : nums) { if (x == 9) { count9++; } } return count9; } }
belfinor/Helium
db/ldb/ldb_test.go
<reponame>belfinor/Helium package ldb // @author <NAME> <<EMAIL>> // @version 1.003 // @date 2018-07-04 import ( "testing" ) func TestDB(t *testing.T) { Close() Close() TestInit() key := []byte("test.key") val := []byte{1, 2, 3} Del(key) res := Get(key) if res != nil { t.Fatal("expecting nil value") } if Has(key) { t.Fatal("Has not working") } Set(key, val) res = Get(key) if res == nil || len(res) != len(val) { t.Fatal("db.Get error") } if !Has(key) { t.Fatal("Has not work") } for i, c := range res { if c != val[i] { t.Fatal("db.Get error") } } res = Get(key) if res == nil || len(res) != len(val) { t.Fatal("db.Get error") } for i, c := range res { if c != val[i] { t.Fatal("db.Get error") } } if Total([]byte{}) != 1 { t.Fatal("wrong key number") } Set([]byte("tkey"), []byte("1")) if Total([]byte{}) != 2 { t.Fatal("wrong key number") } if Total([]byte("tk")) != 1 { t.Fatal("total prefix find error") } }
breeze-easy/thinking-in-java
object.14/src/Documentation1.java
<gh_stars>10-100 //: object/Documentation1.java /** A class comment */ public class Documentation1 { /** A field comment */ public int i; /** A method comment * a list: * <ol> * <li> a * <li> b * <li> c * </ol> */ public void f() {} } ///:~
buland-usgs/neic-traveltime
src/main/java/gov/usgs/traveltime/GenIndex.java
package gov.usgs.traveltime; /** * This generalized index interface allows computed sample points to be used like they were actual * arrays for bilinear interpolation. * * @author <NAME> */ public interface GenIndex { /** * Get the virtual array index from a value. * * @param value Generic value * @return Index of virtual array index from value */ int getIndex(double value); /** * Get the virtual array value from an index. * * @param index Virtual array index * @return Value at that virtual array index */ double getValue(int index); }
xmdas-link/kitty
rpc/proto/kittyrpc/kittyrpc.pb.go
<reponame>xmdas-link/kitty // Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/kittyrpc/kittyrpc.proto package go_micro_srv_kittyrpc import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type Request struct { Model string `protobuf:"bytes,1,opt,name=model,proto3" json:"model,omitempty"` Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"` Search string `protobuf:"bytes,3,opt,name=search,proto3" json:"search,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} func (*Request) Descriptor() ([]byte, []int) { return fileDescriptor_789aa2d084f3f295, []int{0} } func (m *Request) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Request.Unmarshal(m, b) } func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Request.Marshal(b, m, deterministic) } func (m *Request) XXX_Merge(src proto.Message) { xxx_messageInfo_Request.Merge(m, src) } func (m *Request) XXX_Size() int { return xxx_messageInfo_Request.Size(m) } func (m *Request) XXX_DiscardUnknown() { xxx_messageInfo_Request.DiscardUnknown(m) } var xxx_messageInfo_Request proto.InternalMessageInfo func (m *Request) GetModel() string { if m != nil { return m.Model } return "" } func (m *Request) GetAction() string { if m != nil { return m.Action } return "" } func (m *Request) GetSearch() string { if m != nil { return m.Search } return "" } type Response struct { Msg string `protobuf:"bytes,1,opt,name=msg,proto3" json:"msg,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Response) Reset() { *m = Response{} } func (m *Response) String() string { return proto.CompactTextString(m) } func (*Response) ProtoMessage() {} func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor_789aa2d084f3f295, []int{1} } func (m *Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Response.Unmarshal(m, b) } func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Response.Marshal(b, m, deterministic) } func (m *Response) XXX_Merge(src proto.Message) { xxx_messageInfo_Response.Merge(m, src) } func (m *Response) XXX_Size() int { return xxx_messageInfo_Response.Size(m) } func (m *Response) XXX_DiscardUnknown() { xxx_messageInfo_Response.DiscardUnknown(m) } var xxx_messageInfo_Response proto.InternalMessageInfo func (m *Response) GetMsg() string { if m != nil { return m.Msg } return "" } func init() { proto.RegisterType((*Request)(nil), "go.micro.srv.kittyrpc.Request") proto.RegisterType((*Response)(nil), "go.micro.srv.kittyrpc.Response") } func init() { proto.RegisterFile("proto/kittyrpc/kittyrpc.proto", fileDescriptor_789aa2d084f3f295) } var fileDescriptor_789aa2d084f3f295 = []byte{ // 180 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0xcf, 0xce, 0x2c, 0x29, 0xa9, 0x2c, 0x2a, 0x48, 0x86, 0x33, 0xf4, 0xc0, 0xe2, 0x42, 0xa2, 0xe9, 0xf9, 0x7a, 0xb9, 0x99, 0xc9, 0x45, 0xf9, 0x7a, 0xc5, 0x45, 0x65, 0x7a, 0x30, 0x49, 0x25, 0x7f, 0x2e, 0xf6, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x11, 0x2e, 0xd6, 0xdc, 0xfc, 0x94, 0xd4, 0x1c, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x08, 0x47, 0x48, 0x8c, 0x8b, 0x2d, 0x31, 0xb9, 0x24, 0x33, 0x3f, 0x4f, 0x82, 0x09, 0x2c, 0x0c, 0xe5, 0x81, 0xc4, 0x8b, 0x53, 0x13, 0x8b, 0x92, 0x33, 0x24, 0x98, 0x21, 0xe2, 0x10, 0x9e, 0x92, 0x0c, 0x17, 0x47, 0x50, 0x6a, 0x71, 0x41, 0x7e, 0x5e, 0x71, 0xaa, 0x90, 0x00, 0x17, 0x73, 0x6e, 0x71, 0x3a, 0xd4, 0x3c, 0x10, 0xd3, 0x28, 0x94, 0x8b, 0xc3, 0x1b, 0x6a, 0xb5, 0x90, 0x27, 0x17, 0x8b, 0x73, 0x62, 0x4e, 0x8e, 0x90, 0x9c, 0x1e, 0x56, 0xa7, 0xe9, 0x41, 0xdd, 0x25, 0x25, 0x8f, 0x53, 0x1e, 0x62, 0x8d, 0x12, 0x43, 0x12, 0x1b, 0xd8, 0x8f, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x40, 0x8f, 0x5b, 0x89, 0x04, 0x01, 0x00, 0x00, }
AkshayIyer12/hackerrank
queens_attack_2.js
<reponame>AkshayIyer12/hackerrank process.stdin.resume(); process.stdin.setEncoding('ascii'); var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; process.stdin.on('data', function (data) { input_stdin += data; }); process.stdin.on('end', function () { input_stdin_array = input_stdin.split("\n"); main(); }); function readLine() { return input_stdin_array[input_currentline++]; } /////////////// ignore above this line //////////////////// function main() { var n_temp = readLine().split(' '); var n = parseInt(n_temp[0]); var k = parseInt(n_temp[1]); var rQueen_temp = readLine().split(' '); var rQueen = parseInt(rQueen_temp[0]); var cQueen = parseInt(rQueen_temp[1]); let up = n - rQueen let down = rQueen - 1 let left = cQueen - 1 let right = n - cQueen let uld = up < left ? up : left let urd = up < right ? up : right let dld = down < left ? down : left let drd = down < right ? down : right const choose = f => g => f < g? f : g const absDiff = f => g => Math.abs(f-g) - 1 for(var a0 = 0; a0 < k; a0++){ var rObstacle_temp = readLine().split(' '); var rObstacle = parseInt(rObstacle_temp[0]); var cObstacle = parseInt(rObstacle_temp[1]); // your code goes here if (cObstacle === cQueen) { let path = absDiff(rObstacle)(rQueen) if (rQueen<rObstacle) up = choose(up)(path) else down = choose(down)(path) } else if (rObstacle === rQueen) { let path = absDiff(cObstacle)(cQueen) if (cQueen<cObstacle) right = choose(right)(path) else left = choose(right)(path) } else { let path = absDiff(cObstacle)(cQueen) let path1 = absDiff(rObstacle)(rQueen) if (path === path1) { if (cQueen<cObstacle && rQueen<rObstacle) urd = choose(urd)(path) else if (cQueen>cObstacle && rQueen<rObstacle) uld = choose(uld)(path) else if (cQueen<cObstacle && rQueen>rObstacle) drd = choose(drd)(path) else dld = choose(dld)(path) } } } let total = [up, down, left, right, urd, uld, drd, dld] let sum = total.reduce((a, v) => a+v, 0) console.log(sum) }
rceet/TencentOS-tiny
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/components/iot/coap/coap_option.h
/** * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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. * */ /** @file coap_option.h * * @defgroup iot_sdk_coap_option CoAP Option * @ingroup iot_sdk_coap * @{ * @brief Nordic's CoAP Option APIs. */ #ifndef COAP_OPTION_H__ #define COAP_OPTION_H__ /* +-----+---+---+---+---+----------------+--------+--------+----------+ | No. | C | U | N | R | Name | Format | Length | Default | +-----+---+---+---+---+----------------+--------+--------+----------+ | 1 | x | | | x | If-Match | opaque | 0-8 | (none) | | 3 | x | x | - | | Uri-Host | string | 1-255 | (see | | | | | | | | | | below) | | 4 | | | | x | ETag | opaque | 1-8 | (none) | | 5 | x | | | | If-None-Match | empty | 0 | (none) | | 7 | x | x | - | | Uri-Port | uint | 0-2 | (see | | | | | | | | | | below) | | 8 | | | | x | Location-Path | string | 0-255 | (none) | | 11 | x | x | - | x | Uri-Path | string | 0-255 | (none) | | 12 | | | | | Content-Format | uint | 0-2 | (none) | | 14 | | x | - | | Max-Age | uint | 0-4 | 60 | | 15 | x | x | - | x | Uri-Query | string | 0-255 | (none) | | 17 | x | | | | Accept | uint | 0-2 | (none) | | 20 | | | | x | Location-Query | string | 0-255 | (none) | | 23 | x | x | - | - | Block2 | uint | 0-3 | (none) | | 27 | x | x | - | - | Block1 | uint | 0-3 | (none) | | 28 | | | x | | Size2 | uint | 0-4 | (none) | | 35 | x | x | - | | Proxy-Uri | string | 1-1034 | (none) | | 39 | x | x | - | | Proxy-Scheme | string | 1-255 | (none) | | 60 | | | x | | Size1 | uint | 0-4 | (none) | +-----+---+---+---+---+----------------+--------+--------+----------+ */ #include <stdint.h> #include "coap_api.h" #include "nrf_error.h" #include "sdk_errors.h" #ifdef __cplusplus extern "C" { #endif typedef enum { COAP_OPT_FORMAT_EMPTY = 0, COAP_OPT_FORMAT_STRING = 1, COAP_OPT_FORMAT_OPAQUE = 2, COAP_OPT_FORMAT_UINT = 3 } coap_opt_format_t; /**@brief Encode zero-terminated string into utf-8 encoded string. * * @param[out] p_encoded Pointer to buffer that will be used to fill the * encoded string into. * @param[inout] p_length Length of the buffer provided. Will also be used to * return the size of the used buffer. * @param[in] p_string String to encode. * @param[in] str_len Length of the string to encode. * * @retval NRF_SUCCESS Indicates that encoding was successful. * @retval NRF_ERROR_DATA_SIZE Indicates that the buffer provided was not sufficient to * successfully encode the data. */ uint32_t coap_opt_string_encode(uint8_t * p_encoded, uint16_t * p_length, uint8_t * p_string, uint16_t str_len); /**@brief Decode a utf-8 string into a zero-terminated string. * * @param[out] p_string Pointer to the string buffer where the decoded * string will be placed. * @param[inout] p_length p_length of the encoded string. Returns the size of the buffer * used in bytes. * @param[in] p_encoded Buffer to decode. * * @retval NRF_SUCCESS Indicates that decoding was successful. * @retval NRF_ERROR_DATA_SIZE Indicates that the buffer provided was not sufficient to * successfully dencode the data. */ uint32_t coap_opt_string_decode(uint8_t * p_string, uint16_t * p_length, uint8_t * p_encoded); /**@brief Encode a uint value into a uint8_t buffer in network byte order. * * @param[out] p_encoded Pointer to buffer that will be used to fill the * encoded uint into. * @param[inout] p_length Length of the buffer provided. Will also be used to * return the size of the used buffer. * @param[in] data uint value which could be anything from 1 to 4 bytes. * * @retval NRF_SUCCESS Indicates that encoding was successful. * @retval NRF_ERROR_DATA_SIZE Indicates that the buffer provided was not sufficient to * successfully encode the data. */ uint32_t coap_opt_uint_encode(uint8_t * p_encoded, uint16_t * p_length, uint32_t data); /**@brief Decode a uint encoded value in network byte order to a uint32_t value. * * @param[out] p_data Pointer to the uint32_t value where the decoded uint will * be placed. * @param[inout] length Size of the encoded value. * @param[in] p_encoded uint value to be decoded into a uint32_t value. * * @retval NRF_SUCCESS Indicates that decoding was successful. * @retval NRF_ERROR_NULL If p_data or p_encoded pointer is NULL. * @retval NRF_ERROR_INVALID_LENGTH If buffer was greater than uint32_t. */ uint32_t coap_opt_uint_decode(uint32_t * p_data, uint16_t length, uint8_t * p_encoded); #ifdef __cplusplus } #endif #endif // COAP_OPTION_H__ /** @} */
auag92/n2dm
Asap-3.8.4/Projects/ParameterOptimization/fit_alloy.py
#!/usr/bin/env python #PBS -N EMT-alloys #PBS -m n #PBS -q long #PBS -l nodes=2:ppn=4:opteron4 import numpy as np from asap3.Tools.ParameterOptimization import ParameterPerformance from asap3.Tools.ParameterOptimization.Optimization import ParameterOptimization from asap3.Tools.ParameterOptimization.SearchParallel import ParameterSearch from asap3.Tools.ParameterOptimization.EMT import EMT2011Fit, EMTStdParameters # Parameter names: ['eta2', 'lambda', 'kappa/delta', 'E0', 'V0', 'S0', 'n0'] initparam = {${initparam}} varparam = {${varparam}} quantities = [${quantities}] latticeconstants = [${latticeconstants}] calculator = EMT2011Fit(${symbols}, initparam, 'delta') ParameterPerformance(calculator, quantities, latticeconstants, debug=False) #opt = ParameterOptimization(${symbols}, EMT2011Fit, initparam, varparam, # quantities, latticeconstants, ('delta',), False) #(error, optpar, optval) = opt.fit(xtol=1e-3, ftol=5e-2, delta=5e-4, # log='fit.log', err='fit.err') #print 'Optimization ended with error function %.6e' % (error,) #opt.write_result(initparam, optpar, optval) opt = ParameterSearch(${symbols}, EMT2011Fit, initparam, varparam, quantities, latticeconstants, ('delta',), False) opt.run(0.1, 0.144, '8.0h', xtol=1e-3, ftol=5e-2, delta=1e-3, dat='fit.dat', log='fit.log', err='fit.err')
gil0mendes/Infinity-OS
source/kernel/time.c
<filename>source/kernel/time.c /* * Copyright (C) 2010-2014 <NAME> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** * @file * @brief Time handling functions. * * @todo Timers are tied to the CPU that they are created on. * This is the right thing to do with, e.g. the scheduler * timers, but what should we do with user timers? Load * balance them? They'll probably get balanced reasonably * due to thread load balancing. Does it matter that much? */ #include <kernel/time.h> #include <lib/notifier.h> #include <mm/malloc.h> #include <mm/safe.h> #include <proc/thread.h> #include <assert.h> #include <cpu.h> #include <dpc.h> #include <kdb.h> #include <kernel.h> #include <object.h> #include <status.h> #include <time.h> /** Userspace timer structure. */ typedef struct user_timer { uint32_t flags; /**< Flags for the timer. */ timer_t timer; /**< Kernel timer. */ notifier_t notifier; /**< Notifier for the timer event. */ bool fired; /**< Whether the event has fired. */ } user_timer_t; /** Check if a year is a leap year. */ #define LEAPYR(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) /** Get number of days in a year. */ #define DAYS(y) (LEAPYR(y) ? 366 : 365) /** Table containing number of days before a month. */ static unsigned days_before_month[] = { 0, /* Jan. */ 0, /* Feb. */ 31, /* Mar. */ 31 + 28, /* Apr. */ 31 + 28 + 31, /* May. */ 31 + 28 + 31 + 30, /* Jun. */ 31 + 28 + 31 + 30 + 31, /* Jul. */ 31 + 28 + 31 + 30 + 31 + 30, /* Aug. */ 31 + 28 + 31 + 30 + 31 + 30 + 31, /* Sep. */ 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, /* Oct. */ 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, /* Nov. */ 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, /* Dec. */ 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, }; /** The number of nanoseconds since the Epoch the kernel was booted at. */ nstime_t boot_unix_time = 0; /** Hardware timer device. */ static timer_device_t *timer_device = NULL; /** Convert a date/time to nanoseconds since the epoch. * @param year Year. * @param month Month (1-12). * @param day Day of month (1-31). * @param hour Hour (0-23). * @param min Minute (0-59). * @param sec Second (0-59). * @return Number of nanoseconds since the epoch. */ nstime_t time_to_unix(unsigned year, unsigned month, unsigned day, unsigned hour, unsigned min, unsigned sec) { uint32_t seconds = 0; unsigned i; /* Start by adding the time of day and day of month together. */ seconds += sec; seconds += min * 60; seconds += hour * 60 * 60; seconds += (day - 1) * 24 * 60 * 60; /* Convert the month into days. */ seconds += days_before_month[month] * 24 * 60 * 60; /* If this year is a leap year, and we're past February, we need to * add another day. */ if(month > 2 && LEAPYR(year)) seconds += 24 * 60 * 60; /* Add the days in each year before this year from 1970. */ for(i = 1970; i < year; i++) seconds += DAYS(i) * 24 * 60 * 60; return SECS2NSECS(seconds); } /** * Get the number of nanoseconds since the Unix Epoch. * * Returns the number of nanoseconds that have passed since the Unix Epoch, * 00:00:00 UTC, January 1st, 1970. * * @return Number of nanoseconds since epoch. */ nstime_t unix_time(void) { return boot_unix_time + system_time(); } /** Get the system boot time. * @return UNIX time at which the system was booted. */ nstime_t boot_time(void) { return boot_unix_time; } /** Prepares next timer tick. * @param timer Timer to prepare for. */ static void timer_device_prepare(timer_t *timer) { nstime_t length = timer->target - system_time(); timer_device->prepare((length > 0) ? length : 1); } /** Ensure that the timer device is enabled. */ static inline void timer_device_enable(void) { /* The device may not be disabled when we expect it to be (if * timer_stop() is run from a different CPU to the one the timer is * running on, it won't be able to disable the timer if the list * becomes empty). */ if(!curr_cpu->timer_enabled) { timer_device->enable(); curr_cpu->timer_enabled = true; } } /** Disable the timer device. */ static inline void timer_device_disable(void) { /* The timer device should always be enabled when we expect it to be. */ assert(curr_cpu->timer_enabled); timer_device->disable(); curr_cpu->timer_enabled = false; } /** * Set the timer device. * * Sets the device that will provide timer ticks. This function must only be * called once. * * @param device Device to set. */ void timer_device_set(timer_device_t *device) { assert(!timer_device); timer_device = device; if(timer_device->type == TIMER_DEVICE_ONESHOT) curr_cpu->timer_enabled = true; kprintf(LOG_NOTICE, "timer: activated timer device %s\n", device->name); } /** Start a timer, with CPU timer lock held. * @param timer Timer to start. */ static void timer_start_unsafe(timer_t *timer) { timer_t *exist; list_t *pos; assert(list_empty(&timer->header)); /* Work out the absolute completion time. */ timer->target = system_time() + timer->initial; /* Find the insertion point for the timer: the list must be ordered * with nearest expiration time first. */ pos = curr_cpu->timers.next; while(pos != &curr_cpu->timers) { exist = list_entry(pos, timer_t, header); if(exist->target > timer->target) break; pos = pos->next; } list_add_before(pos, &timer->header); } /** DPC function to run a timer function. * @param _timer Pointer to timer. */ static void timer_dpc_request(void *_timer) { timer_t *timer = _timer; timer->func(timer->data); } /** Handles a timer tick. * @return Whether to preempt the current thread. */ bool timer_tick(void) { nstime_t time = system_time(); bool preempt = false; timer_t *timer; assert(timer_device); assert(!local_irq_state()); if(!curr_cpu->timer_enabled) return false; spinlock_lock(&curr_cpu->timer_lock); /* Iterate the list and check for expired timers. */ LIST_FOREACH_SAFE(&curr_cpu->timers, iter) { timer = list_entry(iter, timer_t, header); /* Since the list is ordered soonest expiry first, we can break * if the current timer has not expired. */ if(time < timer->target) break; /* This timer has expired, remove it from the list. */ list_remove(&timer->header); /* Perform its timeout action. */ if(timer->flags & TIMER_THREAD) { dpc_request(timer_dpc_request, timer); } else { if(timer->func(timer->data)) preempt = true; } /* If the timer is periodic, restart it. */ if(timer->mode == TIMER_PERIODIC) timer_start_unsafe(timer); } switch(timer_device->type) { case TIMER_DEVICE_ONESHOT: /* Prepare the next tick if there is still a timer in the list. */ if(!list_empty(&curr_cpu->timers)) timer_device_prepare(list_first(&curr_cpu->timers, timer_t, header)); break; case TIMER_DEVICE_PERIODIC: /* For periodic devices, if the list is empty disable the * device so the timer does not interrupt unnecessarily. */ if(list_empty(&curr_cpu->timers)) timer_device_disable(); break; } spinlock_unlock(&curr_cpu->timer_lock); return preempt; } /** Initialize a timer structure. * @param timer Timer to initialize. * @param name Name of the timer for debugging purposes. * @param func Function to call when the timer expires. * @param data Data argument to pass to timer. * @param flags Behaviour flags for the timer. */ void timer_init(timer_t *timer, const char *name, timer_func_t func, void *data, uint32_t flags) { list_init(&timer->header); timer->func = func; timer->data = data; timer->flags = flags; timer->name = name; } /** Start a timer. * @param timer Timer to start. Must not already be running. * @param length Nanoseconds to run the timer for. If 0 or negative * the function will do nothing. * @param mode Mode for the timer. */ void timer_start(timer_t *timer, nstime_t length, unsigned mode) { bool state; if(length <= 0) return; /* Prevent curr_cpu from changing underneath us. */ state = local_irq_disable(); timer->cpu = curr_cpu; timer->mode = mode; timer->initial = length; spinlock_lock_noirq(&curr_cpu->timer_lock); /* Add the timer to the list. */ timer_start_unsafe(timer); switch(timer_device->type) { case TIMER_DEVICE_ONESHOT: /* If the new timer is at the beginning of the list, then it * has the shortest remaining time, so we need to adjust the * device to tick for it. */ if(timer == list_first(&curr_cpu->timers, timer_t, header)) timer_device_prepare(timer); break; case TIMER_DEVICE_PERIODIC: /* Enable the device. */ timer_device_enable(); break; } spinlock_unlock_noirq(&curr_cpu->timer_lock); local_irq_restore(state); } /** Cancel a running timer. * @param timer Timer to stop. */ void timer_stop(timer_t *timer) { timer_t *first; if(!list_empty(&timer->header)) { assert(timer->cpu); spinlock_lock(&timer->cpu->timer_lock); first = list_first(&timer->cpu->timers, timer_t, header); list_remove(&timer->header); /* If the timer is running on this CPU, adjust the tick length * or disable the device if required. If the timer is on another * CPU, it's no big deal: the tick handler is able to handle * unexpected ticks. */ if(timer->cpu == curr_cpu) { switch(timer_device->type) { case TIMER_DEVICE_ONESHOT: if(first == timer && !list_empty(&curr_cpu->timers)) { first = list_first(&curr_cpu->timers, timer_t, header); timer_device_prepare(first); } break; case TIMER_DEVICE_PERIODIC: if(list_empty(&curr_cpu->timers)) timer_device_disable(); break; } } spinlock_unlock(&timer->cpu->timer_lock); } } /** Sleep for a certain amount of time. * @param nsecs Nanoseconds to sleep for (must be greater than or * equal to 0). If SLEEP_ABSOLUTE is specified, this is * a target system time to sleep until. * @param flags Behaviour flags (see sync/sync.h). * @return STATUS_SUCCESS on success, STATUS_INTERRUPTED if * SLEEP_INTERRUPTIBLE specified and sleep was interrupted. */ status_t delay_etc(nstime_t nsecs, int flags) { status_t ret; assert(nsecs >= 0); ret = thread_sleep(NULL, nsecs, "usleep", flags); if(likely(ret == STATUS_TIMED_OUT || ret == STATUS_WOULD_BLOCK)) ret = STATUS_SUCCESS; return ret; } /** Delay for a period of time. * @param nsecs Nanoseconds to sleep for (must be greater than or * equal to 0). */ void delay(nstime_t nsecs) { delay_etc(nsecs, 0); } /** Dump a list of timers. * @param argc Argument count. * @param argv Argument array. * @return KDB status code. */ static kdb_status_t kdb_cmd_timers(int argc, char **argv, kdb_filter_t *filter) { timer_t *timer; uint64_t id; cpu_t *cpu; if(kdb_help(argc, argv)) { kdb_printf("Usage: %s [<CPU ID>]\n\n", argv[0]); kdb_printf("Prints a list of all timers on a CPU. If no ID given, current CPU\n"); kdb_printf("will be used.\n"); return KDB_SUCCESS; } else if(argc != 1 && argc != 2) { kdb_printf("Incorrect number of argments. See 'help %s' for help.\n", argv[0]); return KDB_FAILURE; } if(argc == 2) { if(kdb_parse_expression(argv[1], &id, NULL) != KDB_SUCCESS) return KDB_FAILURE; if(id > highest_cpu_id || !(cpu = cpus[id])) { kdb_printf("Invalid CPU ID.\n"); return KDB_FAILURE; } } else { cpu = curr_cpu; } kdb_printf("Name Target Function Data\n"); kdb_printf("==== ====== ======== ====\n"); LIST_FOREACH(&cpu->timers, iter) { timer = list_entry(iter, timer_t, header); kdb_printf("%-20s %-16llu %-18p %p\n", timer->name, timer->target, timer->func, timer->data); } return KDB_SUCCESS; } /** Print the system uptime. * @param argc Argument count. * @param argv Argument array. * @param filter Unused. * @return KDB status code. */ static kdb_status_t kdb_cmd_uptime(int argc, char **argv, kdb_filter_t *filter) { nstime_t time; if(kdb_help(argc, argv)) { kdb_printf("Usage: %s\n\n", argv[0]); kdb_printf("Prints how much time has passed since the kernel started.\n"); return KDB_SUCCESS; } time = system_time(); kdb_printf("%llu seconds (%llu nanoseconds)\n", NSECS2SECS(time), time); return KDB_SUCCESS; } /** Initialize the timing system. */ __init_text void time_init(void) { /* Initialize the boot time. */ boot_unix_time = platform_time_from_hardware() - system_time(); /* Register debugger commands. */ kdb_register_command("timers", "Print a list of running timers.", kdb_cmd_timers); kdb_register_command("uptime", "Display the system uptime.", kdb_cmd_uptime); } /** * User timer API. */ /** * Closes a handle to a timer. * * @param handle Handle being closed. */ static void timer_object_close(object_handle_t *handle) { user_timer_t *timer = handle->private; notifier_clear(&timer->notifier); kfree(timer); } /** * Signal that a timer is being waited for. * * @param handle Handle to timer. * @param event Event to wait for. * * @return Status code describing result of the operation. */ static status_t timer_object_wait(object_handle_t *handle, object_event_t *event) { user_timer_t *timer = handle->private; switch(event->event) { case TIMER_EVENT: if(!(event->flags & OBJECT_EVENT_EDGE) && timer->fired) { object_event_signal(event, 0); } else { notifier_register(&timer->notifier, object_event_notifier, event); } return STATUS_SUCCESS; default: return STATUS_INVALID_EVENT; } } /** * Stop waiting for a timer. * * @param handle Handle to timer. * @param event Event to wait for. */ static void timer_object_unwait(object_handle_t *handle, object_event_t *event) { user_timer_t *timer = handle->private; switch(event->event) { case TIMER_EVENT: notifier_unregister(&timer->notifier, object_event_notifier, event); break; } } /** Timer object type. */ static object_type_t timer_object_type = { .id = OBJECT_TYPE_TIMER, .flags = OBJECT_TRANSFERRABLE, .close = timer_object_close, .wait = timer_object_wait, .unwait = timer_object_unwait, }; /** Timer handler function for a userspace timer. * @param _timer Pointer to timer. * @return Whether to preempt. */ static bool user_timer_func(void *_timer) { user_timer_t *timer = _timer; if(timer->timer.mode == TIMER_ONESHOT) { timer->fired = true; } notifier_run(&timer->notifier, NULL, false); return false; } /** * Create a new timer. * * @param flags Flags for the timer. * @param handlep Where to store handle to timer object. * * @return Status code describing result of the operation. */ status_t kern_timer_create(uint32_t flags, handle_t *handlep) { user_timer_t *timer; status_t ret; if(!handlep) return STATUS_INVALID_ARG; timer = kmalloc(sizeof(*timer), MM_KERNEL); timer_init(&timer->timer, "timer_object", user_timer_func, timer, TIMER_THREAD); notifier_init(&timer->notifier, timer); timer->flags = flags; timer->fired = false; ret = object_handle_open(&timer_object_type, timer, NULL, handlep); if(ret != STATUS_SUCCESS) { kfree(timer); } return ret; } /** * Start a timer. * * Starts a timer. A timer can be started in one of two modes. TIMER_ONESHOT * will fire the timer event once after the specified time period. After the * time period has expired, the timer will remain in the fired state, i.e. a * level-triggered wait on the timer event will be immediately signalled, until * it is restarted or stopped. * * TIMER_PERIODIC fires the timer event periodically at the specified interval * until it is restarted or stopped. After each event the fired state is * cleared, i.e. an edge-triggered wait on the timer will see a rising edge * after each period. * * @param handle Handle to timer object. * @param interval Interval of the timer in nanoseconds. * @param mode Mode of the timer. * * @return Status code describing result of the operation. */ status_t kern_timer_start(handle_t handle, nstime_t interval, unsigned mode) { object_handle_t *khandle; user_timer_t *timer; status_t ret; if(interval <= 0 || (mode != TIMER_ONESHOT && mode != TIMER_PERIODIC)) return STATUS_INVALID_ARG; ret = object_handle_lookup(handle, OBJECT_TYPE_TIMER, &khandle); if(ret != STATUS_SUCCESS) return ret; timer = khandle->private; timer_stop(&timer->timer); timer->fired = false; timer_start(&timer->timer, interval, mode); object_handle_release(khandle); return STATUS_SUCCESS; } /** * Stop a timer. * * @param handle Handle to timer object. * @param remp If not NULL, where to store remaining time. * * @return Status code describing result of the operation. */ status_t kern_timer_stop(handle_t handle, nstime_t *remp) { object_handle_t *khandle; user_timer_t *timer; nstime_t rem; status_t ret; ret = object_handle_lookup(handle, OBJECT_TYPE_TIMER, &khandle); if(ret != STATUS_SUCCESS) return ret; timer = khandle->private; if(!list_empty(&timer->timer.header)) { timer_stop(&timer->timer); timer->fired = false; if(remp) { rem = system_time() - timer->timer.target; ret = write_user(remp, rem); } } else if(remp) { ret = write_user(remp, 0); } object_handle_release(khandle); return ret; } /** * Get the current time from a time source. * * Gets the current time, in nanoseconds, from the specified time source. There * are currently 2 time sources defined: * - TIME_SYSTEM: A monotonic timer which gives the time since the system was * started. * - TIME_REAL: Real time given as time since the UNIX epoch. This can be * changed with kern_time_set(). * * @param source Time source to get from. * @param timep Where to store time in nanoseconds. * * @return STATUS_SUCCESS on success. * STATUS_INVALID_ARG if time source is invalid or timep is * NULL. */ status_t kern_time_get(unsigned source, nstime_t *timep) { nstime_t time; if(!timep) return STATUS_INVALID_ARG; switch(source) { case TIME_SYSTEM: time = system_time(); break; case TIME_REAL: time = unix_time(); break; default: return STATUS_INVALID_ARG; } return write_user(timep, time); } /** * Set the current time. * * Sets the current time, in nanoseconds, for a time source. Currently only * the TIME_REAL source (see kern_time_get()) can be changed. * * @param source Time source to set. * @param time New time value in nanoseconds. * * @return STATUS_SUCCESS on success. * STATUS_INVALID_ARG if time source is invalid. */ status_t kern_time_set(unsigned source, nstime_t time) { return STATUS_NOT_IMPLEMENTED; }
atosorigin/blueprint-fabric8
sandbox/process/process-fabric/src/main/java/io/fabric8/process/fabric/ContainerProcessManagerService.java
<reponame>atosorigin/blueprint-fabric8 /** * Copyright 2005-2014 Red Hat, Inc. * * Red Hat 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 io.fabric8.process.fabric; import com.google.common.collect.ImmutableMap; import io.fabric8.api.Container; import io.fabric8.api.FabricService; import io.fabric8.process.fabric.support.ProcessManagerJmxTemplate; import io.fabric8.process.manager.InstallTask; import io.fabric8.process.manager.Installation; import io.fabric8.process.manager.service.ProcessManagerServiceMBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import java.util.List; public class ContainerProcessManagerService implements ContainerProcessManagerServiceMBean { private static final Logger LOGGER = LoggerFactory.getLogger(ContainerProcessManagerService.class); private final ObjectName objectName; private FabricService fabricService; private MBeanServer mbeanServer; public ContainerProcessManagerService() throws MalformedObjectNameException { this.objectName = new ObjectName("io.fabric8:type=FabricProcesses"); } public void bindMBeanServer(MBeanServer mbeanServer) { unbindMBeanServer(this.mbeanServer); this.mbeanServer = mbeanServer; if (mbeanServer != null) { registerMBeanServer(mbeanServer); } } public void unbindMBeanServer(MBeanServer mbeanServer) { if (mbeanServer != null) { unregisterMBeanServer(mbeanServer); this.mbeanServer = null; } } public void registerMBeanServer(MBeanServer mbeanServer) { try { if (!mbeanServer.isRegistered(objectName)) { mbeanServer.registerMBean(this, objectName); } } catch (Exception e) { LOGGER.warn("An error occurred during mbean server registration: " + e, e); } } public void unregisterMBeanServer(MBeanServer mbeanServer) { if (mbeanServer != null) { try { ObjectName name = objectName; if (mbeanServer.isRegistered(name)) { mbeanServer.unregisterMBean(name); } } catch (Exception e) { LOGGER.warn("An error occured during mbean server registration: " + e, e); } } } private ProcessManagerJmxTemplate getJmxTemplate(Container container, String jmxUser, String jmxPassword) { return new ProcessManagerJmxTemplate(container, jmxUser, jmxPassword, true); } public FabricService getFabricService() { return fabricService; } public void setFabricService(FabricService fabricService) { this.fabricService = fabricService; } @Override public List<Installation> listInstallations(final ContainerInstallOptions options) { Container container = options.getContainer(); ProcessManagerJmxTemplate jmxTemplate = getJmxTemplate(container, options.getUser(), options.getPassword()); return jmxTemplate.execute(new ProcessManagerCallback<List<Installation>>() { @Override public List<Installation> doWithProcessManager(ProcessManagerServiceMBean processManagerService) throws Exception { return processManagerService.listInstallations(); } }); } @Override public Installation install(final ContainerInstallOptions options, final InstallTask postInstall) throws Exception { Container container = options.getContainer(); ProcessManagerJmxTemplate jmxTemplate = getJmxTemplate(container, options.getUser(), options.getPassword()); return jmxTemplate.execute(new ProcessManagerCallback<Installation>() { @Override public Installation doWithProcessManager(ProcessManagerServiceMBean processManagerService) throws Exception { return processManagerService.install(options.asInstallOptions(), postInstall); } }); } @Override public Installation installJar(final ContainerInstallOptions options, final InstallTask postInstall) throws Exception { Container container = options.getContainer(); ProcessManagerJmxTemplate jmxTemplate = getJmxTemplate(container, options.getUser(), options.getPassword()); return jmxTemplate.execute(new ProcessManagerCallback<Installation>() { @Override public Installation doWithProcessManager(ProcessManagerServiceMBean processManagerService) throws Exception { return processManagerService.installJar(options.asInstallOptions(), postInstall); } }); } @Override public ImmutableMap<String, Installation> listInstallationMap(final ContainerInstallOptions options) { Container container = options.getContainer(); ProcessManagerJmxTemplate jmxTemplate = getJmxTemplate(container, options.getUser(), options.getPassword()); return jmxTemplate.execute(new ProcessManagerCallback<ImmutableMap<String, Installation>>() { @Override public ImmutableMap<String, Installation> doWithProcessManager(ProcessManagerServiceMBean processManagerService) throws Exception { return processManagerService.listInstallationMap(); } }); } }
inrupt/artifact-generator
src/commandLineProcessor.js
#!/usr/bin/env node // Normally we'd only want to mock out local storage for testing, but in this // case we want to use our generated vocabularies that depend on // localStorage for runtime context (e.g. the currently selected language). // So since we want to use those vocabularies in our Node application here, // they need a mocked local storage to work with. require("mock-local-storage"); const path = require("path"); const debugModule = require("debug"); const yargs = require("yargs"); const App = require("./App"); const { getArtifactDirectoryRoot } = require("./Util"); const CommandLine = require("./CommandLine"); const debug = debugModule("artifact-generator:commandLineProcessor"); const SUPPORTED_COMMANDS = [ CommandLine.COMMAND_GENERATE(), CommandLine.COMMAND_INITIALIZE(), CommandLine.COMMAND_WATCH(), CommandLine.COMMAND_VALIDATE(), ]; function validateCommandLine(argv, options) { // argv._ contains the commands passed to the program if (argv._.length !== 1) { // Only one command is expected throw new Error( `Exactly one command is expected (got [${ argv._.length }], [${argv._.toString()}]), expected one of [${SUPPORTED_COMMANDS}]. (Ensure wildcard file patterns are enclosed in double-quotes!)` ); } if (typeof argv._[0] === "number") { throw new Error( `Invalid command: command must be a string, but we got the number [${argv._[0]}]. Expected one of [${SUPPORTED_COMMANDS}].` ); } if (SUPPORTED_COMMANDS.indexOf(argv._[0]) === -1) { throw new Error( `Unknown command: [${argv._[0]}] is not a recognized command. Expected one of [${SUPPORTED_COMMANDS}].` ); } return true; } function processCommandLine(exitOnFail, commandLineArgs) { // To support multiple unit tests, create an instance of Yargs per // execution (otherwise the Yargs state gets corrupted). const yargsInstance = yargs(); return ( yargsInstance .help() .fail(false) .exitProcess(exitOnFail) .command( CommandLine.COMMAND_GENERATE(), "Generate code artifacts from RDF vocabularies.", (yargs) => yargs .alias("i", "inputResources") .array("inputResources") .describe( "inputResources", "One or more ontology resources (i.e. local RDF files, or HTTP URI's) used to generate source-code artifacts representing the contained vocabulary terms." ) .alias("l", "vocabListFile") .describe( "vocabListFile", "Name of a YAML file providing a list of individual vocabs to bundle together into a single artifact (or potentially multiple artifacts for multiple programming languages)." ) .alias("li", "vocabListFileIgnore") .describe( "vocabListFileIgnore", "Globbing pattern for files or directories to ignore when searching for vocabulary list files." ) // This override is really only relevant if we are generating from a // single vocabulary - if used with a vocab list file, it only applies // to the first vocabulary listed. .alias("no", "namespaceOverride") .describe( "namespaceOverride", "Overrides our namespace determination code to provide an explicit namespace IRI." ) .alias("lv", "solidCommonVocabVersion") .describe( "solidCommonVocabVersion", "The version of the Vocab Term to depend on." ) .default("solidCommonVocabVersion", "^0.5.3") .alias("in", "runNpmInstall") .boolean("runNpmInstall") .describe( "runNpmInstall", "If set will attempt to NPM install the generated artifact from within the output directory." ) .default("runNpmInstall", false) .alias("p", "publish") .array("publish") .describe( "publish", "the values provided to this option will be used as keys to trigger publication according to configurations in the associated YAML file. If not using a YAML file, this option can be used as a flag." ) .alias("tsr", "termSelectionResource") .describe( "termSelectionResource", "Generates Vocab Terms from only the specified ontology resource (file or IRI)." ) .alias("av", "artifactVersion") .describe( "artifactVersion", "The version of the artifact(s) to be generated." ) .default("artifactVersion", "0.0.1") .alias("mnp", "moduleNamePrefix") .describe( "moduleNamePrefix", "A prefix for the name of the output module" ) .default("moduleNamePrefix", "generated-vocab-") .alias("nr", "npmRegistry") .describe( "npmRegistry", "The NPM Registry where artifacts will be published" ) .default("npmRegistry", "http://localhost:4873") .alias("w", "runWidoco") .boolean("runWidoco") .describe( "runWidoco", "If set will run Widoco to generate documentation for this vocabulary." ) .alias("s", "supportBundling") .boolean("supportBundling") .describe( "supportBundling", "If set will use bundling support within generated artifact (currently supports Rollup only)." ) .default("supportBundling", true) .boolean("force") .describe( "force", "Forces generation, even if the target artifacts are considered up-to-date" ) .alias("f", "force") .default("force", false) .boolean("clearOutputDirectory") .describe( "clearOutputDirectory", "Deletes the entire output directory before generation" ) .alias("c", "clearOutputDirectory") .default("clearOutputDirectory", false) // Must provide either an input vocab file, or a file containing a // list of vocab files (but how can we demand at least one of these // two...?). .conflicts("inputResources", "vocabListFile") .strict(), (argv) => { if (!argv.inputResources && !argv.vocabListFile) { const message = "You must provide input, either a single vocabulary using '--inputResources' (e.g. a local RDF file, or a URL that resolves to an RDF vocabulary), or a YAML file using '--vocabListFile' listing multiple vocabularies."; debugModule.enable("artifact-generator:*"); debug(message); throw new Error(message); } return runGeneration(argv); } ) .command( CommandLine.COMMAND_INITIALIZE(), "Initializes a configuration YAML file used for fine-grained " + "control of artifact generation.", (yargs) => yargs, (argv) => { return runInitialization(argv); } ) .command( CommandLine.COMMAND_VALIDATE(), "Validates a configuration YAML file used for artifact generation.", (yargs) => yargs .alias("l", "vocabListFile") .describe( "vocabListFile", "Name of a YAML file providing a list of individual vocabs to bundle together into a single artifact (or potentially multiple artifacts for multiple programming languages)." ) .demandOption(["vocabListFile"]), (argv) => { return runValidation(argv); } ) .command( CommandLine.COMMAND_WATCH(), "Starts a process watching the configured vocabulary" + " resources, and automatically re-generates artifacts whenever it detects" + " a vocabulary change.", (yargs) => yargs .alias("l", "vocabListFile") .describe( "vocabListFile", "Name of a YAML file providing a list of individual vocabs to bundle together into a single artifact (or potentially multiple artifacts for multiple programming languages)." ) .demandOption(["vocabListFile"]), (argv) => { return runWatcher(argv); } ) // The following options are shared between the different commands .alias("q", "quiet") .boolean("quiet") .describe( "quiet", `If set will not display logging output to console (but you can still use the DEBUG environment variable, set to 'artifact-generator:*').` ) .default("quiet", false) .alias("np", "noprompt") .boolean("noprompt") .describe( "noprompt", "If set will not ask any interactive questions and will attempt to perform artifact generation automatically." ) .default("noprompt", false) .alias("o", "outputDirectory") .describe( "outputDirectory", "The output directory for the" + " generated artifacts (defaults to the current directory)." ) .default("outputDirectory", ".") .check(validateCommandLine) .parse(commandLineArgs) ); } function configureLog(argv) { // Unless specifically told to be quiet (i.e. no logging output, although that // will still be overridden by the DEBUG environment variable!), then // determine if any application-specific namespaces have been enabled. If they // haven't been, then turn them all on. if (!argv.quiet) { // Retrieve all currently enabled debug namespaces (and then restore them!). const namespaces = debugModule.disable(); debugModule.enable(namespaces); // Unless our debug logging has been explicitly configured, turn all // debugging on. if (namespaces.indexOf("artifact-generator") === -1) { debugModule.enable("artifact-generator:*"); } } } function runGeneration(argv) { configureLog(argv); return new App(argv) .run() .then((data) => { debug( `\nGeneration process successful to directory [${path.join( data.outputDirectory, getArtifactDirectoryRoot(data) )}]!` ); }) .catch((error) => { const message = `Generation process failed: [${error}]`; debug(message); throw new Error(message); }); } function runInitialization(argv) { configureLog(argv); // Note: No `.catch()` block needed here, as initialization can't fail (even // using weird characters (e.g., '@#$!*&^') in the output directory name // won't throw on Linux). new App(argv).init().then((data) => { debug(`\nSuccessfully initialized configuration file [${data}]`); }); } async function runValidation(argv) { configureLog(argv); return await new App(argv) .validate() .then((data) => { debug(`\nThe provided configuration is valid`); }) .catch((error) => { const message = `Configuration validation failed: [${error}]`; debug(message); throw new Error(message); }); } async function runWatcher(argv) { configureLog(argv); try { const app = new App(argv); const watcherCount = await app.watch(); const plural = watcherCount != 1; debug( `\nSuccessfully initialized file watcher${ plural ? "s" : "" } on [${watcherCount}] vocabulary bundle configuration file${ plural ? "s" : "" }.` ); debug("Press Enter to terminate"); // Pass back our cleanup function. argv.unwatchFunction = () => { app.unwatch(); }; } catch (error) { const message = `Failed to initialise watcher: [${error.message}]`; debug(message); throw new Error(message); } } module.exports = processCommandLine;
myles-novick/ml-workflow
mlflow/src/app/routers/monitoring_router.py
from fastapi import APIRouter, Depends, status from schemas import GetDeploymentsResponse, GetLogsResponse from sqlalchemy.orm import Session, load_only from sqlalchemy.orm.exc import NoResultFound from shared.db.connection import SQLAlchemyClient from shared.db.sql import SQL from shared.models.splice_models import Job from shared.logger.logging_config import logger from shared.api.exceptions import SpliceMachineException, ExceptionCodes MONITORING_ROUTER = APIRouter() DB_SESSION = Depends(SQLAlchemyClient.get_session) def _get_logs(task_id: int, session): """ Retrieve the logs for a given task id :param task_id: the celery task id to get the logs for """ try: job = session.query(Job).options(load_only("logs")).filter_by(id=task_id).one() return job.logs.split('\n') except NoResultFound: logger.warning("Couldn't find the specified job in the jobs table") raise SpliceMachineException(status_code=status.HTTP_404_NOT_FOUND, message="Couldn't find the specified job.", code=ExceptionCodes.DOES_NOT_EXIST) @MONITORING_ROUTER.get('/deployments', summary="Get deployments and statuses", operation_id='get_deployments', response_model=GetDeploymentsResponse, status_code=status.HTTP_200_OK) def get_deployments(db: Session = DB_SESSION): """ Get a list of all deployed models and their associated statuses. Requires Basic Auth validated against the database """ response = db.execute(SQL.get_deployment_status) cols = [col[0] for col in response.cursor.description] rows = response.fetchall() return GetDeploymentsResponse(deployments=dict([(col, [row[i] for row in rows]) for i, col in enumerate(cols)])) @MONITORING_ROUTER.get('/job-logs/{job_id}', summary="Get the logs for a specified job", response_model=GetLogsResponse, status_code=status.HTTP_200_OK, operation_id='get_logs') def get_logs(job_id: int, db: Session = DB_SESSION): """ Get a list of the logs from the job identified with the specified id. Requires Basic Auth validated against the DB. """ return GetLogsResponse(logs=_get_logs(task_id=job_id, session=db))
emamanto/Soar
Core/CLI/src/cli_explain.h
<filename>Core/CLI/src/cli_explain.h<gh_stars>1-10 /* * cli_explain.h * * Created on: Dec 22, 2015 * Author: mazzin */ #ifndef CLI_EXPLAIN_H_ #define CLI_EXPLAIN_H_ #include "cli_Parser.h" #include "cli_Options.h" #include "misc.h" #include "sml_Events.h" namespace cli { class ExplainCommand : public cli::ParserCommand { public: ExplainCommand(cli::CommandLineInterface& cli) : cli(cli), ParserCommand() {} virtual ~ExplainCommand() {} virtual const char* GetString() const { return "explain"; } virtual const char* GetSyntax() const { return "Use 'explain ?' or 'help explain' to learn more about the explain command."; } virtual bool Parse(std::vector< std::string >& argv) { cli::Options opt; OptionsData optionsData[] = { {0, 0, OPTARG_NONE} }; for (;;) { if (!opt.ProcessOptions(argv, optionsData)) { cli.SetError(opt.GetError().c_str()); return cli.AppendError(GetSyntax()); } if (opt.GetOption() == -1) { break; } } std::string arg, arg2; size_t start_arg_position = opt.GetArgument() - opt.GetNonOptionArguments(); size_t num_args = argv.size() - start_arg_position; if (num_args > 0) { arg = argv[start_arg_position]; } if (num_args > 1) { arg2 = argv[start_arg_position+1]; } if (num_args > 2) { return cli.SetError("Too many arguments for the 'explain' command."); } if (num_args == 1) { return cli.DoExplain(&arg); } if (num_args == 2) { return cli.DoExplain(&arg, &arg2); } // case: nothing = full configuration information return cli.DoExplain(); } private: cli::CommandLineInterface& cli; ExplainCommand& operator=(const ExplainCommand&); }; } #endif /* CLI_EXPLAIN_H_ */
2bite/ARK-SDK
SDK/ARKSurvivalEvolved_DinoBlueprintBase_RootBoneName_Crab_functions.cpp
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoBlueprintBase_RootBoneName_Crab_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.CheckForAttackActive // () // Parameters: // class APrimalDinoCharacter* MyDino (Parm, ZeroConstructor, IsPlainOldData) // int RetAttackIndex (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UDinoBlueprintBase_RootBoneName_Crab_C::CheckForAttackActive(class APrimalDinoCharacter* MyDino, int* RetAttackIndex) { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.CheckForAttackActive"); UDinoBlueprintBase_RootBoneName_Crab_C_CheckForAttackActive_Params params; params.MyDino = MyDino; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (RetAttackIndex != nullptr) *RetAttackIndex = params.RetAttackIndex; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.UpdateGrabIdle // () // Parameters: // class APrimalCharacter* OwningChar (Parm, ZeroConstructor, IsPlainOldData) void UDinoBlueprintBase_RootBoneName_Crab_C::UpdateGrabIdle(class APrimalCharacter* OwningChar) { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.UpdateGrabIdle"); UDinoBlueprintBase_RootBoneName_Crab_C_UpdateGrabIdle_Params params; params.OwningChar = OwningChar; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.BlueprintPlayAnimationEvent // () // Parameters: // class UAnimMontage** AnimationMontage (Parm, ZeroConstructor, IsPlainOldData) // float* PlayRate (Parm, ZeroConstructor, IsPlainOldData) // float playedAnimLength (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UDinoBlueprintBase_RootBoneName_Crab_C::BlueprintPlayAnimationEvent(class UAnimMontage** AnimationMontage, float* PlayRate, float* playedAnimLength) { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.BlueprintPlayAnimationEvent"); UDinoBlueprintBase_RootBoneName_Crab_C_BlueprintPlayAnimationEvent_Params params; params.AnimationMontage = AnimationMontage; params.PlayRate = PlayRate; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (playedAnimLength != nullptr) *playedAnimLength = params.playedAnimLength; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4462 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4462() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4462"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4462_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4461 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4461() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4461"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4461_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3091 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3091() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3091"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3091_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3090 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3090() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3090"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3090_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4458 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4458() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4458"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4458_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_RotationOffsetBlendSpace_186 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_RotationOffsetBlendSpace_186() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_RotationOffsetBlendSpace_186"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_RotationOffsetBlendSpace_186_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4457 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4457() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4457"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4457_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3089 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3089() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3089"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3089_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3088 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3088() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3088"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3088_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4456 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4456() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4456"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4456_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4455 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4455() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4455"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4455_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3087 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3087() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3087"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3087_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3086 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3086() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3086"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3086_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3085 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3085() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3085"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3085_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_677 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_677() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_677"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_677_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3084 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3084() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3084"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3084_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3083 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3083() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3083"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3083_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3082 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3082() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3082"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3082_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_174 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_174() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_174"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_174_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_173 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_173() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_173"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_GroundBones_173_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ApplyAdditive_330 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ApplyAdditive_330() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ApplyAdditive_330"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ApplyAdditive_330_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3081 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3081() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3081"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3081_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3080 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3080() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3080"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3080_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3092 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3092() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3092"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3092_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3093 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3093() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3093"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3093_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3094 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3094() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3094"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3094_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3095 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3095() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3095"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3095_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_678 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_678() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_678"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_ModifyBone_678_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4463 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4463() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4463"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_SequencePlayer_4463_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3096 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3096() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3096"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3096_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3074 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3074() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3074"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3074_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3073 // () void UDinoBlueprintBase_RootBoneName_Crab_C::EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3073() { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3073"); UDinoBlueprintBase_RootBoneName_Crab_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_AnimGraphNode_BlendListByBool_3073_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.BlueprintUpdateAnimation // () // Parameters: // float* DeltaTimeX (Parm, ZeroConstructor, IsPlainOldData) void UDinoBlueprintBase_RootBoneName_Crab_C::BlueprintUpdateAnimation(float* DeltaTimeX) { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.BlueprintUpdateAnimation"); UDinoBlueprintBase_RootBoneName_Crab_C_BlueprintUpdateAnimation_Params params; params.DeltaTimeX = DeltaTimeX; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UDinoBlueprintBase_RootBoneName_Crab_C::ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function DinoBlueprintBase_RootBoneName_Crab.DinoBlueprintBase_RootBoneName_Crab_C.ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab"); UDinoBlueprintBase_RootBoneName_Crab_C_ExecuteUbergraph_DinoBlueprintBase_RootBoneName_Crab_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
Disi77/AdventOfCode2021
day16/puzzle.py
<reponame>Disi77/AdventOfCode2021<filename>day16/puzzle.py class Packet(): def __init__(self, input_binary): self.input_binary = input_binary self.version = int(input_binary[:3], 2) self.type_id = int(input_binary[3:6], 2) self.subpackets_binary = "" self.subpackets = [] self.value = None if self.type_id == 4: self.value, self.rest = self.get_literal_value(input_binary[6:]) else: self.length_type_id = int(input_binary[6]) if self.length_type_id == 1: self.number_of_subpackets = int(input_binary[7:18], 2) self.subpackets_binary = input_binary[18:] for _ in range(self.number_of_subpackets): new_packet = Packet(self.subpackets_binary) self.subpackets.append(new_packet) self.subpackets_binary = new_packet.rest self.rest = self.subpackets_binary elif self.length_type_id == 0: self.total_lenght_in_bits = int(input_binary[7:22], 2) self.subpackets_binary = input_binary[22:22 + self.total_lenght_in_bits] self.rest = input_binary[22 + self.total_lenght_in_bits:] if set(self.rest) == {"0"}: self.rest = None while True: new_packet = Packet(self.subpackets_binary) self.subpackets.append(new_packet) self.subpackets_binary = new_packet.rest if not self.subpackets_binary or set(self.subpackets_binary) == {"0"}: break self.calculate_value() def calculate_value(self): from sys import maxsize if self.type_id == 0: self.value = 0 for p in self.subpackets: self.value += p.value elif self.type_id == 1: self.value = 1 for p in self.subpackets: self.value *= p.value elif self.type_id == 2: self.value = maxsize for p in self.subpackets: if p.value < self.value: self.value = p.value elif self.type_id == 3: self.value = -1 * maxsize for p in self.subpackets: if p.value > self.value: self.value = p.value elif self.type_id == 5: self.value = 0 if self.subpackets[0].value > self.subpackets[1].value: self.value = 1 elif self.type_id == 6: self.value = 0 if self.subpackets[0].value < self.subpackets[1].value: self.value = 1 elif self.type_id == 7: self.value = 0 if self.subpackets[0].value == self.subpackets[1].value: self.value = 1 def __str__(self): """ Not needed for final solution. Helper for debugging. """ if self.type_id == 4: return f"version: {self.version}, type ID: {self.type_id}, value: {self.value}" return f"version: {self.version}, type ID: {self.type_id}, length type ID: {self.length_type_id}, value: {self.value}, subpackets: {len(self.subpackets)}" def get_literal_value(self, input_data): result = "" for _ in range(len(input_data) // 5): temp = input_data[:5] input_data = input_data[5:] result += temp[1:] if temp[0] == "0": return int(result, 2), input_data def print_packet(packet, level=0): """ Helps me to understand structure of input transmission - for sure not perfect. Not needed for final solution. """ print(packet) if packet.subpackets: print(level * 3 * " ", " ║") for i, s in enumerate(packet.subpackets): if i == len(packet.subpackets) - 1: print(level * 3 * " ", " ╙--", end="") print_packet(s, level=level+1) else: print(level * 3 * " ", " ╟--", end="") print_packet(s, level=level+1) def get_input_data(): with open("input.txt", mode="r", encoding="utf-8") as file: input_data = file.read().strip() return input_data def from_hex_to_binary(data): input_binary = "" for i in data: b = f"{int(i, 16):04b}" input_binary += b return input_binary def sum_versions(packet, result): result += packet.version if packet.subpackets: for s in packet.subpackets: result = sum_versions(s, result) return result # Puzzle input input_hex = get_input_data() input_binary = from_hex_to_binary(input_hex) # Puzzle 1 a = Packet(input_binary) result = sum_versions(a, 0) print(f"Puzzle 1 = {result}") # Puzzle 2 print(f"Puzzle 2 = {a.value}")
Sjord/estatio
estatioapp/app/src/test/java/org/incode/module/communications/dom/impl/commchannel/CommunicationChannelType_ensureCompatible_Test.java
package org.incode.module.communications.dom.impl.commchannel; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.*; public class CommunicationChannelType_ensureCompatible_Test { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void happy_case() throws Exception { CommunicationChannelType.POSTAL_ADDRESS.ensureCompatible(PostalAddress.class); CommunicationChannelType.PHONE_NUMBER.ensureCompatible(PhoneOrFaxNumber.class); CommunicationChannelType.FAX_NUMBER.ensureCompatible(PhoneOrFaxNumber.class); CommunicationChannelType.EMAIL_ADDRESS.ensureCompatible(EmailAddress.class); } @Test public void POSTAL_ADDRESS_not_compatible_with_PhoneOrFaxNumber() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Class 'PhoneOrFaxNumber' is not compatible with type of 'POSTAL_ADDRESS'"); CommunicationChannelType.POSTAL_ADDRESS.ensureCompatible(PhoneOrFaxNumber.class); } @Test public void POSTAL_ADDRESS_not_compatible_with_EmailAddress() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Class 'EmailAddress' is not compatible with type of 'POSTAL_ADDRESS'"); CommunicationChannelType.POSTAL_ADDRESS.ensureCompatible(EmailAddress.class); } @Test public void PHONE_NUMBER_not_compatible_with_PostalAddress() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Class 'PostalAddress' is not compatible with type of 'PHONE_NUMBER'"); CommunicationChannelType.PHONE_NUMBER.ensureCompatible(PostalAddress.class); } }
knightjdr/prohits-viz-2.0
src/state/post/save-image/save-actions.test.js
<filename>src/state/post/save-image/save-actions.test.js import * as actions from './save-actions'; describe('Save image', () => { it('should dispatch an action when there is an error', () => { const expectedAction = { type: actions.SAVE_ERROR, }; expect(actions.saveError()).toEqual(expectedAction); }); it('should dispatch an action to on saving image', () => { const expectedAction = { type: actions.SAVING_IMAGE, }; expect(actions.savingImage()).toEqual(expectedAction); }); });
LukasBanana/ForkENGINE
sources/Video/RenderSystem/HWRenderer/OpenGL/HardwareBuffer/GLVertexBuffer.cpp
/* * OpenGL vertex buffer file * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by <NAME>) * See "LICENSE.txt" for license information. */ #include "GLVertexBuffer.h" #include "..\GLParamMapper.h" #include "IO/Core/Log.h"//!!! namespace Fork { namespace Video { GLVertexBuffer::GLVertexBuffer() { #ifndef _DEB_CUSTOM_VERTEX_FORMAT_BINDING_ glGenVertexArrays(1, &vaoID_); #endif } GLVertexBuffer::~GLVertexBuffer() { #ifndef _DEB_CUSTOM_VERTEX_FORMAT_BINDING_ glDeleteVertexArrays(1, &vaoID_); #endif } void GLVertexBuffer::SetupFormat(const VertexFormat& format) { #ifndef _DEB_CUSTOM_VERTEX_FORMAT_BINDING_ /* Bind VAO which is to be configured */ activeStateMngr->BindVertexArray(vaoID_); /* Bind VBO to 'attach' it to the VAO */ Bind(); /* Setup each vertex attribute */ GLuint index = 0; for (const auto& attrib : format.GetAttributes()) { glEnableVertexAttribArray(index); glVertexAttribPointer( index, attrib.GetNumComponents(), GLParamMapper::Map(attrib.GetDataType()), GL_FALSE, format.GetFormatSize(), ((const char*)0) + attrib.GetOffset() ); ++index; } activeStateMngr->BindVertexArray(0); #endif /* Store new vertex format */ this->format = format; } void GLVertexBuffer::BindFormatted() { #ifndef _DEB_CUSTOM_VERTEX_FORMAT_BINDING_ /* Bind VAO which contians the entire vertex format */ activeStateMngr->BindVertexArray(vaoID_); #else Bind(); /* Bind vertex format */ GLuint index = 0; for (const auto& attrib : format_.GetAttributes()) { glEnableVertexAttribArray(index); glVertexAttribPointer( index, attrib.GetNumComponents(), GLParamMapper::Map(attrib.GetDataType()), GL_FALSE, format_.GetFormatSize(), ((const char*)0) + attrib.GetOffset() ); ++index; } #endif } void GLVertexBuffer::UnbindFormatted() { #ifndef _DEB_CUSTOM_VERTEX_FORMAT_BINDING_ activeStateMngr->BindVertexArray(0); #else Bind(); /* Unbind vertex format */ GLuint index = 0; for (const auto& attrib : format_.GetAttributes()) { glDisableVertexAttribArray(index); ++index; } Unbind(); #endif } } // /namespace Video } // /namespace Fork // ========================
vprusa/gag-web
persistence/src/main/java/cz/muni/fi/gag/web/persistence/dao/impl/FingerDataLineDaoImpl.java
package cz.muni.fi.gag.web.persistence.dao.impl; import cz.muni.fi.gag.web.persistence.dao.FingerDataLineDao; import cz.muni.fi.gag.web.persistence.entity.FingerDataLine; import java.io.Serializable; import javax.enterprise.context.ApplicationScoped; /** * @author <NAME> * */ @ApplicationScoped public class FingerDataLineDaoImpl extends AbstractGenericDao<FingerDataLine> implements FingerDataLineDao, Serializable { public FingerDataLineDaoImpl() { super(FingerDataLine.class); } }
cnc-thesis-project/probecessor
methods/cluster/tls.py
def get_data(tls_port): print("TLS GET DATA") data = {} data["issuer"] = tls_port.get_property("issuer") return data def match(tls_data1, tls_data2): print("TLS MATCH") return tls_data1["issuer"] == tls_data2["issuer"]
ZhaoJianliuser/libice
test/test.h
<reponame>ZhaoJianliuser/libice<gh_stars>10-100 /* * Copyright (c) 2018 str2num. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /** * @file test.h * @author str2num * @brief * **/ #ifndef __TEST_H_ #define __TEST_H_ #include <rtcbase/logging.h> void test_allocation_sequence(); void test_port_allocator(); void test_p2p_transport_channel(); #endif //__TEST_H_
MSV-Project/IBAMR
ibtk/src/math/PoissonUtilities.h
// Filename: PoissonUtilities.h // Created on 24 Aug 2010 by <NAME> // // Copyright (c) 2002-2013, <NAME> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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 HOLDER 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 included_PoissonUtilities #define included_PoissonUtilities /////////////////////////////// INCLUDES ///////////////////////////////////// #include <vector> #include "PoissonSpecifications.h" #include "tbox/Pointer.h" namespace SAMRAI { namespace hier { template <int DIM> class Index; template <int DIM> class Patch; } // namespace hier namespace pdat { template <int DIM, class TYPE> class CellData; template <int DIM, class TYPE> class SideData; } // namespace pdat namespace solv { template <int DIM> class RobinBcCoefStrategy; } // namespace solv } // namespace SAMRAI /////////////////////////////// CLASS DEFINITION ///////////////////////////// namespace IBTK { /*! * \brief Class PoissonUtilities provides utility functions for constructing * Poisson solvers. */ class PoissonUtilities { public: /*! * Compute the matrix coefficients corresponding to a cell-centered * discretization of the Laplacian. */ static void computeCCMatrixCoefficients( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& matrix_coefficients, const std::vector<SAMRAI::hier::Index<NDIM> >& stencil, const SAMRAI::solv::PoissonSpecifications& poisson_spec, SAMRAI::solv::RobinBcCoefStrategy<NDIM>* bc_coef, double data_time); /*! * Compute the matrix coefficients corresponding to a cell-centered * discretization of the Laplacian. */ static void computeCCMatrixCoefficients( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& matrix_coefficients, const std::vector<SAMRAI::hier::Index<NDIM> >& stencil, const SAMRAI::solv::PoissonSpecifications& poisson_spec, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, double data_time); /*! * Compute the matrix coefficients corresponding to a cell-centered * discretization of the complex Laplacian. */ static void computeCCComplexMatrixCoefficients( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& matrix_coefficients, const std::vector<SAMRAI::hier::Index<NDIM> >& stencil, const SAMRAI::solv::PoissonSpecifications& poisson_spec_real, const SAMRAI::solv::PoissonSpecifications& poisson_spec_imag, SAMRAI::solv::RobinBcCoefStrategy<NDIM>* bc_coef, double data_time); /*! * Compute the matrix coefficients corresponding to a cell-centered * discretization of the complex Laplacian. */ static void computeCCComplexMatrixCoefficients( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& matrix_coefficients, const std::vector<SAMRAI::hier::Index<NDIM> >& stencil, const SAMRAI::solv::PoissonSpecifications& poisson_spec_real, const SAMRAI::solv::PoissonSpecifications& poisson_spec_imag, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, double data_time); /*! * Compute the matrix coefficients corresponding to a side-centered * discretization of the Laplacian. */ static void computeSCMatrixCoefficients( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::SideData<NDIM,double>& matrix_coefficients, const std::vector<SAMRAI::hier::Index<NDIM> >& stencil, const SAMRAI::solv::PoissonSpecifications& poisson_spec, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, double data_time); /*! * Modify the right-hand side entries to account for physical boundary * conditions corresponding to a cell-centered discretization of the * Laplacian. */ static void adjustCCBoundaryRhsEntries( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& rhs_data, const SAMRAI::solv::PoissonSpecifications& poisson_spec, SAMRAI::solv::RobinBcCoefStrategy<NDIM>* bc_coef, double data_time, bool homogeneous_bc); /*! * Modify the right-hand side entries to account for physical boundary * conditions corresponding to a cell-centered discretization of the * Laplacian. */ static void adjustCCBoundaryRhsEntries( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& rhs_data, const SAMRAI::solv::PoissonSpecifications& poisson_spec, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, double data_time, bool homogeneous_bc); /*! * Modify the right-hand side entries to account for physical boundary * conditions corresponding to a cell-centered discretization of the * complex Laplacian. */ static void adjustCCComplexBoundaryRhsEntries( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& rhs_data, const SAMRAI::solv::PoissonSpecifications& poisson_spec_real, const SAMRAI::solv::PoissonSpecifications& poisson_spec_imag, SAMRAI::solv::RobinBcCoefStrategy<NDIM>* bc_coef, double data_time, bool homogeneous_bc); /*! * Modify the right-hand side entries to account for physical boundary * conditions corresponding to a cell-centered discretization of the * complex Laplacian. */ static void adjustCCComplexBoundaryRhsEntries( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::CellData<NDIM,double>& rhs_data, const SAMRAI::solv::PoissonSpecifications& poisson_spec_real, const SAMRAI::solv::PoissonSpecifications& poisson_spec_imag, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, double data_time, bool homogeneous_bc); /*! * Modify the right-hand side entries to account for physical boundary * conditions corresponding to a side-centered discretization of the * Laplacian. */ static void adjustSCBoundaryRhsEntries( SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, SAMRAI::pdat::SideData<NDIM,double>& rhs_data, const SAMRAI::solv::PoissonSpecifications& poisson_spec, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, double data_time, bool homogeneous_bc); protected: private: /*! * \brief Default constructor. * * \note This constructor is not implemented and should not be used. */ PoissonUtilities(); /*! * \brief Copy constructor. * * \note This constructor is not implemented and should not be used. * * \param from The value to copy to this object. */ PoissonUtilities( const PoissonUtilities& from); /*! * \brief Assignment operator. * * \note This operator is not implemented and should not be used. * * \param that The value to assign to this object. * * \return A reference to this object. */ PoissonUtilities& operator=( const PoissonUtilities& that); }; }// namespace IBTK ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef included_PoissonUtilities
lens-biophotonics/v3d_external
v3d_main/common_lib/mingw32/include/time.h
/* * time.h * This file has no copyright assigned and is placed in the Public Domain. * This file is a part of the mingw-runtime package. * No warranty is given; refer to the file DISCLAIMER within the package. * * Date and time functions and types. * */ #ifndef _TIME_H_ #define _TIME_H_ /* All the headers include this file. */ #include <_mingw.h> #define __need_wchar_t #define __need_size_t #define __need_NULL #ifndef RC_INVOKED #include <stddef.h> #endif /* Not RC_INVOKED */ /* * Number of clock ticks per second. A clock tick is the unit by which * processor time is measured and is returned by 'clock'. */ #define CLOCKS_PER_SEC ((clock_t)1000) #define CLK_TCK CLOCKS_PER_SEC #ifndef RC_INVOKED /* * A type for storing the current time and date. This is the number of * seconds since midnight Jan 1, 1970. * NOTE: This is also defined in non-ISO sys/types.h. */ #ifndef _TIME_T_DEFINED typedef long time_t; #define _TIME_T_DEFINED #endif #ifndef __STRICT_ANSI__ /* A 64-bit time_t to get to Y3K */ #ifndef _TIME64_T_DEFINED typedef __int64 __time64_t; #define _TIME64_T_DEFINED #endif #endif /* * A type for measuring processor time (in clock ticks). */ #ifndef _CLOCK_T_DEFINED typedef long clock_t; #define _CLOCK_T_DEFINED #endif #ifndef _TM_DEFINED /* * A structure for storing all kinds of useful information about the * current (or another) time. */ struct tm { int tm_sec; /* Seconds: 0-59 (K&R says 0-61?) */ int tm_min; /* Minutes: 0-59 */ int tm_hour; /* Hours since midnight: 0-23 */ int tm_mday; /* Day of the month: 1-31 */ int tm_mon; /* Months *since* january: 0-11 */ int tm_year; /* Years since 1900 */ int tm_wday; /* Days since Sunday (0-6) */ int tm_yday; /* Days since Jan. 1: 0-365 */ int tm_isdst; /* +1 Daylight Savings Time, 0 No DST, * -1 don't know */ }; #define _TM_DEFINED #endif #ifdef __cplusplus extern "C" { #endif _CRTIMP clock_t __cdecl __MINGW_NOTHROW clock (void); _CRTIMP time_t __cdecl __MINGW_NOTHROW time (time_t*); _CRTIMP double __cdecl __MINGW_NOTHROW difftime (time_t, time_t); _CRTIMP time_t __cdecl __MINGW_NOTHROW mktime (struct tm*); /* * These functions write to and return pointers to static buffers that may * be overwritten by other function calls. Yikes! * * NOTE: localtime, and perhaps the others of the four functions grouped * below may return NULL if their argument is not 'acceptable'. Also note * that calling asctime with a NULL pointer will produce an Invalid Page * Fault and crap out your program. Guess how I know. Hint: stat called on * a directory gives 'invalid' times in st_atime etc... */ _CRTIMP char* __cdecl __MINGW_NOTHROW asctime (const struct tm*); _CRTIMP char* __cdecl __MINGW_NOTHROW ctime (const time_t*); _CRTIMP struct tm* __cdecl __MINGW_NOTHROW gmtime (const time_t*); _CRTIMP struct tm* __cdecl __MINGW_NOTHROW localtime (const time_t*); _CRTIMP size_t __cdecl __MINGW_NOTHROW strftime (char*, size_t, const char*, const struct tm*); #ifndef __STRICT_ANSI__ extern _CRTIMP void __cdecl __MINGW_NOTHROW _tzset (void); #ifndef _NO_OLDNAMES extern _CRTIMP void __cdecl __MINGW_NOTHROW tzset (void); #endif _CRTIMP char* __cdecl __MINGW_NOTHROW _strdate(char*); _CRTIMP char* __cdecl __MINGW_NOTHROW _strtime(char*); /* These require newer versions of msvcrt.dll (6.10 or higher). */ #if __MSVCRT_VERSION__ >= 0x0601 _CRTIMP __time64_t __cdecl __MINGW_NOTHROW _time64( __time64_t*); _CRTIMP __time64_t __cdecl __MINGW_NOTHROW _mktime64 (struct tm*); _CRTIMP char* __cdecl __MINGW_NOTHROW _ctime64 (const __time64_t*); _CRTIMP struct tm* __cdecl __MINGW_NOTHROW _gmtime64 (const __time64_t*); _CRTIMP struct tm* __cdecl __MINGW_NOTHROW _localtime64 (const __time64_t*); #endif /* __MSVCRT_VERSION__ >= 0x0601 */ /* * _daylight: non zero if daylight savings time is used. * _timezone: difference in seconds between GMT and local time. * _tzname: standard/daylight savings time zone names (an array with two * elements). */ #ifdef __MSVCRT__ /* These are for compatibility with pre-VC 5.0 suppied MSVCRT. */ extern _CRTIMP int* __cdecl __MINGW_NOTHROW __p__daylight (void); extern _CRTIMP long* __cdecl __MINGW_NOTHROW __p__timezone (void); extern _CRTIMP char** __cdecl __MINGW_NOTHROW __p__tzname (void); __MINGW_IMPORT int _daylight; __MINGW_IMPORT long _timezone; __MINGW_IMPORT char *_tzname[2]; #else /* not __MSVCRT (ie. crtdll) */ #ifndef __DECLSPEC_SUPPORTED extern int* _imp___daylight_dll; extern long* _imp___timezone_dll; extern char** _imp___tzname; #define _daylight (*_imp___daylight_dll) #define _timezone (*_imp___timezone_dll) #define _tzname (*_imp___tzname) #else /* __DECLSPEC_SUPPORTED */ __MINGW_IMPORT int _daylight_dll; __MINGW_IMPORT long _timezone_dll; __MINGW_IMPORT char* _tzname[2]; #define _daylight _daylight_dll #define _timezone _timezone_dll #endif /* __DECLSPEC_SUPPORTED */ #endif /* not __MSVCRT__ */ #ifndef _NO_OLDNAMES #ifdef __MSVCRT__ /* These go in the oldnames import library for MSVCRT. */ __MINGW_IMPORT int daylight; __MINGW_IMPORT long timezone; __MINGW_IMPORT char *tzname[2]; #else /* not __MSVCRT__ */ /* CRTDLL is royally messed up when it comes to these macros. TODO: import and alias these via oldnames import library instead of macros. */ #define daylight _daylight /* NOTE: timezone not defined as macro because it would conflict with struct timezone in sys/time.h. Also, tzname used to a be macro, but now it's in moldname. */ __MINGW_IMPORT char *tzname[2]; #endif /* not __MSVCRT__ */ #endif /* Not _NO_OLDNAMES */ #endif /* Not __STRICT_ANSI__ */ #ifndef _WTIME_DEFINED /* wide function prototypes, also declared in wchar.h */ #ifndef __STRICT_ANSI__ #ifdef __MSVCRT__ _CRTIMP wchar_t* __cdecl __MINGW_NOTHROW _wasctime(const struct tm*); _CRTIMP wchar_t* __cdecl __MINGW_NOTHROW _wctime(const time_t*); _CRTIMP wchar_t* __cdecl __MINGW_NOTHROW _wstrdate(wchar_t*); _CRTIMP wchar_t* __cdecl __MINGW_NOTHROW _wstrtime(wchar_t*); #if __MSVCRT_VERSION__ >= 0x0601 _CRTIMP wchar_t* __cdecl __MINGW_NOTHROW _wctime64 (const __time64_t*); #endif #endif /* __MSVCRT__ */ #endif /* __STRICT_ANSI__ */ _CRTIMP size_t __cdecl __MINGW_NOTHROW wcsftime (wchar_t*, size_t, const wchar_t*, const struct tm*); #define _WTIME_DEFINED #endif /* _WTIME_DEFINED */ #ifdef __cplusplus } #endif #endif /* Not RC_INVOKED */ #endif /* Not _TIME_H_ */
pierredup/sentry
src/sentry/api/endpoints/setup_wizard.py
<reponame>pierredup/sentry from __future__ import absolute_import import logging from rest_framework.response import Response from sentry import ratelimits from sentry.cache import default_cache from sentry.api.base import Endpoint from sentry.api.serializers import serialize from django.utils.crypto import get_random_string logger = logging.getLogger("sentry.api") SETUP_WIZARD_CACHE_KEY = "setup-wizard-keys:v1:" SETUP_WIZARD_CACHE_TIMEOUT = 600 class SetupWizard(Endpoint): permission_classes = () def delete(self, request, wizard_hash=None): """ This removes the cache content for a specific hash """ if wizard_hash is not None: key = "%s%s" % (SETUP_WIZARD_CACHE_KEY, wizard_hash) default_cache.delete(key) return Response(status=200) def get(self, request, wizard_hash=None): """ This tries to retrieve and return the cache content if possible otherwise creates new cache """ if wizard_hash is not None: key = "%s%s" % (SETUP_WIZARD_CACHE_KEY, wizard_hash) wizard_data = default_cache.get(key) if wizard_data is None: return Response(status=404) elif wizard_data == "empty": # when we just created a clean cache return Response(status=400) return Response(serialize(wizard_data)) else: # This creates a new available hash url for the project wizard rate_limited = ratelimits.is_limited( key="rl:setup-wizard:ip:%s" % request.META["REMOTE_ADDR"], limit=10 ) if rate_limited: logger.info("setup-wizard.rate-limit") return Response({"Too many wizard requests"}, status=403) wizard_hash = get_random_string(64, allowed_chars="abcdefghijklmnopqrstuvwxyz012345679") key = "%s%s" % (SETUP_WIZARD_CACHE_KEY, wizard_hash) default_cache.set(key, "empty", SETUP_WIZARD_CACHE_TIMEOUT) return Response(serialize({"hash": wizard_hash}))
muizidn/couchbase-lite-ios
Objective-C/CBLQueryOrdering.h
<reponame>muizidn/couchbase-lite-ios // // CBLQueryOrdering.h // CouchbaseLite // // Copyright (c) 2017 Couchbase, 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. // #import <Foundation/Foundation.h> @class CBLQuerySortOrder, CBLQueryExpression; NS_ASSUME_NONNULL_BEGIN /** A CBLQueryOrdering represents a single ordering component in the query ORDER BY clause. */ @interface CBLQueryOrdering : NSObject /** Create a sort order instance with a given property name. @param name A propert name in key path format. @return A sort order instance. */ + (CBLQuerySortOrder*) property: (NSString*)name; /** Create a sort order instance with a given expression. @param expression An expression instance. @return A sort order instance. */ + (CBLQuerySortOrder*) expression: (CBLQueryExpression*)expression; - (instancetype) init NS_UNAVAILABLE; @end /** CBLQuerySortOrder allows to specify the ordering direction which is an ascending or a descending order */ @interface CBLQuerySortOrder : CBLQueryOrdering /** Create an ascending CBLQueryOrdering instance. @return An ascending CBLQueryOrdering instance. */ - (CBLQueryOrdering*) ascending; /** Create a descending CBLQueryOrdering instance. @return A descending CBLQueryOrdering instance. */ - (CBLQueryOrdering*) descending; /** Not available. */ - (instancetype) init NS_UNAVAILABLE; @end NS_ASSUME_NONNULL_END
cryptofriend/incognito-chain
metadata/common.go
package metadata import ( "encoding/json" "fmt" "github.com/pkg/errors" ) func ParseMetadata(meta interface{}) (Metadata, error) { if meta == nil { return nil, nil } mtTemp := map[string]interface{}{} metaInBytes, err := json.Marshal(meta) if err != nil { return nil, err } err = json.Unmarshal(metaInBytes, &mtTemp) if err != nil { return nil, err } var md Metadata switch int(mtTemp["Type"].(float64)) { case ResponseBaseMeta: md = &ResponseBase{} case IssuingRequestMeta: md = &IssuingRequest{} case IssuingResponseMeta: md = &IssuingResponse{} case ContractingRequestMeta: md = &ContractingRequest{} case IssuingETHRequestMeta: md = &IssuingETHRequest{} case IssuingETHResponseMeta: md = &IssuingETHResponse{} case BeaconSalaryResponseMeta: md = &BeaconBlockSalaryRes{} case BurningRequestMeta: md = &BurningRequest{} case ShardStakingMeta: md = &StakingMetadata{} case BeaconStakingMeta: md = &StakingMetadata{} case ReturnStakingMeta: md = &ReturnStakingMetadata{} case WithDrawRewardRequestMeta: md = &WithDrawRewardRequest{} case WithDrawRewardResponseMeta: md = &WithDrawRewardResponse{} default: fmt.Printf("[db] parse meta err: %+v\n", meta) return nil, errors.Errorf("Could not parse metadata with type: %d", int(mtTemp["Type"].(float64))) } err = json.Unmarshal(metaInBytes, &md) if err != nil { return nil, err } return md, nil }
xcesco/Kripton
kripton-processor/src/test/java/sqlite/git104/AbstractBean.java
package sqlite.git104; import java.time.ZonedDateTime; import com.abubusoft.kripton.android.annotation.BindSqlColumn; public abstract class AbstractBean { protected final long id; @BindSqlColumn(nullable = false) protected ZonedDateTime updateTime; public AbstractBean(long id, ZonedDateTime updateTime) { this.id = id; this.updateTime = updateTime; } public long getId() { return id; } public ZonedDateTime getUpdateTime() { return updateTime; } }
Personalhomeman/web-stories-wp
assets/src/edit-story/utils/getCaretCharacterOffsetWithin.js
/* * Copyright 2020 Google LLC * * 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. */ /** * This function finds the character offset within a certain element. * * For instance, given the following node with `_` marking the current selection start offset: * * ``` * <p>Corgies are the <em>b_est</em>!</p> * ``` * * This function would return 17 (`'Corgies are the b'.length`). * * If optional coordinates are given, the point under the coordinates will be used, * otherwise the current on-page selection will be used. * * This function includes some cross-browser optimization for older browsers even * though they aren't really supported by the editor at large (IE). * * @param {Node} element DOM node to find current selection within. * @param {number} clientX Optional x coordinate of click. * @param {number} clientY Optional y coordinate of click. * @return {number} Current selection start offset as seen in `element` or 0 if not found. */ function getCaretCharacterOffsetWithin(element, clientX, clientY) { const doc = element.ownerDocument || element.document; const win = doc.defaultView || doc.parentWindow; if (typeof win.getSelection !== 'undefined') { let range; if (clientX && clientY) { if (doc.caretPositionFromPoint) { range = document.caretPositionFromPoint(clientX, clientY); } else if (doc.caretRangeFromPoint) { range = document.caretRangeFromPoint(clientX, clientY); } } if (!range) { const sel = win.getSelection(); if (sel.rangeCount > 0) { range = win.getSelection().getRangeAt(0); } } if (range) { const preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.endContainer, range.endOffset); return preCaretRange.toString().length; } } const sel = doc.selection; if (sel && sel.type !== 'Control') { const textRange = sel.createRange(); if (clientX && clientY) { textRange.moveToPoint(clientX, clientY); } const preCaretTextRange = doc.body.createTextRange(); preCaretTextRange.moveToElementText(element); preCaretTextRange.setEndPoint('EndToEnd', textRange); return preCaretTextRange.text.length; } return 0; } export default getCaretCharacterOffsetWithin;
opengauss-mirror/DataStudio
code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/objectpropertywiew/ViewObjectPropertyTab.java
<gh_stars>0 /* * Copyright (c) 2022 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.opengauss.mppdbide.view.objectpropertywiew; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.widgets.Composite; import org.opengauss.mppdbide.bl.serverdatacache.Database; import org.opengauss.mppdbide.bl.serverdatacache.UserRoleManager; import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; import org.opengauss.mppdbide.presentation.objectproperties.IServerObjectProperties; import org.opengauss.mppdbide.presentation.objectproperties.PropertiesConstants; import org.opengauss.mppdbide.presentation.objectproperties.PropertiesUserRoleImpl; import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; import org.opengauss.mppdbide.view.component.TabGridUIPreference; import org.opengauss.mppdbide.view.component.grid.DSGridComponent; import org.opengauss.mppdbide.view.component.grid.core.DataGrid; /** * * Title: class * * Description: The Class ViewObjectPropertyTab. * * @since 3.0.0 */ public class ViewObjectPropertyTab extends CTabItem { /** * The grid component. */ protected DSGridComponent gridComponent; /** * The composite. */ protected Composite composite; /** * The result grid UI pref. */ protected ObjectPropertyGridUIPreference resultGridUIPref; /** * The resultset displaydata. */ protected IDSGridDataProvider resultsetDisplaydata; /** * The view object properties result display UI manager. */ protected ViewObjectPropertiesResultDisplayUIManager viewObjectPropertiesResultDisplayUIManager; /** * The is tab edited. */ protected boolean isTabEdited; /** * The Constant NULL_VALUE. */ protected static final String NULL_VALUE = "[NULL]"; /** * The tab folder. */ protected CTabFolder tabFolder; /** * Instantiates a new view object property tab. * * @param parent the parent * @param style the style * @param composite the composite * @param resultsetDisplaydata the resultset displaydata * @param viewObjectPropertyTabManager the view object property tab manager */ public ViewObjectPropertyTab(CTabFolder parent, int style, Composite composite, IDSGridDataProvider resultsetDisplaydata, ViewObjectPropertyTabManager viewObjectPropertyTabManager) { super(parent, style); tabFolder = parent; this.resultsetDisplaydata = resultsetDisplaydata; setControl(composite); this.resultGridUIPref = new ObjectPropertyGridUIPreference(resultsetDisplaydata); this.gridComponent = new DSGridComponent(resultGridUIPref, resultsetDisplaydata); this.composite = composite; } /** * Inits the. * * @param viewObjPropsResultDisplayUIManager the view obj props result * display UI manager */ public void init(ViewObjectPropertiesResultDisplayUIManager viewObjPropsResultDisplayUIManager) { this.viewObjectPropertiesResultDisplayUIManager = viewObjPropsResultDisplayUIManager; this.gridComponent.createComponents(this.composite); this.gridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_PROPERITES_COMMIT_DATA, viewObjPropsResultDisplayUIManager); this.gridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, viewObjPropsResultDisplayUIManager); this.gridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, gridComponent.getDataEditListener()); this.gridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_ON_REFRESH_QUERY, viewObjPropsResultDisplayUIManager); this.gridComponent.addListener(IDSGridUIListenable.LISTEN_DATABASE_CONNECT_DISCONNECT_STATUS, viewObjectPropertiesResultDisplayUIManager); this.gridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_ON_CANCEL_PASSWORD, viewObjectPropertiesResultDisplayUIManager); registerDataProviderEditListener(); } /** * Register data provider edit listener. */ protected void registerDataProviderEditListener() { if (null != resultsetDisplaydata && resultsetDisplaydata instanceof DSObjectPropertiesGridDataProvider) { DSObjectPropertiesGridDataProvider editDataProvider = (DSObjectPropertiesGridDataProvider) resultsetDisplaydata; editDataProvider.addListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, gridComponent.getDataEditListener()); editDataProvider.addListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, viewObjectPropertiesResultDisplayUIManager); } } /** * Enable disable tab icons. * * @param isConnected the is connected */ public void enableDisableTabIcons(boolean isConnected) { gridComponent.getToolbar().setDataProvider(this.resultsetDisplaydata); if (resultGridUIPref.isEnableEdit()) { gridComponent.getToolbar().handleDataEditEvent(isConnected); } } /** * Reset data. * * @param result the result */ public void resetData(IDSGridDataProvider result) { resultsetDisplaydata = result; this.gridComponent.setDataProvider(result); registerDataProviderEditListener(); } /** * Checks if is tab edited. * * @return true, if is tab edited */ public boolean isTabEdited() { if (null != resultsetDisplaydata && resultsetDisplaydata instanceof DSObjectPropertiesGridDataProvider) { return ((DSObjectPropertiesGridDataProvider) resultsetDisplaydata).isGridDataEdited(); } return false; } /** * * Title: class * * Description: The Class ObjectPropertyGridUIPreference. */ private static final class ObjectPropertyGridUIPreference extends TabGridUIPreference { private IDSGridDataProvider resultsetDisplaydata; private ObjectPropertyGridUIPreference(IDSGridDataProvider resultsetDisplaydata) { super(); this.resultsetDisplaydata = resultsetDisplaydata; } @Override public boolean isShowQueryArea() { return false; } @Override public boolean isRefreshSupported() { return true; } @Override public boolean isEnableEdit() { return true; } @Override public String getNULLValueText() { return NULL_VALUE; } @Override public Map<String, IComboBoxDataProvider> getComboBoxDataProviders() { Map<String, IComboBoxDataProvider> comboBoxDataProviderMap = new HashMap<>(); if (resultsetDisplaydata instanceof DSObjectPropertiesGridDataProvider) { IServerObjectProperties objecjProperties = ((DSObjectPropertiesGridDataProvider) resultsetDisplaydata) .getObjectPropertyObject(); if (objecjProperties instanceof PropertiesUserRoleImpl) { Database dataBase = resultsetDisplaydata.getDatabse(); comboBoxDataProviderMap.put(PropertiesConstants.RESOURCE_POOL_COMBO_BOX_DATA_PROVIDER, new IComboBoxDataProvider() { @Override public List<?> getValues(int columnIndex, int rowIndex) { List<String> resourcePoolNames = new ArrayList<>(); try { if (dataBase != null) { resourcePoolNames.addAll(UserRoleManager.fetchResourcePool( dataBase.getConnectionManager().getObjBrowserConn())); } } catch (MPPDBIDEException exception) { MPPDBIDELoggerUtility.error("Failed to fetch UserRole resource pool", exception); } return resourcePoolNames; } }); comboBoxDataProviderMap.put(PropertiesConstants.MEMBER_SHIP_COMBO_BOX_DATA_PROVIDER, new IComboBoxDataProvider() { @Override public List<?> getValues(int columnIndex, int rowIndex) { List<String> userRoleNames = new ArrayList<>(); try { userRoleNames.addAll(UserRoleManager .fetchAllUserRole(dataBase.getServer(), dataBase.getConnectionManager().getObjBrowserConn()) .stream().map(userRole -> userRole.getName()) .collect(Collectors.toList())); userRoleNames.remove( ((PropertiesUserRoleImpl) objecjProperties).getUserRole().getName()); } catch (MPPDBIDEException exception) { MPPDBIDELoggerUtility.error("Failed to fetch all user roles", exception); } return userRoleNames; } }); } } return comboBoxDataProviderMap; } } /** * Handle focus. */ public void handleFocus() { this.gridComponent.focus(); } /** * Sets the edited status. * * @param isEdited the new edited status */ public void setEditedStatus(boolean isEdited) { if (isDisposed()) { return; } if (isEdited && !isTabEdited) { setText(getText() + "*"); this.isTabEdited = isEdited; } else if (!isEdited && isTabEdited) { String label = getText(); setText(label.substring(0, label.length() - 1)); this.isTabEdited = isEdited; } } /** * Reset tab buttons. * * @param tabData the tab data */ public void resetTabButtons(IObjectPropertyData tabData) { this.gridComponent.setLoadingStatus(false); } /** * Gets the data grid. * * @return the data grid */ public DataGrid getDataGrid() { return this.gridComponent.getDataGrid(); } }
epedropaulo/MyPython
03 - Estruturas Compostas/ex076.py
<gh_stars>0 Listagem = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.9, 'Estojo', 25, 'Transferidor', 4.2, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.3, 'Livro', 34.9) print('-' * 30) print(f'{"LISTAGEM DE PREÇOS" :^30}') print('-' * 30) for c in range(0, len(Listagem), 2): print(f'{Listagem[c] :.<20}R${Listagem[c + 1] :>7.2f}') print('-' * 30)
robclark/chromium
ui/base/native_theme/native_theme_base.cc
// Copyright (c) 2012 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. #include "ui/base/native_theme/native_theme_base.h" #include <limits> #include "base/logging.h" #include "grit/gfx_resources.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" namespace { // These are the default dimensions of radio buttons and checkboxes. const int kCheckboxAndRadioWidth = 13; const int kCheckboxAndRadioHeight = 13; // These sizes match the sizes in Chromium Win. const int kSliderThumbWidth = 11; const int kSliderThumbHeight = 21; const SkColor kSliderTrackBackgroundColor = SkColorSetRGB(0xe3, 0xdd, 0xd8); const SkColor kSliderThumbLightGrey = SkColorSetRGB(0xf4, 0xf2, 0xef); const SkColor kSliderThumbDarkGrey = SkColorSetRGB(0xea, 0xe5, 0xe0); const SkColor kSliderThumbBorderDarkGrey = SkColorSetRGB(0x9d, 0x96, 0x8e); const SkColor kMenuPopupBackgroundColor = SkColorSetRGB(210, 225, 246); const unsigned int kDefaultScrollbarWidth = 15; const unsigned int kDefaultScrollbarButtonLength = 14; // Get lightness adjusted color. SkColor BrightenColor(const color_utils::HSL& hsl, SkAlpha alpha, double lightness_amount) { color_utils::HSL adjusted = hsl; adjusted.l += lightness_amount; if (adjusted.l > 1.0) adjusted.l = 1.0; if (adjusted.l < 0.0) adjusted.l = 0.0; return color_utils::HSLToSkColor(adjusted, alpha); } } // namespace namespace ui { gfx::Size NativeThemeBase::GetPartSize(Part part, State state, const ExtraParams& extra) const { switch (part) { // Please keep these in the order of NativeTheme::Part. case kCheckbox: return gfx::Size(kCheckboxAndRadioWidth, kCheckboxAndRadioHeight); case kInnerSpinButton: return gfx::Size(scrollbar_width_, 0); case kMenuList: return gfx::Size(); // No default size. case kMenuCheck: case kMenuCheckBackground: case kMenuPopupArrow: NOTIMPLEMENTED(); break; case kMenuPopupBackground: return gfx::Size(); // No default size. case kMenuPopupGutter: case kMenuPopupSeparator: NOTIMPLEMENTED(); break; case kMenuItemBackground: case kProgressBar: case kPushButton: return gfx::Size(); // No default size. case kRadio: return gfx::Size(kCheckboxAndRadioWidth, kCheckboxAndRadioHeight); case kScrollbarDownArrow: case kScrollbarUpArrow: return gfx::Size(scrollbar_width_, scrollbar_button_length_); case kScrollbarLeftArrow: case kScrollbarRightArrow: return gfx::Size(scrollbar_button_length_, scrollbar_width_); case kScrollbarHorizontalThumb: // This matches Firefox on Linux. return gfx::Size(2 * scrollbar_width_, scrollbar_width_); case kScrollbarVerticalThumb: // This matches Firefox on Linux. return gfx::Size(scrollbar_width_, 2 * scrollbar_width_); case kScrollbarHorizontalTrack: return gfx::Size(0, scrollbar_width_); case kScrollbarVerticalTrack: return gfx::Size(scrollbar_width_, 0); case kScrollbarHorizontalGripper: case kScrollbarVerticalGripper: NOTIMPLEMENTED(); break; case kSliderTrack: return gfx::Size(); // No default size. case kSliderThumb: // These sizes match the sizes in Chromium Win. return gfx::Size(kSliderThumbWidth, kSliderThumbHeight); case kTabPanelBackground: NOTIMPLEMENTED(); break; case kTextField: return gfx::Size(); // No default size. case kTrackbarThumb: case kTrackbarTrack: case kWindowResizeGripper: NOTIMPLEMENTED(); break; default: NOTREACHED() << "Unknown theme part: " << part; break; } return gfx::Size(); } void NativeThemeBase::Paint(SkCanvas* canvas, Part part, State state, const gfx::Rect& rect, const ExtraParams& extra) const { switch (part) { // Please keep these in the order of NativeTheme::Part. case kCheckbox: PaintCheckbox(canvas, state, rect, extra.button); break; case kInnerSpinButton: PaintInnerSpinButton(canvas, state, rect, extra.inner_spin); break; case kMenuList: PaintMenuList(canvas, state, rect, extra.menu_list); break; case kMenuCheck: case kMenuCheckBackground: case kMenuPopupArrow: NOTIMPLEMENTED(); break; case kMenuPopupBackground: PaintMenuPopupBackground(canvas, rect.size()); break; case kMenuPopupGutter: case kMenuPopupSeparator: NOTIMPLEMENTED(); break; case kMenuItemBackground: PaintMenuItemBackground(canvas, state, rect, extra.menu_list); break; case kProgressBar: PaintProgressBar(canvas, state, rect, extra.progress_bar); break; case kPushButton: PaintButton(canvas, state, rect, extra.button); break; case kRadio: PaintRadio(canvas, state, rect, extra.button); break; case kScrollbarDownArrow: case kScrollbarUpArrow: case kScrollbarLeftArrow: case kScrollbarRightArrow: PaintArrowButton(canvas, rect, part, state); break; case kScrollbarHorizontalThumb: case kScrollbarVerticalThumb: PaintScrollbarThumb(canvas, part, state, rect); break; case kScrollbarHorizontalTrack: case kScrollbarVerticalTrack: PaintScrollbarTrack(canvas, part, state, extra.scrollbar_track, rect); break; case kScrollbarHorizontalGripper: case kScrollbarVerticalGripper: NOTIMPLEMENTED(); break; case kSliderTrack: PaintSliderTrack(canvas, state, rect, extra.slider); break; case kSliderThumb: PaintSliderThumb(canvas, state, rect, extra.slider); break; case kTabPanelBackground: NOTIMPLEMENTED(); break; case kTextField: PaintTextField(canvas, state, rect, extra.text_field); break; case kTrackbarThumb: case kTrackbarTrack: case kWindowResizeGripper: NOTIMPLEMENTED(); break; default: NOTREACHED() << "Unknown theme part: " << part; break; } } NativeThemeBase::NativeThemeBase() : scrollbar_width_(kDefaultScrollbarWidth), scrollbar_button_length_(kDefaultScrollbarButtonLength) { } NativeThemeBase::~NativeThemeBase() { } void NativeThemeBase::PaintArrowButton( SkCanvas* canvas, const gfx::Rect& rect, Part direction, State state) const { int widthMiddle, lengthMiddle; SkPaint paint; if (direction == kScrollbarUpArrow || direction == kScrollbarDownArrow) { widthMiddle = rect.width() / 2 + 1; lengthMiddle = rect.height() / 2 + 1; } else { lengthMiddle = rect.width() / 2 + 1; widthMiddle = rect.height() / 2 + 1; } // Calculate button color. SkScalar trackHSV[3]; SkColorToHSV(track_color_, trackHSV); SkColor buttonColor = SaturateAndBrighten(trackHSV, 0, 0.2f); SkColor backgroundColor = buttonColor; if (state == kPressed) { SkScalar buttonHSV[3]; SkColorToHSV(buttonColor, buttonHSV); buttonColor = SaturateAndBrighten(buttonHSV, 0, -0.1f); } else if (state == kHovered) { SkScalar buttonHSV[3]; SkColorToHSV(buttonColor, buttonHSV); buttonColor = SaturateAndBrighten(buttonHSV, 0, 0.05f); } SkIRect skrect; skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height()); // Paint the background (the area visible behind the rounded corners). paint.setColor(backgroundColor); canvas->drawIRect(skrect, paint); // Paint the button's outline and fill the middle SkPath outline; switch (direction) { case kScrollbarUpArrow: outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5); outline.rLineTo(0, -(rect.height() - 2)); outline.rLineTo(2, -2); outline.rLineTo(rect.width() - 5, 0); outline.rLineTo(2, 2); outline.rLineTo(0, rect.height() - 2); break; case kScrollbarDownArrow: outline.moveTo(rect.x() + 0.5, rect.y() - 0.5); outline.rLineTo(0, rect.height() - 2); outline.rLineTo(2, 2); outline.rLineTo(rect.width() - 5, 0); outline.rLineTo(2, -2); outline.rLineTo(0, -(rect.height() - 2)); break; case kScrollbarRightArrow: outline.moveTo(rect.x() - 0.5, rect.y() + 0.5); outline.rLineTo(rect.width() - 2, 0); outline.rLineTo(2, 2); outline.rLineTo(0, rect.height() - 5); outline.rLineTo(-2, 2); outline.rLineTo(-(rect.width() - 2), 0); break; case kScrollbarLeftArrow: outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5); outline.rLineTo(-(rect.width() - 2), 0); outline.rLineTo(-2, 2); outline.rLineTo(0, rect.height() - 5); outline.rLineTo(2, 2); outline.rLineTo(rect.width() - 2, 0); break; default: break; } outline.close(); paint.setStyle(SkPaint::kFill_Style); paint.setColor(buttonColor); canvas->drawPath(outline, paint); paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); SkScalar thumbHSV[3]; SkColorToHSV(thumb_inactive_color_, thumbHSV); paint.setColor(OutlineColor(trackHSV, thumbHSV)); canvas->drawPath(outline, paint); // If the button is disabled or read-only, the arrow is drawn with the // outline color. if (state != kDisabled) paint.setColor(SK_ColorBLACK); paint.setAntiAlias(false); paint.setStyle(SkPaint::kFill_Style); SkPath path; // The constants in this block of code are hand-tailored to produce good // looking arrows without anti-aliasing. switch (direction) { case kScrollbarUpArrow: path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle + 2); path.rLineTo(7, 0); path.rLineTo(-4, -4); break; case kScrollbarDownArrow: path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle - 3); path.rLineTo(7, 0); path.rLineTo(-4, 4); break; case kScrollbarRightArrow: path.moveTo(rect.x() + lengthMiddle - 3, rect.y() + widthMiddle - 4); path.rLineTo(0, 7); path.rLineTo(4, -4); break; case kScrollbarLeftArrow: path.moveTo(rect.x() + lengthMiddle + 1, rect.y() + widthMiddle - 5); path.rLineTo(0, 9); path.rLineTo(-4, -4); break; default: break; } path.close(); canvas->drawPath(path, paint); } void NativeThemeBase::PaintScrollbarTrack(SkCanvas* canvas, Part part, State state, const ScrollbarTrackExtraParams& extra_params, const gfx::Rect& rect) const { SkPaint paint; SkIRect skrect; skrect.set(rect.x(), rect.y(), rect.right(), rect.bottom()); SkScalar track_hsv[3]; SkColorToHSV(track_color_, track_hsv); paint.setColor(SaturateAndBrighten(track_hsv, 0, 0)); canvas->drawIRect(skrect, paint); SkScalar thumb_hsv[3]; SkColorToHSV(thumb_inactive_color_, thumb_hsv); paint.setColor(OutlineColor(track_hsv, thumb_hsv)); DrawBox(canvas, rect, paint); } void NativeThemeBase::PaintScrollbarThumb(SkCanvas* canvas, Part part, State state, const gfx::Rect& rect) const { const bool hovered = state == kHovered; const int midx = rect.x() + rect.width() / 2; const int midy = rect.y() + rect.height() / 2; const bool vertical = part == kScrollbarVerticalThumb; SkScalar thumb[3]; SkColorToHSV(hovered ? thumb_active_color_ : thumb_inactive_color_, thumb); SkPaint paint; paint.setColor(SaturateAndBrighten(thumb, 0, 0.02f)); SkIRect skrect; if (vertical) skrect.set(rect.x(), rect.y(), midx + 1, rect.y() + rect.height()); else skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), midy + 1); canvas->drawIRect(skrect, paint); paint.setColor(SaturateAndBrighten(thumb, 0, -0.02f)); if (vertical) { skrect.set( midx + 1, rect.y(), rect.x() + rect.width(), rect.y() + rect.height()); } else { skrect.set( rect.x(), midy + 1, rect.x() + rect.width(), rect.y() + rect.height()); } canvas->drawIRect(skrect, paint); SkScalar track[3]; SkColorToHSV(track_color_, track); paint.setColor(OutlineColor(track, thumb)); DrawBox(canvas, rect, paint); if (rect.height() > 10 && rect.width() > 10) { const int grippy_half_width = 2; const int inter_grippy_offset = 3; if (vertical) { DrawHorizLine(canvas, midx - grippy_half_width, midx + grippy_half_width, midy - inter_grippy_offset, paint); DrawHorizLine(canvas, midx - grippy_half_width, midx + grippy_half_width, midy, paint); DrawHorizLine(canvas, midx - grippy_half_width, midx + grippy_half_width, midy + inter_grippy_offset, paint); } else { DrawVertLine(canvas, midx - inter_grippy_offset, midy - grippy_half_width, midy + grippy_half_width, paint); DrawVertLine(canvas, midx, midy - grippy_half_width, midy + grippy_half_width, paint); DrawVertLine(canvas, midx + inter_grippy_offset, midy - grippy_half_width, midy + grippy_half_width, paint); } } } void NativeThemeBase::PaintCheckbox(SkCanvas* canvas, State state, const gfx::Rect& rect, const ButtonExtraParams& button) const { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* image = NULL; if (button.indeterminate) { image = state == kDisabled ? rb.GetBitmapNamed(IDR_CHECKBOX_DISABLED_INDETERMINATE) : rb.GetBitmapNamed(IDR_CHECKBOX_INDETERMINATE); } else if (button.checked) { image = state == kDisabled ? rb.GetBitmapNamed(IDR_CHECKBOX_DISABLED_ON) : rb.GetBitmapNamed(IDR_CHECKBOX_ON); } else { image = state == kDisabled ? rb.GetBitmapNamed(IDR_CHECKBOX_DISABLED_OFF) : rb.GetBitmapNamed(IDR_CHECKBOX_OFF); } gfx::Rect bounds = rect.Center(gfx::Size(image->width(), image->height())); DrawBitmapInt(canvas, *image, 0, 0, image->width(), image->height(), bounds.x(), bounds.y(), bounds.width(), bounds.height()); } void NativeThemeBase::PaintRadio(SkCanvas* canvas, State state, const gfx::Rect& rect, const ButtonExtraParams& button) const { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* image = NULL; if (state == kDisabled) { image = button.checked ? rb.GetBitmapNamed(IDR_RADIO_DISABLED_ON) : rb.GetBitmapNamed(IDR_RADIO_DISABLED_OFF); } else { image = button.checked ? rb.GetBitmapNamed(IDR_RADIO_ON) : rb.GetBitmapNamed(IDR_RADIO_OFF); } gfx::Rect bounds = rect.Center(gfx::Size(image->width(), image->height())); DrawBitmapInt(canvas, *image, 0, 0, image->width(), image->height(), bounds.x(), bounds.y(), bounds.width(), bounds.height()); } void NativeThemeBase::PaintButton(SkCanvas* canvas, State state, const gfx::Rect& rect, const ButtonExtraParams& button) const { SkPaint paint; const int kRight = rect.right(); const int kBottom = rect.bottom(); SkRect skrect = SkRect::MakeLTRB(rect.x(), rect.y(), kRight, kBottom); SkColor base_color = button.background_color; color_utils::HSL base_hsl; color_utils::SkColorToHSL(base_color, &base_hsl); // Our standard gradient is from 0xdd to 0xf8. This is the amount of // increased luminance between those values. SkColor light_color(BrightenColor(base_hsl, SkColorGetA(base_color), 0.105)); // If the button is too small, fallback to drawing a single, solid color if (rect.width() < 5 || rect.height() < 5) { paint.setColor(base_color); canvas->drawRect(skrect, paint); return; } paint.setColor(SK_ColorBLACK); const int kLightEnd = state == kPressed ? 1 : 0; const int kDarkEnd = !kLightEnd; SkPoint gradient_bounds[2]; gradient_bounds[kLightEnd].iset(rect.x(), rect.y()); gradient_bounds[kDarkEnd].iset(rect.x(), kBottom - 1); SkColor colors[2]; colors[0] = light_color; colors[1] = base_color; SkShader* shader = SkGradientShader::CreateLinear( gradient_bounds, colors, NULL, 2, SkShader::kClamp_TileMode, NULL); paint.setStyle(SkPaint::kFill_Style); paint.setAntiAlias(true); paint.setShader(shader); shader->unref(); canvas->drawRoundRect(skrect, SkIntToScalar(1), SkIntToScalar(1), paint); paint.setShader(NULL); if (button.has_border) { const int kBorderAlpha = state == kHovered ? 0x80 : 0x55; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkIntToScalar(1)); paint.setARGB(kBorderAlpha, 0, 0, 0); skrect.inset(SkFloatToScalar(.5f), SkFloatToScalar(.5f)); canvas->drawRoundRect(skrect, SkIntToScalar(1), SkIntToScalar(1), paint); } } void NativeThemeBase::PaintTextField(SkCanvas* canvas, State state, const gfx::Rect& rect, const TextFieldExtraParams& text) const { // The following drawing code simulates the user-agent css border for // text area and text input so that we do not break layout tests. Once we // have decided the desired looks, we should update the code here and // the layout test expectations. SkRect bounds; bounds.set(rect.x(), rect.y(), rect.right() - 1, rect.bottom() - 1); SkPaint fill_paint; fill_paint.setStyle(SkPaint::kFill_Style); fill_paint.setColor(text.background_color); canvas->drawRect(bounds, fill_paint); if (text.is_text_area) { // Draw text area border: 1px solid black SkPaint stroke_paint; fill_paint.setStyle(SkPaint::kStroke_Style); fill_paint.setColor(SK_ColorBLACK); canvas->drawRect(bounds, fill_paint); } else { // Draw text input and listbox inset border // Text Input: 2px inset #eee // Listbox: 1px inset #808080 const SkColor kLightColor = text.is_listbox ? SkColorSetRGB(0x80, 0x80, 0x80) : SkColorSetRGB(0xee, 0xee, 0xee); const SkColor kDarkColor = text.is_listbox ? SkColorSetRGB(0x2c, 0x2c, 0x2c) : SkColorSetRGB(0x9a, 0x9a, 0x9a); const int kBorderWidth = text.is_listbox ? 1 : 2; SkPaint dark_paint; dark_paint.setAntiAlias(true); dark_paint.setStyle(SkPaint::kFill_Style); dark_paint.setColor(kDarkColor); SkPaint light_paint; light_paint.setAntiAlias(true); light_paint.setStyle(SkPaint::kFill_Style); light_paint.setColor(kLightColor); int left = rect.x(); int top = rect.y(); int right = rect.right(); int bottom = rect.bottom(); SkPath path; path.incReserve(4); // Top path.moveTo(SkIntToScalar(left), SkIntToScalar(top)); path.lineTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(top + kBorderWidth)); path.lineTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(top + kBorderWidth)); path.lineTo(SkIntToScalar(right), SkIntToScalar(top)); canvas->drawPath(path, dark_paint); // Bottom path.reset(); path.moveTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(bottom - kBorderWidth)); path.lineTo(SkIntToScalar(left), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(bottom - kBorderWidth)); canvas->drawPath(path, light_paint); // Left path.reset(); path.moveTo(SkIntToScalar(left), SkIntToScalar(top)); path.lineTo(SkIntToScalar(left), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(bottom - kBorderWidth)); path.lineTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(top + kBorderWidth)); canvas->drawPath(path, dark_paint); // Right path.reset(); path.moveTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(top + kBorderWidth)); path.lineTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right), SkIntToScalar(top)); canvas->drawPath(path, light_paint); } } void NativeThemeBase::PaintMenuList( SkCanvas* canvas, State state, const gfx::Rect& rect, const MenuListExtraParams& menu_list) const { // If a border radius is specified, we let the WebCore paint the background // and the border of the control. if (!menu_list.has_border_radius) { ButtonExtraParams button = { 0 }; button.background_color = menu_list.background_color; button.has_border = menu_list.has_border; PaintButton(canvas, state, rect, button); } SkPaint paint; paint.setColor(SK_ColorBLACK); paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); SkPath path; path.moveTo(menu_list.arrow_x, menu_list.arrow_y - 3); path.rLineTo(6, 0); path.rLineTo(-3, 6); path.close(); canvas->drawPath(path, paint); } void NativeThemeBase::PaintMenuPopupBackground(SkCanvas* canvas, const gfx::Size& size) const { canvas->drawColor(kMenuPopupBackgroundColor, SkXfermode::kSrc_Mode); } void NativeThemeBase::PaintMenuItemBackground( SkCanvas* canvas, State state, const gfx::Rect& rect, const MenuListExtraParams& menu_list) const { // By default don't draw anything over the normal background. } void NativeThemeBase::PaintSliderTrack(SkCanvas* canvas, State state, const gfx::Rect& rect, const SliderExtraParams& slider) const { const int kMidX = rect.x() + rect.width() / 2; const int kMidY = rect.y() + rect.height() / 2; SkPaint paint; paint.setColor(kSliderTrackBackgroundColor); SkRect skrect; if (slider.vertical) { skrect.set(std::max(rect.x(), kMidX - 2), rect.y(), std::min(rect.right(), kMidX + 2), rect.bottom()); } else { skrect.set(rect.x(), std::max(rect.y(), kMidY - 2), rect.right(), std::min(rect.bottom(), kMidY + 2)); } canvas->drawRect(skrect, paint); } void NativeThemeBase::PaintSliderThumb(SkCanvas* canvas, State state, const gfx::Rect& rect, const SliderExtraParams& slider) const { const bool hovered = (state == kHovered) || slider.in_drag; const int kMidX = rect.x() + rect.width() / 2; const int kMidY = rect.y() + rect.height() / 2; SkPaint paint; paint.setColor(hovered ? SK_ColorWHITE : kSliderThumbLightGrey); SkIRect skrect; if (slider.vertical) skrect.set(rect.x(), rect.y(), kMidX + 1, rect.bottom()); else skrect.set(rect.x(), rect.y(), rect.right(), kMidY + 1); canvas->drawIRect(skrect, paint); paint.setColor(hovered ? kSliderThumbLightGrey : kSliderThumbDarkGrey); if (slider.vertical) skrect.set(kMidX + 1, rect.y(), rect.right(), rect.bottom()); else skrect.set(rect.x(), kMidY + 1, rect.right(), rect.bottom()); canvas->drawIRect(skrect, paint); paint.setColor(kSliderThumbBorderDarkGrey); DrawBox(canvas, rect, paint); if (rect.height() > 10 && rect.width() > 10) { DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY, paint); DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY - 3, paint); DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY + 3, paint); } } void NativeThemeBase::PaintInnerSpinButton(SkCanvas* canvas, State state, const gfx::Rect& rect, const InnerSpinButtonExtraParams& spin_button) const { if (spin_button.read_only) state = kDisabled; State north_state = state; State south_state = state; if (spin_button.spin_up) south_state = south_state != kDisabled ? kNormal : kDisabled; else north_state = north_state != kDisabled ? kNormal : kDisabled; gfx::Rect half = rect; half.set_height(rect.height() / 2); PaintArrowButton(canvas, half, kScrollbarUpArrow, north_state); half.set_y(rect.y() + rect.height() / 2); PaintArrowButton(canvas, half, kScrollbarDownArrow, south_state); } void NativeThemeBase::PaintProgressBar(SkCanvas* canvas, State state, const gfx::Rect& rect, const ProgressBarExtraParams& progress_bar) const { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* bar_image = rb.GetBitmapNamed(IDR_PROGRESS_BAR); SkBitmap* left_border_image = rb.GetBitmapNamed(IDR_PROGRESS_BORDER_LEFT); SkBitmap* right_border_image = rb.GetBitmapNamed(IDR_PROGRESS_BORDER_RIGHT); double tile_scale = static_cast<double>(rect.height()) / bar_image->height(); int new_tile_width = static_cast<int>(bar_image->width() * tile_scale); double tile_scale_x = static_cast<double>(new_tile_width) / bar_image->width(); DrawTiledImage(canvas, *bar_image, 0, 0, tile_scale_x, tile_scale, rect.x(), rect.y(), rect.width(), rect.height()); if (progress_bar.value_rect_width) { SkBitmap* value_image = rb.GetBitmapNamed(IDR_PROGRESS_VALUE); new_tile_width = static_cast<int>(value_image->width() * tile_scale); tile_scale_x = static_cast<double>(new_tile_width) / value_image->width(); DrawTiledImage(canvas, *value_image, 0, 0, tile_scale_x, tile_scale, progress_bar.value_rect_x, progress_bar.value_rect_y, progress_bar.value_rect_width, progress_bar.value_rect_height); } int dest_left_border_width = static_cast<int>(left_border_image->width() * tile_scale); SkRect dest_rect; dest_rect.iset(rect.x(), rect.y(), rect.x() + dest_left_border_width, rect.bottom()); canvas->drawBitmapRect(*left_border_image, NULL, dest_rect); int dest_right_border_width = static_cast<int>(right_border_image->width() * tile_scale); dest_rect.iset(rect.right() - dest_right_border_width, rect.y(), rect.right(), rect.bottom()); canvas->drawBitmapRect(*right_border_image, NULL, dest_rect); } bool NativeThemeBase::IntersectsClipRectInt(SkCanvas* canvas, int x, int y, int w, int h) const { SkRect clip; return canvas->getClipBounds(&clip) && clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w), SkIntToScalar(y + h)); } void NativeThemeBase::DrawBitmapInt( SkCanvas* canvas, const SkBitmap& bitmap, int src_x, int src_y, int src_w, int src_h, int dest_x, int dest_y, int dest_w, int dest_h) const { DLOG_ASSERT(src_x + src_w < std::numeric_limits<int16_t>::max() && src_y + src_h < std::numeric_limits<int16_t>::max()); if (src_w <= 0 || src_h <= 0 || dest_w <= 0 || dest_h <= 0) { NOTREACHED() << "Attempting to draw bitmap to/from an empty rect!"; return; } if (!IntersectsClipRectInt(canvas, dest_x, dest_y, dest_w, dest_h)) return; SkRect dest_rect = { SkIntToScalar(dest_x), SkIntToScalar(dest_y), SkIntToScalar(dest_x + dest_w), SkIntToScalar(dest_y + dest_h) }; if (src_w == dest_w && src_h == dest_h) { // Workaround for apparent bug in Skia that causes image to occasionally // shift. SkIRect src_rect = { src_x, src_y, src_x + src_w, src_y + src_h }; canvas->drawBitmapRect(bitmap, &src_rect, dest_rect); return; } // Make a bitmap shader that contains the bitmap we want to draw. This is // basically what SkCanvas.drawBitmap does internally, but it gives us // more control over quality and will use the mipmap in the source image if // it has one, whereas drawBitmap won't. SkShader* shader = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix shader_scale; shader_scale.setScale(SkFloatToScalar(static_cast<float>(dest_w) / src_w), SkFloatToScalar(static_cast<float>(dest_h) / src_h)); shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y)); shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y)); shader->setLocalMatrix(shader_scale); // The rect will be filled by the bitmap. SkPaint p; p.setFilterBitmap(true); p.setShader(shader); shader->unref(); canvas->drawRect(dest_rect, p); } void NativeThemeBase::DrawTiledImage(SkCanvas* canvas, const SkBitmap& bitmap, int src_x, int src_y, double tile_scale_x, double tile_scale_y, int dest_x, int dest_y, int w, int h) const { SkShader* shader = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); if (tile_scale_x != 1.0 || tile_scale_y != 1.0) { SkMatrix shader_scale; shader_scale.setScale(SkDoubleToScalar(tile_scale_x), SkDoubleToScalar(tile_scale_y)); shader->setLocalMatrix(shader_scale); } SkPaint paint; paint.setShader(shader); paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); // CreateBitmapShader returns a Shader with a reference count of one, we // need to unref after paint takes ownership of the shader. shader->unref(); canvas->save(); canvas->translate(SkIntToScalar(dest_x - src_x), SkIntToScalar(dest_y - src_y)); canvas->clipRect(SkRect::MakeXYWH(src_x, src_y, w, h)); canvas->drawPaint(paint); canvas->restore(); } SkColor NativeThemeBase::SaturateAndBrighten(SkScalar* hsv, SkScalar saturate_amount, SkScalar brighten_amount) const { SkScalar color[3]; color[0] = hsv[0]; color[1] = Clamp(hsv[1] + saturate_amount, 0.0, 1.0); color[2] = Clamp(hsv[2] + brighten_amount, 0.0, 1.0); return SkHSVToColor(color); } void NativeThemeBase::DrawVertLine(SkCanvas* canvas, int x, int y1, int y2, const SkPaint& paint) const { SkIRect skrect; skrect.set(x, y1, x + 1, y2 + 1); canvas->drawIRect(skrect, paint); } void NativeThemeBase::DrawHorizLine(SkCanvas* canvas, int x1, int x2, int y, const SkPaint& paint) const { SkIRect skrect; skrect.set(x1, y, x2 + 1, y + 1); canvas->drawIRect(skrect, paint); } void NativeThemeBase::DrawBox(SkCanvas* canvas, const gfx::Rect& rect, const SkPaint& paint) const { const int right = rect.x() + rect.width() - 1; const int bottom = rect.y() + rect.height() - 1; DrawHorizLine(canvas, rect.x(), right, rect.y(), paint); DrawVertLine(canvas, right, rect.y(), bottom, paint); DrawHorizLine(canvas, rect.x(), right, bottom, paint); DrawVertLine(canvas, rect.x(), rect.y(), bottom, paint); } SkScalar NativeThemeBase::Clamp(SkScalar value, SkScalar min, SkScalar max) const { return std::min(std::max(value, min), max); } SkColor NativeThemeBase::OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const { // GTK Theme engines have way too much control over the layout of // the scrollbar. We might be able to more closely approximate its // look-and-feel, if we sent whole images instead of just colors // from the browser to the renderer. But even then, some themes // would just break. // // So, instead, we don't even try to 100% replicate the look of // the native scrollbar. We render our own version, but we make // sure to pick colors that blend in nicely with the system GTK // theme. In most cases, we can just sample a couple of pixels // from the system scrollbar and use those colors to draw our // scrollbar. // // This works fine for the track color and the overall thumb // color. But it fails spectacularly for the outline color used // around the thumb piece. Not all themes have a clearly defined // outline. For some of them it is partially transparent, and for // others the thickness is very unpredictable. // // So, instead of trying to approximate the system theme, we // instead try to compute a reasonable looking choice based on the // known color of the track and the thumb piece. This is difficult // when trying to deal both with high- and low-contrast themes, // and both with positive and inverted themes. // // The following code has been tested to look OK with all of the // default GTK themes. SkScalar min_diff = Clamp((hsv1[1] + hsv2[1]) * 1.2f, 0.28f, 0.5f); SkScalar diff = Clamp(fabs(hsv1[2] - hsv2[2]) / 2, min_diff, 0.5f); if (hsv1[2] + hsv2[2] > 1.0) diff = -diff; return SaturateAndBrighten(hsv2, -0.2f, diff); } } // namespace ui
PasseRR/JavaLeetCode
src/main/java/com/gitee/passerr/leetcode/problem/lcof1/page2/Lcof55I.java
<filename>src/main/java/com/gitee/passerr/leetcode/problem/lcof1/page2/Lcof55I.java package com.gitee.passerr.leetcode.problem.lcof1.page2; import com.gitee.passerr.leetcode.TreeNode; /** * 输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。 * <p> * 例如: * 给定二叉树 [3,9,20,null,null,15,7], * | 3 * | / \ * | 9 20 * | / \ * | 15 7 * 返回它的最大深度 3 。 * <p> * 提示: * 节点总数 <= 10000 * 注意:本题与主站 104 题相同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/ * @author xiehai * @date 2020/07/14 16:25 * @Copyright(c) tellyes tech. inc. co.,ltd */ public class Lcof55I { public int maxDepth(TreeNode root) { if (root == null) { return 0; } return Integer.max(this.maxDepth(root.left), this.maxDepth(root.right)) + 1; } }
nmldiegues/jvm-stm
classpath-0.98/gnu/javax/print/ipp/attribute/supported/OperationsSupported.java
/* OperationsSupported.java -- Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.print.ipp.attribute.supported; import javax.print.attribute.EnumSyntax; import javax.print.attribute.SupportedValuesAttribute; /** * <code>OperationsSupported</code> specifies the enums of the operations * supported by a given printer or job object. The attribute is further * specified in RFC 2911 section 4.4.15. * * @author <NAME> (<EMAIL>) */ public final class OperationsSupported extends EnumSyntax implements SupportedValuesAttribute { /* * Value Operation Name ----------------- ------------------------------------- 0x0000 reserved, not used 0x0001 reserved, not used 0x0002 Print-Job 0x0003 Print-URI 0x0004 Validate-Job 0x0005 Create-Job 0x0006 Send-Document 0x0007 Send-URI 0x0008 Cancel-Job 0x0009 Get-Job-Attributes 0x000A Get-Jobs 0x000B Get-Printer-Attributes 0x000C Hold-Job 0x000D Release-Job 0x000E Restart-Job 0x000F reserved for a future operation 0x0010 Pause-Printer 0x0011 Resume-Printer 0x0012 Purge-Jobs 0x0013-0x3FFF reserved for future IETF standards track operations 0x4000-0x8FFF reserved for vendor extensions */ // standard ipp 1.1 operations /** * Operation to print a job in one request/response. */ public static final OperationsSupported PRINT_JOB = new OperationsSupported(0x02); /** Operation to print a document from an URI */ public static final OperationsSupported PRINT_URI = new OperationsSupported(0x03); /** Operation to validate a job before submission. */ public static final OperationsSupported VALIDATE_JOB = new OperationsSupported(0x04); /** * Operation to create an initial job for use with multiple document per job. */ public static final OperationsSupported CREATE_JOB = new OperationsSupported(0x05); /** * Operation to send a document to a multidoc job created via CREATE_JOB */ public static final OperationsSupported SEND_DOCUMENT = new OperationsSupported(0x06); /** * Operation to send a document uri to a multidoc job created * via CREATE_JOB. The document accessible from this URI will be printed. */ public static final OperationsSupported SEND_URI = new OperationsSupported(0x07); /** Operation to cancel a job by its ID or name. */ public static final OperationsSupported CANCEL_JOB = new OperationsSupported(0x08); /** Operation to get job attributes of a current job. */ public static final OperationsSupported GET_JOB_ATTRIBUTES = new OperationsSupported(0x09); /** Operation to pause a printer. */ public static final OperationsSupported PAUSE_PRINTER = new OperationsSupported(0x10); /** Operation to get all currently queued or processed jobs. */ public static final OperationsSupported GET_JOBS = new OperationsSupported(0x0A); /** Operation to get the attributes of a printer. */ public static final OperationsSupported GET_PRINTER_ATTRIBUTES = new OperationsSupported(0x0B); /** Operation to put a job on hold by its ID or name. */ public static final OperationsSupported HOLD_JOB = new OperationsSupported(0x0C); /** Operation to release a job by its ID or name. */ public static final OperationsSupported RELEASE_JOB = new OperationsSupported(0x0D); /** Operation to restart a job by its ID or name. */ public static final OperationsSupported RESTART_JOB = new OperationsSupported(0x0E); /** Not yet an operation - reserved for futher use. */ public static final OperationsSupported RESERVED = new OperationsSupported(0x0F); /** Operation to resume a printer. */ public static final OperationsSupported RESUME_PRINTER = new OperationsSupported(0x11); /** Operation to remove all jobs from a printer regardless of state. */ public static final OperationsSupported PURGE_JOBS = new OperationsSupported(0x12); private static final String[] stringTable = { "print-job", "print-uri", "validate-job", "create-job", "send-document", "send-uri", "cancel-job", "get-job-attributes", "pause-printer", "get-jobs", "get-printer-attributes", "hold-job", "release-job", "restart-job", "reserved", "resume-printer", "purge-job"}; private static final OperationsSupported[] enumValueTable = { PRINT_JOB, PRINT_URI, VALIDATE_JOB, CREATE_JOB, SEND_DOCUMENT, SEND_URI, CANCEL_JOB, GET_JOB_ATTRIBUTES, PAUSE_PRINTER, GET_JOBS, GET_PRINTER_ATTRIBUTES, HOLD_JOB, RELEASE_JOB, RESTART_JOB, RESERVED, RESUME_PRINTER, PURGE_JOBS}; /** * Constructs a <code>OperationsSupported</code> object. * * @param value the enum value */ protected OperationsSupported(int value) { super(value); } /** * Returns category of this class. * * @return The class <code>OperationsSupported</code> itself. */ public Class getCategory() { return OperationsSupported.class; } /** * Returns the name of this attribute. * * @return The name "operations-supported". */ public String getName() { return "operations-supported"; } /** * Returns a table with the enumeration values represented as strings * for this object. * * @return The enumeration values as strings. */ protected String[] getStringTable() { return stringTable; } /** * Returns a table with the enumeration values for this object. * * @return The enumeration values. */ protected EnumSyntax[] getEnumValueTable() { return enumValueTable; } // we start with 2 protected int getOffset() { return 2; } }
SunYe1234/PDFNetNew
headers/Impl/Convert.inl
<gh_stars>0 void SetFlattenContentImpl(TRN_Obj obj, enum Convert::FlattenFlag flatten, TRN_Obj* result); void SetFlattenThresholdImpl(TRN_Obj obj, enum Convert::FlattenThresholdFlag threshold, TRN_Obj* result); void SetOverprintImpl(TRN_Obj obj, enum PDFRasterizer::OverprintPreviewMode mode, TRN_Obj* result); inline void Convert::FromXps(PDFDoc & in_pdfdoc, const UString & in_filename) { REX(TRN_ConvertFromXps(in_pdfdoc.mp_doc, in_filename.mp_impl)); } inline void Convert::FromXps(PDFDoc & in_pdfdoc, const char* buf, size_t buf_sz) { REX(TRN_ConvertFromXpsMem(in_pdfdoc.mp_doc, buf, buf_sz)); } inline void Convert::FromEmf(PDFDoc & in_pdfdoc, const UString & in_filename) { REX(TRN_ConvertFromEmf(in_pdfdoc.mp_doc, in_filename.mp_impl)); } inline void Convert::FromText(PDFDoc& in_pdfdoc, const UString& in_filename, const SDF::Obj& options) { REX(TRN_ConvertFromText(in_pdfdoc.mp_doc, in_filename.mp_impl, options.mp_obj)); } inline void Convert::ToEmf(PDFDoc & in_pdfdoc, const UString & in_filename) { REX(TRN_ConvertDocToEmf(in_pdfdoc.mp_doc, in_filename.mp_impl)); } inline void Convert::ToEmf(Page & in_page, const UString & in_filename) { REX(TRN_ConvertPageToEmf(in_page.mp_page, in_filename.mp_impl)); } inline SVGOutputOptions::SVGOutputOptions() { m_obj = m_objset.CreateDict().mp_obj; } inline void SVGOutputOptions::SetEmbedImages(bool embed_images) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "EMBEDIMAGES", BToTB(embed_images), &result)); } inline void SVGOutputOptions::SetNoFonts(bool no_fonts) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "NOFONTS", BToTB(no_fonts), &result)); } inline void SVGOutputOptions::SetSvgFonts(bool svg_fonts) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "SVGFONTS", BToTB(svg_fonts), &result)); } inline void SVGOutputOptions::SetEmbedFonts(bool embed_fonts) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "EMBEDFONTS", BToTB(embed_fonts), &result)); } inline void SVGOutputOptions::SetFlattenContent(enum Convert::FlattenFlag flatten) { TRN_Obj result; SetFlattenContentImpl(m_obj, flatten, &result); } inline void SVGOutputOptions::SetFlattenThreshold(enum Convert::FlattenThresholdFlag threshold) { TRN_Obj result; SetFlattenThresholdImpl(m_obj, threshold, &result); } inline void SVGOutputOptions::SetFlattenDPI(UInt32 dpi) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj, "DPI", dpi, &result)); } inline void SVGOutputOptions::SetFlattenMaximumImagePixels(UInt32 max_pixels) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj, "MAX_IMAGE_PIXELS", max_pixels, &result)); } inline void SVGOutputOptions::SetCompress(bool svgz) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "SVGZ", BToTB(svgz), &result)); } inline void SVGOutputOptions::SetOutputThumbnails(bool include_thumbs) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"NOTHUMBS",BToTB(!include_thumbs),&result)); } inline void SVGOutputOptions::SetThumbnailSize(UInt32 size) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"THUMB_SIZE",size,&result)); } inline void SVGOutputOptions::SetCreateXmlWrapper(bool xml) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "NOXMLDOC", BToTB(!xml), &result)); } inline void SVGOutputOptions::SetDtd(bool dtd) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "OMITDTD", BToTB(!dtd), &result)); } inline void SVGOutputOptions::SetAnnots(bool annots) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "NOANNOTS", BToTB(!annots), &result)); } inline void SVGOutputOptions::SetNoUnicode(bool no_unicode) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "NOUNICODE", BToTB(no_unicode), &result)); } inline void SVGOutputOptions::SetIndividualCharPlacement(bool individual_char_placement) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "INDIVIDUALCHARPLACEMENT", BToTB(individual_char_placement), &result)); } inline void SVGOutputOptions::SetRemoveCharPlacement(bool remove_char_placement) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "REMOVECHARPLACEMENT", BToTB(remove_char_placement), &result)); } inline void SVGOutputOptions::SetOverprint(PDFRasterizer::OverprintPreviewMode mode) { TRN_Obj result; SetOverprintImpl(m_obj, mode, &result); } inline void Convert::ToSvg(PDFDoc & in_pdfdoc, const UString & in_filename) { SVGOutputOptions in_options; Convert::ToSvg(in_pdfdoc, in_filename, in_options); } inline void Convert::ToSvg(PDFDoc & in_pdfdoc, const UString & in_filename, const SVGOutputOptions& in_options) { REX(TRN_ConvertDocToSvgWithOptions(in_pdfdoc.mp_doc, in_filename.mp_impl, in_options.m_obj)); } inline void Convert::ToSvg(Page & in_page, const UString & in_filename) { SVGOutputOptions in_options; Convert::ToSvg(in_page, in_filename, in_options); } inline void Convert::ToSvg(Page & in_page, const UString & in_filename, const SVGOutputOptions& in_options) { REX(TRN_ConvertPageToSvgWithOptions(in_page.mp_page, in_filename.mp_impl, in_options.m_obj)); } inline XPSOutputCommonOptions::XPSOutputCommonOptions() { m_obj=m_objset.CreateDict().mp_obj; } inline void XPSOutputCommonOptions::SetPrintMode(bool print_mode) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"PRINTMODE",BToTB(print_mode),&result)); } inline void XPSOutputCommonOptions::SetDPI(UInt32 dpi) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"DPI",dpi,&result)); } inline void XPSOutputCommonOptions::SetRenderPages(bool render) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"RENDER",BToTB(render),&result)); } inline void XPSOutputCommonOptions::SetThickenLines(bool thicken) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"THICKENLINES",BToTB(thicken),&result)); } inline void XPSOutputCommonOptions::GenerateURLLinks(bool generate) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"URL_LINKS",BToTB(generate),&result)); } inline void XPSOutputCommonOptions::SetOverprint(enum OverprintPreviewMode mode) { TRN_Obj result; SetOverprintImpl(m_obj, static_cast<PDFRasterizer::OverprintPreviewMode>(mode), &result); } inline void XPSOutputOptions::SetOpenXps(bool openxps) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"OPENXPS",BToTB(openxps),&result)); } inline void XODOutputOptions::SetOutputThumbnails(bool include_thumbs) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"NOTHUMBS",BToTB(!include_thumbs),&result)); } inline void XODOutputOptions::SetThumbnailSize(UInt32 size) { SetThumbnailSize(size,size); } inline void XODOutputOptions::SetThumbnailSize(UInt32 regular_size, UInt32 large_size) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"THUMB_SIZE",regular_size,&result)); REX(TRN_ObjPutNumber(m_obj,"LARGE_THUMB_SIZE",large_size,&result)); } inline void XODOutputOptions::SetElementLimit(UInt32 element_limit) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"ELEMENTLIMIT",element_limit,&result)); } inline void XODOutputOptions::SetOpacityMaskWorkaround(bool opacity_render) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"MASKRENDER",opacity_render,&result)); } inline void XODOutputOptions::SetMaximumImagePixels(UInt32 max_pixels) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"MAX_IMAGE_PIXELS",max_pixels,&result)); } inline void XODOutputOptions::SetFlattenContent(enum Convert::FlattenFlag flatten) { TRN_Obj result; SetFlattenContentImpl(m_obj, flatten, &result); } inline void XODOutputOptions::SetFlattenThreshold(enum Convert::FlattenThresholdFlag threshold) { TRN_Obj result; SetFlattenThresholdImpl(m_obj, threshold, &result); } inline void XODOutputOptions::SetPreferJPG(bool prefer_jpg) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"PREFER_JPEG",prefer_jpg,&result)); } inline void XODOutputOptions::SetJPGQuality(UInt32 quality) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"JPEG_QUALITY",quality,&result)); } inline void XODOutputOptions::SetSilverlightTextWorkaround(bool workaround) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"REMOVE_ROTATED_TEXT",workaround,&result)); } inline void XODOutputOptions::SetAnnotationOutput(enum AnnotationOutputFlag annot_output) { TRN_Obj result; switch (annot_output) { case e_internal_xfdf: REX(TRN_ObjPutName(m_obj, "ANNOTATION_OUTPUT", "INTERNAL", &result)); break; case e_external_xfdf: REX(TRN_ObjPutName(m_obj, "ANNOTATION_OUTPUT", "EXTERNAL", &result)); break; case e_flatten: REX(TRN_ObjPutName(m_obj, "ANNOTATION_OUTPUT", "FLATTEN", &result)); break; } } inline void XODOutputOptions::SetExternalParts(bool generate) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "EXTERNAL_PARTS", generate, &result)); } inline void XODOutputOptions::SetEncryptPassword(const char* pass) { TRN_Obj result; REX(TRN_ObjPutName(m_obj, "ENCRYPT_PASSWORD", pass, &result)); } inline void XODOutputOptions::UseSilverlightFlashCompatible(bool compatible) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "COMPATIBLE_XOD", compatible, &result)); } inline HTMLOutputOptions::HTMLOutputOptions() { m_obj=m_objset.CreateDict().mp_obj; } inline void HTMLOutputOptions::SetPreferJPG(bool prefer_jpg) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"PREFER_JPEG",prefer_jpg,&result)); } inline void HTMLOutputOptions::SetJPGQuality(UInt32 quality) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"JPEG_QUALITY",quality,&result)); } inline void HTMLOutputOptions::SetDPI(UInt32 dpi) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"DPI",dpi,&result)); } inline void HTMLOutputOptions::SetMaximumImagePixels(UInt32 max_pixels) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"MAX_IMAGE_PIXELS",max_pixels,&result)); } inline void HTMLOutputOptions::SetReflow(bool reflow) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"REFLOW",reflow,&result)); } inline void HTMLOutputOptions::SetScale(double scale) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"SCALE",scale,&result)); } inline void HTMLOutputOptions::SetExternalLinks(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"EXTERNAL_LINKS",enable,&result)); } inline void HTMLOutputOptions::SetInternalLinks(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"INTERNAL_LINKS",enable,&result)); } inline void HTMLOutputOptions::SetSimplifyText(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"SIMPLIFY_TEXT",enable,&result)); } inline void HTMLOutputOptions::SetReportFile(const UString& path) { TRN_Obj result; REX(TRN_ObjPutText(m_obj,"REPORT_FILE",path.mp_impl,&result)); } inline TiffOutputOptions::TiffOutputOptions() { m_obj=m_objset.CreateDict().mp_obj; } inline void TiffOutputOptions::SetBox(enum Page::Box type) { TRN_Obj result; switch (type) { case e_Page_media: REX(TRN_ObjPutName(m_obj, "BOX", "media", &result)); break; case e_Page_crop: REX(TRN_ObjPutName(m_obj, "BOX", "crop", &result)); break; case e_Page_bleed: REX(TRN_ObjPutName(m_obj, "BOX", "bleed", &result)); break; case e_Page_trim: REX(TRN_ObjPutName(m_obj, "BOX", "trim", &result)); break; case e_Page_art: REX(TRN_ObjPutName(m_obj, "BOX", "art", &result)); break; } } inline void TiffOutputOptions::SetRotate(enum Page::Rotate rotation) { TRN_Obj result; switch (rotation) { case e_Page_0: REX(TRN_ObjPutName(m_obj, "ROTATE", "0", &result)); break; case e_Page_90: REX(TRN_ObjPutName(m_obj, "ROTATE", "90", &result)); break; case e_Page_180: REX(TRN_ObjPutName(m_obj, "ROTATE", "180", &result)); break; case e_Page_270: REX(TRN_ObjPutName(m_obj, "ROTATE", "270", &result)); break; } } inline void TiffOutputOptions::SetClip(double x1, double y1, double x2, double y2) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"CLIP_X1",x1,&result)); REX(TRN_ObjPutNumber(m_obj,"CLIP_Y1",y1,&result)); REX(TRN_ObjPutNumber(m_obj,"CLIP_X2",x2,&result)); REX(TRN_ObjPutNumber(m_obj,"CLIP_Y2",y2,&result)); } inline void TiffOutputOptions::SetPages(const char* page_desc) { TRN_Obj result; REX(TRN_ObjPutName(m_obj, "PAGES", page_desc, &result)); } inline void TiffOutputOptions::SetOverprint(enum PDFRasterizer::OverprintPreviewMode mode) { TRN_Obj result; SetOverprintImpl(m_obj, mode, &result); } inline void TiffOutputOptions::SetCMYK(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "CMYK", BToTB(enable), &result)); } inline void TiffOutputOptions::SetDither(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "DITHER", BToTB(enable), &result)); } inline void TiffOutputOptions::SetGray(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "GRAY", BToTB(enable), &result)); } inline void TiffOutputOptions::SetMono(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "MONO", BToTB(enable), &result)); } inline void TiffOutputOptions::SetAnnots(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "ANNOTS", BToTB(enable), &result)); } inline void TiffOutputOptions::SetSmooth(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "SMOOTH", BToTB(enable), &result)); } inline void TiffOutputOptions::SetPrintmode(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "PRINTMODE", BToTB(enable), &result)); } inline void TiffOutputOptions::SetTransparentPage(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "TRANSPARENT_PAGE", BToTB(enable), &result)); } inline void TiffOutputOptions::SetPalettized(bool enable) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj, "PALETTIZED", BToTB(enable), &result)); } inline void TiffOutputOptions::SetDPI(double dpi) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"DPI",dpi,&result)); } inline void TiffOutputOptions::SetGamma(double gamma) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"GAMMA",gamma,&result)); } inline void TiffOutputOptions::SetHRes(int hres) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"HRES",static_cast<double>(hres),&result)); } inline void TiffOutputOptions::SetVRes(int vres) { TRN_Obj result; REX(TRN_ObjPutNumber(m_obj,"VRES",static_cast<double>(vres),&result)); } inline EPUBOutputOptions::EPUBOutputOptions() { m_obj=m_objset.CreateDict().mp_obj; } inline void EPUBOutputOptions::SetExpanded(bool expanded) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"EPUB_EXPANDED",expanded,&result)); } inline void EPUBOutputOptions::SetReuseCover(bool reuse) { TRN_Obj result; REX(TRN_ObjPutBool(m_obj,"EPUB_REUSE_COVER",reuse,&result)); } inline void Convert::ToXps(PDFDoc & in_pdfdoc, const UString & in_filename) { XPSOutputOptions options; Convert::ToXps( in_pdfdoc, in_filename, options); } inline void Convert::ToXps( PDFDoc & in_pdfdoc, const UString & in_filename, const XPSOutputOptions& options) { REX(TRN_ConvertToXps(in_pdfdoc.mp_doc,in_filename.mp_impl, options.m_obj)); } inline void Convert::ToXps(const UString & in_inputFilename, const UString & in_outputFilename) { XPSOutputOptions options; Convert::ToXps( in_inputFilename, in_outputFilename, options); } inline void Convert::ToXps( const UString & in_inputFilename, const UString & in_outputFilename, const XPSOutputOptions& options) { REX(TRN_ConvertFileToXps(in_inputFilename.mp_impl, in_outputFilename.mp_impl, options.m_obj)); } inline void Convert::ToXod(const UString & in_filename, const UString & out_filename) { XODOutputOptions options; Convert::ToXod( in_filename, out_filename, options); } inline void Convert::ToXod( const UString & in_filename, const UString & out_filename, const XODOutputOptions& options) { REX(TRN_ConvertFileToXod(in_filename.mp_impl, out_filename.mp_impl, options.m_obj)); } inline void Convert::ToXod(PDFDoc & in_pdfdoc, const UString & out_filename) { XODOutputOptions options; Convert::ToXod( in_pdfdoc, out_filename, options); } inline void Convert::ToXod(PDFDoc & in_pdfdoc, const UString & out_filename, const XODOutputOptions& options) { REX(TRN_ConvertToXod(in_pdfdoc.mp_doc, out_filename.mp_impl, options.m_obj)); } inline Filters::Filter Convert::ToXod(const UString & in_filename) { XODOutputOptions options; return Convert::ToXod( in_filename, options); } inline Filters::Filter Convert::ToXod( const UString & in_filename, const XODOutputOptions& options) { TRN_Filter result; REX(TRN_ConvertFileToXodStream(in_filename.mp_impl, options.m_obj, &result)); return Filters::Filter(result,true); } inline Filters::Filter Convert::ToXod(PDFDoc& in_pdfdoc) { XODOutputOptions options; return Convert::ToXod( in_pdfdoc, options); } inline Filters::Filter Convert::ToXod(PDFDoc& in_pdfdoc, const XODOutputOptions& options) { TRN_Filter result; REX(TRN_ConvertToXodStream(in_pdfdoc.mp_doc, options.m_obj, &result)); // try return Filters::Filter(result,true); } inline ConversionMonitor Convert::ToXodWithMonitor(PDFDoc& in_pdfdoc) { XODOutputOptions options; return Convert::ToXodWithMonitor( in_pdfdoc, options); } inline ConversionMonitor Convert::ToXodWithMonitor(PDFDoc& in_pdfdoc, const XODOutputOptions& options) { TRN_ConversionMonitor result; REX(TRN_ConvertToXodWithMonitor(in_pdfdoc.mp_doc, options.m_obj, &result)); ConversionMonitor monitor = ConversionMonitor(result,true); return monitor; } inline ConversionMonitor::ConversionMonitor(TRN_ConversionMonitor impl, bool is_owner) { mp_impl=impl; m_owner=is_owner; } inline ConversionMonitor::ConversionMonitor() : mp_impl(0), m_owner(true) {} inline bool ConversionMonitor::Next() { RetBool(TRN_ConversionMonitorNext(mp_impl,&result)); } inline bool ConversionMonitor::Ready() { RetBool(TRN_ConversionMonitorReady(mp_impl,&result)); } inline UInt32 ConversionMonitor::Progress() { UInt32 result; REX(TRN_ConversionMonitorProgress(mp_impl,&result)); return result; } inline Filters::Filter ConversionMonitor::Filter() { TRN_Filter result; REX(TRN_ConversionMonitorFilter(mp_impl, &result)); return Filters::Filter(result,true); } inline ConversionMonitor::ConversionMonitor(const ConversionMonitor& copy) { if(copy.m_owner) { ((ConversionMonitor&)copy).m_owner = false; m_owner=true; } else { m_owner=false; } mp_impl=copy.mp_impl; } inline ConversionMonitor& ConversionMonitor::operator =(const ConversionMonitor& other) { if(m_owner) { REX(TRN_ConversionMonitorDestroy(mp_impl)); mp_impl=0; } if(other.m_owner) { ((ConversionMonitor&)other).m_owner = false; m_owner=true; } else { m_owner=false; } mp_impl=other.mp_impl; return *this; } inline ConversionMonitor::~ConversionMonitor() { if(m_owner) { DREX(mp_impl, TRN_ConversionMonitorDestroy(mp_impl)); } } inline void ConversionMonitor::Destroy() { if(m_owner) { REX(TRN_ConversionMonitorDestroy(mp_impl)); mp_impl = 0; } } inline void Convert::ToHtml(const UString & in_filename, const UString & out_path) { HTMLOutputOptions options; Convert::ToHtml( in_filename, out_path, options); } inline void Convert::ToHtml(const UString & in_filename, const UString & out_path, const HTMLOutputOptions& options) { REX(TRN_ConvertFileToHtml(in_filename.mp_impl, out_path.mp_impl, options.m_obj)); } inline void Convert::ToHtml(PDFDoc & in_pdfdoc, const UString & out_path) { HTMLOutputOptions options; Convert::ToHtml( in_pdfdoc, out_path, options); } inline void Convert::ToHtml(PDFDoc & in_pdfdoc, const UString & out_path, const HTMLOutputOptions& options) { REX(TRN_ConvertToHtml(in_pdfdoc.mp_doc, out_path.mp_impl, options.m_obj)); } inline void Convert::ToTiff(const UString & in_filename, const UString & out_path) { TiffOutputOptions options; Convert::ToTiff( in_filename, out_path, options); } inline void Convert::ToTiff(const UString & in_filename, const UString & out_path, const TiffOutputOptions& options) { REX(TRN_ConvertFileToTiff(in_filename.mp_impl, out_path.mp_impl, options.m_obj)); } inline void Convert::ToTiff(PDFDoc & in_pdfdoc, const UString & out_path) { TiffOutputOptions options; Convert::ToTiff( in_pdfdoc, out_path, options); } inline void Convert::ToTiff(PDFDoc & in_pdfdoc, const UString & out_path, const TiffOutputOptions& options) { REX(TRN_ConvertToTiff(in_pdfdoc.mp_doc, out_path.mp_impl, options.m_obj)); } inline void Convert::ToEpub(const UString & in_filename, const UString & out_path) { HTMLOutputOptions html_options; EPUBOutputOptions epub_options; Convert::ToEpub( in_filename, out_path, html_options, epub_options); } inline void Convert::ToEpub(const UString & in_filename, const UString & out_path, const HTMLOutputOptions& html_options) { EPUBOutputOptions epub_options; Convert::ToEpub( in_filename, out_path, html_options, epub_options); } inline void Convert::ToEpub(const UString & in_filename, const UString & out_path, const HTMLOutputOptions& html_options, const EPUBOutputOptions& epub_options) { REX(TRN_ConvertFileToEpub(in_filename.mp_impl, out_path.mp_impl, html_options.m_obj, epub_options.m_obj)); } inline void Convert::ToEpub(PDFDoc & in_pdfdoc, const UString & out_path) { HTMLOutputOptions html_options; EPUBOutputOptions epub_options; Convert::ToEpub( in_pdfdoc, out_path, html_options, epub_options); } inline void Convert::ToEpub(PDFDoc & in_pdfdoc, const UString & out_path, const HTMLOutputOptions& html_options) { EPUBOutputOptions epub_options; Convert::ToEpub( in_pdfdoc, out_path, html_options, epub_options); } inline void Convert::ToEpub(PDFDoc & in_pdfdoc, const UString & out_path, const HTMLOutputOptions& html_options, const EPUBOutputOptions& epub_options) { REX(TRN_ConvertToEpub(in_pdfdoc.mp_doc, out_path.mp_impl, html_options.m_obj, epub_options.m_obj)); } inline DocumentConversion Convert::WordToPDFConversion(PDFDoc & in_pdfdoc, const UString & in_filename, WordToPDFOptions* options) { DocumentConversion ret((TRN_DocumentConversion)0); // a pointer to a pointer to an sdf doc PDFDoc* ptr = &in_pdfdoc; // a pointer to a pointer to an sdf doc TRN_PDFDoc* to_pass = (TRN_PDFDoc*)ptr; TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; REX(TRN_ConvertWordToPdfConversion(to_pass, in_filename.mp_impl, opt_ptr ,&ret.m_impl)); return ret; } inline void Convert::WordToPDF(PDFDoc & in_pdfdoc, const UString & in_filename, WordToPDFOptions* options) { TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; REX(TRN_ConvertWordToPdf(in_pdfdoc.mp_doc, in_filename.mp_impl, opt_ptr)); } inline DocumentConversion Convert::WordToPDFConversion(PDFDoc & in_pdfdoc, Filters::Filter in_data, WordToPDFOptions* options) { DocumentConversion ret((TRN_DocumentConversion)0); // a pointer to a pointer to an sdf doc PDFDoc* ptr = &in_pdfdoc; // a pointer to a pointer to an sdf doc TRN_PDFDoc* to_pass = (TRN_PDFDoc*)ptr; TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; // make sure the filter doesn't die as it leaves this method scope (the conversion will take ownership) in_data.m_owner = false; REX(TRN_ConvertWordToPdfConversionWithFilter(to_pass, in_data.m_impl, opt_ptr ,&ret.m_impl)); return ret; } inline void Convert::WordToPDF(PDFDoc & in_pdfdoc, Filters::Filter in_data, WordToPDFOptions* options) { TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; // make sure the filter doesn't double-delete as it leaves this method scope // (the conversion will take care of deletion) in_data.m_owner = false; REX(TRN_ConvertWordToPdfWithFilter(in_pdfdoc.mp_doc, in_data.m_impl, opt_ptr)); } ////////////////////////////////////////////////////////////////////////// inline DocumentConversion Convert::StreamingPDFConversion(PDFDoc & in_pdfdoc, const UString & in_filename, ConversionOptions* options) { DocumentConversion ret((TRN_DocumentConversion)0); // a pointer to a pointer to an sdf doc PDFDoc* ptr = &in_pdfdoc; // a pointer to a pointer to an sdf doc TRN_PDFDoc* to_pass = (TRN_PDFDoc*)ptr; TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; REX(TRN_ConvertStreamingPdfConversionWithPdfAndPath(to_pass, in_filename.mp_impl, opt_ptr, &ret.m_impl)); return ret; } inline DocumentConversion Convert::StreamingPDFConversion(const UString & in_filename, ConversionOptions* options) { DocumentConversion ret((TRN_DocumentConversion)0); TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; REX(TRN_ConvertStreamingPdfConversionWithPath(in_filename.mp_impl, opt_ptr, &ret.m_impl)); return ret; } inline void Convert::OfficeToPDF(PDFDoc & in_pdfdoc, const UString & in_filename, ConversionOptions* options) { TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; REX(TRN_ConvertWordToPdf(in_pdfdoc.mp_doc, in_filename.mp_impl, opt_ptr)); } inline DocumentConversion Convert::StreamingPDFConversion(PDFDoc & in_pdfdoc, Filters::Filter in_data, ConversionOptions* options) { DocumentConversion ret((TRN_DocumentConversion)0); // a pointer to a pointer to an sdf doc PDFDoc* ptr = &in_pdfdoc; // a pointer to a pointer to an sdf doc TRN_PDFDoc* to_pass = (TRN_PDFDoc*)ptr; TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; // make sure the filter doesn't die as it leaves this method scope (the conversion will take ownership) in_data.m_owner = false; REX(TRN_ConvertStreamingPdfConversionWithPdfAndFilter(to_pass, in_data.m_impl, opt_ptr, &ret.m_impl)); return ret; } inline DocumentConversion Convert::StreamingPDFConversion(Filters::Filter in_data, ConversionOptions* options) { DocumentConversion ret((TRN_DocumentConversion)0); TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; // make sure the filter doesn't die as it leaves this method scope (the conversion will take ownership) in_data.m_owner = false; REX(TRN_ConvertStreamingPdfConversionWithFilter(in_data.m_impl, opt_ptr, &ret.m_impl)); return ret; } inline void Convert::OfficeToPDF(PDFDoc & in_pdfdoc, Filters::Filter in_data, ConversionOptions* options) { TRN_Obj opt_ptr = options ? options->GetInternalObj().mp_obj : 0; // make sure the filter doesn't double-delete as it leaves this method scope // (the conversion will take care of deletion) in_data.m_owner = false; REX(TRN_ConvertWordToPdfWithFilter(in_pdfdoc.mp_doc, in_data.m_impl, opt_ptr)); } ////////////////////////////////////////////////////////////////////////// inline void Convert::ToPdf(PDFDoc & in_pdfdoc, const UString & in_filename) { REX(TRN_ConvertToPdf(in_pdfdoc.mp_doc, in_filename.mp_impl)); } inline bool Convert::RequiresPrinter(const UString & in_filename) { RetBool(TRN_ConvertRequiresPrinter(in_filename.mp_impl, &result)); } inline void Printer::Install(const UString & in_printerName) { REX(TRN_ConvertPrinterInstall(in_printerName.mp_impl)); } inline void Printer::Uninstall() { REX(TRN_ConvertPrinterUninstall()); } inline const UString Printer::GetPrinterName() { RetStr(TRN_ConvertPrinterGetPrinterName(&result)); } inline void Printer::SetPrinterName(const UString & in_printerName) { REX(TRN_ConvertPrinterSetPrinterName(in_printerName.mp_impl)); } inline bool Printer::IsInstalled(const UString & in_printerName) { RetBool(TRN_ConvertPrinterIsInstalled(in_printerName.mp_impl,&result)); } inline void Printer::SetMode(Mode mode) { REX(TRN_ConvertPrinterSetMode((enum TRN_ConvertPrinterMode)mode)); } inline Printer::Mode Printer::GetMode() { enum TRN_ConvertPrinterMode result; REX(TRN_ConvertPrinterGetMode(&result)); return (Printer::Mode)result; } void SetFlattenContentImpl(TRN_Obj obj, enum Convert::FlattenFlag flatten, TRN_Obj* result) { switch (flatten) { case Convert::e_off: REX(TRN_ObjPutName(obj, "FLATTEN_CONTENT", "OFF", result)); break; case Convert::e_simple: REX(TRN_ObjPutName(obj, "FLATTEN_CONTENT", "SIMPLE", result)); break; case Convert::e_fast: REX(TRN_ObjPutName(obj, "FLATTEN_CONTENT", "FAST", result)); break; case Convert::e_high_quality: REX(TRN_ObjPutName(obj, "FLATTEN_CONTENT", "HIGH_QUALITY", result)); } } void SetFlattenThresholdImpl(TRN_Obj obj, enum Convert::FlattenThresholdFlag threshold, TRN_Obj* result) { switch (threshold) { case Convert::e_very_strict: REX(TRN_ObjPutName(obj, "FLATTEN_THRESHOLD", "VERY_STRICT", result)); break; case Convert::e_strict: REX(TRN_ObjPutName(obj, "FLATTEN_THRESHOLD", "STRICT", result)); break; case Convert::e_default: REX(TRN_ObjPutName(obj, "FLATTEN_THRESHOLD", "DEFAULT", result)); break; case Convert::e_keep_most: REX(TRN_ObjPutName(obj, "FLATTEN_THRESHOLD", "KEEP_MOST", result)); break; case Convert::e_keep_all: REX(TRN_ObjPutName(obj, "FLATTEN_THRESHOLD", "KEEP_ALL", result)); break; } } void SetOverprintImpl(TRN_Obj obj, enum PDFRasterizer::OverprintPreviewMode mode, TRN_Obj* result) { switch (mode) { case PDFRasterizer::e_op_off: REX(TRN_ObjPutName(obj, "OVERPRINT_MODE", "OFF", result)); break; case PDFRasterizer::e_op_on: REX(TRN_ObjPutName(obj, "OVERPRINT_MODE", "ON", result)); break; case PDFRasterizer::e_op_pdfx_on: REX(TRN_ObjPutName(obj, "OVERPRINT_MODE", "PDFX", result)); break; } }
hiljusti/codewars-solutions
javascript/a-no-more-bugs-trilogy-episode-3-make-a-player/solution.js
<reponame>hiljusti/codewars-solutions // https://www.codewars.com/kata/5630c850ed4343c1d0000083 let Player = function(name, position, age, dribbling, pass, shoot) { return {name, position, age, dribbling, pass, shoot}; };
jekyll-one-org/j1-template
packages/300_template_src/assets/themes/j1/adapter/js/bmd.js
--- regenerate: false --- {% capture cache %} {% comment %} # ----------------------------------------------------------------------------- # ~/assets/themes/j1/adapter/js/bmd.js # Liquid template to adapt Bootrap Material Design (BMD) # # Product/Info: # https://jekyll.one # Copyright (C) 2021 <NAME> # # J1 Template is licensed under the MIT License. # For details, see https://jekyll.one # ----------------------------------------------------------------------------- # Test data: # {{ liquid_var | debug }} # ----------------------------------------------------------------------------- {% endcomment %} /* # ----------------------------------------------------------------------------- # ~/assets/themes/j1/adapter/js/bmd.js # J1 Adapter for BMD # # Product/Info: # https://jekyll.one # # Copyright (C) 2021 <NAME> # # J1 Template is licensed under the MIT License. # For details, see https://jekyll.one # ----------------------------------------------------------------------------- # Adapter generated: {{site.time}} # ----------------------------------------------------------------------------- */ // ----------------------------------------------------------------------------- // ESLint shimming // ----------------------------------------------------------------------------- /* eslint indent: "off" */ // ----------------------------------------------------------------------------- 'use strict'; {% comment %} Main -------------------------------------------------------------------------------- {% endcomment %} j1.adapter['bmd'] = (function (j1, window) { {% comment %} Set global variables ------------------------------------------------------------------------------ {% endcomment %} var environment = '{{environment}}'; var moduleOptions = {}; var _this; var logger; var logText; // --------------------------------------------------------------------------- // Helper functions // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Main object // --------------------------------------------------------------------------- return { // ------------------------------------------------------------------------- // Initializer // ------------------------------------------------------------------------- init: function (options) { // ----------------------------------------------------------------------- // globals // ----------------------------------------------------------------------- _this = j1.adapter.bmd; logger = log4javascript.getLogger('j1.adapter.bmd'); // initialize state flag _this.setState('started'); logger.info('\n' + 'state: ' + _this.getState()); logger.info('\n' + 'module is being initialized'); // ----------------------------------------------------------------------- // Default module settings // ----------------------------------------------------------------------- var settings = $.extend({ module_name: 'j1.adapter.bmd', generated: '{{site.time}}' }, options); // ----------------------------------------------------------------------- // BMD initializer // ----------------------------------------------------------------------- var log_text = '\n' + 'BMD is being initialized'; logger.info(log_text); var dependencies_met_j1_finished = setInterval(function() { if (j1.getState() == 'finished') { $('body').bootstrapMaterialDesign(); _this.setState('finished'); logger.info('\n' + 'state: ' + _this.getState()); clearInterval(dependencies_met_j1_finished); } // END dependencies_met_j1_finished }, 25); }, // END init // ------------------------------------------------------------------------- // messageHandler: MessageHandler for J1 CookieConsent module // Manage messages send from other J1 modules // ------------------------------------------------------------------------- messageHandler: function (sender, message) { var json_message = JSON.stringify(message, undefined, 2); logText = '\n' + 'received message from ' + sender + ': ' + json_message; logger.debug(logText); // ----------------------------------------------------------------------- // Process commands|actions // ----------------------------------------------------------------------- if (message.type === 'command' && message.action === 'module_initialized') { // // Place handling of command|action here // logger.info('\n' + message.text); } // // Place handling of other command|action here // return true; }, // END messageHandler // ------------------------------------------------------------------------- // setState() // Sets the current (processing) state of the module // ------------------------------------------------------------------------- setState: function (stat) { _this.state = stat; }, // END setState // ------------------------------------------------------------------------- // getState() // Returns the current (processing) state of the module // ------------------------------------------------------------------------- getState: function () { return _this.state; } // END getState }; // END return })(j1, window); {% endcapture %} {% if production %} {{ cache | minifyJS }} {% else %} {{ cache | strip_empty_lines }} {% endif %} {% assign cache = nil %}
ChunMengLu/Easy4JFinal
easy-core/src/main/java/net/dreamlu/easy/commons/searcher/ResourceMatcherSearcher.java
<reponame>ChunMengLu/Easy4JFinal<gh_stars>1-10 package net.dreamlu.easy.commons.searcher; import java.util.LinkedHashSet; import java.util.Set; import net.dreamlu.easy.commons.searcher.FileSearcher.FileEntry; import net.dreamlu.easy.commons.utils.Matcher; /** * 文件查找查找器 * 从classpath或者jar中查找 * @author L.cm */ public class ResourceMatcherSearcher { /** * 获取文件 * @param packageName 包名数组 * @param pattern 文件匹配 支持*和? * @return 文件集合 */ public static Set<String> getFiles(String[] packageNames, final String pattern) { String[] patterns = new String[]{pattern}; return getFiles(packageNames, patterns); } /** * 获取文件 * @param packageNames 包名数组 * @param patterns 文件匹配 支持*和? * @return 文件集合 */ public static Set<String> getFiles(String[] packageNames, final String[] patterns) { final Set<String> fileSet = new LinkedHashSet<String>(); FileSearcher finder = new FileSearcher() { @Override public void visitFileEntry(FileEntry file) { if (isMatch(file, patterns)) { String fileName = file.getQualifiedFileName(); fileSet.add(fileName); } } }; finder.lookupClasspath(packageNames); return fileSet; } private static boolean isMatch(FileEntry file, String[] patterns) { return !file.isDirectory() && Matcher.matchName(file.getName(), patterns); } }
adilbenmoussa/apollo-client
packages/apollo-utilities/lib/util/stripSymbols.js
<filename>packages/apollo-utilities/lib/util/stripSymbols.js define(['require', 'exports'], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function stripSymbols(data) { return JSON.parse(JSON.stringify(data)); } exports.stripSymbols = stripSymbols; }); //# sourceMappingURL=stripSymbols.js.map
df-service-e2e-test/x_khu2_9th_stress_test_5
hazelcast/src/test/java/com/hazelcast/config/CacheEvictionConfigTest.java
<gh_stars>1-10 /* * Copyright (c) 2008-2019, Hazelcast, 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. */ package com.hazelcast.config; import com.hazelcast.config.CacheEvictionConfig.CacheMaxSizePolicy; import com.hazelcast.config.EvictionConfig.MaxSizePolicy; import com.hazelcast.internal.eviction.EvictableEntryView; import com.hazelcast.internal.eviction.EvictionPolicyComparator; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static com.hazelcast.config.CacheEvictionConfig.CacheMaxSizePolicy.fromMaxSizePolicy; import static com.hazelcast.config.EvictionPolicy.LFU; import static com.hazelcast.config.EvictionPolicy.LRU; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class CacheEvictionConfigTest { @Test public void test_cacheEvictionConfig_shouldInheritConstructors_from_evictionConfig_correctly() { CacheEvictionConfig cacheEvictionConfig1 = new CacheEvictionConfig(1000, MaxSizePolicy.ENTRY_COUNT, LFU); assertEquals(1000, cacheEvictionConfig1.getSize()); assertEquals(MaxSizePolicy.ENTRY_COUNT, cacheEvictionConfig1.getMaximumSizePolicy()); assertEquals(LFU, cacheEvictionConfig1.getEvictionPolicy()); assertNotNull(cacheEvictionConfig1.toString()); CacheEvictionConfig cacheEvictionConfig2 = new CacheEvictionConfig(1000, CacheMaxSizePolicy.ENTRY_COUNT, LFU); assertEquals(1000, cacheEvictionConfig2.getSize()); assertEquals(CacheMaxSizePolicy.ENTRY_COUNT, cacheEvictionConfig2.getMaxSizePolicy()); assertEquals(LFU, cacheEvictionConfig2.getEvictionPolicy()); assertNotNull(cacheEvictionConfig2.toString()); String comparatorName = "myComparator"; CacheEvictionConfig cacheEvictionConfig3 = new CacheEvictionConfig(1000, MaxSizePolicy.ENTRY_COUNT, comparatorName); assertEquals(1000, cacheEvictionConfig3.getSize()); assertEquals(MaxSizePolicy.ENTRY_COUNT, cacheEvictionConfig3.getMaximumSizePolicy()); assertEquals(comparatorName, cacheEvictionConfig3.getComparatorClassName()); assertNotNull(cacheEvictionConfig3.toString()); CacheEvictionConfig cacheEvictionConfig4 = new CacheEvictionConfig(1000, CacheMaxSizePolicy.ENTRY_COUNT, comparatorName); assertEquals(1000, cacheEvictionConfig4.getSize()); assertEquals(CacheMaxSizePolicy.ENTRY_COUNT, cacheEvictionConfig4.getMaxSizePolicy()); assertEquals(comparatorName, cacheEvictionConfig4.getComparatorClassName()); assertNotNull(cacheEvictionConfig4.toString()); EvictionPolicyComparator comparator = new EvictionPolicyComparator() { @Override public int compare(EvictableEntryView e1, EvictableEntryView e2) { return 0; } }; CacheEvictionConfig cacheEvictionConfig5 = new CacheEvictionConfig(1000, MaxSizePolicy.ENTRY_COUNT, comparator); assertEquals(1000, cacheEvictionConfig5.getSize()); assertEquals(MaxSizePolicy.ENTRY_COUNT, cacheEvictionConfig5.getMaximumSizePolicy()); assertEquals(comparator, cacheEvictionConfig5.getComparator()); assertNotNull(cacheEvictionConfig5.toString()); CacheEvictionConfig cacheEvictionConfig6 = new CacheEvictionConfig(1000, CacheMaxSizePolicy.ENTRY_COUNT, comparator); assertEquals(1000, cacheEvictionConfig6.getSize()); assertEquals(CacheMaxSizePolicy.ENTRY_COUNT, cacheEvictionConfig6.getMaxSizePolicy()); assertEquals(comparator, cacheEvictionConfig6.getComparator()); assertNotNull(cacheEvictionConfig6.toString()); } @Test public void cacheEvictionConfig_shouldInheritAttributes_from_evictionConfig_correctly() { CacheEvictionConfig cacheEvictionConfig = new CacheEvictionConfig(); cacheEvictionConfig.setComparatorClassName("myComparator"); cacheEvictionConfig.setEvictionPolicy(LRU); assertEquals("myComparator", cacheEvictionConfig.getComparatorClassName()); assertEquals(LRU, cacheEvictionConfig.getEvictionPolicy()); assertNotNull(cacheEvictionConfig.toString()); CacheEvictionConfig cacheEvictionConfigReadOnly = cacheEvictionConfig.getAsReadOnly(); assertNotNull(cacheEvictionConfigReadOnly); assertEquals("myComparator", cacheEvictionConfigReadOnly.getComparatorClassName()); assertEquals(LRU, cacheEvictionConfigReadOnly.getEvictionPolicy()); assertNotNull(cacheEvictionConfigReadOnly.toString()); } @Test public void cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig_when_maxSizePolicyIs_entryCount() { cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig(MaxSizePolicy.ENTRY_COUNT); } @Test public void cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig_when_maxSizePolicyIs_usedNativeMemorySize() { cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig(MaxSizePolicy.USED_NATIVE_MEMORY_SIZE); } @Test public void cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig_when_maxSizePolicyIs_usedNativeMemoryPercentage() { cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig(MaxSizePolicy.USED_NATIVE_MEMORY_PERCENTAGE); } @Test public void cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig_when_maxSizePolicyIs_freeNativeMemorySize() { cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig(MaxSizePolicy.FREE_NATIVE_MEMORY_SIZE); } @Test public void cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig_when_maxSizePolicyIs_freeNativeMemoryPercentage() { cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig(MaxSizePolicy.FREE_NATIVE_MEMORY_PERCENTAGE); } private void cacheEvictionConfig_shouldDelegate_maxSizePolicy_of_evictionConfig(MaxSizePolicy maxSizePolicy) { CacheMaxSizePolicy cacheMaxSizePolicy = fromMaxSizePolicy(maxSizePolicy); CacheEvictionConfig cacheEvictionConfig = new CacheEvictionConfig(); cacheEvictionConfig.setMaxSizePolicy(cacheMaxSizePolicy); assertEquals(maxSizePolicy, cacheEvictionConfig.getMaxSizePolicy().toMaxSizePolicy()); } }
gczuczy/sfticks
src/FG/DescObject.cc
#include "FG/DescObject.hh" #include "SFT/Exception.hh" #include "misc.hh" namespace FG { static std::map<std::string, uint32_t> g_stacksizes{ {"SS_ONE", 1}, {"SS_SMALL", 50}, {"SS_MEDIUM", 100}, {"SS_BIG", 200}, {"SS_HUGE", 500}, {"SS_FLUID", 0}, }; static std::map<std::string, EResourceForm> g_resourceforms{ {"RF_INVALID", EResourceForm::INVALID}, {"RF_SOLID", EResourceForm::SOLID}, {"RF_LIQUID", EResourceForm::LIQUID}, {"RF_GAS", EResourceForm::GAS}, {"RF_HEAT", EResourceForm::HEAT}, }; std::set<std::string> DescObject::nativeclasses{ "Class'/Script/FactoryGame.FGItemDescriptor'", "Class'/Script/FactoryGame.FGItemDescriptorBiomass'", "Class'/Script/FactoryGame.FGItemDescAmmoTypeProjectile'", "Class'/Script/FactoryGame.FGItemDescAmmoTypeInstantHit'", "Class'/Script/FactoryGame.FGResourceDescriptor'", "Class'/Script/FactoryGame.FGItemDescAmmoTypeColorCartridge'", "Class'/Script/FactoryGame.FGGasMask'", "Class'/Script/FactoryGame.FGItemDescriptorNuclearFuel'", }; DescObject::DescObject(nlohmann::json& _json): JSONObject(ObjectType::DESC) { registerHandler("mForm", [&](nlohmann::json &_json) { auto strform = _json.get<std::string>(); auto it = g_resourceforms.find(strform); if ( it == g_resourceforms.end() ) { EXCEPTION(strprintf("Unable to find form %s", strform.c_str())); } c_form = it->second; }); registerHandler("mStackSize", [&](nlohmann::json &_json) { auto strsize = _json.get<std::string>(); auto it = g_stacksizes.find(strsize); if ( it == g_stacksizes.end() ) { EXCEPTION(strprintf("Unable to find stacksize %s", strsize.c_str())); } c_stacksize = it->second; }); parseData(_json); } DescObject::~DescObject() { } }
Keneral/aframeworks
support/v7/recyclerview/src/android/support/v7/widget/StaggeredGridLayoutManager.java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v7.widget; import static android.support.v7.widget.LayoutState.ITEM_DIRECTION_HEAD; import static android.support.v7.widget.LayoutState.ITEM_DIRECTION_TAIL; import static android.support.v7.widget.LayoutState.LAYOUT_END; import static android.support.v7.widget.LayoutState.LAYOUT_START; import static android.support.v7.widget.RecyclerView.NO_POSITION; import android.content.Context; import android.graphics.PointF; import android.graphics.Rect; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewCompat; import android.support.v4.view.accessibility.AccessibilityEventCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.view.accessibility.AccessibilityRecordCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.List; /** * A LayoutManager that lays out children in a staggered grid formation. * It supports horizontal & vertical layout as well as an ability to layout children in reverse. * <p> * Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps, * StaggeredGridLayoutManager can offset spans independently or move items between spans. You can * control this behavior via {@link #setGapStrategy(int)}. */ public class StaggeredGridLayoutManager extends RecyclerView.LayoutManager { public static final String TAG = "StaggeredGridLayoutManager"; private static final boolean DEBUG = false; public static final int HORIZONTAL = OrientationHelper.HORIZONTAL; public static final int VERTICAL = OrientationHelper.VERTICAL; /** * Does not do anything to hide gaps. */ public static final int GAP_HANDLING_NONE = 0; /** * @deprecated No longer supported. */ @SuppressWarnings("unused") @Deprecated public static final int GAP_HANDLING_LAZY = 1; /** * When scroll state is changed to {@link RecyclerView#SCROLL_STATE_IDLE}, StaggeredGrid will * check if there are gaps in the because of full span items. If it finds, it will re-layout * and move items to correct positions with animations. * <p> * For example, if LayoutManager ends up with the following layout due to adapter changes: * <pre> * AAA * _BC * DDD * </pre> * <p> * It will animate to the following state: * <pre> * AAA * BC_ * DDD * </pre> */ public static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS = 2; private static final int INVALID_OFFSET = Integer.MIN_VALUE; /** * While trying to find next view to focus, LayoutManager will not try to scroll more * than this factor times the total space of the list. If layout is vertical, total space is the * height minus padding, if layout is horizontal, total space is the width minus padding. */ private static final float MAX_SCROLL_FACTOR = 1 / 3f; /** * Number of spans */ private int mSpanCount = -1; private Span[] mSpans; /** * Primary orientation is the layout's orientation, secondary orientation is the orientation * for spans. Having both makes code much cleaner for calculations. */ @NonNull OrientationHelper mPrimaryOrientation; @NonNull OrientationHelper mSecondaryOrientation; private int mOrientation; /** * The width or height per span, depending on the orientation. */ private int mSizePerSpan; @NonNull private final LayoutState mLayoutState; private boolean mReverseLayout = false; /** * Aggregated reverse layout value that takes RTL into account. */ boolean mShouldReverseLayout = false; /** * Temporary variable used during fill method to check which spans needs to be filled. */ private BitSet mRemainingSpans; /** * When LayoutManager needs to scroll to a position, it sets this variable and requests a * layout which will check this variable and re-layout accordingly. */ int mPendingScrollPosition = NO_POSITION; /** * Used to keep the offset value when {@link #scrollToPositionWithOffset(int, int)} is * called. */ int mPendingScrollPositionOffset = INVALID_OFFSET; /** * Keeps the mapping between the adapter positions and spans. This is necessary to provide * a consistent experience when user scrolls the list. */ LazySpanLookup mLazySpanLookup = new LazySpanLookup(); /** * how we handle gaps in UI. */ private int mGapStrategy = GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS; /** * Saved state needs this information to properly layout on restore. */ private boolean mLastLayoutFromEnd; /** * Saved state and onLayout needs this information to re-layout properly */ private boolean mLastLayoutRTL; /** * SavedState is not handled until a layout happens. This is where we keep it until next * layout. */ private SavedState mPendingSavedState; /** * Re-used measurement specs. updated by onLayout. */ private int mFullSizeSpec; /** * Re-used rectangle to get child decor offsets. */ private final Rect mTmpRect = new Rect(); /** * Re-used anchor info. */ private final AnchorInfo mAnchorInfo = new AnchorInfo(); /** * If a full span item is invalid / or created in reverse direction; it may create gaps in * the UI. While laying out, if such case is detected, we set this flag. * <p> * After scrolling stops, we check this flag and if it is set, re-layout. */ private boolean mLaidOutInvalidFullSpan = false; /** * Works the same way as {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}. * see {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)} */ private boolean mSmoothScrollbarEnabled = true; private final Runnable mCheckForGapsRunnable = new Runnable() { @Override public void run() { checkForGaps(); } }; /** * Constructor used when layout manager is set in XML by RecyclerView attribute * "layoutManager". Defaults to single column and vertical. */ @SuppressWarnings("unused") public StaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes); setOrientation(properties.orientation); setSpanCount(properties.spanCount); setReverseLayout(properties.reverseLayout); setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); mLayoutState = new LayoutState(); createOrientationHelpers(); } /** * Creates a StaggeredGridLayoutManager with given parameters. * * @param spanCount If orientation is vertical, spanCount is number of columns. If * orientation is horizontal, spanCount is number of rows. * @param orientation {@link #VERTICAL} or {@link #HORIZONTAL} */ public StaggeredGridLayoutManager(int spanCount, int orientation) { mOrientation = orientation; setSpanCount(spanCount); setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); mLayoutState = new LayoutState(); createOrientationHelpers(); } private void createOrientationHelpers() { mPrimaryOrientation = OrientationHelper.createOrientationHelper(this, mOrientation); mSecondaryOrientation = OrientationHelper .createOrientationHelper(this, 1 - mOrientation); } /** * Checks for gaps in the UI that may be caused by adapter changes. * <p> * When a full span item is laid out in reverse direction, it sets a flag which we check when * scroll is stopped (or re-layout happens) and re-layout after first valid item. */ private boolean checkForGaps() { if (getChildCount() == 0 || mGapStrategy == GAP_HANDLING_NONE || !isAttachedToWindow()) { return false; } final int minPos, maxPos; if (mShouldReverseLayout) { minPos = getLastChildPosition(); maxPos = getFirstChildPosition(); } else { minPos = getFirstChildPosition(); maxPos = getLastChildPosition(); } if (minPos == 0) { View gapView = hasGapsToFix(); if (gapView != null) { mLazySpanLookup.clear(); requestSimpleAnimationsInNextLayout(); requestLayout(); return true; } } if (!mLaidOutInvalidFullSpan) { return false; } int invalidGapDir = mShouldReverseLayout ? LAYOUT_START : LAYOUT_END; final LazySpanLookup.FullSpanItem invalidFsi = mLazySpanLookup .getFirstFullSpanItemInRange(minPos, maxPos + 1, invalidGapDir, true); if (invalidFsi == null) { mLaidOutInvalidFullSpan = false; mLazySpanLookup.forceInvalidateAfter(maxPos + 1); return false; } final LazySpanLookup.FullSpanItem validFsi = mLazySpanLookup .getFirstFullSpanItemInRange(minPos, invalidFsi.mPosition, invalidGapDir * -1, true); if (validFsi == null) { mLazySpanLookup.forceInvalidateAfter(invalidFsi.mPosition); } else { mLazySpanLookup.forceInvalidateAfter(validFsi.mPosition + 1); } requestSimpleAnimationsInNextLayout(); requestLayout(); return true; } @Override public void onScrollStateChanged(int state) { if (state == RecyclerView.SCROLL_STATE_IDLE) { checkForGaps(); } } @Override public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { removeCallbacks(mCheckForGapsRunnable); for (int i = 0; i < mSpanCount; i++) { mSpans[i].clear(); } // SGLM will require fresh layout call to recover state after detach view.requestLayout(); } /** * Checks for gaps if we've reached to the top of the list. * <p> * Intermediate gaps created by full span items are tracked via mLaidOutInvalidFullSpan field. */ View hasGapsToFix() { int startChildIndex = 0; int endChildIndex = getChildCount() - 1; BitSet mSpansToCheck = new BitSet(mSpanCount); mSpansToCheck.set(0, mSpanCount, true); final int firstChildIndex, childLimit; final int preferredSpanDir = mOrientation == VERTICAL && isLayoutRTL() ? 1 : -1; if (mShouldReverseLayout) { firstChildIndex = endChildIndex; childLimit = startChildIndex - 1; } else { firstChildIndex = startChildIndex; childLimit = endChildIndex + 1; } final int nextChildDiff = firstChildIndex < childLimit ? 1 : -1; for (int i = firstChildIndex; i != childLimit; i += nextChildDiff) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (mSpansToCheck.get(lp.mSpan.mIndex)) { if (checkSpanForGap(lp.mSpan)) { return child; } mSpansToCheck.clear(lp.mSpan.mIndex); } if (lp.mFullSpan) { continue; // quick reject } if (i + nextChildDiff != childLimit) { View nextChild = getChildAt(i + nextChildDiff); boolean compareSpans = false; if (mShouldReverseLayout) { // ensure child's end is below nextChild's end int myEnd = mPrimaryOrientation.getDecoratedEnd(child); int nextEnd = mPrimaryOrientation.getDecoratedEnd(nextChild); if (myEnd < nextEnd) { return child;//i should have a better position } else if (myEnd == nextEnd) { compareSpans = true; } } else { int myStart = mPrimaryOrientation.getDecoratedStart(child); int nextStart = mPrimaryOrientation.getDecoratedStart(nextChild); if (myStart > nextStart) { return child;//i should have a better position } else if (myStart == nextStart) { compareSpans = true; } } if (compareSpans) { // equal, check span indices. LayoutParams nextLp = (LayoutParams) nextChild.getLayoutParams(); if (lp.mSpan.mIndex - nextLp.mSpan.mIndex < 0 != preferredSpanDir < 0) { return child; } } } } // everything looks good return null; } private boolean checkSpanForGap(Span span) { if (mShouldReverseLayout) { if (span.getEndLine() < mPrimaryOrientation.getEndAfterPadding()) { // if it is full span, it is OK final View endView = span.mViews.get(span.mViews.size() - 1); final LayoutParams lp = span.getLayoutParams(endView); return !lp.mFullSpan; } } else if (span.getStartLine() > mPrimaryOrientation.getStartAfterPadding()) { // if it is full span, it is OK final View startView = span.mViews.get(0); final LayoutParams lp = span.getLayoutParams(startView); return !lp.mFullSpan; } return false; } /** * Sets the number of spans for the layout. This will invalidate all of the span assignments * for Views. * <p> * Calling this method will automatically result in a new layout request unless the spanCount * parameter is equal to current span count. * * @param spanCount Number of spans to layout */ public void setSpanCount(int spanCount) { assertNotInLayoutOrScroll(null); if (spanCount != mSpanCount) { invalidateSpanAssignments(); mSpanCount = spanCount; mRemainingSpans = new BitSet(mSpanCount); mSpans = new Span[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { mSpans[i] = new Span(i); } requestLayout(); } } /** * Sets the orientation of the layout. StaggeredGridLayoutManager will do its best to keep * scroll position if this method is called after views are laid out. * * @param orientation {@link #HORIZONTAL} or {@link #VERTICAL} */ public void setOrientation(int orientation) { if (orientation != HORIZONTAL && orientation != VERTICAL) { throw new IllegalArgumentException("invalid orientation."); } assertNotInLayoutOrScroll(null); if (orientation == mOrientation) { return; } mOrientation = orientation; OrientationHelper tmp = mPrimaryOrientation; mPrimaryOrientation = mSecondaryOrientation; mSecondaryOrientation = tmp; requestLayout(); } /** * Sets whether LayoutManager should start laying out items from the end of the UI. The order * items are traversed is not affected by this call. * <p> * For vertical layout, if it is set to <code>true</code>, first item will be at the bottom of * the list. * <p> * For horizontal layouts, it depends on the layout direction. * When set to true, If {@link RecyclerView} is LTR, than it will layout from RTL, if * {@link RecyclerView}} is RTL, it will layout from LTR. * * @param reverseLayout Whether layout should be in reverse or not */ public void setReverseLayout(boolean reverseLayout) { assertNotInLayoutOrScroll(null); if (mPendingSavedState != null && mPendingSavedState.mReverseLayout != reverseLayout) { mPendingSavedState.mReverseLayout = reverseLayout; } mReverseLayout = reverseLayout; requestLayout(); } /** * Returns the current gap handling strategy for StaggeredGridLayoutManager. * <p> * Staggered grid may have gaps in the layout due to changes in the adapter. To avoid gaps, * StaggeredGridLayoutManager provides 2 options. Check {@link #GAP_HANDLING_NONE} and * {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} for details. * <p> * By default, StaggeredGridLayoutManager uses {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS}. * * @return Current gap handling strategy. * @see #setGapStrategy(int) * @see #GAP_HANDLING_NONE * @see #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS */ public int getGapStrategy() { return mGapStrategy; } /** * Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameter * is different than the current strategy, calling this method will trigger a layout request. * * @param gapStrategy The new gap handling strategy. Should be * {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} or {@link * #GAP_HANDLING_NONE}. * @see #getGapStrategy() */ public void setGapStrategy(int gapStrategy) { assertNotInLayoutOrScroll(null); if (gapStrategy == mGapStrategy) { return; } if (gapStrategy != GAP_HANDLING_NONE && gapStrategy != GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS) { throw new IllegalArgumentException("invalid gap strategy. Must be GAP_HANDLING_NONE " + "or GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS"); } mGapStrategy = gapStrategy; setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); requestLayout(); } @Override public void assertNotInLayoutOrScroll(String message) { if (mPendingSavedState == null) { super.assertNotInLayoutOrScroll(message); } } /** * Returns the number of spans laid out by StaggeredGridLayoutManager. * * @return Number of spans in the layout */ public int getSpanCount() { return mSpanCount; } /** * For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items. * <p> * If you need to cancel current assignments, you can call this method which will clear all * assignments and request a new layout. */ public void invalidateSpanAssignments() { mLazySpanLookup.clear(); requestLayout(); } /** * Calculates the views' layout order. (e.g. from end to start or start to end) * RTL layout support is applied automatically. So if layout is RTL and * {@link #getReverseLayout()} is {@code true}, elements will be laid out starting from left. */ private void resolveShouldLayoutReverse() { // A == B is the same result, but we rather keep it readable if (mOrientation == VERTICAL || !isLayoutRTL()) { mShouldReverseLayout = mReverseLayout; } else { mShouldReverseLayout = !mReverseLayout; } } boolean isLayoutRTL() { return getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; } /** * Returns whether views are laid out in reverse order or not. * <p> * Not that this value is not affected by RecyclerView's layout direction. * * @return True if layout is reversed, false otherwise * @see #setReverseLayout(boolean) */ public boolean getReverseLayout() { return mReverseLayout; } @Override public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) { // we don't like it to wrap content in our non-scroll direction. final int width, height; final int horizontalPadding = getPaddingLeft() + getPaddingRight(); final int verticalPadding = getPaddingTop() + getPaddingBottom(); if (mOrientation == VERTICAL) { final int usedHeight = childrenBounds.height() + verticalPadding; height = chooseSize(hSpec, usedHeight, getMinimumHeight()); width = chooseSize(wSpec, mSizePerSpan * mSpanCount + horizontalPadding, getMinimumWidth()); } else { final int usedWidth = childrenBounds.width() + horizontalPadding; width = chooseSize(wSpec, usedWidth, getMinimumWidth()); height = chooseSize(hSpec, mSizePerSpan * mSpanCount + verticalPadding, getMinimumHeight()); } setMeasuredDimension(width, height); } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { onLayoutChildren(recycler, state, true); } private void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state, boolean shouldCheckForGaps) { final AnchorInfo anchorInfo = mAnchorInfo; if (mPendingSavedState != null || mPendingScrollPosition != NO_POSITION) { if (state.getItemCount() == 0) { removeAndRecycleAllViews(recycler); anchorInfo.reset(); return; } } if (!anchorInfo.mValid || mPendingScrollPosition != NO_POSITION || mPendingSavedState != null) { anchorInfo.reset(); if (mPendingSavedState != null) { applyPendingSavedState(anchorInfo); } else { resolveShouldLayoutReverse(); anchorInfo.mLayoutFromEnd = mShouldReverseLayout; } updateAnchorInfoForLayout(state, anchorInfo); anchorInfo.mValid = true; } if (mPendingSavedState == null && mPendingScrollPosition == NO_POSITION) { if (anchorInfo.mLayoutFromEnd != mLastLayoutFromEnd || isLayoutRTL() != mLastLayoutRTL) { mLazySpanLookup.clear(); anchorInfo.mInvalidateOffsets = true; } } if (getChildCount() > 0 && (mPendingSavedState == null || mPendingSavedState.mSpanOffsetsSize < 1)) { if (anchorInfo.mInvalidateOffsets) { for (int i = 0; i < mSpanCount; i++) { // Scroll to position is set, clear. mSpans[i].clear(); if (anchorInfo.mOffset != INVALID_OFFSET) { mSpans[i].setLine(anchorInfo.mOffset); } } } else { for (int i = 0; i < mSpanCount; i++) { mSpans[i].cacheReferenceLineAndClear(mShouldReverseLayout, anchorInfo.mOffset); } } } detachAndScrapAttachedViews(recycler); mLayoutState.mRecycle = false; mLaidOutInvalidFullSpan = false; updateMeasureSpecs(mSecondaryOrientation.getTotalSpace()); updateLayoutState(anchorInfo.mPosition, state); if (anchorInfo.mLayoutFromEnd) { // Layout start. setLayoutStateDirection(LAYOUT_START); fill(recycler, mLayoutState, state); // Layout end. setLayoutStateDirection(LAYOUT_END); mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection; fill(recycler, mLayoutState, state); } else { // Layout end. setLayoutStateDirection(LAYOUT_END); fill(recycler, mLayoutState, state); // Layout start. setLayoutStateDirection(LAYOUT_START); mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection; fill(recycler, mLayoutState, state); } repositionToWrapContentIfNecessary(); if (getChildCount() > 0) { if (mShouldReverseLayout) { fixEndGap(recycler, state, true); fixStartGap(recycler, state, false); } else { fixStartGap(recycler, state, true); fixEndGap(recycler, state, false); } } boolean hasGaps = false; if (shouldCheckForGaps && !state.isPreLayout()) { final boolean needToCheckForGaps = mGapStrategy != GAP_HANDLING_NONE && getChildCount() > 0 && (mLaidOutInvalidFullSpan || hasGapsToFix() != null); if (needToCheckForGaps) { removeCallbacks(mCheckForGapsRunnable); if (checkForGaps()) { hasGaps = true; } } } if (state.isPreLayout()) { mAnchorInfo.reset(); } mLastLayoutFromEnd = anchorInfo.mLayoutFromEnd; mLastLayoutRTL = isLayoutRTL(); if (hasGaps) { mAnchorInfo.reset(); onLayoutChildren(recycler, state, false); } } @Override public void onLayoutCompleted(RecyclerView.State state) { super.onLayoutCompleted(state); mPendingScrollPosition = NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; mPendingSavedState = null; // we don't need this anymore mAnchorInfo.reset(); } private void repositionToWrapContentIfNecessary() { if (mSecondaryOrientation.getMode() == View.MeasureSpec.EXACTLY) { return; // nothing to do } float maxSize = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i ++) { View child = getChildAt(i); float size = mSecondaryOrientation.getDecoratedMeasurement(child); if (size < maxSize) { continue; } LayoutParams layoutParams = (LayoutParams) child.getLayoutParams(); if (layoutParams.isFullSpan()) { size = 1f * size / mSpanCount; } maxSize = Math.max(maxSize, size); } int before = mSizePerSpan; int desired = Math.round(maxSize * mSpanCount); if (mSecondaryOrientation.getMode() == View.MeasureSpec.AT_MOST) { desired = Math.min(desired, mSecondaryOrientation.getTotalSpace()); } updateMeasureSpecs(desired); if (mSizePerSpan == before) { return; // nothing has changed } for (int i = 0; i < childCount; i ++) { View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mFullSpan) { continue; } if (isLayoutRTL() && mOrientation == VERTICAL) { int newOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * mSizePerSpan; int prevOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * before; child.offsetLeftAndRight(newOffset - prevOffset); } else { int newOffset = lp.mSpan.mIndex * mSizePerSpan; int prevOffset = lp.mSpan.mIndex * before; if (mOrientation == VERTICAL) { child.offsetLeftAndRight(newOffset - prevOffset); } else { child.offsetTopAndBottom(newOffset - prevOffset); } } } } private void applyPendingSavedState(AnchorInfo anchorInfo) { if (DEBUG) { Log.d(TAG, "found saved state: " + mPendingSavedState); } if (mPendingSavedState.mSpanOffsetsSize > 0) { if (mPendingSavedState.mSpanOffsetsSize == mSpanCount) { for (int i = 0; i < mSpanCount; i++) { mSpans[i].clear(); int line = mPendingSavedState.mSpanOffsets[i]; if (line != Span.INVALID_LINE) { if (mPendingSavedState.mAnchorLayoutFromEnd) { line += mPrimaryOrientation.getEndAfterPadding(); } else { line += mPrimaryOrientation.getStartAfterPadding(); } } mSpans[i].setLine(line); } } else { mPendingSavedState.invalidateSpanInfo(); mPendingSavedState.mAnchorPosition = mPendingSavedState.mVisibleAnchorPosition; } } mLastLayoutRTL = mPendingSavedState.mLastLayoutRTL; setReverseLayout(mPendingSavedState.mReverseLayout); resolveShouldLayoutReverse(); if (mPendingSavedState.mAnchorPosition != NO_POSITION) { mPendingScrollPosition = mPendingSavedState.mAnchorPosition; anchorInfo.mLayoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; } else { anchorInfo.mLayoutFromEnd = mShouldReverseLayout; } if (mPendingSavedState.mSpanLookupSize > 1) { mLazySpanLookup.mData = mPendingSavedState.mSpanLookup; mLazySpanLookup.mFullSpanItems = mPendingSavedState.mFullSpanItems; } } void updateAnchorInfoForLayout(RecyclerView.State state, AnchorInfo anchorInfo) { if (updateAnchorFromPendingData(state, anchorInfo)) { return; } if (updateAnchorFromChildren(state, anchorInfo)) { return; } if (DEBUG) { Log.d(TAG, "Deciding anchor info from fresh state"); } anchorInfo.assignCoordinateFromPadding(); anchorInfo.mPosition = 0; } private boolean updateAnchorFromChildren(RecyclerView.State state, AnchorInfo anchorInfo) { // We don't recycle views out of adapter order. This way, we can rely on the first or // last child as the anchor position. // Layout direction may change but we should select the child depending on the latest // layout direction. Otherwise, we'll choose the wrong child. anchorInfo.mPosition = mLastLayoutFromEnd ? findLastReferenceChildPosition(state.getItemCount()) : findFirstReferenceChildPosition(state.getItemCount()); anchorInfo.mOffset = INVALID_OFFSET; return true; } boolean updateAnchorFromPendingData(RecyclerView.State state, AnchorInfo anchorInfo) { // Validate scroll position if exists. if (state.isPreLayout() || mPendingScrollPosition == NO_POSITION) { return false; } // Validate it. if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { mPendingScrollPosition = NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; return false; } if (mPendingSavedState == null || mPendingSavedState.mAnchorPosition == NO_POSITION || mPendingSavedState.mSpanOffsetsSize < 1) { // If item is visible, make it fully visible. final View child = findViewByPosition(mPendingScrollPosition); if (child != null) { // Use regular anchor position, offset according to pending offset and target // child anchorInfo.mPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition(); if (mPendingScrollPositionOffset != INVALID_OFFSET) { if (anchorInfo.mLayoutFromEnd) { final int target = mPrimaryOrientation.getEndAfterPadding() - mPendingScrollPositionOffset; anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedEnd(child); } else { final int target = mPrimaryOrientation.getStartAfterPadding() + mPendingScrollPositionOffset; anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedStart(child); } return true; } // no offset provided. Decide according to the child location final int childSize = mPrimaryOrientation.getDecoratedMeasurement(child); if (childSize > mPrimaryOrientation.getTotalSpace()) { // Item does not fit. Fix depending on layout direction. anchorInfo.mOffset = anchorInfo.mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); return true; } final int startGap = mPrimaryOrientation.getDecoratedStart(child) - mPrimaryOrientation.getStartAfterPadding(); if (startGap < 0) { anchorInfo.mOffset = -startGap; return true; } final int endGap = mPrimaryOrientation.getEndAfterPadding() - mPrimaryOrientation.getDecoratedEnd(child); if (endGap < 0) { anchorInfo.mOffset = endGap; return true; } // child already visible. just layout as usual anchorInfo.mOffset = INVALID_OFFSET; } else { // Child is not visible. Set anchor coordinate depending on in which direction // child will be visible. anchorInfo.mPosition = mPendingScrollPosition; if (mPendingScrollPositionOffset == INVALID_OFFSET) { final int position = calculateScrollDirectionForPosition( anchorInfo.mPosition); anchorInfo.mLayoutFromEnd = position == LAYOUT_END; anchorInfo.assignCoordinateFromPadding(); } else { anchorInfo.assignCoordinateFromPadding(mPendingScrollPositionOffset); } anchorInfo.mInvalidateOffsets = true; } } else { anchorInfo.mOffset = INVALID_OFFSET; anchorInfo.mPosition = mPendingScrollPosition; } return true; } void updateMeasureSpecs(int totalSpace) { mSizePerSpan = totalSpace / mSpanCount; //noinspection ResourceType mFullSizeSpec = View.MeasureSpec.makeMeasureSpec( totalSpace, mSecondaryOrientation.getMode()); } @Override public boolean supportsPredictiveItemAnimations() { return mPendingSavedState == null; } /** * Returns the adapter position of the first visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the first visible item in each span. If a span does not have * any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstCompletelyVisibleItemPositions(int[]) * @see #findLastVisibleItemPositions(int[]) */ public int[] findFirstVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findFirstVisibleItemPosition(); } return into; } /** * Returns the adapter position of the first completely visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the first fully visible item in each span. If a span does * not have any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstVisibleItemPositions(int[]) * @see #findLastCompletelyVisibleItemPositions(int[]) */ public int[] findFirstCompletelyVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findFirstCompletelyVisibleItemPosition(); } return into; } /** * Returns the adapter position of the last visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the last visible item in each span. If a span does not have * any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findLastCompletelyVisibleItemPositions(int[]) * @see #findFirstVisibleItemPositions(int[]) */ public int[] findLastVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findLastVisibleItemPosition(); } return into; } /** * Returns the adapter position of the last completely visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the last fully visible item in each span. If a span does not * have any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstCompletelyVisibleItemPositions(int[]) * @see #findLastVisibleItemPositions(int[]) */ public int[] findLastCompletelyVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findLastCompletelyVisibleItemPosition(); } return into; } @Override public int computeHorizontalScrollOffset(RecyclerView.State state) { return computeScrollOffset(state); } private int computeScrollOffset(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollOffset(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled, mShouldReverseLayout); } @Override public int computeVerticalScrollOffset(RecyclerView.State state) { return computeScrollOffset(state); } @Override public int computeHorizontalScrollExtent(RecyclerView.State state) { return computeScrollExtent(state); } private int computeScrollExtent(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollExtent(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled); } @Override public int computeVerticalScrollExtent(RecyclerView.State state) { return computeScrollExtent(state); } @Override public int computeHorizontalScrollRange(RecyclerView.State state) { return computeScrollRange(state); } private int computeScrollRange(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollRange(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled); } @Override public int computeVerticalScrollRange(RecyclerView.State state) { return computeScrollRange(state); } private void measureChildWithDecorationsAndMargin(View child, LayoutParams lp, boolean alreadyMeasured) { if (lp.mFullSpan) { if (mOrientation == VERTICAL) { measureChildWithDecorationsAndMargin(child, mFullSizeSpec, getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true), alreadyMeasured); } else { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true), mFullSizeSpec, alreadyMeasured); } } else { if (mOrientation == VERTICAL) { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(mSizePerSpan, getWidthMode(), 0, lp.width, false), getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true), alreadyMeasured); } else { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true), getChildMeasureSpec(mSizePerSpan, getHeightMode(), 0, lp.height, false), alreadyMeasured); } } } private void measureChildWithDecorationsAndMargin(View child, int widthSpec, int heightSpec, boolean alreadyMeasured) { calculateItemDecorationsForChild(child, mTmpRect); LayoutParams lp = (LayoutParams) child.getLayoutParams(); widthSpec = updateSpecWithExtra(widthSpec, lp.leftMargin + mTmpRect.left, lp.rightMargin + mTmpRect.right); heightSpec = updateSpecWithExtra(heightSpec, lp.topMargin + mTmpRect.top, lp.bottomMargin + mTmpRect.bottom); final boolean measure = alreadyMeasured ? shouldReMeasureChild(child, widthSpec, heightSpec, lp) : shouldMeasureChild(child, widthSpec, heightSpec, lp); if (measure) { child.measure(widthSpec, heightSpec); } } private int updateSpecWithExtra(int spec, int startInset, int endInset) { if (startInset == 0 && endInset == 0) { return spec; } final int mode = View.MeasureSpec.getMode(spec); if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) { return View.MeasureSpec.makeMeasureSpec( Math.max(0, View.MeasureSpec.getSize(spec) - startInset - endInset), mode); } return spec; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof SavedState) { mPendingSavedState = (SavedState) state; requestLayout(); } else if (DEBUG) { Log.d(TAG, "invalid saved state class"); } } @Override public Parcelable onSaveInstanceState() { if (mPendingSavedState != null) { return new SavedState(mPendingSavedState); } SavedState state = new SavedState(); state.mReverseLayout = mReverseLayout; state.mAnchorLayoutFromEnd = mLastLayoutFromEnd; state.mLastLayoutRTL = mLastLayoutRTL; if (mLazySpanLookup != null && mLazySpanLookup.mData != null) { state.mSpanLookup = mLazySpanLookup.mData; state.mSpanLookupSize = state.mSpanLookup.length; state.mFullSpanItems = mLazySpanLookup.mFullSpanItems; } else { state.mSpanLookupSize = 0; } if (getChildCount() > 0) { state.mAnchorPosition = mLastLayoutFromEnd ? getLastChildPosition() : getFirstChildPosition(); state.mVisibleAnchorPosition = findFirstVisibleItemPositionInt(); state.mSpanOffsetsSize = mSpanCount; state.mSpanOffsets = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { int line; if (mLastLayoutFromEnd) { line = mSpans[i].getEndLine(Span.INVALID_LINE); if (line != Span.INVALID_LINE) { line -= mPrimaryOrientation.getEndAfterPadding(); } } else { line = mSpans[i].getStartLine(Span.INVALID_LINE); if (line != Span.INVALID_LINE) { line -= mPrimaryOrientation.getStartAfterPadding(); } } state.mSpanOffsets[i] = line; } } else { state.mAnchorPosition = NO_POSITION; state.mVisibleAnchorPosition = NO_POSITION; state.mSpanOffsetsSize = 0; } if (DEBUG) { Log.d(TAG, "saved state:\n" + state); } return state; } @Override public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler, RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) { ViewGroup.LayoutParams lp = host.getLayoutParams(); if (!(lp instanceof LayoutParams)) { super.onInitializeAccessibilityNodeInfoForItem(host, info); return; } LayoutParams sglp = (LayoutParams) lp; if (mOrientation == HORIZONTAL) { info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1, -1, -1, sglp.mFullSpan, false)); } else { // VERTICAL info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( -1, -1, sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1, sglp.mFullSpan, false)); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); if (getChildCount() > 0) { final AccessibilityRecordCompat record = AccessibilityEventCompat .asRecord(event); final View start = findFirstVisibleItemClosestToStart(false, true); final View end = findFirstVisibleItemClosestToEnd(false, true); if (start == null || end == null) { return; } final int startPos = getPosition(start); final int endPos = getPosition(end); if (startPos < endPos) { record.setFromIndex(startPos); record.setToIndex(endPos); } else { record.setFromIndex(endPos); record.setToIndex(startPos); } } } /** * Finds the first fully visible child to be used as an anchor child if span count changes when * state is restored. If no children is fully visible, returns a partially visible child instead * of returning null. */ int findFirstVisibleItemPositionInt() { final View first = mShouldReverseLayout ? findFirstVisibleItemClosestToEnd(true, true) : findFirstVisibleItemClosestToStart(true, true); return first == null ? NO_POSITION : getPosition(first); } @Override public int getRowCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state) { if (mOrientation == HORIZONTAL) { return mSpanCount; } return super.getRowCountForAccessibility(recycler, state); } @Override public int getColumnCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state) { if (mOrientation == VERTICAL) { return mSpanCount; } return super.getColumnCountForAccessibility(recycler, state); } /** * This is for internal use. Not necessarily the child closest to start but the first child * we find that matches the criteria. * This method does not do any sorting based on child's start coordinate, instead, it uses * children order. */ View findFirstVisibleItemClosestToStart(boolean fullyVisible, boolean acceptPartiallyVisible) { final int boundsStart = mPrimaryOrientation.getStartAfterPadding(); final int boundsEnd = mPrimaryOrientation.getEndAfterPadding(); final int limit = getChildCount(); View partiallyVisible = null; for (int i = 0; i < limit; i++) { final View child = getChildAt(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if(childEnd <= boundsStart || childStart >= boundsEnd) { continue; // not visible at all } if (childStart >= boundsStart || !fullyVisible) { // when checking for start, it is enough even if part of the child's top is visible // as long as fully visible is not requested. return child; } if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child; } } return partiallyVisible; } /** * This is for internal use. Not necessarily the child closest to bottom but the first child * we find that matches the criteria. * This method does not do any sorting based on child's end coordinate, instead, it uses * children order. */ View findFirstVisibleItemClosestToEnd(boolean fullyVisible, boolean acceptPartiallyVisible) { final int boundsStart = mPrimaryOrientation.getStartAfterPadding(); final int boundsEnd = mPrimaryOrientation.getEndAfterPadding(); View partiallyVisible = null; for (int i = getChildCount() - 1; i >= 0; i--) { final View child = getChildAt(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if(childEnd <= boundsStart || childStart >= boundsEnd) { continue; // not visible at all } if (childEnd <= boundsEnd || !fullyVisible) { // when checking for end, it is enough even if part of the child's bottom is visible // as long as fully visible is not requested. return child; } if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child; } } return partiallyVisible; } private void fixEndGap(RecyclerView.Recycler recycler, RecyclerView.State state, boolean canOffsetChildren) { final int maxEndLine = getMaxEnd(Integer.MIN_VALUE); if (maxEndLine == Integer.MIN_VALUE) { return; } int gap = mPrimaryOrientation.getEndAfterPadding() - maxEndLine; int fixOffset; if (gap > 0) { fixOffset = -scrollBy(-gap, recycler, state); } else { return; // nothing to fix } gap -= fixOffset; if (canOffsetChildren && gap > 0) { mPrimaryOrientation.offsetChildren(gap); } } private void fixStartGap(RecyclerView.Recycler recycler, RecyclerView.State state, boolean canOffsetChildren) { final int minStartLine = getMinStart(Integer.MAX_VALUE); if (minStartLine == Integer.MAX_VALUE) { return; } int gap = minStartLine - mPrimaryOrientation.getStartAfterPadding(); int fixOffset; if (gap > 0) { fixOffset = scrollBy(gap, recycler, state); } else { return; // nothing to fix } gap -= fixOffset; if (canOffsetChildren && gap > 0) { mPrimaryOrientation.offsetChildren(-gap); } } private void updateLayoutState(int anchorPosition, RecyclerView.State state) { mLayoutState.mAvailable = 0; mLayoutState.mCurrentPosition = anchorPosition; int startExtra = 0; int endExtra = 0; if (isSmoothScrolling()) { final int targetPos = state.getTargetScrollPosition(); if (targetPos != NO_POSITION) { if (mShouldReverseLayout == targetPos < anchorPosition) { endExtra = mPrimaryOrientation.getTotalSpace(); } else { startExtra = mPrimaryOrientation.getTotalSpace(); } } } // Line of the furthest row. final boolean clipToPadding = getClipToPadding(); if (clipToPadding) { mLayoutState.mStartLine = mPrimaryOrientation.getStartAfterPadding() - startExtra; mLayoutState.mEndLine = mPrimaryOrientation.getEndAfterPadding() + endExtra; } else { mLayoutState.mEndLine = mPrimaryOrientation.getEnd() + endExtra; mLayoutState.mStartLine = -startExtra; } mLayoutState.mStopInFocusable = false; mLayoutState.mRecycle = true; mLayoutState.mInfinite = mPrimaryOrientation.getMode() == View.MeasureSpec.UNSPECIFIED && mPrimaryOrientation.getEnd() == 0; } private void setLayoutStateDirection(int direction) { mLayoutState.mLayoutDirection = direction; mLayoutState.mItemDirection = (mShouldReverseLayout == (direction == LAYOUT_START)) ? ITEM_DIRECTION_TAIL : ITEM_DIRECTION_HEAD; } @Override public void offsetChildrenHorizontal(int dx) { super.offsetChildrenHorizontal(dx); for (int i = 0; i < mSpanCount; i++) { mSpans[i].onOffset(dx); } } @Override public void offsetChildrenVertical(int dy) { super.offsetChildrenVertical(dy); for (int i = 0; i < mSpanCount; i++) { mSpans[i].onOffset(dy); } } @Override public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.REMOVE); } @Override public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.ADD); } @Override public void onItemsChanged(RecyclerView recyclerView) { mLazySpanLookup.clear(); requestLayout(); } @Override public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) { handleUpdate(from, to, AdapterHelper.UpdateOp.MOVE); } @Override public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.UPDATE); } /** * Checks whether it should invalidate span assignments in response to an adapter change. */ private void handleUpdate(int positionStart, int itemCountOrToPosition, int cmd) { int minPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition(); final int affectedRangeEnd;// exclusive final int affectedRangeStart;// inclusive if (cmd == AdapterHelper.UpdateOp.MOVE) { if (positionStart < itemCountOrToPosition) { affectedRangeEnd = itemCountOrToPosition + 1; affectedRangeStart = positionStart; } else { affectedRangeEnd = positionStart + 1; affectedRangeStart = itemCountOrToPosition; } } else { affectedRangeStart = positionStart; affectedRangeEnd = positionStart + itemCountOrToPosition; } mLazySpanLookup.invalidateAfter(affectedRangeStart); switch (cmd) { case AdapterHelper.UpdateOp.ADD: mLazySpanLookup.offsetForAddition(positionStart, itemCountOrToPosition); break; case AdapterHelper.UpdateOp.REMOVE: mLazySpanLookup.offsetForRemoval(positionStart, itemCountOrToPosition); break; case AdapterHelper.UpdateOp.MOVE: // TODO optimize mLazySpanLookup.offsetForRemoval(positionStart, 1); mLazySpanLookup.offsetForAddition(itemCountOrToPosition, 1); break; } if (affectedRangeEnd <= minPosition) { return; } int maxPosition = mShouldReverseLayout ? getFirstChildPosition() : getLastChildPosition(); if (affectedRangeStart <= maxPosition) { requestLayout(); } } private int fill(RecyclerView.Recycler recycler, LayoutState layoutState, RecyclerView.State state) { mRemainingSpans.set(0, mSpanCount, true); // The target position we are trying to reach. final int targetLine; // Line of the furthest row. if (mLayoutState.mInfinite) { if (layoutState.mLayoutDirection == LAYOUT_END) { targetLine = Integer.MAX_VALUE; } else { // LAYOUT_START targetLine = Integer.MIN_VALUE; } } else { if (layoutState.mLayoutDirection == LAYOUT_END) { targetLine = layoutState.mEndLine + layoutState.mAvailable; } else { // LAYOUT_START targetLine = layoutState.mStartLine - layoutState.mAvailable; } } updateAllRemainingSpans(layoutState.mLayoutDirection, targetLine); if (DEBUG) { Log.d(TAG, "FILLING targetLine: " + targetLine + "," + "remaining spans:" + mRemainingSpans + ", state: " + layoutState); } // the default coordinate to add new view. final int defaultNewViewLine = mShouldReverseLayout ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); boolean added = false; while (layoutState.hasMore(state) && (mLayoutState.mInfinite || !mRemainingSpans.isEmpty())) { View view = layoutState.next(recycler); LayoutParams lp = ((LayoutParams) view.getLayoutParams()); final int position = lp.getViewLayoutPosition(); final int spanIndex = mLazySpanLookup.getSpan(position); Span currentSpan; final boolean assignSpan = spanIndex == LayoutParams.INVALID_SPAN_ID; if (assignSpan) { currentSpan = lp.mFullSpan ? mSpans[0] : getNextSpan(layoutState); mLazySpanLookup.setSpan(position, currentSpan); if (DEBUG) { Log.d(TAG, "assigned " + currentSpan.mIndex + " for " + position); } } else { if (DEBUG) { Log.d(TAG, "using " + spanIndex + " for pos " + position); } currentSpan = mSpans[spanIndex]; } // assign span before measuring so that item decorators can get updated span index lp.mSpan = currentSpan; if (layoutState.mLayoutDirection == LAYOUT_END) { addView(view); } else { addView(view, 0); } measureChildWithDecorationsAndMargin(view, lp, false); final int start; final int end; if (layoutState.mLayoutDirection == LAYOUT_END) { start = lp.mFullSpan ? getMaxEnd(defaultNewViewLine) : currentSpan.getEndLine(defaultNewViewLine); end = start + mPrimaryOrientation.getDecoratedMeasurement(view); if (assignSpan && lp.mFullSpan) { LazySpanLookup.FullSpanItem fullSpanItem; fullSpanItem = createFullSpanItemFromEnd(start); fullSpanItem.mGapDir = LAYOUT_START; fullSpanItem.mPosition = position; mLazySpanLookup.addFullSpanItem(fullSpanItem); } } else { end = lp.mFullSpan ? getMinStart(defaultNewViewLine) : currentSpan.getStartLine(defaultNewViewLine); start = end - mPrimaryOrientation.getDecoratedMeasurement(view); if (assignSpan && lp.mFullSpan) { LazySpanLookup.FullSpanItem fullSpanItem; fullSpanItem = createFullSpanItemFromStart(end); fullSpanItem.mGapDir = LAYOUT_END; fullSpanItem.mPosition = position; mLazySpanLookup.addFullSpanItem(fullSpanItem); } } // check if this item may create gaps in the future if (lp.mFullSpan && layoutState.mItemDirection == ITEM_DIRECTION_HEAD) { if (assignSpan) { mLaidOutInvalidFullSpan = true; } else { final boolean hasInvalidGap; if (layoutState.mLayoutDirection == LAYOUT_END) { hasInvalidGap = !areAllEndsEqual(); } else { // layoutState.mLayoutDirection == LAYOUT_START hasInvalidGap = !areAllStartsEqual(); } if (hasInvalidGap) { final LazySpanLookup.FullSpanItem fullSpanItem = mLazySpanLookup .getFullSpanItem(position); if (fullSpanItem != null) { fullSpanItem.mHasUnwantedGapAfter = true; } mLaidOutInvalidFullSpan = true; } } } attachViewToSpans(view, lp, layoutState); final int otherStart; final int otherEnd; if (isLayoutRTL() && mOrientation == VERTICAL) { otherEnd = lp.mFullSpan ? mSecondaryOrientation.getEndAfterPadding() : mSecondaryOrientation.getEndAfterPadding() - (mSpanCount - 1 - currentSpan.mIndex) * mSizePerSpan; otherStart = otherEnd - mSecondaryOrientation.getDecoratedMeasurement(view); } else { otherStart = lp.mFullSpan ? mSecondaryOrientation.getStartAfterPadding() : currentSpan.mIndex * mSizePerSpan + mSecondaryOrientation.getStartAfterPadding(); otherEnd = otherStart + mSecondaryOrientation.getDecoratedMeasurement(view); } if (mOrientation == VERTICAL) { layoutDecoratedWithMargins(view, otherStart, start, otherEnd, end); } else { layoutDecoratedWithMargins(view, start, otherStart, end, otherEnd); } if (lp.mFullSpan) { updateAllRemainingSpans(mLayoutState.mLayoutDirection, targetLine); } else { updateRemainingSpans(currentSpan, mLayoutState.mLayoutDirection, targetLine); } recycle(recycler, mLayoutState); if (mLayoutState.mStopInFocusable && view.isFocusable()) { if (lp.mFullSpan) { mRemainingSpans.clear(); } else { mRemainingSpans.set(currentSpan.mIndex, false); } } added = true; } if (!added) { recycle(recycler, mLayoutState); } final int diff; if (mLayoutState.mLayoutDirection == LAYOUT_START) { final int minStart = getMinStart(mPrimaryOrientation.getStartAfterPadding()); diff = mPrimaryOrientation.getStartAfterPadding() - minStart; } else { final int maxEnd = getMaxEnd(mPrimaryOrientation.getEndAfterPadding()); diff = maxEnd - mPrimaryOrientation.getEndAfterPadding(); } return diff > 0 ? Math.min(layoutState.mAvailable, diff) : 0; } private LazySpanLookup.FullSpanItem createFullSpanItemFromEnd(int newItemTop) { LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem(); fsi.mGapPerSpan = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { fsi.mGapPerSpan[i] = newItemTop - mSpans[i].getEndLine(newItemTop); } return fsi; } private LazySpanLookup.FullSpanItem createFullSpanItemFromStart(int newItemBottom) { LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem(); fsi.mGapPerSpan = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { fsi.mGapPerSpan[i] = mSpans[i].getStartLine(newItemBottom) - newItemBottom; } return fsi; } private void attachViewToSpans(View view, LayoutParams lp, LayoutState layoutState) { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { if (lp.mFullSpan) { appendViewToAllSpans(view); } else { lp.mSpan.appendToSpan(view); } } else { if (lp.mFullSpan) { prependViewToAllSpans(view); } else { lp.mSpan.prependToSpan(view); } } } private void recycle(RecyclerView.Recycler recycler, LayoutState layoutState) { if (!layoutState.mRecycle || layoutState.mInfinite) { return; } if (layoutState.mAvailable == 0) { // easy, recycle line is still valid if (layoutState.mLayoutDirection == LAYOUT_START) { recycleFromEnd(recycler, layoutState.mEndLine); } else { recycleFromStart(recycler, layoutState.mStartLine); } } else { // scrolling case, recycle line can be shifted by how much space we could cover // by adding new views if (layoutState.mLayoutDirection == LAYOUT_START) { // calculate recycle line int scrolled = layoutState.mStartLine - getMaxStart(layoutState.mStartLine); final int line; if (scrolled < 0) { line = layoutState.mEndLine; } else { line = layoutState.mEndLine - Math.min(scrolled, layoutState.mAvailable); } recycleFromEnd(recycler, line); } else { // calculate recycle line int scrolled = getMinEnd(layoutState.mEndLine) - layoutState.mEndLine; final int line; if (scrolled < 0) { line = layoutState.mStartLine; } else { line = layoutState.mStartLine + Math.min(scrolled, layoutState.mAvailable); } recycleFromStart(recycler, line); } } } private void appendViewToAllSpans(View view) { // traverse in reverse so that we end up assigning full span items to 0 for (int i = mSpanCount - 1; i >= 0; i--) { mSpans[i].appendToSpan(view); } } private void prependViewToAllSpans(View view) { // traverse in reverse so that we end up assigning full span items to 0 for (int i = mSpanCount - 1; i >= 0; i--) { mSpans[i].prependToSpan(view); } } private void updateAllRemainingSpans(int layoutDir, int targetLine) { for (int i = 0; i < mSpanCount; i++) { if (mSpans[i].mViews.isEmpty()) { continue; } updateRemainingSpans(mSpans[i], layoutDir, targetLine); } } private void updateRemainingSpans(Span span, int layoutDir, int targetLine) { final int deletedSize = span.getDeletedSize(); if (layoutDir == LAYOUT_START) { final int line = span.getStartLine(); if (line + deletedSize <= targetLine) { mRemainingSpans.set(span.mIndex, false); } } else { final int line = span.getEndLine(); if (line - deletedSize >= targetLine) { mRemainingSpans.set(span.mIndex, false); } } } private int getMaxStart(int def) { int maxStart = mSpans[0].getStartLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanStart = mSpans[i].getStartLine(def); if (spanStart > maxStart) { maxStart = spanStart; } } return maxStart; } private int getMinStart(int def) { int minStart = mSpans[0].getStartLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanStart = mSpans[i].getStartLine(def); if (spanStart < minStart) { minStart = spanStart; } } return minStart; } boolean areAllEndsEqual() { int end = mSpans[0].getEndLine(Span.INVALID_LINE); for (int i = 1; i < mSpanCount; i++) { if (mSpans[i].getEndLine(Span.INVALID_LINE) != end) { return false; } } return true; } boolean areAllStartsEqual() { int start = mSpans[0].getStartLine(Span.INVALID_LINE); for (int i = 1; i < mSpanCount; i++) { if (mSpans[i].getStartLine(Span.INVALID_LINE) != start) { return false; } } return true; } private int getMaxEnd(int def) { int maxEnd = mSpans[0].getEndLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanEnd = mSpans[i].getEndLine(def); if (spanEnd > maxEnd) { maxEnd = spanEnd; } } return maxEnd; } private int getMinEnd(int def) { int minEnd = mSpans[0].getEndLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanEnd = mSpans[i].getEndLine(def); if (spanEnd < minEnd) { minEnd = spanEnd; } } return minEnd; } private void recycleFromStart(RecyclerView.Recycler recycler, int line) { while (getChildCount() > 0) { View child = getChildAt(0); if (mPrimaryOrientation.getDecoratedEnd(child) <= line && mPrimaryOrientation.getTransformedEndWithDecoration(child) <= line) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't recycle the last View in a span not to lose span's start/end lines if (lp.mFullSpan) { for (int j = 0; j < mSpanCount; j++) { if (mSpans[j].mViews.size() == 1) { return; } } for (int j = 0; j < mSpanCount; j++) { mSpans[j].popStart(); } } else { if (lp.mSpan.mViews.size() == 1) { return; } lp.mSpan.popStart(); } removeAndRecycleView(child, recycler); } else { return;// done } } } private void recycleFromEnd(RecyclerView.Recycler recycler, int line) { final int childCount = getChildCount(); int i; for (i = childCount - 1; i >= 0; i--) { View child = getChildAt(i); if (mPrimaryOrientation.getDecoratedStart(child) >= line && mPrimaryOrientation.getTransformedStartWithDecoration(child) >= line) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't recycle the last View in a span not to lose span's start/end lines if (lp.mFullSpan) { for (int j = 0; j < mSpanCount; j++) { if (mSpans[j].mViews.size() == 1) { return; } } for (int j = 0; j < mSpanCount; j++) { mSpans[j].popEnd(); } } else { if (lp.mSpan.mViews.size() == 1) { return; } lp.mSpan.popEnd(); } removeAndRecycleView(child, recycler); } else { return;// done } } } /** * @return True if last span is the first one we want to fill */ private boolean preferLastSpan(int layoutDir) { if (mOrientation == HORIZONTAL) { return (layoutDir == LAYOUT_START) != mShouldReverseLayout; } return ((layoutDir == LAYOUT_START) == mShouldReverseLayout) == isLayoutRTL(); } /** * Finds the span for the next view. */ private Span getNextSpan(LayoutState layoutState) { final boolean preferLastSpan = preferLastSpan(layoutState.mLayoutDirection); final int startIndex, endIndex, diff; if (preferLastSpan) { startIndex = mSpanCount - 1; endIndex = -1; diff = -1; } else { startIndex = 0; endIndex = mSpanCount; diff = 1; } if (layoutState.mLayoutDirection == LAYOUT_END) { Span min = null; int minLine = Integer.MAX_VALUE; final int defaultLine = mPrimaryOrientation.getStartAfterPadding(); for (int i = startIndex; i != endIndex; i += diff) { final Span other = mSpans[i]; int otherLine = other.getEndLine(defaultLine); if (otherLine < minLine) { min = other; minLine = otherLine; } } return min; } else { Span max = null; int maxLine = Integer.MIN_VALUE; final int defaultLine = mPrimaryOrientation.getEndAfterPadding(); for (int i = startIndex; i != endIndex; i += diff) { final Span other = mSpans[i]; int otherLine = other.getStartLine(defaultLine); if (otherLine > maxLine) { max = other; maxLine = otherLine; } } return max; } } @Override public boolean canScrollVertically() { return mOrientation == VERTICAL; } @Override public boolean canScrollHorizontally() { return mOrientation == HORIZONTAL; } @Override public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) { return scrollBy(dx, recycler, state); } @Override public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { return scrollBy(dy, recycler, state); } private int calculateScrollDirectionForPosition(int position) { if (getChildCount() == 0) { return mShouldReverseLayout ? LAYOUT_END : LAYOUT_START; } final int firstChildPos = getFirstChildPosition(); return position < firstChildPos != mShouldReverseLayout ? LAYOUT_START : LAYOUT_END; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { LinearSmoothScroller scroller = new LinearSmoothScroller(recyclerView.getContext()) { @Override public PointF computeScrollVectorForPosition(int targetPosition) { final int direction = calculateScrollDirectionForPosition(targetPosition); if (direction == 0) { return null; } if (mOrientation == HORIZONTAL) { return new PointF(direction, 0); } else { return new PointF(0, direction); } } }; scroller.setTargetPosition(position); startSmoothScroll(scroller); } @Override public void scrollToPosition(int position) { if (mPendingSavedState != null && mPendingSavedState.mAnchorPosition != position) { mPendingSavedState.invalidateAnchorPositionInfo(); } mPendingScrollPosition = position; mPendingScrollPositionOffset = INVALID_OFFSET; requestLayout(); } /** * Scroll to the specified adapter position with the given offset from layout start. * <p> * Note that scroll position change will not be reflected until the next layout call. * <p> * If you are just trying to make a position visible, use {@link #scrollToPosition(int)}. * * @param position Index (starting at 0) of the reference item. * @param offset The distance (in pixels) between the start edge of the item view and * start edge of the RecyclerView. * @see #setReverseLayout(boolean) * @see #scrollToPosition(int) */ public void scrollToPositionWithOffset(int position, int offset) { if (mPendingSavedState != null) { mPendingSavedState.invalidateAnchorPositionInfo(); } mPendingScrollPosition = position; mPendingScrollPositionOffset = offset; requestLayout(); } int scrollBy(int dt, RecyclerView.Recycler recycler, RecyclerView.State state) { final int referenceChildPosition; final int layoutDir; if (dt > 0) { // layout towards end layoutDir = LAYOUT_END; referenceChildPosition = getLastChildPosition(); } else { layoutDir = LAYOUT_START; referenceChildPosition = getFirstChildPosition(); } mLayoutState.mRecycle = true; updateLayoutState(referenceChildPosition, state); setLayoutStateDirection(layoutDir); mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection; final int absDt = Math.abs(dt); mLayoutState.mAvailable = absDt; int consumed = fill(recycler, mLayoutState, state); final int totalScroll; if (absDt < consumed) { totalScroll = dt; } else if (dt < 0) { totalScroll = -consumed; } else { // dt > 0 totalScroll = consumed; } if (DEBUG) { Log.d(TAG, "asked " + dt + " scrolled" + totalScroll); } mPrimaryOrientation.offsetChildren(-totalScroll); // always reset this if we scroll for a proper save instance state mLastLayoutFromEnd = mShouldReverseLayout; return totalScroll; } private int getLastChildPosition() { final int childCount = getChildCount(); return childCount == 0 ? 0 : getPosition(getChildAt(childCount - 1)); } private int getFirstChildPosition() { final int childCount = getChildCount(); return childCount == 0 ? 0 : getPosition(getChildAt(0)); } /** * Finds the first View that can be used as an anchor View. * * @return Position of the View or 0 if it cannot find any such View. */ private int findFirstReferenceChildPosition(int itemCount) { final int limit = getChildCount(); for (int i = 0; i < limit; i++) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { return position; } } return 0; } /** * Finds the last View that can be used as an anchor View. * * @return Position of the View or 0 if it cannot find any such View. */ private int findLastReferenceChildPosition(int itemCount) { for (int i = getChildCount() - 1; i >= 0; i--) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { return position; } } return 0; } @SuppressWarnings("deprecation") @Override public RecyclerView.LayoutParams generateDefaultLayoutParams() { if (mOrientation == HORIZONTAL) { return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT); } else { return new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } @Override public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) { return new LayoutParams(c, attrs); } @Override public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { if (lp instanceof ViewGroup.MarginLayoutParams) { return new LayoutParams((ViewGroup.MarginLayoutParams) lp); } else { return new LayoutParams(lp); } } @Override public boolean checkLayoutParams(RecyclerView.LayoutParams lp) { return lp instanceof LayoutParams; } public int getOrientation() { return mOrientation; } @Nullable @Override public View onFocusSearchFailed(View focused, int direction, RecyclerView.Recycler recycler, RecyclerView.State state) { if (getChildCount() == 0) { return null; } final View directChild = findContainingItemView(focused); if (directChild == null) { return null; } resolveShouldLayoutReverse(); final int layoutDir = convertFocusDirectionToLayoutDirection(direction); if (layoutDir == LayoutState.INVALID_LAYOUT) { return null; } LayoutParams prevFocusLayoutParams = (LayoutParams) directChild.getLayoutParams(); boolean prevFocusFullSpan = prevFocusLayoutParams.mFullSpan; final Span prevFocusSpan = prevFocusLayoutParams.mSpan; final int referenceChildPosition; if (layoutDir == LAYOUT_END) { // layout towards end referenceChildPosition = getLastChildPosition(); } else { referenceChildPosition = getFirstChildPosition(); } updateLayoutState(referenceChildPosition, state); setLayoutStateDirection(layoutDir); mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection; mLayoutState.mAvailable = (int) (MAX_SCROLL_FACTOR * mPrimaryOrientation.getTotalSpace()); mLayoutState.mStopInFocusable = true; mLayoutState.mRecycle = false; fill(recycler, mLayoutState, state); mLastLayoutFromEnd = mShouldReverseLayout; if (!prevFocusFullSpan) { View view = prevFocusSpan.getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } // either could not find from the desired span or prev view is full span. // traverse all spans if (preferLastSpan(layoutDir)) { for (int i = mSpanCount - 1; i >= 0; i --) { View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } } else { for (int i = 0; i < mSpanCount; i ++) { View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } } return null; } /** * Converts a focusDirection to orientation. * * @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} * or 0 for not applicable * @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction * is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise. */ private int convertFocusDirectionToLayoutDirection(int focusDirection) { switch (focusDirection) { case View.FOCUS_BACKWARD: if (mOrientation == VERTICAL) { return LayoutState.LAYOUT_START; } else if (isLayoutRTL()) { return LayoutState.LAYOUT_END; } else { return LayoutState.LAYOUT_START; } case View.FOCUS_FORWARD: if (mOrientation == VERTICAL) { return LayoutState.LAYOUT_END; } else if (isLayoutRTL()) { return LayoutState.LAYOUT_START; } else { return LayoutState.LAYOUT_END; } case View.FOCUS_UP: return mOrientation == VERTICAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_DOWN: return mOrientation == VERTICAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; case View.FOCUS_LEFT: return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_RIGHT: return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; default: if (DEBUG) { Log.d(TAG, "Unknown focus request:" + focusDirection); } return LayoutState.INVALID_LAYOUT; } } /** * LayoutParams used by StaggeredGridLayoutManager. * <p> * Note that if the orientation is {@link #VERTICAL}, the width parameter is ignored and if the * orientation is {@link #HORIZONTAL} the height parameter is ignored because child view is * expected to fill all of the space given to it. */ public static class LayoutParams extends RecyclerView.LayoutParams { /** * Span Id for Views that are not laid out yet. */ public static final int INVALID_SPAN_ID = -1; // Package scope to be able to access from tests. Span mSpan; boolean mFullSpan; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(RecyclerView.LayoutParams source) { super(source); } /** * When set to true, the item will layout using all span area. That means, if orientation * is vertical, the view will have full width; if orientation is horizontal, the view will * have full height. * * @param fullSpan True if this item should traverse all spans. * @see #isFullSpan() */ public void setFullSpan(boolean fullSpan) { mFullSpan = fullSpan; } /** * Returns whether this View occupies all available spans or just one. * * @return True if the View occupies all spans or false otherwise. * @see #setFullSpan(boolean) */ public boolean isFullSpan() { return mFullSpan; } /** * Returns the Span index to which this View is assigned. * * @return The Span index of the View. If View is not yet assigned to any span, returns * {@link #INVALID_SPAN_ID}. */ public final int getSpanIndex() { if (mSpan == null) { return INVALID_SPAN_ID; } return mSpan.mIndex; } } // Package scoped to access from tests. class Span { static final int INVALID_LINE = Integer.MIN_VALUE; private ArrayList<View> mViews = new ArrayList<>(); int mCachedStart = INVALID_LINE; int mCachedEnd = INVALID_LINE; int mDeletedSize = 0; final int mIndex; private Span(int index) { mIndex = index; } int getStartLine(int def) { if (mCachedStart != INVALID_LINE) { return mCachedStart; } if (mViews.size() == 0) { return def; } calculateCachedStart(); return mCachedStart; } void calculateCachedStart() { final View startView = mViews.get(0); final LayoutParams lp = getLayoutParams(startView); mCachedStart = mPrimaryOrientation.getDecoratedStart(startView); if (lp.mFullSpan) { LazySpanLookup.FullSpanItem fsi = mLazySpanLookup .getFullSpanItem(lp.getViewLayoutPosition()); if (fsi != null && fsi.mGapDir == LAYOUT_START) { mCachedStart -= fsi.getGapForSpan(mIndex); } } } // Use this one when default value does not make sense and not having a value means a bug. int getStartLine() { if (mCachedStart != INVALID_LINE) { return mCachedStart; } calculateCachedStart(); return mCachedStart; } int getEndLine(int def) { if (mCachedEnd != INVALID_LINE) { return mCachedEnd; } final int size = mViews.size(); if (size == 0) { return def; } calculateCachedEnd(); return mCachedEnd; } void calculateCachedEnd() { final View endView = mViews.get(mViews.size() - 1); final LayoutParams lp = getLayoutParams(endView); mCachedEnd = mPrimaryOrientation.getDecoratedEnd(endView); if (lp.mFullSpan) { LazySpanLookup.FullSpanItem fsi = mLazySpanLookup .getFullSpanItem(lp.getViewLayoutPosition()); if (fsi != null && fsi.mGapDir == LAYOUT_END) { mCachedEnd += fsi.getGapForSpan(mIndex); } } } // Use this one when default value does not make sense and not having a value means a bug. int getEndLine() { if (mCachedEnd != INVALID_LINE) { return mCachedEnd; } calculateCachedEnd(); return mCachedEnd; } void prependToSpan(View view) { LayoutParams lp = getLayoutParams(view); lp.mSpan = this; mViews.add(0, view); mCachedStart = INVALID_LINE; if (mViews.size() == 1) { mCachedEnd = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view); } } void appendToSpan(View view) { LayoutParams lp = getLayoutParams(view); lp.mSpan = this; mViews.add(view); mCachedEnd = INVALID_LINE; if (mViews.size() == 1) { mCachedStart = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view); } } // Useful method to preserve positions on a re-layout. void cacheReferenceLineAndClear(boolean reverseLayout, int offset) { int reference; if (reverseLayout) { reference = getEndLine(INVALID_LINE); } else { reference = getStartLine(INVALID_LINE); } clear(); if (reference == INVALID_LINE) { return; } if ((reverseLayout && reference < mPrimaryOrientation.getEndAfterPadding()) || (!reverseLayout && reference > mPrimaryOrientation.getStartAfterPadding())) { return; } if (offset != INVALID_OFFSET) { reference += offset; } mCachedStart = mCachedEnd = reference; } void clear() { mViews.clear(); invalidateCache(); mDeletedSize = 0; } void invalidateCache() { mCachedStart = INVALID_LINE; mCachedEnd = INVALID_LINE; } void setLine(int line) { mCachedEnd = mCachedStart = line; } void popEnd() { final int size = mViews.size(); View end = mViews.remove(size - 1); final LayoutParams lp = getLayoutParams(end); lp.mSpan = null; if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(end); } if (size == 1) { mCachedStart = INVALID_LINE; } mCachedEnd = INVALID_LINE; } void popStart() { View start = mViews.remove(0); final LayoutParams lp = getLayoutParams(start); lp.mSpan = null; if (mViews.size() == 0) { mCachedEnd = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(start); } mCachedStart = INVALID_LINE; } public int getDeletedSize() { return mDeletedSize; } LayoutParams getLayoutParams(View view) { return (LayoutParams) view.getLayoutParams(); } void onOffset(int dt) { if (mCachedStart != INVALID_LINE) { mCachedStart += dt; } if (mCachedEnd != INVALID_LINE) { mCachedEnd += dt; } } public int findFirstVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(mViews.size() - 1, -1, false) : findOneVisibleChild(0, mViews.size(), false); } public int findFirstCompletelyVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(mViews.size() - 1, -1, true) : findOneVisibleChild(0, mViews.size(), true); } public int findLastVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(0, mViews.size(), false) : findOneVisibleChild(mViews.size() - 1, -1, false); } public int findLastCompletelyVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(0, mViews.size(), true) : findOneVisibleChild(mViews.size() - 1, -1, true); } int findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible) { final int start = mPrimaryOrientation.getStartAfterPadding(); final int end = mPrimaryOrientation.getEndAfterPadding(); final int next = toIndex > fromIndex ? 1 : -1; for (int i = fromIndex; i != toIndex; i += next) { final View child = mViews.get(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if (childStart < end && childEnd > start) { if (completelyVisible) { if (childStart >= start && childEnd <= end) { return getPosition(child); } } else { return getPosition(child); } } } return NO_POSITION; } /** * Depending on the layout direction, returns the View that is after the given position. */ public View getFocusableViewAfter(int referenceChildPosition, int layoutDir) { View candidate = null; if (layoutDir == LAYOUT_START) { final int limit = mViews.size(); for (int i = 0; i < limit; i++) { final View view = mViews.get(i); if (view.isFocusable() && (getPosition(view) > referenceChildPosition == mReverseLayout) ) { candidate = view; } else { break; } } } else { for (int i = mViews.size() - 1; i >= 0; i--) { final View view = mViews.get(i); if (view.isFocusable() && (getPosition(view) > referenceChildPosition == !mReverseLayout)) { candidate = view; } else { break; } } } return candidate; } } /** * An array of mappings from adapter position to span. * This only grows when a write happens and it grows up to the size of the adapter. */ static class LazySpanLookup { private static final int MIN_SIZE = 10; int[] mData; List<FullSpanItem> mFullSpanItems; /** * Invalidates everything after this position, including full span information */ int forceInvalidateAfter(int position) { if (mFullSpanItems != null) { for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= position) { mFullSpanItems.remove(i); } } } return invalidateAfter(position); } /** * returns end position for invalidation. */ int invalidateAfter(int position) { if (mData == null) { return RecyclerView.NO_POSITION; } if (position >= mData.length) { return RecyclerView.NO_POSITION; } int endPosition = invalidateFullSpansAfter(position); if (endPosition == RecyclerView.NO_POSITION) { Arrays.fill(mData, position, mData.length, LayoutParams.INVALID_SPAN_ID); return mData.length; } else { // just invalidate items in between Arrays.fill(mData, position, endPosition + 1, LayoutParams.INVALID_SPAN_ID); return endPosition + 1; } } int getSpan(int position) { if (mData == null || position >= mData.length) { return LayoutParams.INVALID_SPAN_ID; } else { return mData[position]; } } void setSpan(int position, Span span) { ensureSize(position); mData[position] = span.mIndex; } int sizeForPosition(int position) { int len = mData.length; while (len <= position) { len *= 2; } return len; } void ensureSize(int position) { if (mData == null) { mData = new int[Math.max(position, MIN_SIZE) + 1]; Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID); } else if (position >= mData.length) { int[] old = mData; mData = new int[sizeForPosition(position)]; System.arraycopy(old, 0, mData, 0, old.length); Arrays.fill(mData, old.length, mData.length, LayoutParams.INVALID_SPAN_ID); } } void clear() { if (mData != null) { Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID); } mFullSpanItems = null; } void offsetForRemoval(int positionStart, int itemCount) { if (mData == null || positionStart >= mData.length) { return; } ensureSize(positionStart + itemCount); System.arraycopy(mData, positionStart + itemCount, mData, positionStart, mData.length - positionStart - itemCount); Arrays.fill(mData, mData.length - itemCount, mData.length, LayoutParams.INVALID_SPAN_ID); offsetFullSpansForRemoval(positionStart, itemCount); } private void offsetFullSpansForRemoval(int positionStart, int itemCount) { if (mFullSpanItems == null) { return; } final int end = positionStart + itemCount; for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition < positionStart) { continue; } if (fsi.mPosition < end) { mFullSpanItems.remove(i); } else { fsi.mPosition -= itemCount; } } } void offsetForAddition(int positionStart, int itemCount) { if (mData == null || positionStart >= mData.length) { return; } ensureSize(positionStart + itemCount); System.arraycopy(mData, positionStart, mData, positionStart + itemCount, mData.length - positionStart - itemCount); Arrays.fill(mData, positionStart, positionStart + itemCount, LayoutParams.INVALID_SPAN_ID); offsetFullSpansForAddition(positionStart, itemCount); } private void offsetFullSpansForAddition(int positionStart, int itemCount) { if (mFullSpanItems == null) { return; } for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition < positionStart) { continue; } fsi.mPosition += itemCount; } } /** * Returns when invalidation should end. e.g. hitting a full span position. * Returned position SHOULD BE invalidated. */ private int invalidateFullSpansAfter(int position) { if (mFullSpanItems == null) { return RecyclerView.NO_POSITION; } final FullSpanItem item = getFullSpanItem(position); // if there is an fsi at this position, get rid of it. if (item != null) { mFullSpanItems.remove(item); } int nextFsiIndex = -1; final int count = mFullSpanItems.size(); for (int i = 0; i < count; i++) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= position) { nextFsiIndex = i; break; } } if (nextFsiIndex != -1) { FullSpanItem fsi = mFullSpanItems.get(nextFsiIndex); mFullSpanItems.remove(nextFsiIndex); return fsi.mPosition; } return RecyclerView.NO_POSITION; } public void addFullSpanItem(FullSpanItem fullSpanItem) { if (mFullSpanItems == null) { mFullSpanItems = new ArrayList<>(); } final int size = mFullSpanItems.size(); for (int i = 0; i < size; i++) { FullSpanItem other = mFullSpanItems.get(i); if (other.mPosition == fullSpanItem.mPosition) { if (DEBUG) { throw new IllegalStateException("two fsis for same position"); } else { mFullSpanItems.remove(i); } } if (other.mPosition >= fullSpanItem.mPosition) { mFullSpanItems.add(i, fullSpanItem); return; } } // if it is not added to a position. mFullSpanItems.add(fullSpanItem); } public FullSpanItem getFullSpanItem(int position) { if (mFullSpanItems == null) { return null; } for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { final FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition == position) { return fsi; } } return null; } /** * @param minPos inclusive * @param maxPos exclusive * @param gapDir if not 0, returns FSIs on in that direction * @param hasUnwantedGapAfter If true, when full span item has unwanted gaps, it will be * returned even if its gap direction does not match. */ public FullSpanItem getFirstFullSpanItemInRange(int minPos, int maxPos, int gapDir, boolean hasUnwantedGapAfter) { if (mFullSpanItems == null) { return null; } final int limit = mFullSpanItems.size(); for (int i = 0; i < limit; i++) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= maxPos) { return null; } if (fsi.mPosition >= minPos && (gapDir == 0 || fsi.mGapDir == gapDir || (hasUnwantedGapAfter && fsi.mHasUnwantedGapAfter))) { return fsi; } } return null; } /** * We keep information about full span items because they may create gaps in the UI. */ static class FullSpanItem implements Parcelable { int mPosition; int mGapDir; int[] mGapPerSpan; // A full span may be laid out in primary direction but may have gaps due to // invalidation of views after it. This is recorded during a reverse scroll and if // view is still on the screen after scroll stops, we have to recalculate layout boolean mHasUnwantedGapAfter; public FullSpanItem(Parcel in) { mPosition = in.readInt(); mGapDir = in.readInt(); mHasUnwantedGapAfter = in.readInt() == 1; int spanCount = in.readInt(); if (spanCount > 0) { mGapPerSpan = new int[spanCount]; in.readIntArray(mGapPerSpan); } } public FullSpanItem() { } int getGapForSpan(int spanIndex) { return mGapPerSpan == null ? 0 : mGapPerSpan[spanIndex]; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mPosition); dest.writeInt(mGapDir); dest.writeInt(mHasUnwantedGapAfter ? 1 : 0); if (mGapPerSpan != null && mGapPerSpan.length > 0) { dest.writeInt(mGapPerSpan.length); dest.writeIntArray(mGapPerSpan); } else { dest.writeInt(0); } } @Override public String toString() { return "FullSpanItem{" + "mPosition=" + mPosition + ", mGapDir=" + mGapDir + ", mHasUnwantedGapAfter=" + mHasUnwantedGapAfter + ", mGapPerSpan=" + Arrays.toString(mGapPerSpan) + '}'; } public static final Parcelable.Creator<FullSpanItem> CREATOR = new Parcelable.Creator<FullSpanItem>() { @Override public FullSpanItem createFromParcel(Parcel in) { return new FullSpanItem(in); } @Override public FullSpanItem[] newArray(int size) { return new FullSpanItem[size]; } }; } } /** * @hide */ public static class SavedState implements Parcelable { int mAnchorPosition; int mVisibleAnchorPosition; // Replacement for span info when spans are invalidated int mSpanOffsetsSize; int[] mSpanOffsets; int mSpanLookupSize; int[] mSpanLookup; List<LazySpanLookup.FullSpanItem> mFullSpanItems; boolean mReverseLayout; boolean mAnchorLayoutFromEnd; boolean mLastLayoutRTL; public SavedState() { } SavedState(Parcel in) { mAnchorPosition = in.readInt(); mVisibleAnchorPosition = in.readInt(); mSpanOffsetsSize = in.readInt(); if (mSpanOffsetsSize > 0) { mSpanOffsets = new int[mSpanOffsetsSize]; in.readIntArray(mSpanOffsets); } mSpanLookupSize = in.readInt(); if (mSpanLookupSize > 0) { mSpanLookup = new int[mSpanLookupSize]; in.readIntArray(mSpanLookup); } mReverseLayout = in.readInt() == 1; mAnchorLayoutFromEnd = in.readInt() == 1; mLastLayoutRTL = in.readInt() == 1; //noinspection unchecked mFullSpanItems = in.readArrayList( LazySpanLookup.FullSpanItem.class.getClassLoader()); } public SavedState(SavedState other) { mSpanOffsetsSize = other.mSpanOffsetsSize; mAnchorPosition = other.mAnchorPosition; mVisibleAnchorPosition = other.mVisibleAnchorPosition; mSpanOffsets = other.mSpanOffsets; mSpanLookupSize = other.mSpanLookupSize; mSpanLookup = other.mSpanLookup; mReverseLayout = other.mReverseLayout; mAnchorLayoutFromEnd = other.mAnchorLayoutFromEnd; mLastLayoutRTL = other.mLastLayoutRTL; mFullSpanItems = other.mFullSpanItems; } void invalidateSpanInfo() { mSpanOffsets = null; mSpanOffsetsSize = 0; mSpanLookupSize = 0; mSpanLookup = null; mFullSpanItems = null; } void invalidateAnchorPositionInfo() { mSpanOffsets = null; mSpanOffsetsSize = 0; mAnchorPosition = NO_POSITION; mVisibleAnchorPosition = NO_POSITION; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mAnchorPosition); dest.writeInt(mVisibleAnchorPosition); dest.writeInt(mSpanOffsetsSize); if (mSpanOffsetsSize > 0) { dest.writeIntArray(mSpanOffsets); } dest.writeInt(mSpanLookupSize); if (mSpanLookupSize > 0) { dest.writeIntArray(mSpanLookup); } dest.writeInt(mReverseLayout ? 1 : 0); dest.writeInt(mAnchorLayoutFromEnd ? 1 : 0); dest.writeInt(mLastLayoutRTL ? 1 : 0); dest.writeList(mFullSpanItems); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * Data class to hold the information about an anchor position which is used in onLayout call. */ class AnchorInfo { int mPosition; int mOffset; boolean mLayoutFromEnd; boolean mInvalidateOffsets; boolean mValid; public AnchorInfo() { reset(); } void reset() { mPosition = NO_POSITION; mOffset = INVALID_OFFSET; mLayoutFromEnd = false; mInvalidateOffsets = false; mValid = false; } void assignCoordinateFromPadding() { mOffset = mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); } void assignCoordinateFromPadding(int addedDistance) { if (mLayoutFromEnd) { mOffset = mPrimaryOrientation.getEndAfterPadding() - addedDistance; } else { mOffset = mPrimaryOrientation.getStartAfterPadding() + addedDistance; } } } }
baininghan/wxadmin
src/main/java/com/fancye/wx/comm/model/base/BaseAdmin.java
<reponame>baininghan/wxadmin package com.fancye.wx.comm.model.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings("serial") public abstract class BaseAdmin<M extends BaseAdmin<M>> extends Model<M> implements IBean { public void setId(java.lang.Integer id) { set("id", id); } public java.lang.Integer getId() { return getInt("id"); } public void setNickname(java.lang.String nickname) { set("nickname", nickname); } public java.lang.String getNickname() { return getStr("nickname"); } public void setMobilephone(java.lang.String mobilephone) { set("mobilephone", mobilephone); } public java.lang.String getMobilephone() { return getStr("mobilephone"); } public void setEmail(java.lang.String email) { set("email", email); } public java.lang.String getEmail() { return getStr("email"); } public void setLoginPwd(java.lang.String loginPwd) { set("login_pwd", loginPwd); } public java.lang.String getLoginPwd() { return getStr("login_pwd"); } public void setRid(java.lang.Integer rid) { set("rid", rid); } public java.lang.Integer getRid() { return getInt("rid"); } public void setStatus(java.lang.Integer status) { set("status", status); } public java.lang.Integer getStatus() { return getInt("status"); } public void setAddress(java.lang.String address) { set("address", address); } public java.lang.String getAddress() { return getStr("address"); } public void setCreateTime(java.util.Date createTime) { set("create_time", createTime); } public java.util.Date getCreateTime() { return get("create_time"); } public void setUpdateTime(java.util.Date updateTime) { set("update_time", updateTime); } public java.util.Date getUpdateTime() { return get("update_time"); } }
phlahut/Wonder.js
lib/es6_global/src/service/primitive/job/JobService.js
import * as List from "../../../../../../node_modules/bs-platform/lib/es6/list.js"; import * as Pervasives from "../../../../../../node_modules/bs-platform/lib/es6/pervasives.js"; import * as Log$WonderLog from "../../../../../../node_modules/wonder-log/lib/es6_global/src/Log.js"; function handleGetNoneNoWorkerJob(name, list) { Log$WonderLog.warn("job:" + (String(name) + " is none")); return list; } function handleGetNoneWorkerJob(name, jobHandleMap) { return Log$WonderLog.fatal(Log$WonderLog.buildFatalMessage("get no job", "can\'t find job handle function whose job name is " + (String(name) + ""), "", "make sure that the job name defined in config record be correctly", "jobHandleMap:" + (Log$WonderLog.getJsonStr(jobHandleMap) + ("\nname: " + (String(name) + ""))))); } function addJob(param, jobList) { var targetHandleFunc = param[3]; var targetJobName = param[0]; if (param[2]) { var afterJobName = param[1]; return List.fold_left((function (list, jobItem) { var match = jobItem[0] === afterJobName; if (match) { return Pervasives.$at(list, /* :: */[ jobItem, /* :: */[ /* tuple */[ targetJobName, targetHandleFunc ], /* [] */0 ] ]); } else { return Pervasives.$at(list, /* :: */[ jobItem, /* [] */0 ]); } }), /* [] */0, jobList); } else { return /* :: */[ /* tuple */[ targetJobName, targetHandleFunc ], jobList ]; } } function removeJob(targetJobName, jobList) { return List.filter((function (param) { return param[0] !== targetJobName; }))(jobList); } export { handleGetNoneNoWorkerJob , handleGetNoneWorkerJob , addJob , removeJob , } /* Log-WonderLog Not a pure module */
alphamatic/amp
dataflow/model/utils.py
""" Contain functions used by both `run_experiment.py` and `run_notebook.py` to run experiments. Import as: import dataflow.model.utils as dtfmodutil """ # TODO(gp): -> experiment_utils.py # TODO(gp): All these functions should be tested. The problem is that these functions # rely on results from experiments and the format of the experiment is still in flux. # One approach is to: # - have unit tests that run short experiments (typically disabled) # - save the results of the experiments on S3 (or on disk) # - use the S3 experiments as mocks for the real unit tests # If the format of the experiment changes, we can just re-run the mock experiments # and refresh them on S3. import argparse import collections import glob import json import logging import os import re import sys from typing import Any, Dict, Iterable, List, Match, Optional, Tuple, cast import pandas as pd from tqdm.autonotebook import tqdm import core.config as cconfig import core.signal_processing as csigproc import dataflow.core as dtf import helpers.hdbg as hdbg import helpers.hio as hio import helpers.hparser as hparser import helpers.hpickle as hpickle import helpers.hprint as hprint import helpers.hs3 as hs3 _LOG = logging.getLogger(__name__) def add_experiment_arg( parser: argparse.ArgumentParser, dst_dir_required: bool, dst_dir_default: Optional[str] = None, ) -> argparse.ArgumentParser: """ Add common command line options to run experiments and notebooks. :param dst_dir_required: whether the user must specify a destination directory or not. If not, a default value should be passed through `dst_dir_default` :param dst_dir_default: a default destination dir """ parser = hparser.add_dst_dir_arg( parser, dst_dir_required=dst_dir_required, dst_dir_default=dst_dir_default ) parser = hparser.add_parallel_processing_arg(parser) parser.add_argument( "--index", action="store", default=None, help="Run a single experiment corresponding to the i-th config", ) parser.add_argument( "--config_builder", action="store", required=True, help=""" Full invocation of Python function to create configs, e.g., `nlp.build_configs.build_Task1297_configs(random_seed_variants=[911,2,0])` """, ) parser.add_argument( "--start_from_index", action="store", default=None, help="Run experiments starting from a specified index", ) return parser # type: ignore # TODO(gp): Generalize this logic for `parallel_execute`. # Each task writes in a directory and if it terminates, the success.txt file is # written. def skip_configs_already_executed( configs: List[cconfig.Config], incremental: bool ) -> Tuple[List[cconfig.Config], int]: """ Remove from the list the configs that have already been executed. """ configs_out = [] num_skipped = 0 for config in configs: # If there is already a success file in the dir, skip the experiment. experiment_result_dir = config[("meta", "experiment_result_dir")] file_name = os.path.join(experiment_result_dir, "success.txt") if incremental and os.path.exists(file_name): idx = config[("meta", "id")] _LOG.warning("Found file '%s': skipping run %d", file_name, idx) num_skipped += 1 else: configs_out.append(config) return configs_out, num_skipped def mark_config_as_success(experiment_result_dir: str) -> None: """ Publish an empty file to indicate a successful finish. """ file_name = os.path.join(experiment_result_dir, "success.txt") _LOG.info("Creating file_name='%s'", file_name) hio.to_file(file_name, "success") def setup_experiment_dir(config: cconfig.Config) -> None: """ Set up the directory and the book-keeping artifacts for the experiment running `config`. :return: whether we need to run this config or not """ hdbg.dassert_isinstance(config, cconfig.Config) # Create subdirectory structure for experiment results. experiment_result_dir = config[("meta", "experiment_result_dir")] _LOG.info("Creating experiment dir '%s'", experiment_result_dir) hio.create_dir(experiment_result_dir, incremental=True) # Prepare book-keeping files. file_name = os.path.join(experiment_result_dir, "config.pkl") _LOG.debug("Saving '%s'", file_name) hpickle.to_pickle(config, file_name) # file_name = os.path.join(experiment_result_dir, "config.txt") _LOG.debug("Saving '%s'", file_name) hio.to_file(file_name, str(config)) def select_config( configs: List[cconfig.Config], index: Optional[int], start_from_index: Optional[int], ) -> List[cconfig.Config]: """ Select configs to run based on the command line parameters. :param configs: list of configs :param index: index of a config to execute, if not `None` :param start_from_index: index of a config to start execution from, if not `None` :return: list of configs to execute """ hdbg.dassert_container_type(configs, List, cconfig.Config) hdbg.dassert_lte(1, len(configs)) if index is not None: index = int(index) _LOG.warning("Only config %d will be executed because of --index", index) hdbg.dassert_lte(0, index) hdbg.dassert_lt(index, len(configs)) configs = [configs[index]] elif start_from_index is not None: start_from_index = int(start_from_index) _LOG.warning( "Only configs >= %d will be executed because of --start_from_index", start_from_index, ) hdbg.dassert_lte(0, start_from_index) hdbg.dassert_lt(start_from_index, len(configs)) configs = [c for idx, c in enumerate(configs) if idx >= start_from_index] _LOG.info("Selected %s configs", len(configs)) hdbg.dassert_container_type(configs, List, cconfig.Config) return configs def get_configs_from_command_line( args: argparse.Namespace, ) -> List[cconfig.Config]: """ Return all the configs to run given the command line interface. The configs are patched with all the information from the command line (e.g., `idx`, `config_builder`, `experiment_builder`, `dst_dir`, `experiment_result_dir`). """ # Build the map with the config parameters. config_builder = args.config_builder configs = cconfig.get_configs_from_builder(config_builder) params = { "config_builder": args.config_builder, "dst_dir": args.dst_dir, } if hasattr(args, "experiment_builder"): params["experiment_builder"] = args.experiment_builder # Patch the configs with the command line parameters. configs = cconfig.patch_configs(configs, params) _LOG.info("Generated %d configs from the builder", len(configs)) # Select the configs based on command line options. index = args.index start_from_index = args.start_from_index configs = select_config(configs, index, start_from_index) _LOG.info("Selected %d configs from command line", len(configs)) # Remove the configs already executed. incremental = not args.no_incremental configs, num_skipped = skip_configs_already_executed(configs, incremental) _LOG.info("Removed %d configs since already executed", num_skipped) _LOG.info("Need to execute %d configs", len(configs)) # Handle --dry_run, if needed. if args.dry_run: _LOG.warning( "The following configs will not be executed due to passing --dry_run:" ) for i, config in enumerate(configs): print(hprint.frame("Config %d/%s" % (i + 1, len(configs)))) print(str(config)) sys.exit(0) return configs def report_failed_experiments( configs: List[cconfig.Config], rcs: List[int] ) -> int: """ Report failing experiments. :return: return code """ # Get the experiment selected_idxs. experiment_ids = [int(config[("meta", "id")]) for config in configs] # Match experiment selected_idxs with their return codes. failed_experiment_ids = [ i for i, rc in zip(experiment_ids, rcs) if rc is not None and rc != 0 ] # Report. if failed_experiment_ids: _LOG.error( "There are %d failed experiments: %s", len(failed_experiment_ids), failed_experiment_ids, ) rc = -1 else: rc = 0 # TODO(gp): Save on a file the failed experiments' configs. return rc # ############################################################################# # Load and save experiment `ResultBundle`. # ############################################################################# def save_experiment_result_bundle( config: cconfig.Config, result_bundle: dtf.ResultBundle, file_name: str = "result_bundle.pkl", ) -> None: """ Save the `ResultBundle` from running `Config`. """ # TODO(Paul): Consider having the caller provide the dir instead. file_name = os.path.join(config["meta", "experiment_result_dir"], file_name) result_bundle.to_pickle(file_name, use_pq=True) # ############################################################################# def _retrieve_archived_experiment_artifacts_from_S3( s3_file_name: str, dst_dir: str, aws_profile: str, ) -> str: """ Retrieve a package containing experiment artifacts from S3. :param s3_file_name: S3 file name containing the archive. E.g., s3://alphamatic-data/experiments/experiment.RH1E.v1.20210726-20_09_53.5T.tgz :param dst_dir: where to save the data :param aws_profile: the AWS profile to use it to access the archive :return: path to local dir with the content of the decompressed archive """ hs3.dassert_is_s3_path(s3_file_name) # Get the file name and the enclosing dir name. dir_name = os.path.basename(os.path.dirname(s3_file_name)) if dir_name != "experiments": _LOG.warning( "The file name '%s' is not under `experiments` dir", s3_file_name ) hdbg.dassert_file_extension(s3_file_name, "tgz") tgz_dst_dir = hs3.retrieve_archived_data_from_s3( s3_file_name, dst_dir, aws_profile ) _LOG.info("Retrieved artifacts to '%s'", tgz_dst_dir) return tgz_dst_dir # type: ignore[no-any-return] def _get_experiment_subdirs( src_dir: str, selected_idxs: Optional[Iterable[int]] = None, aws_profile: Optional[str] = None, ) -> Tuple[str, Dict[int, str]]: """ Get the subdirectories under `src_dir` with a format like `result_*`. This function works also for archived (S3 or local) tarballs of experiment results. :param src_dir: directory with results or S3 path to archive :param selected_idxs: config indices to consider. `None` means all available experiments :return: the dir used to retrieve the experiment subdirectory, dict `config idx` to `experiment subdirectory` """ # Handle the situation where the file is an archived file. if src_dir.endswith(".tgz"): scratch_dir = "." if hs3.is_s3_path(src_dir): hdbg.dassert_is_not(aws_profile, None) aws_profile = cast(str, aws_profile) tgz_file = _retrieve_archived_experiment_artifacts_from_S3( src_dir, scratch_dir, aws_profile ) else: tgz_file = src_dir # Expand. src_dir = hs3.expand_archived_data(tgz_file, scratch_dir) _LOG.debug("src_dir=%s", src_dir) # Retrieve all the subdirectories in `src_dir` that store results. hdbg.dassert_dir_exists(src_dir) subdirs = [d for d in glob.glob(f"{src_dir}/result_*") if os.path.isdir(d)] _LOG.info("Found %d experiment subdirs in '%s'", len(subdirs), src_dir) # Build a mapping from `config_idx` to `experiment_dir`. config_idx_to_dir: Dict[int, str] = {} for subdir in subdirs: _LOG.debug("subdir='%s'", subdir) # E.g., `result_123" m = re.match(r"^result_(\d+)$", os.path.basename(subdir)) hdbg.dassert(m) m = cast(Match[str], m) key = int(m.group(1)) hdbg.dassert_not_in(key, config_idx_to_dir) config_idx_to_dir[key] = subdir # Select the indices of files to load. config_idxs = config_idx_to_dir.keys() if selected_idxs is None: # All indices. selected_keys = sorted(config_idxs) else: idxs_l = set(selected_idxs) hdbg.dassert_is_subset(idxs_l, set(config_idxs)) selected_keys = [key for key in sorted(config_idxs) if key in idxs_l] # Subset the experiment subdirs based on the selected keys. experiment_subdirs = {key: config_idx_to_dir[key] for key in selected_keys} hdbg.dassert_lte( 1, len(experiment_subdirs), "Can't find subdirs in '%s'", experiment_subdirs, ) return src_dir, experiment_subdirs def _load_experiment_artifact( file_name: str, load_rb_kwargs: Optional[Dict[str, Any]] = None, ) -> Any: """ Load an experiment artifact whose format is encoded in name and extension. The content of a `result` dir looks like: config.pkl config.txt result_bundle_v1.0.pkl result_bundle_v2.0.pkl result_bundle_v2.0.pkl run_experiment.0.log - `result_bundle.v2_0.*`: a `ResultBundle` split between a pickle and Parquet - `result_bundle.v1_0.pkl`: a pickle file containing an entire `ResultBundle` - `config.pkl`: a pickle file containing a `Config` :param load_rb_kwargs: parameters passed to `ResultBundle.from_pickle` """ base_name = os.path.basename(file_name) if base_name == "result_bundle.v2_0.pkl": # Load a `ResultBundle` stored in `rb` format. res = dtf.ResultBundle.from_pickle( file_name, use_pq=True, **load_rb_kwargs ) elif base_name == "result_bundle.v1_0.pkl": # Load `ResultBundle` stored as a single pickle. res = dtf.ResultBundle.from_pickle( file_name, use_pq=False, **load_rb_kwargs ) elif base_name == "config.pkl": # Load a `Config` stored as a pickle file. res = hpickle.from_pickle(file_name, log_level=logging.DEBUG) # TODO(gp): We should convert it to a `Config`. elif base_name.endswith(".json"): # Load JSON files. # TODO(gp): Use hpickle.to_json with open(file_name, "r") as file: res = json.load(file) elif base_name.endswith(".txt"): # Load txt files. res = hio.from_file(file_name) else: raise ValueError(f"Invalid file_name='{file_name}'") return res def yield_experiment_artifacts( src_dir: str, file_name: str, load_rb_kwargs: Dict[str, Any], selected_idxs: Optional[Iterable[int]] = None, aws_profile: Optional[str] = None, ) -> Iterable[Tuple[str, Any]]: """ Create an iterator returning the key of the experiment and an artifact. Same inputs as `load_experiment_artifacts()`. """ _LOG.info("# Load artifacts '%s' from '%s'", file_name, src_dir) # Get the experiment subdirs. src_dir, experiment_subdirs = _get_experiment_subdirs( src_dir, selected_idxs, aws_profile=aws_profile ) # Iterate over experiment directories. for key, subdir in tqdm(experiment_subdirs.items(), desc="Loading artifacts"): # Build the name of the file. hdbg.dassert_dir_exists(subdir) file_name_tmp = os.path.join(subdir, file_name) _LOG.debug("Loading '%s'", file_name_tmp) if not os.path.exists(file_name_tmp): _LOG.warning("Can't find '%s': skipping", file_name_tmp) continue obj = _load_experiment_artifact(file_name_tmp, load_rb_kwargs) yield key, obj def _yield_rolling_experiment_out_of_sample_df( src_dir: str, file_name_prefix: str, load_rb_kwargs: Dict[str, Any], selected_idxs: Optional[Iterable[int]] = None, aws_profile: Optional[str] = None, ) -> Iterable[Tuple[str, pd.DataFrame]]: """ Return in experiment dirs under `src_dir` matching `file_name_prefix*`. This function stitches together out-of-sample predictions from consecutive runs to form a single out-of-sample dataframe. Same inputs as `load_experiment_artifacts()`. """ # TODO(gp): Not sure what are the acceptable prefixes. hdbg.dassert_in( file_name_prefix, ("result_bundle.v1_0.pkl", "result_bundle.v2_0.pkl") ) # TODO(Paul): Generalize to loading fit `ResultBundle`s. _LOG.info("# Load artifacts '%s' from '%s'", file_name_prefix, src_dir) # Get the experiment subdirs. src_dir, experiment_subdirs = _get_experiment_subdirs( src_dir, selected_idxs, aws_profile=aws_profile ) # Iterate over experiment directories. for key, subdir in tqdm(experiment_subdirs.items(), desc="Loading artifacts"): hdbg.dassert_dir_exists(subdir) # TODO(Paul): Sort these explicitly. Currently we rely on an implicit # order. files = glob.glob(os.path.join(subdir, file_name_prefix) + "*") dfs = [] # Iterate over OOS chunks. for file_name_tmp in files: _LOG.debug("Loading '%s'", file_name_tmp) if not os.path.exists(file_name_tmp): _LOG.warning("Can't find '%s': skipping", file_name_tmp) continue hdbg.dassert(os.path.basename(file_name_tmp)) rb = _load_experiment_artifact(file_name_tmp, load_rb_kwargs) dfs.append(rb["result_df"]) if dfs: df = pd.concat(dfs, axis=0) hdbg.dassert_strictly_increasing_index(df) df = csigproc.resample(df, rule=dfs[0].index.freq).sum(min_count=1) yield key, df def load_experiment_artifacts( src_dir: str, file_name: str, experiment_type: str, load_rb_kwargs: Optional[Dict[str, Any]] = None, selected_idxs: Optional[Iterable[int]] = None, aws_profile: Optional[str] = None, ) -> Dict[str, Any]: """ Load the results of an experiment. The function returns the contents of the files, indexed by the key extracted from the subdirectory index name. This function assumes subdirectories under `src_dir` have the following structure: ``` {src_dir}/result_{idx}/{file_name} ``` where `idx` denotes an integer encoded in the subdirectory name, representing the key of the experiment. :param src_dir: directory containing subdirectories of experiment results It is the directory that was specified as `--dst_dir` in `run_experiment.py` and `run_notebook.py` :param file_name: the file name within each run results subdirectory to load E.g., `result_bundle.v1_0.pkl` or `result_bundle.v2_0.pkl` :param load_rb_kwargs: parameters for loading a `ResultBundle` (see :param selected_idxs: specific experiment indices to load. `None` (default) loads all available indices """ _LOG.info( "Before load_experiment_artifacts: memory_usage=%s", hdbg.get_memory_usage_as_str(None), ) if experiment_type == "ins_oos": iterator = yield_experiment_artifacts elif experiment_type == "rolling_oos": iterator = _yield_rolling_experiment_out_of_sample_df else: raise ValueError("Invalid experiment_type='%s'", experiment_type) iter = iterator( src_dir, file_name, load_rb_kwargs=load_rb_kwargs, selected_idxs=selected_idxs, aws_profile=aws_profile, ) # TODO(gp): We might want also to compare to the original experiments Configs. artifacts = collections.OrderedDict() for key, artifact in iter: _LOG.info( "load_experiment_artifacts: memory_usage=%s", hdbg.get_memory_usage_as_str(None), ) artifacts[key] = artifact hdbg.dassert(artifacts, "No data read from '%s'", src_dir) _LOG.info( "After load_experiment_artifacts: memory_usage=%s", hdbg.get_memory_usage_as_str(None), ) return artifacts
Kikehulk/ors-map-client
src/fragments/forms/map-form/components/place-and-directions/components/route-details/components/steps/i18n/steps.i18n.pt-br.js
<reponame>Kikehulk/ors-map-client export default { steps: { instruction: 'Instrução', on: 'em', step: 'passo', gotoStep: 'Ir para passo' } }
Semicheche/foa_frappe_docker
frappe-bench/apps/erpnext/erpnext/non_profit/doctype/chapter/chapter.py
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.website.website_generator import WebsiteGenerator class Chapter(WebsiteGenerator): _website = frappe._dict( condition_field = "published", ) def get_context(self, context): context.no_cache = True context.show_sidebar = True context.parents = [dict(label='View All Chapters', route='chapters', title='View Chapters')] def validate(self): if not self.route: #pylint: disable=E0203 self.route = 'chapters/' + self.scrub(self.name) def enable(self): chapter = frappe.get_doc('Chapter', frappe.form_dict.name) chapter.append('members', dict(enable=self.value)) chapter.save(ignore_permissions=1) frappe.db.commit() def get_list_context(context): context.allow_guest = True context.no_cache = True context.show_sidebar = True context.title = 'All Chapters' context.no_breadcrumbs = True context.order_by = 'creation desc' context.introduction = '<p>All Chapters</p>' @frappe.whitelist() def leave(title, user_id, leave_reason): chapter = frappe.get_doc("Chapter", title) for member in chapter.members: if member.user == user_id: member.enabled = 0 member.leave_reason = leave_reason chapter.save(ignore_permissions=1) frappe.db.commit() return "Thank you for Feedback"
AYCHCOM/Transporter
spec/factories/shopify/order.rb
FactoryBot.define do factory :shopify_order_hash, class: Hash do skip_create sequence(:name) { |n| "name-#{n}" } sequence(:email) { |n| "email-#{n}" } sequence(:financial_status) { |n| "financial-status-#{n}" } sequence(:fulfillment_status) { |n| "fulfillment-status-#{n}" } sequence(:currency) { |n| "currency-#{n}" } sequence(:buyer_accepts_marketing) { |n| "buyer-accepts-marketing-#{n}" } sequence(:cancel_reason) { |n| "cancel-reason-#{n}" } sequence(:cancelled_at) { |n| "cancelled-at-#{n}" } sequence(:closed_at) { |n| "closed-at-#{n}" } sequence(:tags) { |n| "tags-#{n}" } sequence(:note) { |n| "note-#{n}" } sequence(:phone) { |n| "phone-#{n}" } sequence(:referring_site) { |n| "referring-site#{n}" } sequence(:processed_at) { |n| "processed-at-#{n}" } sequence(:source_name) { |n| "source-name-#{n}" } sequence(:total_weight) { |n| "total-weight-#{n}" } sequence(:total_tax) { |n| "total-tax-#{n}" } trait :with_line_items do transient do line_item_count { 1 } tax_line_count { 1 } end line_items do if tax_line_count > 0 create_list(:order_line_item, line_item_count, :with_tax_lines, tax_line_count: tax_line_count) else create_list(:order_line_item, line_item_count) end end end trait :with_shipping_address do association :shipping_address, factory: :address initialize_with do attributes.stringify_keys end end trait :with_billing_address do association :billing_address, factory: :address initialize_with do attributes.stringify_keys end end trait :with_metafields do transient do metafields { nil } metafield_count { 1 } end after(:build) do |order, evaluator| order['metafields'] = evaluator.metafields || create_list(:metafield, evaluator.metafield_count) end end trait :with_transactions do transactions do [ { 'amount': '1000', 'kind': 'sale', 'status': 'success' }.stringify_keys, { 'amount': '500', 'kind': 'refund', 'status': 'success' }.stringify_keys ] end end trait :with_discounts do discounts do [ { 'amount': 25, 'code': '25OFF', 'type': 'fixed_amount' }.stringify_keys, { 'amount': 20, 'code': 'FREESHIPPINGUNDER20', 'type': 'shipping' }.stringify_keys ] end end trait :with_shipping_lines do shipping_lines do [ { 'code': 'FedEx 1-day Air', 'title': 'FedEx 1-day Air', 'price': 35, 'source': 'Magento', 'carrier_identifier': 'FedEx', 'tax_lines': [ { 'price': 3.5 }, ], }.deep_stringify_keys, ] end end trait :complete do transient do tax_line_count { 0 } end with_line_items with_shipping_address with_billing_address with_metafields end initialize_with { attributes.stringify_keys } end factory :order_line_item, class: Hash do skip_create sequence(:name) { |n| "name-#{n}" } sequence(:quantity) { |n| "quantity-#{n}" } sequence(:price) { |n| "price-#{n}" } sequence(:taxable) { |n| "taxable-#{n}" } sequence(:requires_shipping) { |n| "requires-shipping#{n}" } sequence(:sku) { |n| "sku-#{n}" } sequence(:fulfillment_status) { |n| "fulfillment-status#{n}" } trait :with_tax_lines do transient do tax_line_count = 1 end tax_lines do create_list(:line_item_tax_line, tax_line_count) end end initialize_with { attributes.stringify_keys } end factory :line_item_tax_line, class: Hash do skip_create sequence(:title) { |n| "title-#{n}" } sequence(:price) { |n| "price-#{n}" } sequence(:rate) { |n| "rate-#{n}" } initialize_with { attributes.stringify_keys } end end
TrojanVulgar/Netflix-App-tip
app/src/main/java/com/easyplex/EasyPlexApp.java
package com.easyplex; import android.app.Activity; import android.app.Application; import android.content.Context; import androidx.multidex.MultiDexApplication; import com.easyplex.di.AppInjector; import com.easyplex.util.Tools; import com.facebook.ads.AudienceNetworkAds; import com.google.android.gms.ads.MobileAds; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.HasAndroidInjector; import timber.log.Timber; /** * Application level class. * * @author Yobex. */ public class EasyPlexApp extends MultiDexApplication implements HasAndroidInjector { @Inject DispatchingAndroidInjector<Object> androidInjector; private static Context context; @Override public void onCreate() { super.onCreate(); AppInjector.init(this); // Initialize the Audience Network SDK AudienceNetworkAds.initialize(this); // Initialize the Mobile Ads SDK. MobileAds.initialize(this, initializationStatus -> {}); // Initialize the Audience Network SDK AudienceNetworkAds.initialize(this); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } Timber.i("Creating our Application"); EasyPlexApp.context = getApplicationContext(); } public static Context getInstance() { return EasyPlexApp.context; } public static boolean hasNetwork() { return Tools.checkIfHasNetwork(context); } public static Context getContext() { return context; } @Override public AndroidInjector<Object> androidInjector() { AppInjector.init(this); return androidInjector; } } /* * Application has activities that is why we implement HasActivityInjector interface. * Activities have fragments so we have to implement HasFragmentInjector/HasSupportFragmentInjector * in our activities. * No child fragment and don’t inject anything in your fragments, no need to implement * HasSupportFragmentInjector. */
damb/seiscomp3
src/sed/apps/scwfparam/util.cpp
<reponame>damb/seiscomp3<gh_stars>10-100 /*************************************************************************** * Copyright (C) by ETHZ/SED, GNS New Zealand, GeoScience Australia * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * SeisComP Public License for more details. * * * * Developed by gempa GmbH * ***************************************************************************/ #include "util.h" #include <seiscomp3/core/strings.h> #include <seiscomp3/datamodel/pick.h> #include <seiscomp3/datamodel/arrival.h> #include <seiscomp3/datamodel/origin.h> #include <seiscomp3/datamodel/amplitude.h> #include <seiscomp3/datamodel/waveformstreamid.h> /* #include <seiscomp3/core/platform/platform.h> #ifdef MACOSX // On OSX HOST_NAME_MAX is not define in sys/params.h. Therefore we use // instead on this platform. #include <sys/param.h> #define HOST_NAME_MAX MAXHOSTNAMELEN #endif */ #include <seiscomp3/core/system.h> #include <iomanip> using namespace std; namespace Seiscomp { namespace Private { namespace { bool passes(const StringSet &ids, const std::string &id) { StringSet::iterator it; for ( it = ids.begin(); it != ids.end(); ++it ) { if ( Core::wildcmp(*it, id) ) return true; } return false; } } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StringFirewall::isAllowed(const std::string &s) const { // If no rules are configured, don't cache anything and just return true if ( allow.empty() && deny.empty() ) return true; StringPassMap::const_iterator it = cache.find(s); // Not yet cached, evaluate the string if ( it == cache.end() ) { bool check = (allow.empty()?true:passes(allow, s)) && (deny.empty()?true:!passes(deny, s)); cache[s] = check; return check; } // Return cached result return it->second; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StringFirewall::isBlocked(const std::string &s) const { return !isAllowed(s); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool equivalent(const DataModel::WaveformStreamID &wfid1, const DataModel::WaveformStreamID &wfid2) { if ( wfid1.networkCode() != wfid2.networkCode() ) return false; if ( wfid1.stationCode() != wfid2.stationCode() ) return false; if ( wfid1.channelCode() != wfid2.channelCode() ) return false; // here we consider diffenent location codes to be irrelevant return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> double arrivalWeight(const DataModel::Arrival *arr, double defaultWeight) { try { return arr->weight(); } catch ( Core::ValueException& ) { return defaultWeight; } } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> double arrivalDistance(const DataModel::Arrival *arr) { // TODO: If there is no distance set an exception will be thrown. // The distance has to be calculated manually then. return arr->distance(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DataModel::EvaluationStatus status(const DataModel::Origin *origin) { DataModel::EvaluationStatus status = DataModel::CONFIRMED; try { status = origin->evaluationStatus(); } catch ( Core::ValueException& ) {} return status; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> char shortPhaseName(const std::string &phase) { for ( std::string::const_reverse_iterator it = phase.rbegin(); it != phase.rend(); ++it ) { if ( isupper(*it ) ) return *it; } return phase[0]; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> std::string toStationID(const DataModel::WaveformStreamID &wfid) { const std::string &net = wfid.networkCode(), &sta = wfid.stationCode(); return net + "." + sta; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> std::string toStreamID(const DataModel::WaveformStreamID &wfid) { const std::string &net = wfid.networkCode(), &sta = wfid.stationCode(), &loc = wfid.locationCode(), &cha = wfid.channelCode(); return net + "." + sta + "." + loc + "." + cha; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DataModel::WaveformStreamID setStreamComponent(const DataModel::WaveformStreamID &id, char comp) { return DataModel::WaveformStreamID( id.networkCode(), id.stationCode(), id.locationCode(), id.channelCode().substr(0,id.channelCode().size()-1) + comp, id.resourceURI()); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DataModel::Stream* findStream(DataModel::Station *station, const Core::Time &time, Processing::WaveformProcessor::SignalUnit requestedUnit) { for ( size_t i = 0; i < station->sensorLocationCount(); ++i ) { DataModel::SensorLocation *loc = station->sensorLocation(i); try { if ( loc->end() <= time ) continue; } catch ( Core::ValueException& ) {} if ( loc->start() > time ) continue; for ( size_t j = 0; j < loc->streamCount(); ++j ) { DataModel::Stream *stream = loc->stream(j); try { if ( stream->end() <= time ) continue; } catch ( Core::ValueException& ) {} if ( stream->start() > time ) continue; //Sensor *sensor = Sensor::Find(stream->sensor()); //if ( !sensor ) continue; Processing::WaveformProcessor::SignalUnit unit; // Unable to retrieve the unit enumeration from string //if ( !unit.fromString(sensor->unit().c_str()) ) continue; if ( !unit.fromString(stream->gainUnit().c_str()) ) continue; if ( unit != requestedUnit ) continue; return stream; } } return NULL; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DataModel::Stream* findStreamMaxSR(DataModel::Station *station, const Core::Time &time, Processing::WaveformProcessor::SignalUnit requestedUnit, const StringFirewall *firewall) { string stationID = station->network()->code() + "." + station->code(); DataModel::Stream *res = NULL; double fsampMax = 0.0; for ( size_t i = 0; i < station->sensorLocationCount(); ++i ) { DataModel::SensorLocation *loc = station->sensorLocation(i); try { if ( loc->end() <= time ) continue; } catch ( Core::ValueException& ) {} if ( loc->start() > time ) continue; for ( size_t j = 0; j < loc->streamCount(); ++j ) { DataModel::Stream *stream = loc->stream(j); try { if ( stream->end() <= time ) continue; } catch ( Core::ValueException& ) {} if ( stream->start() > time ) continue; Processing::WaveformProcessor::SignalUnit unit; // Unable to retrieve the unit enumeration from string //if ( !unit.fromString(sensor->unit().c_str()) ) continue; string gainUnit = stream->gainUnit(); std::transform(gainUnit.begin(), gainUnit.end(), gainUnit.begin(), ::toupper); if ( !unit.fromString(gainUnit) ) continue; if ( unit != requestedUnit ) continue; if ( firewall != NULL ) { string streamID = stationID + "." + loc->code() + "." + stream->code(); if ( firewall->isBlocked(streamID) ) continue; } try { if ( stream->sampleRateDenominator() == 0 ) { if ( res == NULL ) res = stream; continue; } else { double fsamp = stream->sampleRateNumerator() / stream->sampleRateDenominator(); if ( fsamp > fsampMax ) { res = stream; fsampMax = fsamp; continue; } } } catch ( Core::ValueException& ) { if ( res == NULL ) res = stream; continue; } } } return res; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } }
mrpapercut/wscript-malware-analyser
lib/common/Enumerator.js
'use strict'; /** * Enumerator.js * This Object spoofs the Scripting.FileSystemObject Enumerator Object * Properties and methods taken from Microsoft documentation * https://msdn.microsoft.com/en-us/library/x32bxwys(v=vs.100).aspx */ /** * An Enumerator is used on collections, as collections don't allow * direct member access, except with for..in loops. As our collections * are simple arrays, this is easily emulated. */ class Enumerator { constructor(collection) { if (collection instanceof Array === false) { throw new TypeError('Invalid type'); } this._collection = collection; this._index = 0; this._length = collection.length; } // Default methods // https://msdn.microsoft.com/en-us/library/b8w3zzse(v=vs.100).aspx atEnd() { return this._index >= this._length; } // https://msdn.microsoft.com/en-us/library/y4s58h5h(v=vs.100).aspx item() { return this.atEnd() ? undefined : this._collection[this._index]; } // https://msdn.microsoft.com/en-us/library/5whkkbkf(v=vs.100).aspx moveFirst() { this._index = 0; } // https://msdn.microsoft.com/en-us/library/s1t8z1b3(v=vs.100).aspx moveNext() { this._index++; } } module.exports = class EnumeratorProxy { constructor() { return new Proxy(new Enumerator(...arguments), { get(target, propKey, receiver) { const methods = Object.getOwnPropertyNames(target.constructor.prototype); const props = Object.keys(target); const regex = new RegExp(`^${propKey}$`, 'i'); let matched = null; for (let i in methods) { if (regex.test(methods[i])) { matched = methods[i]; } } for (let i in props) { if (regex.test(props[i])) { matched = props[i]; } } return target[matched]; } }); } };
AustinShalit/RobotBuilder
src/main/java/robotbuilder/data/CommandGroupEntry.java
<filename>src/main/java/robotbuilder/data/CommandGroupEntry.java package robotbuilder.data; import java.io.Serializable; import java.util.ArrayList; import lombok.Data; import lombok.NoArgsConstructor; import robotbuilder.MainFrame; import robotbuilder.data.properties.ParameterDescriptor; import robotbuilder.data.properties.ParametersProperty; import robotbuilder.data.properties.Validatable; import robotbuilder.robottree.RobotTree; /** * * @author <NAME> */ @Data @NoArgsConstructor public class CommandGroupEntry implements Validatable, Serializable { private static final long serialVersionUID = -1811590357861066730L; // Strings because snakeyaml doesn't like enums public static final String SEQUENTIAL = "Sequential"; public static final String PARALLEL = "Parallel"; /** * The command that this command runs after. */ private CommandGroupEntry previous = null; /** * The model for the command this contains. */ private RobotComponentModel command; /** * The order this command runs in. Defaults to sequential. */ private String order = SEQUENTIAL; /** * The parameters passed to the command. */ private ParametersProperty parameters; /** * Flag for this entry having a matching command in the robot tree. */ private boolean hasMatch = true; public CommandGroupEntry(RobotComponent command) { this.command = command.getModel(); this.parameters = new ParametersProperty("ParametersProperty", new ArrayList<>(), null, command); this.parameters.matchUpWith((ParametersProperty) command.getProperty("Parameters")); } @Override public String getName() { return command.getName(); } @Override public String toString() { return "CommandGroupEntry(name=" + getName() + ",order=" + order + ")"; } public boolean isSequential() { return SEQUENTIAL.equals(order); } public boolean isParallel() { return PARALLEL.equals(order); } @Override public boolean isValid() { return hasMatch && parameters.getValue().stream().allMatch(ParameterDescriptor::isValid); } public void setOrder(String order) { if (SEQUENTIAL.equals(order) || PARALLEL.equals(order)) { this.order = order; } else { // maybe log it? } } /** * Matches the parameters of this command to the parameters of the command * in the tree corresponding to this one. If no command in the tree has the * same name as this one, there is no match and this method returns * {@code false}. * * @return true if the parameters were matched, false if they weren't */ public boolean matchToTree() { RobotTree robot = MainFrame.getInstance().getCurrentRobotTree(); RobotComponent commandInTree = robot.getComponentByName(command.getName()); if (commandInTree == null) { return false; } parameters.matchUpWith((ParametersProperty) commandInTree.getProperty("Parameters")); return true; } }
timower/libnsfb-reMarkable
src/surface/x.c
/* * Copyright 2009 <NAME> <<EMAIL>> * * This file is part of libnsfb, http://www.netsurf-browser.org/ * Licenced under the MIT License, * http://www.opensource.org/licenses/mit-license.php */ #define _XOPEN_SOURCE 500 #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/ipc.h> #include <sys/shm.h> #include <xcb/xcb.h> #include <xcb/xcb_image.h> #include <xcb/xcb_atom.h> #include <xcb/xcb_icccm.h> #include <xcb/xcb_aux.h> #include <xcb/xcb_keysyms.h> #include "libnsfb.h" #include "libnsfb_event.h" #include "libnsfb_plot.h" #include "libnsfb_plot_util.h" #include "nsfb.h" #include "surface.h" #include "plot.h" #include "cursor.h" #if defined(NSFB_NEED_HINTS_ALLOC) static xcb_size_hints_t * xcb_alloc_size_hints(void) { return calloc(1, sizeof(xcb_size_hints_t)); } static void xcb_free_size_hints(xcb_size_hints_t *hints) { free(hints); } #endif #if defined(NSFB_NEED_ICCCM_API_PREFIX) #define xcb_size_hints_set_max_size xcb_icccm_size_hints_set_max_size #define xcb_size_hints_set_min_size xcb_icccm_size_hints_set_min_size #define xcb_set_wm_size_hints xcb_icccm_set_wm_size_hints #endif #if (NSFB_XCBPROTO_MAJOR_VERSION > 1) || \ (NSFB_XCBPROTO_MAJOR_VERSION == 1 && NSFB_XCBPROTO_MINOR_VERSION >= 6) #define WM_NORMAL_HINTS XCB_ATOM_WM_NORMAL_HINTS #endif #define X_BUTTON_LEFT 1 #define X_BUTTON_MIDDLE 2 #define X_BUTTON_RIGHT 3 #define X_BUTTON_WHEELUP 4 #define X_BUTTON_WHEELDOWN 5 typedef struct xstate_s { xcb_connection_t *connection; /* The x server connection */ xcb_screen_t *screen; /* The screen to put the window on */ xcb_key_symbols_t *keysymbols; /* keysym mappings */ xcb_shm_segment_info_t shminfo; xcb_image_t *image; /* The X image buffer */ xcb_window_t window; /* The handle to the window */ xcb_pixmap_t pmap; /* The handle to the backing pixmap */ xcb_gcontext_t gc; /* The handle to the pixmap plotting graphics context */ xcb_shm_seg_t segment; /* The handle to the image shared memory */ } xstate_t; /* X keyboard codepage to nsfb mapping */ static enum nsfb_key_code_e XCSKeyboardMap[256] = { NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_BACKSPACE, /* XK_BackSpace */ NSFB_KEY_TAB, /* XK_Tab */ NSFB_KEY_UNKNOWN, /* XK_Linefeed */ NSFB_KEY_CLEAR, /* XK_Clear */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_RETURN, /* XK_Return */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x10 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_PAUSE, /* XK_Pause */ NSFB_KEY_UNKNOWN, /* XK_Scroll_Lock */ NSFB_KEY_UNKNOWN, /* XK_Sys_Req */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_ESCAPE, /* XK_Escape */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x20 */ NSFB_KEY_UNKNOWN, /* XK_Multi_key */ NSFB_KEY_UNKNOWN, /* XK_Kanji */ NSFB_KEY_UNKNOWN, /* XK_Muhenkan */ NSFB_KEY_UNKNOWN, /* XK_Henkan_Mode */ NSFB_KEY_UNKNOWN, /* XK_Henkan */ NSFB_KEY_UNKNOWN, /* XK_Romaji */ NSFB_KEY_UNKNOWN, /* XK_Hiragana*/ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x30 */ NSFB_KEY_UNKNOWN, /* XK_Eisu_toggle */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_Codeinput */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_SingleCandidate */ NSFB_KEY_UNKNOWN, /* XK_MultipleCandidate */ NSFB_KEY_UNKNOWN, /* XK_PreviousCandidate */ NSFB_KEY_UNKNOWN, /* */ /* 0x40 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x50 */ NSFB_KEY_HOME, /* XK_Home */ NSFB_KEY_LEFT, /* XK_Left */ NSFB_KEY_UP, /* XK_Up */ NSFB_KEY_RIGHT, /* XK_Right */ NSFB_KEY_DOWN, /* XK_Down */ NSFB_KEY_PAGEUP, /* XK_Page_Up */ NSFB_KEY_PAGEDOWN, /* XK_Page_Down */ NSFB_KEY_END, /* XK_End */ NSFB_KEY_UNKNOWN, /* XK_Begin */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x60 */ NSFB_KEY_UNKNOWN, /* XK_Select */ NSFB_KEY_UNKNOWN, /* XK_Print*/ NSFB_KEY_UNKNOWN, /* XK_Execute*/ NSFB_KEY_UNKNOWN, /* XK_Insert*/ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_Undo*/ NSFB_KEY_UNKNOWN, /* XK_Redo */ NSFB_KEY_UNKNOWN, /* XK_Menu */ NSFB_KEY_UNKNOWN, /* XK_Find */ NSFB_KEY_UNKNOWN, /* XK_Cancel */ NSFB_KEY_UNKNOWN, /* XK_Help */ NSFB_KEY_UNKNOWN, /* XK_Break*/ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x70 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_Mode_switch */ NSFB_KEY_UNKNOWN, /* XK_Num_Lock */ /* 0x80 */ NSFB_KEY_UNKNOWN, /* XK_KP_Space */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_KP_Tab */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_KP_Enter */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0x90 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_KP_F1*/ NSFB_KEY_UNKNOWN, /* XK_KP_F2*/ NSFB_KEY_UNKNOWN, /* XK_KP_F3*/ NSFB_KEY_UNKNOWN, /* XK_KP_F4*/ NSFB_KEY_UNKNOWN, /* XK_KP_Home*/ NSFB_KEY_UNKNOWN, /* XK_KP_Left*/ NSFB_KEY_UNKNOWN, /* XK_KP_Up*/ NSFB_KEY_UNKNOWN, /* XK_KP_Right*/ NSFB_KEY_UNKNOWN, /* XK_KP_Down*/ NSFB_KEY_UNKNOWN, /* XK_KP_Page_Up*/ NSFB_KEY_UNKNOWN, /* XK_KP_Page_Down*/ NSFB_KEY_UNKNOWN, /* XK_KP_End*/ NSFB_KEY_UNKNOWN, /* XK_KP_Begin*/ NSFB_KEY_UNKNOWN, /* XK_KP_Insert*/ NSFB_KEY_UNKNOWN, /* XK_KP_Delete*/ /* 0xa0 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_KP_Multiply*/ NSFB_KEY_UNKNOWN, /* XK_KP_Add*/ NSFB_KEY_UNKNOWN, /* XK_KP_Separator*/ NSFB_KEY_UNKNOWN, /* XK_KP_Subtract*/ NSFB_KEY_UNKNOWN, /* XK_KP_Decimal*/ NSFB_KEY_UNKNOWN, /* XK_KP_Divide*/ /* 0xb0 */ NSFB_KEY_UNKNOWN, /* XK_KP_0 */ NSFB_KEY_UNKNOWN, /* XK_KP_1 */ NSFB_KEY_UNKNOWN, /* XK_KP_2 */ NSFB_KEY_UNKNOWN, /* XK_KP_3 */ NSFB_KEY_UNKNOWN, /* XK_KP_4 */ NSFB_KEY_UNKNOWN, /* XK_KP_5 */ NSFB_KEY_UNKNOWN, /* XK_KP_6 */ NSFB_KEY_UNKNOWN, /* XK_KP_7 */ NSFB_KEY_UNKNOWN, /* XK_KP_8 */ NSFB_KEY_UNKNOWN, /* XK_KP_9 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_F1, /* XK_F1 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* XK_KP_Equal */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_F2, /* XK_F2 */ /* 0xc0 */ NSFB_KEY_F3, /* XK_F3*/ NSFB_KEY_F4, /* XK_F4*/ NSFB_KEY_F5, /* XK_F5*/ NSFB_KEY_F6, /* XK_F6*/ NSFB_KEY_F7, /* XK_F7*/ NSFB_KEY_F8, /* XK_F8*/ NSFB_KEY_F9, /* XK_F9*/ NSFB_KEY_F10, /* XK_F10*/ NSFB_KEY_F11, /* XK_F11*/ NSFB_KEY_F12, /* XK_F12*/ NSFB_KEY_F13, /* XK_F13 */ NSFB_KEY_F14, /* XK_F14 */ NSFB_KEY_F15, /* XK_F15 */ NSFB_KEY_UNKNOWN, /* XK_F16 */ NSFB_KEY_UNKNOWN, /* XK_F17 */ NSFB_KEY_UNKNOWN, /* XK_F18*/ /* 0xd0 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ /* 0xe0 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_LSHIFT, /* XK_Shift_L*/ NSFB_KEY_RSHIFT, /* XK_Shift_R*/ NSFB_KEY_UNKNOWN, /* XK_Control_L*/ NSFB_KEY_UNKNOWN, /* XK_Control_R*/ NSFB_KEY_UNKNOWN, /* XK_Caps_Lock*/ NSFB_KEY_UNKNOWN, /* XK_Shift_Lock*/ NSFB_KEY_UNKNOWN, /* XK_Meta_L*/ NSFB_KEY_UNKNOWN, /* XK_Meta_R*/ NSFB_KEY_UNKNOWN, /* XK_Alt_L */ NSFB_KEY_UNKNOWN, /* XK_Alt_R*/ NSFB_KEY_UNKNOWN, /* XK_Super_L*/ NSFB_KEY_UNKNOWN, /* XK_Super_R*/ NSFB_KEY_UNKNOWN, /* XK_Hyper_L*/ NSFB_KEY_UNKNOWN, /* XK_Hyper_R*/ NSFB_KEY_UNKNOWN, /* */ /* 0xf0 */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ NSFB_KEY_UNKNOWN, /* */ }; /* Convert an X keysym into a nsfb key code. * * Our approach is primarily to assume both codings are roughly ascii like. * * The Keysyms are defined in X11/keysymdef.h and our mapping for the * "keyboard" keys i.e. those from code set 255 is from there */ static enum nsfb_key_code_e xkeysym_to_nsfbkeycode(xcb_keysym_t ks) { enum nsfb_key_code_e nsfb_key = NSFB_KEY_UNKNOWN; uint8_t codeset = (ks & 0xFF00) >> 8; uint8_t chrcode = ks & 0xFF; if (ks != XCB_NO_SYMBOL) { switch (codeset) { case 0x00: /* Latin 1 */ case 0x01: /* Latin 2 */ case 0x02: /* Latin 3 */ case 0x03: /* Latin 4 */ case 0x04: /* Katakana */ case 0x05: /* Arabic */ case 0x06: /* Cyrillic */ case 0x07: /* Greek */ case 0x08: /* Technical */ case 0x0A: /* Publishing */ case 0x0C: /* Hebrew */ case 0x0D: /* Thai */ /* this is somewhat incomplete, but the nsfb codes are lined up on * the ascii codes and x seems to have done similar */ nsfb_key = (enum nsfb_key_code_e)chrcode; break; case 0xFF: /* Keyboard */ nsfb_key = XCSKeyboardMap[chrcode]; break; } } return nsfb_key; } /* static void set_palette(nsfb_t *nsfb) { X_Surface *x_screen = nsfb->surface_priv; X_Color palette[256]; int rloop, gloop, bloop; int loop = 0; // build a linear R:3 G:3 B:2 colour cube palette. for (rloop = 0; rloop < 8; rloop++) { for (gloop = 0; gloop < 8; gloop++) { for (bloop = 0; bloop < 4; bloop++) { palette[loop].r = (rloop << 5) | (rloop << 2) | (rloop >> 1); palette[loop].g = (gloop << 5) | (gloop << 2) | (gloop >> 1); palette[loop].b = (bloop << 6) | (bloop << 4) | (bloop << 2) | (bloop); nsfb->palette[loop] = palette[loop].r | palette[loop].g << 8 | palette[loop].b << 16; loop++; } } } // Set palette //X_SetColors(x_screen, palette, 0, 256); } */ static int update_pixmap(xstate_t *xstate, int x, int y, int width, int height) { if (xstate->shminfo.shmseg == 0) { /* not using shared memory */ xcb_put_image(xstate->connection, xstate->image->format, xstate->pmap, xstate->gc, xstate->image->width, height, 0, y, 0, xstate->image->depth, (height) * xstate->image->stride, xstate->image->data + (y * xstate->image->stride)); } else { /* shared memory */ xcb_image_shm_put(xstate->connection, xstate->pmap, xstate->gc, xstate->image, xstate->shminfo, x,y, x,y, width,height,0); } return 0; } static int update_and_redraw_pixmap(xstate_t *xstate, int x, int y, int width, int height) { update_pixmap(xstate, x, y, width, height); xcb_copy_area(xstate->connection, xstate->pmap, xstate->window, xstate->gc, x, y, x, y, width, height); xcb_flush(xstate->connection); return 0; } static bool xcopy(nsfb_t *nsfb, nsfb_bbox_t *srcbox, nsfb_bbox_t *dstbox) { xstate_t *xstate = nsfb->surface_priv; nsfb_bbox_t allbox; struct nsfb_cursor_s *cursor = nsfb->cursor; uint8_t *srcptr; uint8_t *dstptr; int srcx = srcbox->x0; int srcy = srcbox->y0; int dstx = dstbox->x0; int dsty = dstbox->y0; int width = dstbox->x1 - dstbox->x0; int height = dstbox->y1 - dstbox->y0; int hloop; nsfb_plot_add_rect(srcbox, dstbox, &allbox); /* clear the cursor if its within the region to be altered */ if ((cursor != NULL) && (cursor->plotted == true) && (nsfb_plot_bbox_intersect(&allbox, &cursor->loc))) { nsfb_cursor_clear(nsfb, cursor); update_pixmap(xstate, cursor->savloc.x0, cursor->savloc.y0, cursor->savloc.x1 - cursor->savloc.x0, cursor->savloc.y1 - cursor->savloc.y0); /* must sync here or local framebuffer and remote pixmap will not be * consistant */ xcb_aux_sync(xstate->connection); } /* copy the area on the server */ xcb_copy_area(xstate->connection, xstate->pmap, xstate->pmap, xstate->gc, srcbox->x0, srcbox->y0, dstbox->x0, dstbox->y0, srcbox->x1 - srcbox->x0, srcbox->y1 - srcbox->y0); /* do the copy in the local memory too */ srcptr = (nsfb->ptr + (srcy * nsfb->linelen) + ((srcx * nsfb->bpp) / 8)); dstptr = (nsfb->ptr + (dsty * nsfb->linelen) + ((dstx * nsfb->bpp) / 8)); if (width == nsfb->width) { /* take shortcut and use memmove */ memmove(dstptr, srcptr, (width * height * nsfb->bpp) / 8); } else { if (srcy > dsty) { for (hloop = height; hloop > 0; hloop--) { memmove(dstptr, srcptr, (width * nsfb->bpp) / 8); srcptr += nsfb->linelen; dstptr += nsfb->linelen; } } else { srcptr += height * nsfb->linelen; dstptr += height * nsfb->linelen; for (hloop = height; hloop > 0; hloop--) { srcptr -= nsfb->linelen; dstptr -= nsfb->linelen; memmove(dstptr, srcptr, (width * nsfb->bpp) / 8); } } } if ((cursor != NULL) && (cursor->plotted == false)) { nsfb_cursor_plot(nsfb, cursor); } /* update the x window */ xcb_copy_area(xstate->connection, xstate->pmap, xstate->window, xstate->gc, dstx, dsty, dstx, dsty, width, height); return true; } static int x_set_geometry(nsfb_t *nsfb, int width, int height, enum nsfb_format_e format) { if (nsfb->surface_priv != NULL) return -1; /* if were already initialised fail */ nsfb->width = width; nsfb->height = height; nsfb->format = format; /* select default sw plotters for format */ select_plotters(nsfb); nsfb->plotter_fns->copy = xcopy; return 0; } static xcb_format_t * find_format(xcb_connection_t * c, uint8_t depth, uint8_t bpp) { const xcb_setup_t *setup = xcb_get_setup(c); xcb_format_t *fmt = xcb_setup_pixmap_formats(setup); xcb_format_t *fmtend = fmt + xcb_setup_pixmap_formats_length(setup); for(; fmt != fmtend; ++fmt) { if((fmt->depth == depth) && (fmt->bits_per_pixel == bpp)) { return fmt; } } return 0; } static xcb_image_t * create_shm_image(xstate_t *xstate, int width, int height, int bpp) { const xcb_setup_t *setup = xcb_get_setup(xstate->connection); unsigned char *image_data; xcb_format_t *fmt; int depth = bpp; uint32_t image_size; int shmid; xcb_shm_query_version_reply_t *rep; xcb_shm_query_version_cookie_t ck; xcb_void_cookie_t shm_attach_cookie; xcb_generic_error_t *generic_error; ck = xcb_shm_query_version(xstate->connection); rep = xcb_shm_query_version_reply(xstate->connection, ck , NULL); if (!rep) { fprintf (stderr, "Server has no shm support.\n"); return NULL; } if ((rep->major_version < 1) || (rep->major_version == 1 && rep->minor_version == 0)) { fprintf(stderr, "server SHM support is insufficient.\n"); free(rep); return NULL; } free(rep); if (bpp == 32) depth = 24; fmt = find_format(xstate->connection, depth, bpp); if (fmt == NULL) return NULL; /* doing it this way ensures we deal with bpp smaller than 8 */ image_size = (bpp * width * height) >> 3; /* get the shared memory segment */ shmid = shmget(IPC_PRIVATE, image_size, IPC_CREAT|0777); if (shmid == -1) return NULL; xstate->shminfo.shmid = shmid; xstate->shminfo.shmaddr = shmat(xstate->shminfo.shmid, 0, 0); image_data = xstate->shminfo.shmaddr; xstate->shminfo.shmseg = xcb_generate_id(xstate->connection); shm_attach_cookie = xcb_shm_attach_checked(xstate->connection, xstate->shminfo.shmseg, xstate->shminfo.shmid, 0); generic_error = xcb_request_check(xstate->connection, shm_attach_cookie); /* either there is an error and the shm us no longer needed, or it now * belongs to the x server - regardless release local reference to shared * memory segment */ shmctl(xstate->shminfo.shmid, IPC_RMID, 0); if (generic_error != NULL) { /* unable to attach shm */ xstate->shminfo.shmseg = 0; free(generic_error); return NULL; } return xcb_image_create(width, height, XCB_IMAGE_FORMAT_Z_PIXMAP, fmt->scanline_pad, fmt->depth, fmt->bits_per_pixel, 0, setup->image_byte_order, XCB_IMAGE_ORDER_LSB_FIRST, image_data, image_size, image_data); } static xcb_image_t * create_image(xcb_connection_t *c, int width, int height, int bpp) { const xcb_setup_t *setup = xcb_get_setup(c); unsigned char *image_data; xcb_format_t *fmt; int depth = bpp; uint32_t image_size; if (bpp == 32) depth = 24; fmt = find_format(c, depth, bpp); if (fmt == NULL) return NULL; /* doing it this way ensures we deal with bpp smaller than 8 */ image_size = (bpp * width * height) >> 3; image_data = calloc(1, image_size); if (image_data == NULL) return NULL; return xcb_image_create(width, height, XCB_IMAGE_FORMAT_Z_PIXMAP, fmt->scanline_pad, fmt->depth, fmt->bits_per_pixel, 0, setup->image_byte_order, XCB_IMAGE_ORDER_LSB_FIRST, image_data, image_size, image_data); } /** * Create a blank cursor. * The empty pixmaps is leaked. * * @param conn xcb connection * @param scr xcb XCB screen */ static xcb_cursor_t create_blank_cursor(xcb_connection_t *conn, const xcb_screen_t *scr) { xcb_cursor_t cur = xcb_generate_id(conn); xcb_pixmap_t pix = xcb_generate_id(conn); xcb_void_cookie_t ck; xcb_generic_error_t *err; ck = xcb_create_pixmap_checked (conn, 1, pix, scr->root, 1, 1); err = xcb_request_check (conn, ck); if (err) { fprintf (stderr, "Cannot create pixmap: %d", err->error_code); free (err); } ck = xcb_create_cursor_checked (conn, cur, pix, pix, 0, 0, 0, 0, 0, 0, 0, 0); err = xcb_request_check (conn, ck); if (err) { fprintf (stderr, "Cannot create cursor: %d", err->error_code); free (err); } return cur; } static int x_initialise(nsfb_t *nsfb) { uint32_t mask; uint32_t values[3]; xcb_size_hints_t *hints; xstate_t *xstate = nsfb->surface_priv; xcb_cursor_t blank_cursor; if (xstate != NULL) return -1; /* already initialised */ /* sanity check bpp. */ if ((nsfb->bpp != 32) && (nsfb->bpp != 16) && (nsfb->bpp != 8)) return -1; xstate = calloc(1, sizeof(xstate_t)); if (xstate == NULL) return -1; /* no memory */ /* open connection with the server */ xstate->connection = xcb_connect(NULL, NULL); if (xstate->connection == NULL) { fprintf(stderr, "Memory error opening display\n"); free(xstate); return -1; /* no memory */ } if (xcb_connection_has_error(xstate->connection) != 0) { fprintf(stderr, "Error opening display\n"); free(xstate); return -1; /* no memory */ } /* get screen */ xstate->screen = xcb_setup_roots_iterator(xcb_get_setup(xstate->connection)).data; /* create image */ xstate->image = create_shm_image(xstate, nsfb->width, nsfb->height, nsfb->bpp); if (xstate->image == NULL) xstate->image = create_image(xstate->connection, nsfb->width, nsfb->height, nsfb->bpp); if (xstate->image == NULL) { fprintf(stderr, "Unable to create image\n"); free(xstate); xcb_disconnect(xstate->connection); return -1; } /* ensure plotting information is stored */ nsfb->surface_priv = xstate; nsfb->ptr = xstate->image->data; nsfb->linelen = xstate->image->stride; /* get blank cursor */ blank_cursor = create_blank_cursor(xstate->connection, xstate->screen); /* get keysymbol maps */ xstate->keysymbols = xcb_key_symbols_alloc(xstate->connection); /* create window */ mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK | XCB_CW_CURSOR; values[0] = xstate->screen->white_pixel; values[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION; values[2] = blank_cursor; xstate->window = xcb_generate_id(xstate->connection); xcb_create_window (xstate->connection, XCB_COPY_FROM_PARENT, xstate->window, xstate->screen->root, 0, 0, xstate->image->width, xstate->image->height, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT, xstate->screen->root_visual, mask, values); /* set size hits on window */ hints = xcb_alloc_size_hints(); if (hints != NULL) { xcb_size_hints_set_max_size(hints, xstate->image->width, xstate->image->height); xcb_size_hints_set_min_size(hints, xstate->image->width, xstate->image->height); xcb_set_wm_size_hints(xstate->connection, xstate->window, WM_NORMAL_HINTS, hints); xcb_free_size_hints(hints); } /* create backing pixmap */ xstate->pmap = xcb_generate_id(xstate->connection); xcb_create_pixmap(xstate->connection, 24, xstate->pmap, xstate->window, xstate->image->width, xstate->image->height); /* create pixmap plot gc */ mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND; values[0] = xstate->screen->black_pixel; values[1] = 0xffffff; xstate->gc = xcb_generate_id (xstate->connection); xcb_create_gc(xstate->connection, xstate->gc, xstate->pmap, mask, values); /* if (nsfb->bpp == 8) set_palette(nsfb); */ /* put the image into the pixmap */ update_and_redraw_pixmap(xstate, 0, 0, xstate->image->width, xstate->image->height); /* show the window */ xcb_map_window (xstate->connection, xstate->window); xcb_flush(xstate->connection); return 0; } static int x_finalise(nsfb_t *nsfb) { xstate_t *xstate = nsfb->surface_priv; if (xstate == NULL) return 0; xcb_key_symbols_free(xstate->keysymbols); /* free pixmap */ xcb_free_pixmap(xstate->connection, xstate->pmap); /* close connection to server */ xcb_disconnect(xstate->connection); return 0; } static bool x_input(nsfb_t *nsfb, nsfb_event_t *event, int timeout) { xcb_generic_event_t *e; xcb_expose_event_t *ee; xcb_motion_notify_event_t *emn; xcb_button_press_event_t *ebp; xcb_key_press_event_t *ekp; xcb_key_press_event_t *ekr; xstate_t *xstate = nsfb->surface_priv; if (xstate == NULL) return false; xcb_flush(xstate->connection); /* try and retrive an event immediately */ e = xcb_poll_for_event(xstate->connection); if ((e == NULL) && (timeout != 0)) { if (timeout > 0) { int confd; fd_set rfds; struct timeval tv; int retval; confd = xcb_get_file_descriptor(xstate->connection); FD_ZERO(&rfds); FD_SET(confd, &rfds); tv.tv_sec = timeout / 1000; tv.tv_usec = timeout % 1000; retval = select(confd + 1, &rfds, NULL, NULL, &tv); if (retval == 0) { /* timeout, nothing happened */ event->type = NSFB_EVENT_CONTROL; event->value.controlcode = NSFB_CONTROL_TIMEOUT; return true; } } e = xcb_wait_for_event(xstate->connection); } if (e == NULL) { if (xcb_connection_has_error(xstate->connection) != 0) { /* connection closed quiting time */ event->type = NSFB_EVENT_CONTROL; event->value.controlcode = NSFB_CONTROL_QUIT; return true; } else { return false; /* no event */ } } event->type = NSFB_EVENT_NONE; switch (e->response_type) { case XCB_EXPOSE: ee = (xcb_expose_event_t *)e; xcb_copy_area(xstate->connection, xstate->pmap, xstate->window, xstate->gc, ee->x, ee->y, ee->x, ee->y, ee->width, ee->height); xcb_flush (xstate->connection); break; case XCB_MOTION_NOTIFY: emn = (xcb_motion_notify_event_t *)e; event->type = NSFB_EVENT_MOVE_ABSOLUTE; event->value.vector.x = emn->event_x; event->value.vector.y = emn->event_y; event->value.vector.z = 0; break; case XCB_BUTTON_PRESS: ebp = (xcb_button_press_event_t *)e; event->type = NSFB_EVENT_KEY_DOWN; switch (ebp->detail) { case X_BUTTON_LEFT: event->value.keycode = NSFB_KEY_MOUSE_1; break; case X_BUTTON_MIDDLE: event->value.keycode = NSFB_KEY_MOUSE_2; break; case X_BUTTON_RIGHT: event->value.keycode = NSFB_KEY_MOUSE_3; break; case X_BUTTON_WHEELUP: event->value.keycode = NSFB_KEY_MOUSE_4; break; case X_BUTTON_WHEELDOWN: event->value.keycode = NSFB_KEY_MOUSE_5; break; } break; case XCB_BUTTON_RELEASE: ebp = (xcb_button_press_event_t *)e; event->type = NSFB_EVENT_KEY_UP; switch (ebp->detail) { case X_BUTTON_LEFT: event->value.keycode = NSFB_KEY_MOUSE_1; break; case X_BUTTON_MIDDLE: event->value.keycode = NSFB_KEY_MOUSE_2; break; case X_BUTTON_RIGHT: event->value.keycode = NSFB_KEY_MOUSE_3; break; case X_BUTTON_WHEELUP: event->value.keycode = NSFB_KEY_MOUSE_4; break; case X_BUTTON_WHEELDOWN: event->value.keycode = NSFB_KEY_MOUSE_5; break; } break; case XCB_KEY_PRESS: ekp = (xcb_key_press_event_t *)e; event->type = NSFB_EVENT_KEY_DOWN; event->value.keycode = xkeysym_to_nsfbkeycode(xcb_key_symbols_get_keysym(xstate->keysymbols, ekp->detail, 0)); break; case XCB_KEY_RELEASE: ekr = (xcb_key_release_event_t *)e; event->type = NSFB_EVENT_KEY_UP; event->value.keycode = xkeysym_to_nsfbkeycode(xcb_key_symbols_get_keysym(xstate->keysymbols, ekr->detail, 0)); break; } free(e); return true; } static int x_claim(nsfb_t *nsfb, nsfb_bbox_t *box) { struct nsfb_cursor_s *cursor = nsfb->cursor; if ((cursor != NULL) && (cursor->plotted == true) && (nsfb_plot_bbox_intersect(box, &cursor->loc))) { nsfb_cursor_clear(nsfb, cursor); } return 0; } static int x_cursor(nsfb_t *nsfb, struct nsfb_cursor_s *cursor) { xstate_t *xstate = nsfb->surface_priv; nsfb_bbox_t redraw; nsfb_bbox_t fbarea; if ((cursor != NULL) && (cursor->plotted == true)) { nsfb_plot_add_rect(&cursor->savloc, &cursor->loc, &redraw); /* screen area */ fbarea.x0 = 0; fbarea.y0 = 0; fbarea.x1 = nsfb->width; fbarea.y1 = nsfb->height; nsfb_plot_clip(&fbarea, &redraw); nsfb_cursor_clear(nsfb, cursor); nsfb_cursor_plot(nsfb, cursor); /* TODO: This is hediously ineficient - should keep the pointer image * as a pixmap and plot server side */ update_and_redraw_pixmap(xstate, redraw.x0, redraw.y0, redraw.x1 - redraw.x0, redraw.y1 - redraw.y0); } return true; } static int x_update(nsfb_t *nsfb, nsfb_bbox_t *box) { xstate_t *xstate = nsfb->surface_priv; struct nsfb_cursor_s *cursor = nsfb->cursor; if ((cursor != NULL) && (cursor->plotted == false)) { nsfb_cursor_plot(nsfb, cursor); } update_and_redraw_pixmap(xstate, box->x0, box->y0, box->x1 - box->x0, box->y1 - box->y0); return 0; } const nsfb_surface_rtns_t x_rtns = { .initialise = x_initialise, .finalise = x_finalise, .input = x_input, .claim = x_claim, .update = x_update, .cursor = x_cursor, .geometry = x_set_geometry, }; NSFB_SURFACE_DEF(x, NSFB_SURFACE_X, &x_rtns) /* * Local variables: * c-basic-offset: 4 * tab-width: 8 * End: */
NotDiscordOfficial/Fortnite_SDK
BP_SpeedLines_Looping_Camera_Lens_classes.h
<gh_stars>0 // BlueprintGeneratedClass BP_SpeedLines_Looping_Camera_Lens.BP_SpeedLines_Looping_Camera_Lens_C // Size: 0x2e0 (Inherited: 0x2e0) struct ABP_SpeedLines_Looping_Camera_Lens_C : AEmitterCameraLensEffectBase { };
Tau-Coin/libTAU4j-Android
taucoin-android/src/main/java/io/taucoin/torrent/publishing/receiver/SchedulerReceiver.java
<reponame>Tau-Coin/libTAU4j-Android package io.taucoin.torrent.publishing.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import io.taucoin.torrent.publishing.core.model.TauDaemon; import io.taucoin.torrent.publishing.service.Scheduler; import static io.taucoin.torrent.publishing.service.Scheduler.SCHEDULER_WORK_WAKE_UP_APP_SERVICE; /** * The receiver for AlarmManager scheduling */ public class SchedulerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() == null){ return; } Context appContext = context.getApplicationContext(); switch (intent.getAction()) { case SCHEDULER_WORK_WAKE_UP_APP_SERVICE: wakeUpAppService(appContext); break; } } /** * 唤醒App Service */ private void wakeUpAppService(Context appContext) { TauDaemon.getInstance(appContext).start(); Scheduler.setWakeUpAppAlarm(appContext); } }
ckamtsikis/cmssw
Fireworks/Core/interface/FWSimpleProxyHelper.h
<gh_stars>100-1000 #ifndef Fireworks_Core_FWSimpleProxyHelper_h #define Fireworks_Core_FWSimpleProxyHelper_h // -*- C++ -*- // // Package: Core // Class : FWSimpleProxyHelper // /**\class FWSimpleProxyHelper FWSimpleProxyHelper.h Fireworks/Core/interface/FWSimpleProxyHelper.h Description: Implements some common functionality needed by all Simple ProxyBuilders Usage: <usage> */ // // Original Author: <NAME> // Created: Tue Dec 2 15:13:17 EST 2008 // // system include files #include <typeinfo> #include <string> // user include files // forward declarations class FWEventItem; class FWSimpleProxyHelper { public: FWSimpleProxyHelper(const std::type_info&); //virtual ~FWSimpleProxyHelper(); // ---------- const member functions --------------------- const void* offsetObject(const void* iObj) const { return static_cast<const char*>(iObj) + m_objectOffset; } // ---------- static member functions -------------------- // ---------- member functions --------------------------- void itemChanged(const FWEventItem*); private: //FWSimpleProxyHelper(const FWSimpleProxyHelper&); // stop default //const FWSimpleProxyHelper& operator=(const FWSimpleProxyHelper&); // stop default // ---------- member data -------------------------------- const std::type_info* m_itemType; unsigned int m_objectOffset; }; #endif
colloquial-solutions/scimitar
spec/requests/engine_spec.rb
require 'spec_helper' RSpec.describe Scimitar::Engine do before :each do allow_any_instance_of(Scimitar::ApplicationController).to receive(:authenticated?).and_return(true) end context 'parameter parser' do # "params" given here as a String, expecting the engine's custom parser to # decode it for us. # it 'decodes simple JSON', type: :model do post '/Users.scim', params: '{"userName": "foo"}', headers: { 'CONTENT_TYPE' => 'application/scim+json' } expect(response.status).to eql(201) expect(JSON.parse(response.body)['userName']).to eql('foo') end it 'decodes nested JSON', type: :model do post '/Users.scim', params: '{"userName": "foo", "name": {"givenName": "bar", "familyName": "baz"}}', headers: { 'CONTENT_TYPE' => 'application/scim+json' } expect(response.status).to eql(201) expect(JSON.parse(response.body)['userName']).to eql('foo') expect(JSON.parse(response.body)['name']['givenName']).to eql('bar') expect(JSON.parse(response.body)['name']['familyName']).to eql('baz') end it 'is case insensitive at the top level', type: :model do post '/Users.scim', params: '{"USERNAME": "foo"}', headers: { 'CONTENT_TYPE' => 'application/scim+json' } expect(response.status).to eql(201) expect(JSON.parse(response.body)['userName']).to eql('foo') end it 'is case insensitive in nested levels', type: :model do post '/Users.scim', params: '{"USERNAME": "foo", "NAME": {"GIVENNAME": "bar", "FAMILYNAME": "baz"}}', headers: { 'CONTENT_TYPE' => 'application/scim+json' } expect(response.status).to eql(201) expect(JSON.parse(response.body)['userName']).to eql('foo') expect(JSON.parse(response.body)['name']['givenName']).to eql('bar') expect(JSON.parse(response.body)['name']['familyName']).to eql('baz') end end # "context 'parameter parser' do" end
rqu/worker
tests/tasks.cpp
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <memory> #include <fstream> #include "tasks/internal/archivate_task.h" #include "tasks/internal/cp_task.h" #include "tasks/internal/extract_task.h" #include "tasks/internal/mkdir_task.h" #include "tasks/internal/rename_task.h" #include "tasks/internal/rm_task.h" #include "tasks/internal/fetch_task.h" #include "tasks/internal/exists_task.h" #include "tasks/external_task.h" #include "tasks/root_task.h" #include "tasks/task_factory.h" #include "tasks/create_params.h" #include "config/sandbox_config.h" #include "mocks.h" #define BOOST_FILESYSTEM_NO_DEPRECATED #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> namespace fs = boost::filesystem; std::shared_ptr<task_metadata> get_task_meta() { auto res = std::make_shared<task_metadata>(); res->task_id = "id2"; res->priority = 3; res->fatal_failure = false; res->dependencies = {"dep1", "dep2", "dep3"}; res->binary = "command"; res->cmd_args = {"arg1", "arg2"}; res->sandbox = std::make_shared<sandbox_config>(); res->sandbox->loaded_limits.insert( std::pair<std::string, std::shared_ptr<sandbox_limits>>("group1", std::make_shared<sandbox_limits>())); return res; } std::shared_ptr<task_metadata> get_three_args() { auto res = get_task_meta(); res->cmd_args = {"one", "two", "three"}; return res; } std::shared_ptr<task_metadata> get_two_args() { auto res = get_task_meta(); res->cmd_args = {"one", "two"}; return res; } std::shared_ptr<task_metadata> get_one_args() { auto res = get_task_meta(); res->cmd_args = {"one"}; return res; } std::shared_ptr<task_metadata> get_zero_args() { auto res = get_task_meta(); res->cmd_args = {}; return res; } TEST(Tasks, InternalArchivateTask) { EXPECT_THROW(archivate_task(1, get_three_args()), task_exception); EXPECT_THROW(archivate_task(1, get_one_args()), task_exception); EXPECT_THROW(archivate_task(1, get_zero_args()), task_exception); EXPECT_NO_THROW(archivate_task(1, get_two_args())); } TEST(Tasks, InternalCpTask) { EXPECT_THROW(cp_task(1, get_three_args()), task_exception); EXPECT_THROW(cp_task(1, get_one_args()), task_exception); EXPECT_THROW(cp_task(1, get_zero_args()), task_exception); EXPECT_NO_THROW(cp_task(1, get_two_args())); } TEST(Tasks, InternalCpTaskExceptionBug) { auto meta = get_task_meta(); meta->cmd_args = {"/proc/self/cmdline", "/nonexistingdir/a"}; std::shared_ptr<task_results> res; EXPECT_NO_THROW(res = cp_task(1, meta).run()); EXPECT_EQ(task_status::FAILED, res->status); } TEST(Tasks, InternalCpTaskWildcards) { // prepare directories and files auto temp = fs::temp_directory_path(); auto src_dir = temp / fs::unique_path(); auto dst_dir = temp / fs::unique_path(); fs::create_directories(src_dir); fs::create_directories(dst_dir); for (const auto &i : {"a1", "a2", "b1"}) { std::ofstream ofs((src_dir / i).string()); ofs << i; } // run the test and check asserts auto meta = get_task_meta(); meta->cmd_args = {src_dir.string() + "/a*", dst_dir.string()}; std::shared_ptr<task_results> res; EXPECT_NO_THROW(res = cp_task(1, meta).run()); EXPECT_EQ(task_status::OK, res->status); EXPECT_TRUE(fs::is_regular_file(dst_dir / "a1")); EXPECT_TRUE(fs::is_regular_file(dst_dir / "a2")); EXPECT_FALSE(fs::is_regular_file(dst_dir / "b1")); // cleanup fs::remove_all(src_dir); fs::remove_all(dst_dir); } TEST(Tasks, InternalExtractTask) { EXPECT_THROW(extract_task(1, get_three_args()), task_exception); EXPECT_THROW(extract_task(1, get_one_args()), task_exception); EXPECT_THROW(extract_task(1, get_zero_args()), task_exception); EXPECT_NO_THROW(extract_task(1, get_two_args())); } TEST(Tasks, InternalMkdirTask) { EXPECT_NO_THROW(mkdir_task(1, get_three_args())); EXPECT_NO_THROW(mkdir_task(1, get_one_args())); EXPECT_THROW(mkdir_task(1, get_zero_args()), task_exception); EXPECT_NO_THROW(mkdir_task(1, get_two_args())); } TEST(Tasks, InternalRenameTask) { EXPECT_THROW(rename_task(1, get_three_args()), task_exception); EXPECT_THROW(rename_task(1, get_one_args()), task_exception); EXPECT_THROW(rename_task(1, get_zero_args()), task_exception); EXPECT_NO_THROW(rename_task(1, get_two_args())); } TEST(Tasks, InternalRmTask) { EXPECT_NO_THROW(rm_task(1, get_three_args())); EXPECT_NO_THROW(rm_task(1, get_one_args())); EXPECT_THROW(rm_task(1, get_zero_args()), task_exception); EXPECT_NO_THROW(rm_task(1, get_two_args())); } TEST(Tasks, InternalFetchTask) { EXPECT_THROW(fetch_task(1, get_three_args(), nullptr), task_exception); EXPECT_THROW(fetch_task(1, get_one_args(), nullptr), task_exception); EXPECT_THROW(fetch_task(1, get_zero_args(), nullptr), task_exception); EXPECT_NO_THROW(fetch_task(1, get_two_args(), nullptr)); } TEST(Tasks, InternalExistsTask) { EXPECT_THROW(exists_task(1, get_zero_args()), task_exception); EXPECT_THROW(exists_task(1, get_one_args()), task_exception); EXPECT_NO_THROW(exists_task(1, get_two_args())); EXPECT_NO_THROW(exists_task(1, get_three_args())); } class test_task_base : public task_base { public: test_task_base(std::size_t id, std::shared_ptr<task_metadata> task_meta) : task_base(id, task_meta) { } virtual ~test_task_base() { } std::shared_ptr<task_results> run() { return nullptr; } }; TEST(Tasks, TaskBase) { test_task_base base(1, get_task_meta()); EXPECT_EQ(base.get_cmd(), "command"); std::vector<std::string> dep{"dep1", "dep2", "dep3"}; EXPECT_EQ(base.get_dependencies(), dep); EXPECT_EQ(base.get_fatal_failure(), false); EXPECT_EQ(base.get_id(), static_cast<std::size_t>(1)); EXPECT_EQ(base.get_priority(), static_cast<std::size_t>(3)); EXPECT_EQ(base.get_task_id(), "id2"); EXPECT_TRUE(base.get_children().empty()); auto children = std::shared_ptr<task_base>(new test_task_base(2, get_task_meta())); base.add_children(children); EXPECT_EQ(base.get_children()[0]->get_task_id(), children->get_task_id()); } TEST(Tasks, TaskFactory) { task_factory factory(nullptr); auto meta = get_task_meta(); std::shared_ptr<task_base> task; // archivate task meta->binary = "archivate"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<archivate_task>(task), nullptr); // cp task meta->binary = "cp"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<cp_task>(task), nullptr); // extract task meta->binary = "extract"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<extract_task>(task), nullptr); // fetch task meta->binary = "fetch"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<fetch_task>(task), nullptr); // mkdir task meta->binary = "mkdir"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<mkdir_task>(task), nullptr); // rename task meta->binary = "rename"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<rename_task>(task), nullptr); // rm task meta->binary = "rm"; task = factory.create_internal_task(0, meta); EXPECT_NE(std::dynamic_pointer_cast<rm_task>(task), nullptr); // root task // - with explicit nullptr argument meta->binary = "archivate"; task = factory.create_internal_task(0, nullptr); EXPECT_NE(std::dynamic_pointer_cast<root_task>(task), nullptr); // - without explicit meta argument task = factory.create_internal_task(0); EXPECT_NE(std::dynamic_pointer_cast<root_task>(task), nullptr); // unknown internal task meta->binary = "unknown_internal_bianry"; task = factory.create_internal_task(0, meta); EXPECT_EQ(task, nullptr); // worker config auto worker_conf = std::make_shared<mock_worker_config>(); EXPECT_CALL((*worker_conf), get_worker_id()).WillRepeatedly(Return(8)); // external task meta->binary = "external_command"; create_params params = {worker_conf, 1, meta, meta->sandbox->loaded_limits["group1"], nullptr, "", fs::path()}; EXPECT_THROW(factory.create_sandboxed_task(params), task_exception); // Sandbox config is nullptr meta->sandbox = std::make_shared<sandbox_config>(); meta->sandbox->name = "whatever_sandbox"; EXPECT_THROW(factory.create_sandboxed_task(params), task_exception); // Unknown sandbox type // Isolate only supported on linux platform #ifndef _WIN32 meta->sandbox->name = "isolate"; task = factory.create_sandboxed_task(params); EXPECT_NE(std::dynamic_pointer_cast<external_task>(task), nullptr); #endif }
wkma/bk-sops
gcloud/err_code.py
<filename>gcloud/err_code.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 <NAME>, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ _BK_SOPS_PREFIX = "35" class ErrorCode(object): def __init__(self, code, description, ignore_prefix=False): self.code = int(code) if ignore_prefix else int(f"{_BK_SOPS_PREFIX}{code}") self.description = description def __str__(self): return self.code SUCCESS = ErrorCode(code="0", description="success", ignore_prefix=True) REQUEST_PARAM_INVALID = ErrorCode(code="40000", description="the content of param in your request is invalid") REQUEST_FORBIDDEN_INVALID = ErrorCode(code="40100", description="you have no permission") CONTENT_NOT_EXIST = ErrorCode(code="40400", description="the content you reqeust does not exist") INVALID_OPERATION = ErrorCode(code="45000", description="invalid operation") OPERATION_FAIL = ErrorCode(code="45100", description="invalid operation") VALIDATION_ERROR = ErrorCode(code="46100", description="validation error") ENV_ERROR = ErrorCode(code="55000", description="environment error") UNKNOWN_ERROR = ErrorCode(code="99999", description="unknow error")
marcosherreroa/Fundamentos-de-Programacion
Solved exams/June exams/June 2017 DG/Lotes.cpp
<gh_stars>0 //<NAME> #include "Lotes.h" #include "checkML.h" bool operator<(tLotes const & lote1, tLotes const & lote2){ if (lote1.tipo < lote2.tipo) return true; else if (lote1.tipo == lote2.tipo && lote1.id < lote2.id) return true; else return false; } bool operator==(tLotes const & lote1, tLotes const & lote2){ return lote1.id == lote2.id; } std::istream &operator>>(std::istream & flujo, tLotes & lote) { flujo >> lote.id >> lote.tipo >> lote.peso >> lote.precio; return flujo; } void mostrarLote(tLotes const & lote){ std::cout << "Lote: " << std::setw(10) << lote.id << std::setw(10)<<' '<<"Peso del lote: " << std::setprecision(2) << std::fixed << lote.peso << "\nTipo: " << std::setw(10) << lote.tipo<< std::setw(10)<<' '<< "Precio de salida: " << std::setprecision(2)<<std::fixed<<lote.precio<<'\n'; } void mostrarPrecio(tLotes const & lote){ std::cout << "Lote: " << std::setw(10) << lote.id << std::setw(10) << ' ' << "Comprador: " << lote.idcomprador << "\nTipo: " << std::setw(10) << lote.tipo << std::setw(10) << ' ' << "Precio de compra: " << std::setprecision(2)<<std::fixed<<lote.precio << '\n'; } void modificarLote(tLotes & lote, long long int idcomprador, float precio){ lote.idcomprador = idcomprador; lote.precio = precio; }
LNBIG-COM/lnbig-server
adjustChannels/openChannelsBetweenMyNodes.js
<gh_stars>1-10 /* * Copyright (c) 2019 LNB<EMAIL> * All rights reserved. */ // Должен быть первым - загружает переменные require('dotenv').config() let listChannels = require('../lib/listChannels') let pendingChannels = require('../lib/pendingChannels') var PromisePool = require('es6-promise-pool') const pTimeout = require('p-timeout') const OPEN_CHANNEL_TIMEOUT = 10000 process.umask(0o77); const nodeStorage = require('../global/nodeStorage'); const debug = require('debug')('lnbig:dwoc') let myNodes = {}, myInternalChannels = {} let $listChannels, $pendingChannels if (process.env.CRYPT_PASSWORD) { // The password for crypted macaroon files in env settings (.env file for example) main(process.env.CRYPT_PASSWORD) } else { // Or prompt the password from terminal var read = require("read"); read( { prompt: 'Password: ', silent: true, replace: '*', terminal: true }, (error, password) => { if (error) throw new Error(error); main(password); } ) } async function main(password) { // To create object for node storage // load node storage data included crypted macaroon files, and decrypt macaroon files by password. After the password to be cleaned from memory await nodeStorage.init(require('../global/nodesInfo'), password); let key for (key in nodeStorage.nodes) myNodes[nodeStorage.nodes[key].pubKey] = key debug("Мои ноды: %o", myNodes) // To connect to nodes await nodeStorage.connect({longsAsNumbers: false}); debug('Запускаются асинхронные команды listChannels...') $listChannels = listChannels(nodeStorage) $pendingChannels = pendingChannels(nodeStorage) debug('Ожидается завершение асинхронных команд listChannels...') $listChannels = await $listChannels $pendingChannels = await $pendingChannels debug('Данные получены полностью, обработка') for (key in nodeStorage.nodes) { if (nodeStorage.nodes[key].client) findChannelsToMyNodes(key, $listChannels[key], $pendingChannels[key]) } debug("myInternalChannels после анализа: %o", myInternalChannels) openNewChannels() } function* openChannelPromise() { // Проходим по каналам и собираем информацию для корректировки let openChannelData = [] for (let key1 in nodeStorage.nodes) { if (nodeStorage.nodes[key1].client) { // Для каждой ноды проверяет - есть каналы со своими for (let key2 in nodeStorage.nodes) { if (nodeStorage.nodes[key2].client) { // И вот здесь корфмируем список if ( key1 !== key2 && (!myInternalChannels[key1] || !myInternalChannels[key1][key2] || myInternalChannels[key1][key2] < 8000000) ){ // Канала нет - создаём openChannelData.push({ where: key1, pubKey: nodeStorage.nodes[key2].pubKey, address: `${nodeStorage.nodes[key2].internalHost}.${process.env.INTERNAL_DOMAIN_FOR_PUBLIC_INTERFACE}:9735`, amount: 2**24 - 1, rand: Math.random() }) } } } } } openChannelData = openChannelData.sort((a, b) => a.rand- b.rand) console.log("Будет открыто %d каналов на сумму: %d BTC", openChannelData.length, openChannelData.reduce((acc,val) => {return acc + val.amount}, 0)/1E8) debug("Массив каналов: %o", openChannelData) for (let item of openChannelData) { console.log("Открытие канала %o", item) //yield Promise.resolve(1) yield openChannelWithNode(item.pubKey, item.where, item.address, item.amount) } } async function openNewChannels() { // The number of promises to process simultaneously. let concurrency = 100 // Create a pool. let pool = new PromisePool(openChannelPromise(), concurrency) pool.addEventListener('fulfilled', function () { // The event contains: // - target: the PromisePool itself // - data: // - promise: the Promise that got fulfilled // - result: the result of that Promise //console.log('update policy: result: %o', event.data.result) }) pool.addEventListener('rejected', function (event) { // The event contains: // - target: the PromisePool itself // - data: // - promise: the Promise that got rejected // - error: the Error for the rejection console.log('update policy - ОШИБКА: error: %o: ', event.data.error.message) }) console.log(`Запускается открытие каналов (в параллель: ${concurrency})`) // Start the pool. let poolPromise = pool.start() // Wait for the pool to settle. await poolPromise console.log('Всё завершено успешно') } function findChannelsToMyNodes(key, listChannels, pendingChannels) { let channel // Собираем статистику по каналам, которые уже есть и с теми условиями, с которыми нам надо // В данном случае - учитываем те каналы, где есть средства с нашей стороны for (channel of listChannels.channels) { if (myNodes[channel.remote_pubkey]) { // Значит канал с моей ноды - заносим данные myInternalChannels[key] = myInternalChannels[key] || {} myInternalChannels[key][myNodes[channel.remote_pubkey]] = Math.max(myInternalChannels[key][myNodes[channel.remote_pubkey]] || 0, +channel.local_balance) } } for (channel of pendingChannels.pending_open_channels) { if (myNodes[channel.channel.remote_node_pub]) { // Значит канал с моей ноды - заносим данные myInternalChannels[key] = myInternalChannels[key] || {} myInternalChannels[key][myNodes[channel.channel.remote_node_pub]] = Math.max(myInternalChannels[key][myNodes[channel.channel.remote_node_pub]] || 0, +channel.channel.local_balance) } } } async function openChannelWithNode(pubKey, whereOpen, address, amnt = CHANNEL_CAPACITY) { let myNode try { myNode = nodeStorage.nodes[whereOpen] let connected = false try { console.log("p_3, pubKey=%s, whereOpen=%s, address=%s, amnt=%d", pubKey, whereOpen, address, amnt) let connect_res = await myNode.client.connectPeer({addr: {pubkey: pubKey, host: address}, perm: false}) debug("openChannelWithNode(%s): результат коннекта канала: %o", pubKey, connect_res) connected = true } catch (e) { if (/already connected to peer/.test(e.message)) connected = true console.log("openChannelWithNode(%s): коннект (%s) НЕУДАЧЕН (%s) - %s...", pubKey, address, e.message, connected ? 'уже подключены - попробуем создать канал' : 'игнорируем эту ноду') } if (connected) { try { let res = await pTimeout( // TODO изменить node_pubkey_string здесь и везде на node_pubkey (Buffer.from(pukey, 'hex')) myNode.client.openChannelSync({ node_pubkey_string: pubKey, local_funding_amount: amnt, push_sat: 0, target_conf: 30, private: false, remote_csv_delay: 20, min_htlc_msat: 1, min_confs: 0, spend_unconfirmed: true }), OPEN_CHANNEL_TIMEOUT ) console.log("openChannelWithNode(%s): результат открытия канала: %o", pubKey, res) return res; } catch (e) { console.error("openChannelWithNode(%s): ошибка (%s) открытия канала (коннект есть), возможно кончились средства (%s)", pubKey, e.message, whereOpen) return null } } else { return null } } catch (e) { console.log("Пойманная ошибка openChannelWithNode(%s) @ %s: %o", pubKey, myNode.key, e) throw Error(`Ошибка openChannelWithNode(${pubKey}): ${e.message}, ${e.stack}`) } }
Agustinefe/TP2Algoritmos3
src/main/java/edu/fiuba/algo3/algoblocks/Bloque.java
package edu.fiuba.algo3.algoblocks;/* Author: firmapaz ;created on 12/12/20*/ public interface Bloque { void ejecutarComportamientoSobrePizarraEn(Personaje estePersonaje); void ejecutarComportamientoInversoSobrePizarraEn(Personaje estePersonaje); Bloque duplicar(); }
fangziming-ff/buykop
src/main/java/com/buykop/console/controller/MsgTemplateController.java
<reponame>fangziming-ff/buykop package com.buykop.console.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import com.buykop.console.service.MsgService; import com.buykop.console.util.Constants; import com.buykop.framework.annotation.Menu; import com.buykop.framework.annotation.Module; import com.buykop.framework.annotation.Security; import com.buykop.framework.entity.DiyInf; import com.buykop.framework.entity.SynTableDataConfig; import com.buykop.framework.scan.MsgTemplate; import com.buykop.framework.http.HttpEntity; import com.buykop.framework.http.PageInfo; import com.buykop.framework.log.Logger; import com.buykop.framework.log.LoggerFactory; import com.buykop.framework.oauth2.PRole; import com.buykop.framework.oauth2.UserToken; import com.buykop.framework.scan.Field; import com.buykop.framework.scan.MQProcessing; import com.buykop.framework.scan.MsgTemplate; import com.buykop.framework.scan.PRoot; import com.buykop.framework.scan.PSysCode; import com.buykop.framework.scan.Statement; import com.buykop.framework.scan.Table; import com.buykop.framework.scan.ChartForm; import com.buykop.framework.util.BosConstants; import com.buykop.framework.util.CacheTools; import com.buykop.framework.util.ClassInnerNotice; import com.buykop.framework.util.data.DataChange; import com.buykop.framework.util.data.MyString; import com.buykop.framework.util.query.BaseQuery; import com.buykop.framework.util.type.BaseController; import com.buykop.framework.util.type.BosEntity; import com.buykop.framework.util.type.QueryFetchInfo; import com.buykop.framework.util.type.QueryListInfo; import com.buykop.framework.util.type.SelectBidding; import com.buykop.framework.util.type.ServiceInf; @Module(display = "通用接口配置", sys = Constants.current_sys) @RestController public class MsgTemplateController extends BaseController { private static Logger logger = LoggerFactory.getLogger(MsgTemplateController.class); protected static final String URI = "/msg/template"; @Autowired private MsgService service; @Menu(js = "msgTemplate", name = "消息模板", trunk = "开发服务,模板管理") @Security(accessType = "1", displayName = "消息模板列表", needLogin = true, isEntAdmin = false, isSysAdmin = false, roleId = BosConstants.role_tech) @RequestMapping(value = URI + "/fetch", method = RequestMethod.POST) @ResponseBody public JSONObject fetch(@RequestBody HttpEntity json, HttpServletRequest request) throws Exception { try { UserToken ut = super.securityCheck(json, request); if (ut == null) { return json.jsonValue(); } MsgTemplate search = json.getSearch(MsgTemplate.class, null, ut, this.service); PageInfo page = json.getPageInfo(MsgTemplate.class); QueryFetchInfo<MsgTemplate> fetch = this.service.getMgClient().getFetch(search, "className,templateCode,templateName", page.getCurrentPage(), page.getPageSize(),this.service); fetch.initBiddingForSysClassName(this, json, "sys", "className", null); super.fetchToJson(fetch, json, BosConstants.getTable(MsgTemplate.class.getName())); super.selectToJson(PRoot.getJsonForSelect(this.service), json, MsgTemplate.class.getName(), "sys"); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "消息模板列表保存", needLogin = true, isEntAdmin = false, isSysAdmin = false, roleId = BosConstants.role_tech) @RequestMapping(value = URI + "/saveList", method = RequestMethod.POST) @ResponseBody public JSONObject saveList(@RequestBody HttpEntity json, HttpServletRequest request) throws Exception { try { UserToken ut = super.securityCheck(json, request); if (ut == null) { return json.jsonValue(); } List<MsgTemplate> list = json.getList(MsgTemplate.class, "templateCode,templateName,sys,className,status,pushScope", this.service); for (MsgTemplate x : list) { x.setTemplateCode(x.getTemplateCode().toUpperCase()); this.service.save(x, ut); BosConstants.getExpireHash().remove(MsgTemplate.class, x.getTemplateId()); new ClassInnerNotice().invoke(MsgTemplate.class.getSimpleName(), x.getTemplateId()); } json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "消息模板详情", needLogin = true, isEntAdmin = false, isSysAdmin = false, roleId = BosConstants.role_tech) @RequestMapping(value = URI + "/info", method = RequestMethod.POST) @ResponseBody public JSONObject info(@RequestBody HttpEntity json, HttpServletRequest request) throws Exception { try { UserToken ut = super.securityCheck(json, request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, URI + "/info", MsgTemplate.class.getName(), null, true, this.getService()); MsgTemplate obj = this.service.getMgClient().getById(id, MsgTemplate.class); if (obj == null) { json.setUnSuccessForNoRecord(MsgTemplate.class); return json.jsonValue(); } Table table = BosConstants.getTable(obj.getClassName()); if (table == null) { json.setUnSuccessForNoRecord(Table.class); return json.jsonValue(); } if (DataChange.isEmpty(obj.getSys())) { json.setUnSuccess(-1, "请设置所属系统"); return json.jsonValue(); } if (DataChange.isEmpty(obj.getClassName())) { json.setUnSuccess(-1, "请设置绑定业务类"); return json.jsonValue(); } SelectBidding sb=new SelectBidding(); //加入属性的选择项目 pushScope;// 0:机构 1:部门 2:用户 3:指定属性 if(obj.getPushScope()!=null) { if(obj.getPushScope().intValue()==0) { sb=Field.getJsonForSelectWithFK(obj.getClassName(), BosConstants.memberClassName, service); }else if(obj.getPushScope().intValue()==1) { sb=Field.getJsonForSelectWithFK(obj.getClassName(), BosConstants.orgClassName, service); }else if(obj.getPushScope().intValue()==2) { sb=Field.getJsonForSelectWithFK(obj.getClassName(), BosConstants.userClassName, service); }else if(obj.getPushScope().intValue()==3) { for (Field t : table.getFields()) { if(!t.judgeDB()) continue; if(t.getIsKey()!=null && t.getIsKey().intValue()==1) continue; if(!DataChange.isEmpty(t.getFkClasss())) continue; if(t.getCustomer()==null) continue; //0:开发人员定义 1:平台字段 if(t.getCustomer().intValue()==1) continue; sb.put(t.getProperty(), t.getProperty() + "[" + t.getDisplay() + "]"); } } } super.selectToJson(sb, json, MsgTemplate.class, "property"); super.objToJson(obj, json); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "消息模板删除", needLogin = true, isEntAdmin = false, isSysAdmin = false, roleId = BosConstants.role_tech) @RequestMapping(value = URI + "/delete", method = RequestMethod.POST) @ResponseBody public JSONObject delete(@RequestBody HttpEntity json, HttpServletRequest request) throws Exception { try { UserToken ut = super.securityCheck(json, request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, URI + "/delete", MsgTemplate.class.getName(), null, true, this.getService()); MsgTemplate obj = this.service.getMgClient().getById(id, MsgTemplate.class); if (obj == null) { json.setUnSuccessForNoRecord(MsgTemplate.class); return json.jsonValue(); } this.service.deleteById(id, MsgTemplate.class.getName(), ut); BosConstants.getExpireHash().remove(MsgTemplate.class, id); new ClassInnerNotice().invoke(MsgTemplate.class.getSimpleName(), id); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "消息模板单个保存", needLogin = true, isEntAdmin = false, isSysAdmin = false, roleId = BosConstants.role_tech) @RequestMapping(value = URI + "/save", method = RequestMethod.POST) @ResponseBody public JSONObject save(@RequestBody HttpEntity json, HttpServletRequest request) throws Exception { try { UserToken ut = super.securityCheck(json, request); if (ut == null) { return json.jsonValue(); } MsgTemplate obj = json.getObj(MsgTemplate.class, "templateCode,templateName,sys,className", this.service); this.service.save(obj, ut); BosConstants.getExpireHash().remove(MsgTemplate.class, obj.getTemplateId()); new ClassInnerNotice().invoke(MsgTemplate.class.getSimpleName(), obj.getTemplateId()); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Override public ServiceInf getService() throws Exception { // TODO Auto-generated method stub return this.service; } }
Krisa/sftools
src/server/src/modules/connections/router.js
import {ensureAuthenticated} from '../../middleware' import * as connection from './controller' export const baseUrl = '/Connection' export default [ { method: 'POST', route: '/', handlers: [ ensureAuthenticated, connection.createConnection, connection.authorize ] }, { method: 'PUT', route: '/:_id', handlers: [ ensureAuthenticated, connection.getConnection, connection.updateConnection ] }, { method: 'GET', route: '/getDescribeMetadata', handlers: [ ensureAuthenticated, connection.getDescribeMetadata ] }, { method: 'GET', route: '/getMetadata', handlers: [ ensureAuthenticated, connection.getMetadata ] }, { method: 'GET', route: '/', handlers: [ ensureAuthenticated, connection.getConnections ] }, { method: 'GET', route: '/callback', handlers: [ ensureAuthenticated, connection.callback ] }, { method: 'GET', route: '/:_id', handlers: [ ensureAuthenticated, connection.getConnection ] }, { method: 'DELETE', route: '/:_id', handlers: [ ensureAuthenticated, connection.deleteConnection ] } ];
otto-de/synapse
synapse-core/src/main/java/de/otto/synapse/subscription/Subscriptions.java
package de.otto.synapse.subscription; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.slf4j.Logger; import javax.annotation.concurrent.ThreadSafe; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentMap; import static com.google.common.collect.Maps.newConcurrentMap; import static org.slf4j.LoggerFactory.getLogger; @ThreadSafe public class Subscriptions { private static final Logger LOG = getLogger(Subscriptions.class); final ConcurrentMap<String, Map<String, Subscription>> subscriptions = newConcurrentMap(); public void addIfMissing(final Subscription subscription) { final String channelName = subscription.getChannelName(); LOG.info("Received subscription for channel " + channelName); subscriptions.putIfAbsent(channelName, Maps.newConcurrentMap()); subscriptions.get(channelName).putIfAbsent(subscription.getId(), subscription); } public void subscribe(final String subscriptionId, final Set<String> subscribedEntities) { get(subscriptionId).orElseThrow(() -> new IllegalArgumentException("Subscription does not exist")).subscribe(subscribedEntities); } public void unsubscribe(final String subscriptionId, final Set<String> unsubscribedEntities) { get(subscriptionId).ifPresent(subscription -> subscription.unsubscribe(unsubscribedEntities)); } public Collection<Subscription> subscriptionsFor(final String channelName) { return subscriptions.getOrDefault(channelName, ImmutableMap.of()).values(); } public Optional<Subscription> get(final String subscriptionId) { for (Map<String, Subscription> s : subscriptions.values()) { final Optional<Subscription> optionalSubscription = s.values() .stream() .filter(subscription -> subscription.getId().equals(subscriptionId)) .findAny(); if (optionalSubscription.isPresent()) { return optionalSubscription; } } return Optional.empty(); } public void remove(final String subscriptionId) { LOG.info("Removed subscription " + subscriptionId); subscriptions.values().forEach(map -> map.remove(subscriptionId)); } }
erique/embeddedsw
XilinxProcessorIPLib/drivers/uartpsv/src/xuartpsv_g.c
/****************************************************************************** * Copyright (C) 2017 - 2021 Xilinx, Inc. All Rights Reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ #include "xparameters.h" #include "xuartpsv.h" /* * The configuration table for devices */ XUartPsv_Config XUartPsv_ConfigTable[] = { { XPAR_SBSA_UART_DEVICE_ID, XPAR_SBSA_UART_BASEADDR, XPAR_SBSA_UART_CLK_FREQ_HZ, XPAR_SBSA_UART_HAS_MODEM } };