hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
45d381607ce081f47f40548888fcbeb23e426a39
3,143
package com.rzblog.project.blog.blogcontent.utils; import java.io.PrintWriter; import java.text.MessageFormat; import com.rzblog.common.constant.ThirdPartyCallConstant; import com.rzblog.common.utils.security.ShiroUtils; import com.rzblog.project.blog.blogcontent.domain.Blogcontent; import com.rzblog.project.blog.softcontent.domain.Softcontent; /** * @author ricozhou * @date Oct 17, 2018 5:46:16 PM * @Desc */ public class BlogUtil { public static void writerToHtml(PrintWriter writer, String... msgs) { if (null == writer) { return; } for (String msg : msgs) { writer.print("<script>printMessage('" + msg + "');</script>"); // writer.print( msg); System.out.println(writer); writer.flush(); } } public static void shutdownWriter(PrintWriter writer) { writerToHtml(writer, "爬取结束...", "shutdown"); if (null != writer) { writer.close(); } } // 对象转换 public static void turnSoftcontentFromBlogcontent(Blogcontent blogcontent, Softcontent softcontent) { if (softcontent == null) { softcontent = new Softcontent(); } if (blogcontent == null) { return; } softcontent.setCid(blogcontent.getCid()); softcontent.setSoftName(blogcontent.getSoftName()); softcontent.setSoftType(blogcontent.getSoftType()); softcontent.setSoftWebsite(blogcontent.getSoftWebsite()); softcontent.setSoftDownUrl(blogcontent.getSoftDownUrl()); softcontent.setSoftUpdateUrl(blogcontent.getSoftUpdateUrl()); softcontent.setSoftDocUrl(blogcontent.getSoftDocUrl()); softcontent.setSoftLicense(blogcontent.getSoftLicense()); softcontent.setSoftLanguage(blogcontent.getSoftLanguage()); softcontent.setSoftOperateSystem(blogcontent.getSoftOperateSystem()); softcontent.setSoftAuthor(blogcontent.getSoftAuthor()); softcontent.setCreateBy(ShiroUtils.getLoginName()); softcontent.setUpdateBy(ShiroUtils.getLoginName()); blogcontent.setSoftcontent(softcontent); } /** * 提交链接到百度的接口地址 * * @param type * urls: 推送, update: 更新, del: 删除 * @param site * 待提交的站点 * @param baiduPushToken * 百度推送的token,百度站长平台获取 * @return */ public static String getBaiduPushUrl(Integer type, String site, String baiduPushToken) { String pushType = ThirdPartyCallConstant.THIRD_PARTY_CALL_BAIDU_PUSH_TYPE_PUSH; if (type == 1) { pushType = ThirdPartyCallConstant.THIRD_PARTY_CALL_BAIDU_PUSH_TYPE_UPDATE; } else if (type == 2) { pushType = ThirdPartyCallConstant.THIRD_PARTY_CALL_BAIDU_PUSH_TYPE_DELETE; } return MessageFormat.format(ThirdPartyCallConstant.THIRD_PARTY_CALL_BAIDU_PUSH_URL_PATTERN, pushType, site, baiduPushToken); } // 获取请求的域名拼接 public static String getRequestDomain(String networkProtocol, String ip, int port) { String domain = null; if ("http".equals(networkProtocol)) { if (port == 80) { domain = networkProtocol + "://" + ip; } else { domain = networkProtocol + "://" + ip + ":" + port; } } else if ("https".equals(networkProtocol)) { if (port == 443) { domain = networkProtocol + "://" + ip; } else { domain = networkProtocol + "://" + ip + ":" + port; } } return domain; } }
30.514563
109
0.715877
c25d0b5a19a861378cde70d1089d806d14b8bb78
275
package com.fit.testdatagen.se.memory; public class TwoDimensionStructSymbolicVariable extends TwoDimensionStructureSymbolicVariable { public TwoDimensionStructSymbolicVariable(String name, String type, int scopeLevel) { super(name, type, scopeLevel); } }
27.5
95
0.789091
225cf79fcdd14a2fe2a8ce9ba95e14f8a5a90adf
3,548
package de.gurkenlabs.utiliti.swing.panels; import de.gurkenlabs.litiengine.Direction; import de.gurkenlabs.litiengine.entities.EntityPivotType; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperty; import de.gurkenlabs.utiliti.swing.Icons; import java.awt.LayoutManager; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; @SuppressWarnings("serial") public class SpawnpointPanel extends PropertyPanel { private final JTextField textFieldInfo; private final JSpinner spinnerOffsetX; private final JSpinner spinnerOffsetY; private final JComboBox<Direction> comboBoxDirection; private final JComboBox<EntityPivotType> comboBoxPivot; public SpawnpointPanel() { super("panel_spawnPoint", Icons.SPAWNPOINT); this.textFieldInfo = new JTextField(); this.textFieldInfo.setColumns(10); this.spinnerOffsetX = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 100.0, 0.1)); this.spinnerOffsetY = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 100.0, 0.1)); this.comboBoxDirection = new JComboBox<>(); this.comboBoxDirection.setModel(new DefaultComboBoxModel<Direction>(Direction.values())); this.comboBoxPivot = new JComboBox<>(); this.comboBoxPivot.setModel( new DefaultComboBoxModel<EntityPivotType>(EntityPivotType.values())); setLayout(this.createLayout()); this.setupChangedListeners(); } @Override protected void clearControls() { this.textFieldInfo.setText(""); this.spinnerOffsetX.setValue(0.0); this.spinnerOffsetY.setValue(0.0); this.comboBoxDirection.setSelectedItem(Direction.DOWN); this.comboBoxPivot.setSelectedItem(EntityPivotType.DIMENSION_CENTER); } @Override protected void setControlValues(IMapObject mapObject) { this.textFieldInfo.setText(mapObject.getStringValue(MapObjectProperty.SPAWN_INFO)); this.spinnerOffsetX.setValue(mapObject.getDoubleValue(MapObjectProperty.SPAWN_PIVOT_OFFSETX)); this.spinnerOffsetY.setValue(mapObject.getDoubleValue(MapObjectProperty.SPAWN_PIVOT_OFFSETY)); this.comboBoxDirection.setSelectedItem( mapObject.getEnumValue(MapObjectProperty.SPAWN_DIRECTION, Direction.class, Direction.DOWN)); this.comboBoxPivot.setSelectedItem( mapObject.getEnumValue( MapObjectProperty.SPAWN_PIVOT, EntityPivotType.class, EntityPivotType.DIMENSION_CENTER)); } private void setupChangedListeners() { this.setup(this.textFieldInfo, MapObjectProperty.SPAWN_INFO); this.setup(this.spinnerOffsetX, MapObjectProperty.SPAWN_PIVOT_OFFSETX); this.setup(this.spinnerOffsetY, MapObjectProperty.SPAWN_PIVOT_OFFSETY); this.setup(this.comboBoxDirection, MapObjectProperty.SPAWN_DIRECTION); this.setup(this.comboBoxPivot, MapObjectProperty.SPAWN_PIVOT); } private LayoutManager createLayout() { LayoutItem[] layoutItems = new LayoutItem[] { new LayoutItem("panel_direction", this.comboBoxDirection), new LayoutItem("panel_pivot", this.comboBoxPivot), new LayoutItem("panel_pivotOffsetX", this.spinnerOffsetX), new LayoutItem("panel_pivotOffsetY", this.spinnerOffsetY), new LayoutItem("panel_entity", this.textFieldInfo), }; return this.createLayout(layoutItems); } }
41.255814
101
0.748309
840a0ba96979e603f9e6ca9f334654cdb94704a9
1,570
/* * * * */ package main; import BDD.BDD; import classe.ClasseManager; import console.Console; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.xpath.XPathExpressionException; import netserv.NetworkServeur; import outils.log.MyLogger; import org.xml.sax.SAXException; import outils.Utils; import outils.xml.XPathEmptyValueException; /** * ServeurManager.java * */ public class ServeurManager implements StartNStop { private static final Logger LOGGER = Logger.getGlobal(); private static final Level LOG_LEVEL = Level.ALL; private static ServeurManager serveur; private final Console console; private final NetworkServeur netServ; private ServeurManager() { this.console = new Console(this); this.netServ = new NetworkServeur(); } @Override public void onStart() throws IOException, SAXException, XPathExpressionException, XPathEmptyValueException, SQLException, Exception { BDD.init(); this.console.start(); ClasseManager.start(); this.netServ.start(); } @Override public void onStop() { // throw new Error(); this.netServ.stop(); this.console.stop(); BDD.stop(); Utils.EXEC.shutdown(); LOGGER.info("Arrêt du serveur terminé"); MyLogger.stop(); } public static void main(String[] args) { try { MyLogger.init(); LOGGER.setLevel(LOG_LEVEL); serveur = new ServeurManager(); serveur.start(); } catch (Exception ex) { Logger.getGlobal().log(Level.SEVERE, null, ex); } } }
19.625
134
0.719108
9cdfdfbe59d6ae24cc112c18bab0b06b10a9ca19
2,672
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.coeus.sys.framework.service; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.config.ConfigurationException; import org.kuali.rice.core.api.config.property.ConfigContext; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * Exports services in the {@link org.kuali.rice.core.api.config.property.ConfigContext#getCurrentContextConfig()} as beans available to Spring. * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class ConfigContextConfigObjectFactoryBean implements FactoryBean<Object>, InitializingBean { private String objectName; private boolean singleton; private boolean mustExist; public ConfigContextConfigObjectFactoryBean() { this.mustExist = true; } public Object getObject() throws Exception { Object o = ConfigContext.getCurrentContextConfig().getObject(this.getObjectName()); if (mustExist && o == null) { throw new IllegalStateException("Service must exist and no service could be located with name='" + this.getObjectName() + "'"); } return o; } public Class<?> getObjectType() { if (getObjectName() == null) { return null; } else { try { // getObject throws java.lang.Exception return getObject().getClass(); } catch (Exception e) { return null; } } } public boolean isSingleton() { return singleton; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public void setSingleton(boolean singleton) { this.singleton = singleton; } public boolean isMustExist() { return mustExist; } public void setMustExist(boolean mustExist) { this.mustExist = mustExist; } public void afterPropertiesSet() throws Exception { if (StringUtils.isBlank(this.getObjectName())) { throw new ConfigurationException("No objectName given."); } } }
28.731183
144
0.715569
277b7d5462317507c728e9fa87021ed7c94c990c
366
package com.felix.design.principle.liskovsubstitution.version_input_final; import java.util.Map; /** * Created by lifei */ public class Child extends Base { // @Override // public void method(HashMap map) { // System.out.println("子类HashMap入参方法被执行"); // } public void method(Map map) { System.out.println("子类HashMap入参方法被执行"); } }
20.333333
74
0.669399
32641cd6db41a34bcf71fa9765a967b5b974d516
998
package io.virtdata.api.composers; import io.virtdata.annotations.ThreadSafeMapper; import io.virtdata.api.DataMapper; import io.virtdata.core.DataMapperFunctionMapper; import io.virtdata.core.ResolvedFunction; public interface FunctionComposer<T> { Object getFunctionObject(); FunctionComposer andThen(Object outer); default ResolvedFunction getResolvedFunction() { return new ResolvedFunction( getFunctionObject(), getFunctionObject().getClass().getAnnotation(ThreadSafeMapper.class) != null, null, null, null, null ); } default ResolvedFunction getResolvedFunction(boolean isThreadSafe) { return new ResolvedFunction( getFunctionObject(), isThreadSafe, null, null, null, null ); } default <R> DataMapper<R> getDataMapper() { return DataMapperFunctionMapper.map(getFunctionObject()); } }
26.972973
93
0.647295
d3f84755e4306d70ec6b6faad91a5299db449f62
3,196
package org.delusion.engine.graphics.primitive; import org.delusion.engine.graphics.IndexBuffer; import org.delusion.engine.graphics.Renderer; import org.delusion.engine.graphics.VertexArray; import org.delusion.engine.graphics.VertexBuffer; import org.joml.*; public class Quad { private static float[] quad_vbo_dat = { -0.5f,-0.5f,-0.5f, -0.5f,0.5f,-0.5f, 0.5f,-0.5f,-0.5f, 0.5f,0.5f,-0.5f }; private static int[] quad_ebo_dat = { 0,2,1, // bl br tl 1,2,3 // tl br tr }; private static float[] quad_vbo_norm_dat = { 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1 }; private IndexBuffer ebo; private VertexBuffer vbo; private VertexBuffer vboN; private Vector3f position; private Vector2f size; private Quaternionf rotation; private Vector4f color; private VertexArray vao; private boolean dirty; private Matrix4f cachedModelMatrix; public Quad(Vector3f position) { this(position, new Vector2f(1,1), new Quaternionf(), new Vector4f(0,0,0,1)); } public Quad(Vector3f position, Quaternionf rotation) { this(position, new Vector2f(1,1), rotation, new Vector4f(0,0,0,1)); } public Quad(Vector3f position, Vector2f size) { this(position, size, new Quaternionf(), new Vector4f(0,0,0,1)); } public Quad(Vector3f position, Vector2f size, Quaternionf rotation) { this(position, size, rotation, new Vector4f(0,0,0,1)); } public Quad(Vector3f position, Vector4f color) { this(position, new Vector2f(1,1), new Quaternionf(), color); } public Quad(Vector3f position, Quaternionf rotation, Vector4f color) { this(position, new Vector2f(1,1), rotation, color); } public Quad(Vector3f position, Vector2f size, Vector4f color) { this(position, size, new Quaternionf(), color); } public Quad(Vector3f position, Vector2f size, Quaternionf rotation, Vector4f color) { this.position = new Vector3f(position); this.size = new Vector2f(size); this.rotation = new Quaternionf(rotation); this.color = new Vector4f(color); this.dirty = true; vao = new VertexArray(); vao.bind(); vbo = new VertexBuffer(quad_vbo_dat); vao.attribute(vbo,0,3,3, 0); vboN = new VertexBuffer(quad_vbo_norm_dat); vao.attribute(vboN,1,3,3, 0); ebo = new IndexBuffer(quad_ebo_dat); vao.elementBuffer(ebo); } public Matrix4f model() { if (isDirty()) { cachedModelMatrix = new Matrix4f().translate(position).scale(size.x, 1f, size.y).rotate(rotation); dirty = false; } return cachedModelMatrix; } private void markDirty() { dirty = true; } public boolean isDirty() { return dirty; } public Vector4f getColor() { return color; } public void rotate(float angle, float x, float y, float z) { rotation.rotateAxis(angle, x, y, z); markDirty(); } public VertexArray getVAO() { return vao; } }
26.857143
110
0.610451
73a16cffacef66f7e47c59eb76e49eaa90ee4f56
1,877
/* * Copyright 2019 EIS Ltd and/or one of its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kraken.testproduct.domain; import kraken.testproduct.domain.meta.Identifiable; import java.time.LocalDate; public class AccessTrackInfo extends Identifiable { private LocalDate createdOn; private String createdBy; private LocalDate updatedOn; private String updatedBy; public AccessTrackInfo() { } public AccessTrackInfo(LocalDate createdOn, String createdBy, LocalDate updatedOn, String updatedBy) { this.createdOn = createdOn; this.createdBy = createdBy; this.updatedOn = updatedOn; this.updatedBy = updatedBy; } public LocalDate getCreatedOn() { return createdOn; } public void setCreatedOn(LocalDate createdOn) { this.createdOn = createdOn; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public LocalDate getUpdatedOn() { return updatedOn; } public void setUpdatedOn(LocalDate updatedOn) { this.updatedOn = updatedOn; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } }
25.364865
106
0.689931
c7644c2ebbdce987c2e39c9630653ce34586b638
477
package aitoa.searchSpaces.bitstrings; import org.junit.Ignore; /** Test the bit string 1-flip unary operator */ @Ignore public class TestBitStringUnaryOperatorMOverNFlip0To1Dist extends TestBitStringUnaryOperator { /** * create the unary operator test * * @param unary * the unary operator */ public TestBitStringUnaryOperatorMOverNFlip0To1Dist( final BitStringUnaryOperatorMOverNFlip0To1Dist unary) { super(unary.mN, unary); } }
23.85
61
0.735849
f6f2a006dcab0c32a65a3eefaade00e9e68f5b71
2,757
package org.apache.olingo.jpa.processor.core.filter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.apache.olingo.client.api.uri.URIBuilder; import org.apache.olingo.commons.api.ex.ODataException; import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.jpa.processor.core.util.ServerCallSimulator; import org.apache.olingo.jpa.processor.core.util.TestBase; import org.junit.Test; import com.fasterxml.jackson.databind.node.ArrayNode; public class TestJPAEnumFilter extends TestBase { @Test public void testEnumStringBasedEq() throws IOException, ODataException { final URIBuilder uriBuilder = newUriBuilder().appendEntitySetSegment("DatatypeConversionEntities").filter( "AStringMappedEnum eq java.time.chrono.IsoEra'CE'"); final ServerCallSimulator helper = new ServerCallSimulator(persistenceAdapter, uriBuilder); helper.execute(HttpStatusCode.OK.getStatusCode()); final ArrayNode dces = helper.getJsonObjectValues(); assertEquals(1, dces.size()); assertEquals("CE", dces.get(0).get("AStringMappedEnum").asText()); } @Test public void testEnumStringBasedNe() throws IOException, ODataException { final URIBuilder uriBuilder = newUriBuilder().appendEntitySetSegment("DatatypeConversionEntities").filter( "AStringMappedEnum ne java.time.chrono.IsoEra'BCE'"); final ServerCallSimulator helper = new ServerCallSimulator(persistenceAdapter, uriBuilder); helper.execute(HttpStatusCode.OK.getStatusCode()); final ArrayNode dces = helper.getJsonObjectValues(); assertTrue(dces.size() > 0); } @Test public void testEnumOrdinalBased() throws IOException, ODataException { final URIBuilder uriBuilder = newUriBuilder().appendEntitySetSegment("DatatypeConversionEntities").filter( "AOrdinalMappedEnum eq java.time.temporal.ChronoUnit'NANOS'"); final ServerCallSimulator helper = new ServerCallSimulator(persistenceAdapter, uriBuilder); helper.execute(HttpStatusCode.OK.getStatusCode()); final ArrayNode dces = helper.getJsonObjectValues(); assertEquals(1, dces.size()); assertEquals("NANOS", dces.get(0).get("AOrdinalMappedEnum").asText()); } @Test public void testEnumCollection() throws IOException, ODataException { final URIBuilder uriBuilder = newUriBuilder().appendEntitySetSegment("DatatypeConversionEntities").select("ID") .filter("EnumCollection/$count gt 0"); final ServerCallSimulator helper = new ServerCallSimulator(persistenceAdapter, uriBuilder); helper.execute(HttpStatusCode.OK.getStatusCode()); final ArrayNode dces = helper.getJsonObjectValues(); assertEquals(2, dces.size()); } }
39.956522
115
0.772579
ce89eefd0b92e353eca2fdbba235827cffaa29af
991
/* * Copyright 2017 gen0083 * * 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 jp.gcreate.sample.samplejobqueue.api; import java.util.List; import jp.gcreate.sample.samplejobqueue.model.Repository; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface GitHubService { String BASE_URL = "https://api.github.com/"; @GET("users/{user}/repos") Call<List<Repository>> getRepositoriesList(@Path("user") String user); }
30.96875
75
0.744702
5379c1dffe9b413c7f7d5a046165b50fdc2e0854
3,595
/* * 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.aliyuncs.sofa.transform.v20190815; import java.util.ArrayList; import java.util.List; import com.aliyuncs.sofa.model.v20190815.ListLinkeLinktProjectmodulesResponse; import com.aliyuncs.sofa.model.v20190815.ListLinkeLinktProjectmodulesResponse.DataItem; import com.aliyuncs.transform.UnmarshallerContext; public class ListLinkeLinktProjectmodulesResponseUnmarshaller { public static ListLinkeLinktProjectmodulesResponse unmarshall(ListLinkeLinktProjectmodulesResponse listLinkeLinktProjectmodulesResponse, UnmarshallerContext _ctx) { listLinkeLinktProjectmodulesResponse.setRequestId(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.RequestId")); listLinkeLinktProjectmodulesResponse.setResultCode(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.ResultCode")); listLinkeLinktProjectmodulesResponse.setResultMessage(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.ResultMessage")); listLinkeLinktProjectmodulesResponse.setErrorCode(_ctx.longValue("ListLinkeLinktProjectmodulesResponse.ErrorCode")); listLinkeLinktProjectmodulesResponse.setErrorMessage(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.ErrorMessage")); listLinkeLinktProjectmodulesResponse.setResponseStatusCode(_ctx.longValue("ListLinkeLinktProjectmodulesResponse.ResponseStatusCode")); listLinkeLinktProjectmodulesResponse.setSuccess(_ctx.booleanValue("ListLinkeLinktProjectmodulesResponse.Success")); List<DataItem> data = new ArrayList<DataItem>(); for (int i = 0; i < _ctx.lengthValue("ListLinkeLinktProjectmodulesResponse.Data.Length"); i++) { DataItem dataItem = new DataItem(); dataItem.setCreatedAt(_ctx.longValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].CreatedAt")); dataItem.setCreator(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Creator")); dataItem.setDeleted(_ctx.booleanValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Deleted")); dataItem.setDescription(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Description")); dataItem.setId(_ctx.longValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Id")); dataItem.setModifier(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Modifier")); dataItem.setName(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Name")); dataItem.setOwners(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Owners")); dataItem.setParentId(_ctx.longValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].ParentId")); dataItem.setProjectSign(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].ProjectSign")); dataItem.setRegion(_ctx.stringValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].Region")); dataItem.setUpdatedAt(_ctx.longValue("ListLinkeLinktProjectmodulesResponse.Data["+ i +"].UpdatedAt")); data.add(dataItem); } listLinkeLinktProjectmodulesResponse.setData(data); return listLinkeLinktProjectmodulesResponse; } }
60.932203
165
0.80612
f47341e672202411c6768d4f285b934708fb69c2
1,663
package de.htw_berlin.HoboOthello.Core; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.*; /** * Created by Steffen Exler on 11.12.16. */ public class Savegames { private File file = new File("savegame.json"); /** * Load the last game from this.file * * @return the last which was played on the machiene */ public Game load() { Game game = null; try { if (!this.file.exists()) { this.file.createNewFile(); } FileReader fr = new FileReader(this.file); BufferedReader br = new BufferedReader(fr); String row; String content = ""; while ((row = br.readLine()) != null) { content = content + row; } br.close(); Gson gson = new GsonBuilder().create(); game = gson.fromJson(content, Game.class); if (game != null) { game.updatePlayerTyp(); } } catch (IOException e) { e.printStackTrace(); } return game; } /** * Save the Current Game to a JSON file * * @param game the game which should be saved */ public void save(Game game) { Gson gson = new GsonBuilder().create(); String content = gson.toJson(game); try { FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
22.780822
67
0.516536
725f86a2960ca8d2d50c6dffad4a7eda2a88899e
968
//,temp,TestRMAppTransitions.java,901,922,temp,TestRMAppTransitions.java,680,700 //,3 public class xxx { @Test (timeout = 30000) public void testAppNewKill() throws IOException { LOG.info("--- START: testAppNewKill ---"); UserGroupInformation fooUser = UserGroupInformation.createUserForTesting( "fooTestAppNewKill", new String[] {"foo_group"}); RMApp application = createNewTestApp(null); // NEW => KILLED event RMAppEventType.KILL RMAppEvent event = new RMAppKillByClientEvent( application.getApplicationId(), "Application killed by user.", fooUser, Server.getRemoteIp()); application.handle(event); rmDispatcher.await(); sendAppUpdateSavedEvent(application); assertKilled(application); assertAppFinalStateNotSaved(application); verifyApplicationFinished(RMAppState.KILLED); verifyAppRemovedSchedulerEvent(RMAppState.KILLED); verifyRMAppFieldsForFinalTransitions(application); } };
37.230769
80
0.741736
28345e33f0e910c9ab5805237e5023e6cb25d664
881
package data.usecases.orthodontist; import domain.entities.Orthodontist; import domain.entities.Schedule; import domain.entities.Assistent; import domain.usecases.orthodontist.EditOrthodontist; import domain.entities.Clinic; import java.util.List; public class LocalEditOrthodontist implements EditOrthodontist{ private final Clinic clinic; public LocalEditOrthodontist(Clinic clinic){ this.clinic = clinic; } @Override public void editOrthodontist(Orthodontist orthodontist){ List<Orthodontist> orthodontists = clinic.getOrthodontists(); if(!orthodontists.isEmpty()){ for(int i = 0; i<orthodontists.size(); i++){ if(orthodontists.get(i).getId() == orthodontist.getId()){ orthodontists.set(i, orthodontist); break; } } } } }
29.366667
73
0.660613
a651edf1b6de54bda595fe22e4421b6d7c715458
1,565
package cn.org.easysite.spring.boot.interceptor; import org.apache.commons.io.IOUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; import java.io.InputStream; /** * client response 代理 * * @author yinlin */ public class EnhancerClientHttpResponse implements ClientHttpResponse { private ClientHttpResponse clientHttpResponse; /** 原始响应体 */ private String responseText; private InputStream inputStream; public EnhancerClientHttpResponse(ClientHttpResponse clientHttpResponse) { this.clientHttpResponse = clientHttpResponse; } public String responseText() { try { responseText = IOUtils.toString(clientHttpResponse.getBody(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } return responseText; } @Override public InputStream getBody() throws IOException { inputStream = IOUtils.toInputStream(responseText, "UTF-8"); return inputStream; } @Override public HttpHeaders getHeaders() { return clientHttpResponse.getHeaders(); } @Override public HttpStatus getStatusCode() throws IOException { return clientHttpResponse.getStatusCode(); } @Override public int getRawStatusCode() throws IOException { return clientHttpResponse.getRawStatusCode(); } @Override public String getStatusText() throws IOException { return clientHttpResponse.getStatusText(); } @Override public void close() { clientHttpResponse.close(); IOUtils.closeQuietly(inputStream); } }
22.042254
75
0.773163
688c0837a77222845d477bbea6e5f81576c932ea
538
/* */ package android.support.v4.view; /* */ /* */ import android.view.ViewConfiguration; /* */ /* */ class ViewConfigurationCompatFroyo /* */ { /* */ public static int getScaledPagingTouchSlop(ViewConfiguration config) /* */ { /* 26 */ return config.getScaledPagingTouchSlop(); /* */ } /* */ } /* Location: C:\Users\Administrator\Desktop\android-support-v4.jar * Qualified Name: android.support.v4.view.ViewConfigurationCompatFroyo * JD-Core Version: 0.6.0 */
33.625
80
0.60223
8bb0a6da01306b21a82ba4de0655088d992f1b9e
3,444
package com.hnust.controller.vo; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.LinkedHashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_EMPTY) public class R extends LinkedHashMap<String, Object> { private static final long serialVersionUID = 1L; public R() { } public R(int status) { put("code", status); put("message", "success"); } @Override public R put(String key, Object value) { super.put(key, value); return this; } /** * 成功 * * @return */ public static R OK() { R res = new R(); res.put("timeStamp", System.currentTimeMillis()); res.put("code", 200); res.put("message", "success"); res.put("body", null); return res; } /** * 成功 * * @return */ public static R OK(Res res) { R response = new R(); response.put("timeStamp", System.currentTimeMillis()); response.put("code", res.getCode()); response.put("message", res.getMessage()); response.put("body", null); return response; } /** * 成功 * * @return */ public static R OK(Res res, Map<String, Object> body) { R response = new R(); response.put("timeStamp", System.currentTimeMillis()); response.put("code", res.getCode()); response.put("message", res.getMessage()); response.put("body", body); return response; } /** * 成功 * * @param body * @return */ public static R OK(Map<String, Object> body) { R res = new R(); res.put("timeStamp", System.currentTimeMillis()); res.put("code", 200); res.put("message", "success"); res.put("body", body); return res; } /** * 成功 * * @param body * @return */ public static R OK(Object body) { R res = new R(); res.put("timeStamp", System.currentTimeMillis()); res.put("code", 200); res.put("message", "success"); res.put("body", body); return res; } /** * 成功 * * @param code * @return */ public static R OK(int code, String message) { R res = new R(); res.put("timeStamp", System.currentTimeMillis()); res.put("code", code); res.put("message", message); res.put("body", null); return res; } /** * 失败 * * @param code * @return */ public static R ERROR(int code, String message) { R res = new R(); res.put("timeStamp", System.currentTimeMillis()); res.put("code", code); res.put("message", message); res.put("body", null); return res; } public static R ERROR(Res res) { R response = new R(); response.put("timeStamp", System.currentTimeMillis()); response.put("code", res.getCode()); response.put("message", res.getMessage()); response.put("body", null); return response; } public static R ERROR(Res res, String message) { R response = new R(); response.put("timeStamp", System.currentTimeMillis()); response.put("code", res.getCode()); response.put("message", res.getMessage() + message); response.put("body", null); return response; } }
22.96
62
0.527294
b9336b59682b0db92c9ab753cc7af327310473b6
510
package com.nexosis.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; public class FeatureImportanceResponse extends SessionResponse{ @JsonProperty("featureImportance") private Map<String, Double> scores; @JsonProperty("featureImportance") public Map<String, Double> getScores(){ return this.scores; } @JsonProperty("featureImportance") public void setData(String column, double value) { this.scores.put(column, value); } }
24.285714
63
0.723529
1f9b670960e7d6dbac8e65f080fb69603fa201de
1,590
package utilities.JavaFXutilities.DragAndDropFilePanes.imagePanes; import gameAuthoring.mainclasses.Constants; import java.io.File; import utilities.JavaFXutilities.imageView.StringToImageViewConverter; import utilities.errorPopup.ErrorPopup; import javafx.scene.image.ImageView; public abstract class DragAndDropImagePane extends DragAndDropFilePane { protected ImageView myImageView; protected File myFile; public DragAndDropImagePane (double width, double height) { super(width, height, new String[] { ".jpeg", ".jpg", ".png" }); } public ImageView getImageView () { return myImageView; } public String getImagePath () { return myFile.getPath(); } public void setHeight (double height) { myImageView.setPreserveRatio(true); myImageView.setFitHeight(height); myImageView.autosize(); myContainer.setPrefHeight(height); } public void displayImage () { myContainer.getChildren().remove(myDragAndDropPane); myImageView = StringToImageViewConverter.getImageView(myDragAndDropPane.getWidth(), myDragAndDropPane.getHeight(), myFile.getPath()); myContainer.getChildren().add(myImageView); this.setChanged(); this.notifyObservers(myFile.getPath()); } public boolean hasFileBeenDropped () { new ErrorPopup(Constants.NO_PROJECTILE_IMG); return myFile == null; } }
31.8
92
0.640881
fef189f5669d3faff0c0c852bca96b6d671933df
2,045
package com.okcoin.commons.okex.open.api.bean.futures.param; /** * New Order * * @author Tony Tian * @version 1.0.0 * @date 2018/3/9 15:38 */ public class Order { /** * The id of the futures, eg: BTC-USD-180629 */ protected String instrument_id; /** * You setting order id.(optional) */ private String client_oid; /** * The execution type {@link com.okcoin.commons.okex.open.api.enums.FuturesTransactionTypeEnum} */ private String type; /** * The order amount: Maximum 1 million */ private String size; /** * Match best counter party price (BBO)? 0: No 1: Yes If yes, the 'price' field is ignored */ private String match_price; private String order_type; /** * The order price: Maximum 1 million */ private String price; public void setInstrument_id(String instrument_id) { this.instrument_id = instrument_id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getMatch_price() { return match_price; } public void setMatch_price(String match_price) { this.match_price = match_price; } public String getOrder_type() { return order_type; } public void setOrder_type(String order_type) { this.order_type = order_type; } public String getInstrument_id() { return instrument_id; } public void setinstrument_id(String instrument_id) { this.instrument_id = instrument_id; } public String getClient_oid() { return client_oid; } public void setClient_oid(String client_oid) { this.client_oid = client_oid; } }
19.292453
99
0.606846
f6edc1f796de1f379ff721cc570ffd2b1c50c60a
5,015
/* * Copyright (c) 2000-2015 TeamDev Ltd. All rights reserved. * TeamDev PROPRIETARY and CONFIDENTIAL. * Use is subject to license terms. */ package com.teamdev.jxbrowser.chromium.demo; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * @author TeamDev Ltd. */ public class TabCaption extends JPanel { private boolean selected; private TabCaptionComponent component; public TabCaption() { setLayout(new BorderLayout()); setOpaque(false); add(createComponent(), BorderLayout.CENTER); add(Box.createHorizontalStrut(1), BorderLayout.EAST); } private JComponent createComponent() { component = new TabCaptionComponent(); component.addPropertyChangeListener("CloseButtonPressed", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { firePropertyChange("CloseButtonPressed", evt.getOldValue(), evt.getNewValue()); } }); component.addPropertyChangeListener("TabClicked", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { setSelected(true); } }); return component; } @Override public Dimension getPreferredSize() { return new Dimension(155, 26); } @Override public Dimension getMinimumSize() { return new Dimension(50, 26); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } public void setTitle(String title) { component.setTitle(title); } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { boolean oldValue = this.selected; this.selected = selected; component.setSelected(selected); firePropertyChange("TabSelected", oldValue, selected); } private static class TabCaptionComponent extends JPanel { private JLabel label; private final Color defaultBackground; private TabCaptionComponent() { defaultBackground = getBackground(); setLayout(new BorderLayout()); setOpaque(false); add(createLabel(), BorderLayout.CENTER); add(createCloseButton(), BorderLayout.EAST); } private JComponent createLabel() { label = new JLabel(); label.setOpaque(false); label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { firePropertyChange("TabClicked", false, true); } if (e.getButton() == MouseEvent.BUTTON2) { firePropertyChange("CloseButtonPressed", false, true); } } }); return label; } private JComponent createCloseButton() { JButton closeButton = new JButton(); closeButton.setOpaque(false); closeButton.setToolTipText("Close"); closeButton.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); closeButton.setPressedIcon(Resources.getIcon("close-pressed.png")); closeButton.setIcon(Resources.getIcon("close.png")); closeButton.setContentAreaFilled(false); closeButton.setFocusable(false); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { firePropertyChange("CloseButtonPressed", false, true); } }); return closeButton; } public void setTitle(final String title) { SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText(title); label.setToolTipText(title); } }); } public void setSelected(boolean selected) { setBackground(selected ? defaultBackground : new Color(150, 150, 150)); repaint(); } @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setPaint(new GradientPaint(0, 0, Color.LIGHT_GRAY, 0, getHeight(), getBackground())); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.dispose(); super.paint(g); } } }
32.777778
101
0.605583
11b9cf75728fffbe1d8e03b0b3a866c569988a7f
25,337
package org.pbjar.jxlayer.plaf.ext; /* * Copyright (c) 2009, Piet Blok * All rights reserved. * <p> * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * <p> * * 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 the copyright holder nor the names of the * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * <p> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.image.BufferedImage; import java.beans.PropertyChangeListener; import java.util.*; import java.util.logging.Logger; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeListener; import javax.swing.text.GlyphView.GlyphPainter; import javax.swing.text.JTextComponent; import com.github.weisj.darklaf.util.LogUtil; import org.jdesktop.jxlayer.JXLayer; import org.jdesktop.jxlayer.plaf.AbstractBufferedLayerUI; import org.jdesktop.jxlayer.plaf.LayerUI; import org.jdesktop.swingx.ForwardingRepaintManager; import org.pbjar.jxlayer.plaf.ext.transform.*; import org.pbjar.jxlayer.repaint.RepaintManagerProvider; import org.pbjar.jxlayer.repaint.RepaintManagerUtils; import org.pbjar.jxlayer.repaint.WrappedRepaintManager; import com.sun.java.swing.SwingUtilities3; /** * This class provides for all necessary functionality when using transformations in a {@link LayerUI}. * <p> * Some implementation details: * <ul> * <li>It extends {@link MouseEventUI} because, when applying transformations, the whereabouts of * child components on screen (device space) do not necessarily match the location according * to their bounds as set by layout managers (component space). So, mouse events must always * be redirected to the intended recipients. * <li>When enabled, this implementation sets a different {@link LayoutManager} to be used by * {@link JXLayer}. Instead of setting the size of the view to {@link JXLayer}'s inner area, * it sets the size of the view to the view's <em>preferred</em> size and centers it in the * inner area. Also, when calculating the preferred size of {@link JXLayer}, it transforms the * normally calculated size with the {@link AffineTransform} returned from {@link * #getPreferredTransform(Dimension, JXLayer)}. * <li>This implementation allocates a fresh {@link BufferedImage} the size of the clip area, each * time that the {@link #paint(Graphics, JComponent)} method is invoked. This is different * from the implementation of {@link AbstractBufferedLayerUI}, that maintains a cached image, * the size of the view. An important reason to not follow the {@link AbstractBufferedLayerUI} * strategy is that, when applying scaling transformations with a large scaling factor, a * {@link OutOfMemoryError} may be thrown because it will try to allocate a buffer of an * extreme size, even if not all of its contents will actually be visible on the screen. * <li>Rather than configuring the screen graphics object, the image's graphics object is * configured through {@link #configureGraphics(Graphics2D, JXLayer)}. * <li>Regardless of whether or not the view is opaque, a background color is painted. It is * obtained from the first component upwards in the hierarchy starting with the view, that is * opaque. If an opaque component is not found, the background color of the layer is used. * Painting the background is necessary to prevent visual artifacts when the transformation is * changed dynamically. * <li>Rendering hints may be set with {@link #setRenderingHints(Map)}, {@link * #addRenderingHint(RenderingHints.Key, Object)} and {@link #addRenderingHints(Map)}. * </ul> * <p> * Known limitations: * <ol> * <li>In Java versions <b>before Java 6u10</b>, this implementation employs a custom {@link * RepaintManager} in order to have descendant's repaint requests propagated up to the {@link * JXLayer} ancestor. This {@link RepaintManager} will work well with and without other {@link * RepaintManager} that are either subclasses of the {@link WrappedRepaintManager} or SwingX's * {@link ForwardingRepaintManager}. Other {@link RepaintManager}s may cause conflicts. * <p> * In Java versions <b>6u10 or higher</b>, an attempt will be made to use the new * RepaintManager delegate facility that has been designed for JavaFX. * <li>Transformations will be applied on the whole of the content of the {@link JXLayer}. The * result is that {@link Border}s and other content within {@link JXLayer}'s insets will * generally either be invisible, or will be rendered in a very undesirable way. If you want a * {@link Border} to be transformed together with {@link JXLayer}'s view, that border should * be set on the view instead. On the other hand, if you want the {@link Border} not to be * transformed, that border must be set on {@link JXLayer}'s parent. * </ol> * <b>Note:</b> A {@link TransformUI} instance cannot be shared and can be set to a single {@link * JXLayer} instance only. * * @author Piet Blok */ public class TransformUI extends MouseEventUI<JComponent> { private static final LayoutManager transformLayout = new TransformLayout(); private static final String KEY_VIEW = "view"; private static final boolean delegatePossible; private static final RepaintManager wrappedManager = new TransformRepaintManager(); private static final Logger LOGGER = LogUtil.getLogger(TransformUI.class); static { boolean value; try { SwingUtilities3.class.getMethod("setDelegateRepaintManager", JComponent.class, RepaintManager.class); value = true; } catch (Throwable t) { value = false; } delegatePossible = value; LOGGER.info("Java " + System.getProperty("java.version") + " " + System.getProperty("java.vm.version") + (delegatePossible ? ": RepaintManager delegate facility for JavaFX will be used." : ": RepaintManager.setCurrentManager() will be used.")); } private final ChangeListener changeListener = e -> revalidateLayer(); private final RepaintManagerProvider rpmProvider = new RepaintManagerProvider() { @Override public Class<? extends ForwardingRepaintManager> getForwardingRepaintManagerClass() { return TransformRPMSwingX.class; } @Override public Class<? extends WrappedRepaintManager> getWrappedRepaintManagerClass() { return TransformRPMFallBack.class; } @Override public boolean isAdequate(final Class<? extends RepaintManager> manager) { return manager.isAnnotationPresent(TransformRPMAnnotation.class); } }; private final Map<RenderingHints.Key, Object> renderingHints = new HashMap<>(); private final Set<JComponent> originalDoubleBuffered = new HashSet<>(); private JComponent view; private final PropertyChangeListener viewChangeListener = evt -> setView((JComponent) evt.getNewValue()); private TransformModel transformModel; private LayoutManager originalLayout; /** * Construct a {@link TransformUI} with a {@link DefaultTransformModel}. */ public TransformUI() { this(new DefaultTransformModel()); } /** * Construct a {@link TransformUI} with a specified model. * * @param model the model */ public TransformUI(final TransformModel model) { super(); this.setModel(model); } private void revalidateLayer() { JXLayer<? extends JComponent> installedLayer = this.getInstalledLayer(); if (installedLayer != null) { installedLayer.revalidate(); installedLayer.repaint(); } } /** * {@link JTextComponent} and its descendants have some caret position problems when used inside a transformed * {@link JXLayer}. When you plan to use {@link JTextComponent}(s) inside the hierarchy of a transformed {@link * JXLayer}, call this method in an early stage, before instantiating any {@link JTextComponent}. * <p> * It executes the following method: * * <pre> * System.setProperty(&quot;i18n&quot;, Boolean.TRUE.toString()); * </pre> * <p> * As a result, a {@link GlyphPainter} will be selected that uses floating point instead of * fixed point calculations. */ public static void prepareForJTextComponent() { System.setProperty("i18n", Boolean.TRUE.toString()); } /** * Add one rendering hint to the currently active rendering hints. * * @param key the key * @param value the value */ public void addRenderingHint(final RenderingHints.Key key, final Object value) { this.renderingHints.put(key, value); } /** * Add new rendering hints to the currently active rendering hints. * * @param hints the new rendering hints */ public void addRenderingHints(final Map<RenderingHints.Key, Object> hints) { this.renderingHints.putAll(hints); } /** * Get the {@link TransformModel}. * * @return the {@link TransformModel} * @see #setModel(TransformModel) */ public final TransformModel getModel() { return transformModel; } /** * Set a new {@link TransformModel}. The new model may not be {@code null}. * * @param transformModel the new model * @throws NullPointerException if transformModel is {@code null} * @see #getModel() */ public final void setModel(final TransformModel transformModel) throws NullPointerException { if (transformModel == null) { throw new NullPointerException("The TransformModel may not be null"); } if (this.transformModel != null) { this.transformModel.removeChangeListener(this.changeListener); } this.transformModel = transformModel; this.transformModel.addChangeListener(this.changeListener); revalidateLayer(); } /** * Get a preferred {@link AffineTransform}. This method will typically be invoked by programs that calculate a * preferred size. * <p> * The {@code size} argument will be used to compute anchor values for some types of * transformations. If the {@code size} argument is {@code null} a value of (0,0) is used for the anchor. * <p> * In {@code enabled} state this method is delegated to the {@link TransformModel} that has * been set. Otherwise {@code null} will be returned. * * @param size a {@link Dimension} instance to be used for an anchor or {@code null} * @param layer the {@link JXLayer}. * @return a {@link AffineTransform} instance or {@code null} */ public AffineTransform getPreferredTransform(final Dimension size, final JXLayer<? extends JComponent> layer) { return this.transformModel != null ? this.transformModel.getPreferredTransform(size, layer) : new AffineTransform(); } /* * {@inheritDoc} * <p> * This implementation does the following: * <ol> * <li> * A {@link BufferedImage} is created the size of the clip bounds of the * argument graphics object.</li> * <li> * A Graphics object is obtained from the image.</li> * <li> * The image is filled with a background color.</li> * <li> * The image graphics is translated according to x and y of the clip bounds. * </li> * <li> * The clip from the argument graphics object is set to the image graphics.</li> * <li> * {@link #configureGraphics(Graphics2D, JXLayer)} is invoked with the image * graphics as an argument.</li> * <li> * {@link #paintLayer(Graphics2D, JXLayer)} is invoked with the image * graphics as an argument.</li> * <li> * The image graphics is disposed.</li> * <li> * The image is drawn on the argument graphics object.</li> * </ol> */ /* * @SuppressWarnings("unchecked") * * @Override * public final void paint(Graphics g, JComponent component) { * Graphics2D g2 = (Graphics2D) g; * JXLayer<? extends JComponent> layer = (JXLayer<? extends JComponent>) component; * Shape clip = g2.getClip(); * Rectangle clipBounds = g2.getClipBounds(); * BufferedImage buffer = layer.getGraphicsConfiguration() * .createCompatibleImage(clipBounds.width, clipBounds.height, * Transparency.OPAQUE);// * Graphics2D g3 = buffer.createGraphics(); * try { * g3.setColor(this.getBackgroundColor(layer)); * g3.fillRect(0, 0, buffer.getWidth(), buffer.getHeight()); * g3.translate(-clipBounds.x, -clipBounds.y); * g3.setClip(clip); * configureGraphics(g3, layer); * paintLayer(g3, layer); * } catch (Throwable t) { */ /* * Under some rare circumstances, the graphics engine may throw a * transformation exception like this: * * sun.dc.pr.PRError: setPenT4: invalid pen transformation * (singular) * * As far as I understand this happens when the result of the * transformation has a zero sized surface. * * It will happen for example when shear X and shear Y are both set * to 1. * * It will also happen when scale X or scale Y are set to 0. * * Since this Exception only seems to be thrown under the condition * of a zero sized painting surface, no harm is done. Therefore the * error logging below has been commented out, but remain in the * source for the case that someone wants to investigate this * phenomenon in more depth. * * The Exception however MUST be caught, not only to be able dispose * the image's graphics object, but also to prevent that JXLayer * enters a problematic state (the isPainting flag would not be * reset). */ // System.err.println(t); // AffineTransform at = g3.getTransform(); // System.err.println(at); // System.err.println("scaleX = " + at.getScaleX() + " scaleY = " // + at.getScaleY() + " shearX = " + at.getShearX() // + " shearY = " + at.getShearY()); /* * } finally { * g3.dispose(); * } * g2.drawImage(buffer, clipBounds.x, clipBounds.y, null); * setDirty(false); * } */ /** * Overridden to replace the {@link LayoutManager}, to add some listeners and to ensure that an appropriate {@link * RepaintManager} is installed. * * @see #uninstallUI(JComponent) */ @Override public void installUI(final JComponent component) { super.installUI(component); JXLayer<? extends JComponent> installedLayer = this.getInstalledLayer(); originalLayout = installedLayer.getLayout(); installedLayer.addPropertyChangeListener(KEY_VIEW, this.viewChangeListener); installedLayer.setLayout(transformLayout); setView(installedLayer.getView()); if (!delegatePossible) { RepaintManagerUtils.ensureRepaintManagerSet(installedLayer, rpmProvider); } } /** * Overridden to restore the original {@link LayoutManager} and remove some listeners. * * @param c the component. */ @Override public void uninstallUI(final JComponent c) { JXLayer<? extends JComponent> installedLayer = this.getInstalledLayer(); Objects.requireNonNull(installedLayer) .removePropertyChangeListener(KEY_VIEW, this.viewChangeListener); installedLayer.setLayout(originalLayout); setView(null); super.uninstallUI(c); } private void setView(final JComponent view) { if (delegatePossible) { if (this.view != null) { SwingUtilities3.setDelegateRepaintManager(this.view, null); } } this.view = view; if (delegatePossible) { if (this.view != null) { SwingUtilities3.setDelegateRepaintManager(this.view, wrappedManager); } } setDirty(true); } /** * Replace the currently active rendering hints with new hints. * * @param hints the new rendering hints or {@code null} to clear all rendering hints */ public void setRenderingHints(final Map<RenderingHints.Key, Object> hints) { this.renderingHints.clear(); if (hints != null) { this.renderingHints.putAll(hints); } } /** * Primarily intended for use by {@link RepaintManager}. * * @param rect a rectangle * @param layer the layer * @return the argument rectangle if no {@link AffineTransform} is available, else a new rectangle */ public final Rectangle transform(final Rectangle rect, final JXLayer<? extends JComponent> layer) { AffineTransform at = getTransform(layer); if (at == null) { return rect; } else { Area area = new Area(rect); area.transform(at); return area.getBounds(); } } /** * Mark {@link TransformUI} as dirty if the LookAndFeel was changed. * * @param layer the {@link JXLayer} this {@link TransformUI} is set to */ @Override public void updateUI(final JXLayer<? extends JComponent> layer) { setDirty(true); } /* * Get the most suitable background color. */ private Color getBackgroundColor(final JXLayer<? extends JComponent> layer) { Container colorProvider = layer.getView() == null ? layer : layer.getView(); while (colorProvider != null && !colorProvider.isOpaque()) { colorProvider = colorProvider.getParent(); } return colorProvider == null ? SystemColor.desktop : colorProvider.getBackground(); } /** * Set a complete hierarchy to non double buffered and remember the components that were double buffered. * * @param component the component. */ private void setToNoDoubleBuffering(final Component component) { if (component instanceof JComponent) { JComponent comp = (JComponent) component; if (comp.isDoubleBuffered()) { originalDoubleBuffered.add(comp); comp.setDoubleBuffered(false); } } if (component instanceof Container) { Container container = (Container) component; for (int index = 0; index < container.getComponentCount(); index++) { setToNoDoubleBuffering(container.getComponent(index)); } } } /** * If the view of the {@link JXLayer} is (partly) obscured by its parent (this is the case when the size of the view * (in component space) is larger than the size of the {@link JXLayer}), the obscured parts will not be painted by * the super implementation. Therefore, only under this condition, a special painting technique is executed: * <ol> * <li>All descendants of the {@link JXLayer} are temporarily set to non double buffered. * <li>The graphics object is translated for the X and Y coordinates of the view. * <li>The view is painted. * <li>The original double buffered property is restored for all descendants. * </ol> * <p> * In all other cases, the super method is invoked. * <p> * The {@code g2} argument is a graphics object obtained from a {@link BufferedImage}. * * @see #paint(Graphics, JComponent) */ @Override protected final void paintLayer(final Graphics2D g2, final JXLayer<? extends JComponent> layer) { JComponent view = layer.getView(); if (view != null) { if (view.getX() < 0 || view.getY() < 0) { setToNoDoubleBuffering(view); g2.translate(view.getX(), view.getY()); view.paint(g2); for (JComponent comp : originalDoubleBuffered) { comp.setDoubleBuffered(true); } originalDoubleBuffered.clear(); return; } } super.paintLayer(g2, layer); } /** * Get the {@link AffineTransform} customized for the {@code layer} argument. * <p> * In {@code enabled} state this method is delegated to the {@link TransformModel} that has * been set. Otherwise {@code null} will be returned. */ @Override protected final AffineTransform getTransform(final JXLayer<? extends JComponent> layer) { return transformModel != null ? transformModel.getTransform(layer) : new AffineTransform(); } /** * Get the rendering hints. * * @return the rendering hints * @see #setRenderingHints(Map) * @see #addRenderingHints(Map) * @see #addRenderingHint(RenderingHints.Key, Object) */ @Override protected Map<RenderingHints.Key, Object> getRenderingHints(final JXLayer<? extends JComponent> layer) { return renderingHints; } /** * A delegate {@link RepaintManager} that can be set on the view of a {@link JXLayer} in Java versions starting with * Java 6u10. * <p> * For older Java versions, {@link RepaintManager#setCurrentManager(RepaintManager)} will be * used with either {@link TransformRPMFallBack} or {@link TransformRPMSwingX}. */ protected static final class TransformRepaintManager extends RepaintManager { private TransformRepaintManager() {} /** * Finds the JXLayer ancestor and have ancestor marked invalid via the current {@link RepaintManager}. */ @Override public void addInvalidComponent(final JComponent invalidComponent) { JXLayer<? extends JComponent> layer = findJXLayer(invalidComponent); RepaintManager.currentManager(layer).addInvalidComponent(layer); } /** * Finds the JXLayer ancestor and have the ancestor marked as dirty with the transformed rectangle via the * current {@link RepaintManager}. */ @Override public void addDirtyRegion(final JComponent c, final int x, final int y, final int w, final int h) { if (c.isShowing()) { JXLayer<? extends JComponent> layer = findJXLayer(c); TransformUI ui = (TransformUI) layer.getUI(); Point point = c.getLocationOnScreen(); SwingUtilities.convertPointFromScreen(point, layer); Rectangle transformPortRegion = ui.transform(new Rectangle(x + point.x, y + point.y, w, h), layer); RepaintManager.currentManager(layer).addDirtyRegion(layer, transformPortRegion.x, transformPortRegion.y, transformPortRegion.width, transformPortRegion.height); } } /** * Find the ancestor {@link JXLayer} instance. * * @param c a component * @return the ancestor {@link JXLayer} instance */ @SuppressWarnings("unchecked") private JXLayer<? extends JComponent> findJXLayer(final JComponent c) { JXLayer<?> layer = (JXLayer<?>) SwingUtilities.getAncestorOfClass(JXLayer.class, c); if (layer != null) { LayerUI<?> layerUI = layer.getUI(); if (layerUI instanceof TransformUI) { return (JXLayer<? extends JComponent>) layer; } else { return findJXLayer(layer); } } throw new Error("No parent JXLayer with TransformUI found"); } } }
41.741351
120
0.650866
8a51edca443e8d9151a76fac56ba2097ad87b8a2
2,374
package com.yurset.wiipm.vect; import com.yurset.wiipm.R; import com.yurset.wiipm.base.FPublic; import com.yurset.wiipm.logi.VData; import android.content.Context; import android.graphics.Bitmap; public class SHero { // ========================== 成员变量 =============================== public int markS = 0; // 状态 private int currS = 0; private int limitT = 0; private final int imageId = R.drawable.cynthia; private Bitmap bitmap = null; private Bitmap[] bitMove = null; private boolean lisp = true; // ================================================================== // ========================== 成员函数 =============================== public SHero(Context context) { bitMove = new Bitmap[16]; bitmap = FPublic.CreateBitmap(context, imageId, VData.roleSize * 4, VData.roleSize * 4); markS = VData.STAY_FACE; reFresh(); } public void reFresh() { // release(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { bitMove[4 * i + j] = Bitmap.createBitmap(bitmap, j * VData.roleSize, i * VData.roleSize, VData.roleSize, VData.roleSize); } } } public Bitmap getStatusBitmap(int status) { Bitmap bitStatus = null; switch (status) { case VData.MOVE_FACE: bitStatus = bitMove[currS + 1]; break; case VData.MOVE_LEFT: bitStatus = bitMove[currS + 5]; break; case VData.MOVE_RIGHT: bitStatus = bitMove[currS + 9]; break; case VData.MOVE_BACK: bitStatus = bitMove[currS + 13]; break; case VData.STAY_FACE: bitStatus = bitMove[0]; break; case VData.STAY_LEFT: bitStatus = bitMove[4]; break; case VData.STAY_RIGHT: bitStatus = bitMove[8]; break; case VData.STAY_BACK: bitStatus = bitMove[12]; break; } if (limitT++ > 3) { limitT = 0; switch (currS) { case 0: currS++; lisp = true; break; case 1: if (lisp) { currS++; } else { currS--; } break; case 2: currS--; lisp = false; break; } } return bitStatus; } // public void release() { // for (int r = 0; bitMove != null && r < bitMove.length; r++) { // if (bitMove[r] == null) // continue; // if (bitMove[r].isRecycled()) // continue; // bitMove[r].recycle(); // } // bitMove = new Bitmap[16]; // } // ================================================================== }
22.396226
70
0.537068
3c441f115d487f8fc88c194f9c4103904e57c8c3
5,393
/* * Copyright (C) 2019 The Flogger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.flogger.util; import org.checkerframework.checker.nullness.compatqual.NullableDecl; /** * Helper to call a static no-arg getter to obtain an instance of a specified type. This is used for * logging platform "plugins" which are expected to have a singleton available. It is expected that * these getter methods will be invoked once during logger initialization and then the results * cached in the platform class (thus there is no requirement for the class being invoked to handle * efficient caching of the result). */ public final class StaticMethodCaller { /** * Returns the value of calling the static no-argument {@code getInstance()} method on a class * specified in a system property. * * @param propertyName the name of a system property which is expected to hold a fully qualified * class name, which has a public static no-argument {@code getInstance()} method which * returns an instance of the given type. * @param defaultClassName a default class name for the system property. * @param type the expected type (or supertype) of the returned value (generified types are not * supported). */ @NullableDecl public static <T> T getInstanceFromSystemProperty( String propertyName, @NullableDecl String defaultClassName, Class<T> type) { String className = readProperty(propertyName, defaultClassName); if (className == null) { return null; } return callStaticMethod(className, "getInstance", type); } /** * Returns the value of calling a static no-argument method specified in a system property, or * {@code null} if the method cannot be called or the returned value is of the wrong type. * * @param propertyName the name of a system property which is expected to hold a value like {@code * "com.foo.Bar#someMethod"}, where the referenced method is a public, no-argument getter for * an instance of the given type. * @param defaultValue a default value for the system property. * @param type the expected type (or supertype) of the returned value (generified types are not * supported). */ @NullableDecl public static <T> T callGetterFromSystemProperty( String propertyName, @NullableDecl String defaultValue, Class<T> type) { String getter = readProperty(propertyName, defaultValue); if (getter == null) { return null; } int idx = getter.indexOf('#'); if (idx <= 0 || idx == getter.length() - 1) { error("invalid getter (expected <class>#<method>): %s\n", getter); return null; } return callStaticMethod(getter.substring(0, idx), getter.substring(idx + 1), type); } /** * Returns the value of calling a static no-argument method specified in a system property, or * {@code null} if the method cannot be called or the returned value is of the wrong type. * * @param propertyName the name of a system property which is expected to hold a value like {@code * "com.foo.Bar#someMethod"}, where the referenced method is a public, no-argument getter for * an instance of the given type. * @param type the expected type (or supertype) of the returned value (generified types are not * supported). */ @NullableDecl public static <T> T callGetterFromSystemProperty(String propertyName, Class<T> type) { return callGetterFromSystemProperty(propertyName, null, type); } private static String readProperty(String propertyName, @NullableDecl String defaultValue) { Checks.checkNotNull(propertyName, "property name"); try { return System.getProperty(propertyName, defaultValue); } catch (SecurityException e) { error("cannot read property name %s: %s", propertyName, e); } return null; } private static <T> T callStaticMethod(String className, String methodName, Class<T> type) { try { return type.cast(Class.forName(className).getMethod(methodName).invoke(null)); } catch (ClassNotFoundException e) { // Expected if an optional aspect is not being used (no error). } catch (ClassCastException e) { error( "cannot cast result of calling '%s#%s' to '%s': %s\n", className, methodName, type.getName(), e); } catch (Exception e) { // Catches SecurityException *and* ReflexiveOperationException (which doesn't exist in 1.6). error( "cannot call expected no-argument static method '%s#%s': %s\n", className, methodName, e); } return null; } // This cannot use a fluent logger here and it's even risky to use a JDK logger. private static void error(String msg, Object... args) { System.err.println(StaticMethodCaller.class + ": " + String.format(msg, args)); } private StaticMethodCaller() {} }
43.144
100
0.703875
e34b66a0b499cfa2d67c9c3d8c937e1f6c8470a6
4,209
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.aws.sqs; import java.util.List; import org.apache.nifi.processors.aws.AbstractAWSProcessor; import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderControllerService; import org.apache.nifi.processors.aws.sns.PutSNS; import org.apache.nifi.util.MockFlowFile; import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunners; import org.junit.Ignore; import org.junit.Test; @Ignore("For local testing only - interacts with S3 so the credentials file must be configured and all necessary buckets created") public class TestGetSQS { private final String CREDENTIALS_FILE = System.getProperty("user.home") + "/aws-credentials.properties"; @Test public void testSimpleGet() { final TestRunner runner = TestRunners.newTestRunner(new GetSQS()); runner.setProperty(PutSNS.CREDENTIALS_FILE, CREDENTIALS_FILE); runner.setProperty(GetSQS.TIMEOUT, "30 secs"); runner.setProperty(GetSQS.QUEUE_URL, "https://sqs.us-west-2.amazonaws.com/100515378163/test-queue-000000000"); runner.run(1); final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(GetSQS.REL_SUCCESS); for (final MockFlowFile mff : flowFiles) { System.out.println(mff.getAttributes()); System.out.println(new String(mff.toByteArray())); } } @Test public void testSimpleGetWithEL() { System.setProperty("test-account-property", "100515378163"); System.setProperty("test-queue-property", "test-queue-000000000"); final TestRunner runner = TestRunners.newTestRunner(new GetSQS()); runner.setProperty(PutSNS.CREDENTIALS_FILE, CREDENTIALS_FILE); runner.setProperty(GetSQS.TIMEOUT, "30 secs"); runner.setProperty(GetSQS.QUEUE_URL, "https://sqs.us-west-2.amazonaws.com/${test-account-property}/${test-queue-property}"); runner.run(1); final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(GetSQS.REL_SUCCESS); for (final MockFlowFile mff : flowFiles) { System.out.println(mff.getAttributes()); System.out.println(new String(mff.toByteArray())); } } @Test public void testSimpleGetUsingCredentailsProviderService() throws Throwable { final TestRunner runner = TestRunners.newTestRunner(new GetSQS()); runner.setProperty(GetSQS.TIMEOUT, "30 secs"); String queueUrl = "Add queue url here"; runner.setProperty(GetSQS.QUEUE_URL, queueUrl); final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService(); runner.addControllerService("awsCredentialsProvider", serviceImpl); runner.setProperty(serviceImpl, AbstractAWSProcessor.CREDENTIALS_FILE, System.getProperty("user.home") + "/aws-credentials.properties"); runner.enableControllerService(serviceImpl); runner.assertValid(serviceImpl); runner.setProperty(GetSQS.AWS_CREDENTIALS_PROVIDER_SERVICE, "awsCredentialsProvider"); runner.run(1); final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(GetSQS.REL_SUCCESS); for (final MockFlowFile mff : flowFiles) { System.out.println(mff.getAttributes()); System.out.println(new String(mff.toByteArray())); } } }
43.391753
144
0.726776
5bc01e740e53c9b5e6479fa1bdd3f09a54da0c17
500
package com.gravspace.messages; import java.util.List; public class PersistanceMessage implements Message{ final String persistanceTask; final List<?> args; public PersistanceMessage(final String persistanceTask, final List<?> args){ this.persistanceTask = persistanceTask; this.args = args; } public String getPersistanceTask() { // TODO Auto-generated method stub return persistanceTask; } public List<?> getArgs() { // TODO Auto-generated method stub return args; } }
19.230769
77
0.742
79ce8f0b3df426fdbe637b8261262889e10a0b6f
349
package up.erp.view.exporter; public class FloatData extends Data { public Float value; public FloatData() { } public FloatData(float value) { this.value = value; } public Float get_Value(){ return this.value; } public void set_Value(Float value){ this.value = value; } }
14.541667
43
0.581662
75d70f67f4df7d608cb299d2d716fa94d95f5177
851
package grafioschtrader.repository; import java.util.List; import grafioschtrader.dto.HistoryquotePeriodDeleteAndCreateMultiple; import grafioschtrader.entities.HistoryquotePeriod; import grafioschtrader.entities.Security; import grafioschtrader.entities.User; public interface HistoryquotePeriodJpaRepositoryCustom { /** * When the lifetime of a security with history quote period is changed the * corresponding period must also be adjusted. * * @param security */ void adjustHistoryquotePeriod(Security security); /** * History quote period are created manually, normally used when one price does * not fit the whole lifetime of a security * * @param user * @param hpdacm * @return */ List<HistoryquotePeriod> deleteAndCreateMultiple(User user, HistoryquotePeriodDeleteAndCreateMultiple hpdacm); }
28.366667
112
0.776733
fadf91bf722eb217ac9454eb6cf35267f838dbc3
1,255
package com.dharmab.sheets.server.database; import com.dharmab.sheets.server.character.CharacterService; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import org.flywaydb.core.Flyway; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import javax.sql.DataSource; public class DatabaseModule extends AbstractModule { private DataSource dataSource; public DatabaseModule(DataSource dataSource) { this.dataSource = dataSource; } @Override protected void configure() { bind(CharacterService.class); } @Provides Flyway provideFlyway() { Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); return flyway; } @Provides @Singleton SessionFactory provideSessionFactory() { Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } }
29.880952
132
0.752988
ed2566a7ec211bdf4d190fd11c870e611dd99803
6,677
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jrt; import java.util.Arrays; public class Test { @org.junit.Test public void testNothing() {} /** * Supervisor extension with some extra statistics used for * testing. **/ public static class Orb extends Supervisor { public volatile int readRequestCount = 0; public volatile int readReplyCount = 0; public volatile int readErrorCount = 0; public volatile long readBytes = 0; public volatile int writeRequestCount = 0; public volatile int writeReplyCount = 0; public volatile int writeErrorCount = 0; public volatile long writeBytes = 0; public Orb(Transport t) { super(t); } public boolean checkReadCounts(int request, int reply, int error) { return (request == readRequestCount && reply == readReplyCount && error == readErrorCount); } public boolean checkWriteCounts(int request, int reply, int error) { return (request == writeRequestCount && reply == writeReplyCount && error == writeErrorCount); } public void readPacket(PacketInfo info) { if (info.packetCode() == Packet.PCODE_REQUEST) { readRequestCount++; } else if (info.packetCode() == Packet.PCODE_REPLY) { readReplyCount++; } else if (info.packetCode() == Packet.PCODE_ERROR) { readErrorCount++; } readBytes += info.packetLength(); super.readPacket(info); } public void writePacket(PacketInfo info) { if (info.packetCode() == Packet.PCODE_REQUEST) { writeRequestCount++; } else if (info.packetCode() == Packet.PCODE_REPLY) { writeReplyCount++; } else if (info.packetCode() == Packet.PCODE_ERROR) { writeErrorCount++; } writeBytes += info.packetLength(); super.writePacket(info); } } /** * A simple object used to wait for the completion of an * asynchronous request. **/ public static class Waiter implements RequestWaiter { private boolean done = false; public boolean isDone() { return done; } public synchronized void handleRequestDone(Request req) { done = true; notify(); } public synchronized void waitDone() { while (!isDone()) { try { wait(); } catch (InterruptedException e) {} } } } /** * A simple object used to make one thread wait until another * thread tells it to continue. **/ public static class Barrier { private boolean broken = false; public synchronized void reset() { broken = false; } public synchronized void breakIt() { broken = true; notify(); } public synchronized void waitFor() { while (!broken) { try { wait(); } catch (InterruptedException e) {} } } } /** * A simple object used to pass a single object from one thread to * another. **/ public static class Receptor { private Object obj = null; public synchronized void reset() { obj = null; } public synchronized Object get() { while (obj == null) { try { wait(); } catch (InterruptedException e) {} } return obj; } public synchronized void put(Object obj) { this.obj = obj; notify(); } } public static boolean equals(byte[][] a, byte[][] b) { if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (!Arrays.equals(a[i], b[i])) { return false; } } return true; } public static boolean equals(Value a, Value b) { if (a == null || b == null) { return false; } if (a.type() != b.type()) { return false; } switch (a.type()) { case Value.INT8: return (a.asInt8() == b.asInt8()); case Value.INT8_ARRAY: return Arrays.equals(a.asInt8Array(), b.asInt8Array()); case Value.INT16: return (a.asInt16() == b.asInt16()); case Value.INT16_ARRAY: return Arrays.equals(a.asInt16Array(), b.asInt16Array()); case Value.INT32: return (a.asInt32() == b.asInt32()); case Value.INT32_ARRAY: return Arrays.equals(a.asInt32Array(), b.asInt32Array()); case Value.INT64: return (a.asInt64() == b.asInt64()); case Value.INT64_ARRAY: return Arrays.equals(a.asInt64Array(), b.asInt64Array()); case Value.FLOAT: return (a.asFloat() == b.asFloat()); case Value.FLOAT_ARRAY: return Arrays.equals(a.asFloatArray(), b.asFloatArray()); case Value.DOUBLE: return (a.asDouble() == b.asDouble()); case Value.DOUBLE_ARRAY: return Arrays.equals(a.asDoubleArray(), b.asDoubleArray()); case Value.DATA: return Arrays.equals(a.asData(), b.asData()); case Value.DATA_ARRAY: return equals(a.asDataArray(), b.asDataArray()); case Value.STRING: return a.asString().equals(b.asString()); case Value.STRING_ARRAY: return Arrays.equals(a.asStringArray(), b.asStringArray()); default: return false; } } public static boolean equals(Values a, Values b) { if (a == null || b == null) { return false; } if (a.size() != b.size()) { return false; } for (int i = 0; i < a.size(); i++) { if (!equals(a.get(i), b.get(i))) { return false; } } return true; } }
34.241026
104
0.494234
8a157fc5f81c338823c80c3733cea38c268cfcf0
18,219
package com.google.firebase.iid; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import androidx.core.content.ContextCompat; import com.google.android.gms.internal.firebase_messaging.zzc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Properties; final class zzy { zzy() { } /* access modifiers changed from: package-private */ public final zzz zzb(Context context, String str) throws zzaa { zzz zzd = zzd(context, str); if (zzd != null) { return zzd; } return zzc(context, str); } /* access modifiers changed from: package-private */ public final zzz zzc(Context context, String str) { zzz zzz = new zzz(zza.zzb(), System.currentTimeMillis()); zzz zza = zza(context, str, zzz, true); if (zza == null || zza.equals(zzz)) { if (Log.isLoggable("FirebaseInstanceId", 3)) { Log.d("FirebaseInstanceId", "Generated new key"); } zza(context, str, zzz); return zzz; } if (Log.isLoggable("FirebaseInstanceId", 3)) { Log.d("FirebaseInstanceId", "Loaded key after generating new one, using loaded one"); } return zza; } static void zza(Context context) { for (File file : zzb(context).listFiles()) { if (file.getName().startsWith("com.google.InstanceId")) { file.delete(); } } } private final zzz zzd(Context context, String str) throws zzaa { try { zzz zze = zze(context, str); if (zze != null) { zza(context, str, zze); return zze; } e = null; try { zzz zza = zza(context.getSharedPreferences("com.google.android.gms.appid", 0), str); if (zza != null) { zza(context, str, zza, false); return zza; } } catch (zzaa e) { e = e; } if (e == null) { return null; } throw e; } catch (zzaa e2) { e = e2; } } private static KeyPair zzc(String str, String str2) throws zzaa { try { byte[] decode = Base64.decode(str, 8); byte[] decode2 = Base64.decode(str2, 8); try { KeyFactory instance = KeyFactory.getInstance("RSA"); return new KeyPair(instance.generatePublic(new X509EncodedKeySpec(decode)), instance.generatePrivate(new PKCS8EncodedKeySpec(decode2))); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { String valueOf = String.valueOf(e); StringBuilder sb = new StringBuilder(String.valueOf(valueOf).length() + 19); sb.append("Invalid key stored "); sb.append(valueOf); Log.w("FirebaseInstanceId", sb.toString()); throw new zzaa((Exception) e); } } catch (IllegalArgumentException e2) { throw new zzaa((Exception) e2); } } private final zzz zze(Context context, String str) throws zzaa { File zzf = zzf(context, str); if (!zzf.exists()) { return null; } try { return zza(zzf); } catch (zzaa | IOException e) { if (Log.isLoggable("FirebaseInstanceId", 3)) { String valueOf = String.valueOf(e); StringBuilder sb = new StringBuilder(String.valueOf(valueOf).length() + 40); sb.append("Failed to read key from file, retrying: "); sb.append(valueOf); Log.d("FirebaseInstanceId", sb.toString()); } try { return zza(zzf); } catch (IOException e2) { String valueOf2 = String.valueOf(e2); StringBuilder sb2 = new StringBuilder(String.valueOf(valueOf2).length() + 45); sb2.append("IID file exists, but failed to read from it: "); sb2.append(valueOf2); Log.w("FirebaseInstanceId", sb2.toString()); throw new zzaa((Exception) e2); } } } /* JADX WARNING: Code restructure failed: missing block: B:37:0x00a4, code lost: r12 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:38:0x00a5, code lost: if (r9 != null) goto L_0x00a7; */ /* JADX WARNING: Code restructure failed: missing block: B:40:?, code lost: zza(r11, r9); */ /* JADX WARNING: Code restructure failed: missing block: B:41:0x00aa, code lost: throw r12; */ /* JADX WARNING: Code restructure failed: missing block: B:45:0x00ad, code lost: r11 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:47:?, code lost: zza(r9, r3); */ /* JADX WARNING: Code restructure failed: missing block: B:48:0x00b1, code lost: throw r11; */ /* JADX WARNING: Unknown top exception splitter block from list: {B:19:0x0060=Splitter:B:19:0x0060, B:31:0x009e=Splitter:B:31:0x009e} */ /* Code decompiled incorrectly, please refer to instructions dump. */ private final com.google.firebase.iid.zzz zza(android.content.Context r9, java.lang.String r10, com.google.firebase.iid.zzz r11, boolean r12) { /* r8 = this; java.lang.String r0 = "FirebaseInstanceId" r1 = 3 boolean r2 = android.util.Log.isLoggable(r0, r1) if (r2 == 0) goto L_0x000e java.lang.String r2 = "Writing key to properties file" android.util.Log.d(r0, r2) L_0x000e: java.util.Properties r2 = new java.util.Properties r2.<init>() java.lang.String r3 = r11.zzv() java.lang.String r4 = "pub" r2.setProperty(r4, r3) java.lang.String r3 = r11.zzw() java.lang.String r4 = "pri" r2.setProperty(r4, r3) long r3 = r11.zzbs java.lang.String r3 = java.lang.String.valueOf(r3) java.lang.String r4 = "cre" r2.setProperty(r4, r3) java.io.File r9 = zzf(r9, r10) r10 = 0 r9.createNewFile() // Catch:{ IOException -> 0x00b2 } java.io.RandomAccessFile r3 = new java.io.RandomAccessFile // Catch:{ IOException -> 0x00b2 } java.lang.String r4 = "rw" r3.<init>(r9, r4) // Catch:{ IOException -> 0x00b2 } java.nio.channels.FileChannel r9 = r3.getChannel() // Catch:{ all -> 0x00ab } r9.lock() // Catch:{ all -> 0x00a2 } r4 = 0 if (r12 == 0) goto L_0x008f long r6 = r9.size() // Catch:{ all -> 0x00a2 } int r12 = (r6 > r4 ? 1 : (r6 == r4 ? 0 : -1)) if (r12 <= 0) goto L_0x008f r9.position(r4) // Catch:{ IOException -> 0x0066, zzaa -> 0x0064 } com.google.firebase.iid.zzz r11 = zza((java.nio.channels.FileChannel) r9) // Catch:{ IOException -> 0x0066, zzaa -> 0x0064 } if (r9 == 0) goto L_0x0060 zza((java.lang.Throwable) r10, (java.nio.channels.FileChannel) r9) // Catch:{ all -> 0x00ab } L_0x0060: zza((java.lang.Throwable) r10, (java.io.RandomAccessFile) r3) // Catch:{ IOException -> 0x00b2 } return r11 L_0x0064: r12 = move-exception goto L_0x0067 L_0x0066: r12 = move-exception L_0x0067: boolean r1 = android.util.Log.isLoggable(r0, r1) // Catch:{ all -> 0x00a2 } if (r1 == 0) goto L_0x008f java.lang.String r12 = java.lang.String.valueOf(r12) // Catch:{ all -> 0x00a2 } java.lang.String r1 = java.lang.String.valueOf(r12) // Catch:{ all -> 0x00a2 } int r1 = r1.length() // Catch:{ all -> 0x00a2 } int r1 = r1 + 64 java.lang.StringBuilder r6 = new java.lang.StringBuilder // Catch:{ all -> 0x00a2 } r6.<init>(r1) // Catch:{ all -> 0x00a2 } java.lang.String r1 = "Tried reading key pair before writing new one, but failed with: " r6.append(r1) // Catch:{ all -> 0x00a2 } r6.append(r12) // Catch:{ all -> 0x00a2 } java.lang.String r12 = r6.toString() // Catch:{ all -> 0x00a2 } android.util.Log.d(r0, r12) // Catch:{ all -> 0x00a2 } L_0x008f: r9.position(r4) // Catch:{ all -> 0x00a2 } java.io.OutputStream r12 = java.nio.channels.Channels.newOutputStream(r9) // Catch:{ all -> 0x00a2 } r2.store(r12, r10) // Catch:{ all -> 0x00a2 } if (r9 == 0) goto L_0x009e zza((java.lang.Throwable) r10, (java.nio.channels.FileChannel) r9) // Catch:{ all -> 0x00ab } L_0x009e: zza((java.lang.Throwable) r10, (java.io.RandomAccessFile) r3) // Catch:{ IOException -> 0x00b2 } return r11 L_0x00a2: r11 = move-exception throw r11 // Catch:{ all -> 0x00a4 } L_0x00a4: r12 = move-exception if (r9 == 0) goto L_0x00aa zza((java.lang.Throwable) r11, (java.nio.channels.FileChannel) r9) // Catch:{ all -> 0x00ab } L_0x00aa: throw r12 // Catch:{ all -> 0x00ab } L_0x00ab: r9 = move-exception throw r9 // Catch:{ all -> 0x00ad } L_0x00ad: r11 = move-exception zza((java.lang.Throwable) r9, (java.io.RandomAccessFile) r3) // Catch:{ IOException -> 0x00b2 } throw r11 // Catch:{ IOException -> 0x00b2 } L_0x00b2: r9 = move-exception java.lang.String r9 = java.lang.String.valueOf(r9) java.lang.String r11 = java.lang.String.valueOf(r9) int r11 = r11.length() int r11 = r11 + 21 java.lang.StringBuilder r12 = new java.lang.StringBuilder r12.<init>(r11) java.lang.String r11 = "Failed to write key: " r12.append(r11) r12.append(r9) java.lang.String r9 = r12.toString() android.util.Log.w(r0, r9) return r10 */ throw new UnsupportedOperationException("Method not decompiled: com.google.firebase.iid.zzy.zza(android.content.Context, java.lang.String, com.google.firebase.iid.zzz, boolean):com.google.firebase.iid.zzz"); } private static File zzb(Context context) { File noBackupFilesDir = ContextCompat.getNoBackupFilesDir(context); if (noBackupFilesDir != null && noBackupFilesDir.isDirectory()) { return noBackupFilesDir; } Log.w("FirebaseInstanceId", "noBackupFilesDir doesn't exist, using regular files directory instead"); return context.getFilesDir(); } private static File zzf(Context context, String str) { String str2; if (TextUtils.isEmpty(str)) { str2 = "com.google.InstanceId.properties"; } else { try { String encodeToString = Base64.encodeToString(str.getBytes("UTF-8"), 11); StringBuilder sb = new StringBuilder(String.valueOf(encodeToString).length() + 33); sb.append("com.google.InstanceId_"); sb.append(encodeToString); sb.append(".properties"); str2 = sb.toString(); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } return new File(zzb(context), str2); } /* JADX WARNING: Code restructure failed: missing block: B:15:0x0025, code lost: r2 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:16:0x0026, code lost: if (r8 != null) goto L_0x0028; */ /* JADX WARNING: Code restructure failed: missing block: B:18:?, code lost: zza(r1, r8); */ /* JADX WARNING: Code restructure failed: missing block: B:19:0x002b, code lost: throw r2; */ /* JADX WARNING: Code restructure failed: missing block: B:23:0x002e, code lost: r1 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:24:0x002f, code lost: zza(r8, r0); */ /* JADX WARNING: Code restructure failed: missing block: B:25:0x0032, code lost: throw r1; */ /* Code decompiled incorrectly, please refer to instructions dump. */ private final com.google.firebase.iid.zzz zza(java.io.File r8) throws com.google.firebase.iid.zzaa, java.io.IOException { /* r7 = this; java.io.FileInputStream r0 = new java.io.FileInputStream r0.<init>(r8) java.nio.channels.FileChannel r8 = r0.getChannel() // Catch:{ all -> 0x002c } r2 = 0 r4 = 9223372036854775807(0x7fffffffffffffff, double:NaN) r6 = 1 r1 = r8 r1.lock(r2, r4, r6) // Catch:{ all -> 0x0023 } com.google.firebase.iid.zzz r1 = zza((java.nio.channels.FileChannel) r8) // Catch:{ all -> 0x0023 } r2 = 0 if (r8 == 0) goto L_0x001f zza((java.lang.Throwable) r2, (java.nio.channels.FileChannel) r8) // Catch:{ all -> 0x002c } L_0x001f: zza((java.lang.Throwable) r2, (java.io.FileInputStream) r0) return r1 L_0x0023: r1 = move-exception throw r1 // Catch:{ all -> 0x0025 } L_0x0025: r2 = move-exception if (r8 == 0) goto L_0x002b zza((java.lang.Throwable) r1, (java.nio.channels.FileChannel) r8) // Catch:{ all -> 0x002c } L_0x002b: throw r2 // Catch:{ all -> 0x002c } L_0x002c: r8 = move-exception throw r8 // Catch:{ all -> 0x002e } L_0x002e: r1 = move-exception zza((java.lang.Throwable) r8, (java.io.FileInputStream) r0) throw r1 */ throw new UnsupportedOperationException("Method not decompiled: com.google.firebase.iid.zzy.zza(java.io.File):com.google.firebase.iid.zzz"); } private static zzz zza(FileChannel fileChannel) throws zzaa, IOException { Properties properties = new Properties(); properties.load(Channels.newInputStream(fileChannel)); String property = properties.getProperty("pub"); String property2 = properties.getProperty("pri"); if (property == null || property2 == null) { throw new zzaa("Invalid properties file"); } try { return new zzz(zzc(property, property2), Long.parseLong(properties.getProperty("cre"))); } catch (NumberFormatException e) { throw new zzaa((Exception) e); } } private static zzz zza(SharedPreferences sharedPreferences, String str) throws zzaa { String string = sharedPreferences.getString(zzaw.zzd(str, "|P|"), (String) null); String string2 = sharedPreferences.getString(zzaw.zzd(str, "|K|"), (String) null); if (string == null || string2 == null) { return null; } return new zzz(zzc(string, string2), zzb(sharedPreferences, str)); } private final void zza(Context context, String str, zzz zzz) { SharedPreferences sharedPreferences = context.getSharedPreferences("com.google.android.gms.appid", 0); try { if (zzz.equals(zza(sharedPreferences, str))) { return; } } catch (zzaa unused) { } if (Log.isLoggable("FirebaseInstanceId", 3)) { Log.d("FirebaseInstanceId", "Writing key to shared preferences"); } SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString(zzaw.zzd(str, "|P|"), zzz.zzv()); edit.putString(zzaw.zzd(str, "|K|"), zzz.zzw()); edit.putString(zzaw.zzd(str, "cre"), String.valueOf(zzz.zzbs)); edit.commit(); } private static long zzb(SharedPreferences sharedPreferences, String str) { String string = sharedPreferences.getString(zzaw.zzd(str, "cre"), (String) null); if (string == null) { return 0; } try { return Long.parseLong(string); } catch (NumberFormatException unused) { return 0; } } private static /* synthetic */ void zza(Throwable th, FileChannel fileChannel) { if (th != null) { try { fileChannel.close(); } catch (Throwable th2) { zzc.zza(th, th2); } } else { fileChannel.close(); } } private static /* synthetic */ void zza(Throwable th, RandomAccessFile randomAccessFile) { if (th != null) { try { randomAccessFile.close(); } catch (Throwable th2) { zzc.zza(th, th2); } } else { randomAccessFile.close(); } } private static /* synthetic */ void zza(Throwable th, FileInputStream fileInputStream) { if (th != null) { try { fileInputStream.close(); } catch (Throwable th2) { zzc.zza(th, th2); } } else { fileInputStream.close(); } } }
41.219457
215
0.557275
825c35b3871f5f5cf0151898e6cb82bdbbcac471
1,562
package com.josedab.interviewbit.strings; import java.util.ArrayList; /** * Given a string containing only digits, restore it by returning all possible valid IP address combinations. A valid IP address must be in the form of A.B.C.D, where A,B,C and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0. Example: Given “25525511135”, return [“255.255.11.135”, “255.255.111.35”]. (Make sure the returned strings are sorted in order) */ public class ValidIpAddresses { public ArrayList<String> restoreIpAddresses(String str) { ArrayList<String> result = new ArrayList<>(); dfs("", str, result, 0); return result; } private void dfs(String candidate, String str, ArrayList<String> result, int count) { if (count == 3 && isValidNumberForIp(str)) { result.add(candidate + str); return; } for (int i = 1; i <=3 && i < str.length(); i++) { String substr = str.substring(0, i); if (isValidNumberForIp(substr)) { dfs(candidate + substr + '.', str.substring(i), result, count + 1); } } } private boolean isValidNumberForIp(String s) { if (s.charAt(0) == '0') return s.equals("0"); int num = Integer.parseInt(s); return num <= 255 && num > 0; } public static void main(String[] args) { ValidIpAddresses solution = new ValidIpAddresses(); System.out.println(solution.restoreIpAddresses("25525511135")); } }
30.627451
109
0.606914
d24a3ae8eeb02f1aac63d166d2e8c4101326860c
2,718
package com.gwenson.common.utils; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * properties工具类 * @author Gwensong email : gwenson@163.com * */ public class PropertiesUtil { private static Logger log=LoggerFactory.getLogger(PropertiesUtil.class); /** * 根据Key读取Value * @param filePath * @param key * @return */ public static String GetValueByKey(String filePath, String key) { Properties pps = new Properties(); try { // InputStream in = new BufferedInputStream (new FileInputStream(filePath)); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); pps.load(in); String value = pps.getProperty(key); log.info(key + " = " + value); return value; }catch (IOException e) { e.printStackTrace(); return null; } } /** * 读取Properties的全部信息 * @param filePath * @return * @throws IOException */ @SuppressWarnings("rawtypes") public static Map<String, String> GetAllProperties(String filePath,Class<?> c ) throws IOException { Properties pps = new Properties(); InputStream in = c.getClass().getResourceAsStream(filePath); pps.load(in); Enumeration en = pps.propertyNames(); //得到配置文件的名字 Map<String, String> map=new HashMap<String, String>(); while(en.hasMoreElements()) { String strKey = (String) en.nextElement(); String strValue = pps.getProperty(strKey); log.info(strKey + "=" + strValue); map.put(strKey, strValue); } return map; } /** * 写入Properties信息 * @param filePath * @param pKey * @param pValue * @throws IOException */ public static void WriteProperties (String filePath, String pKey, String pValue,Class<?> c ) throws IOException { Properties pps = new Properties(); InputStream in = c.getClass().getResourceAsStream(filePath); //从输入流中读取属性列表(键和元素对) pps.load(in); //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。 //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。 OutputStream out = new FileOutputStream(filePath); pps.setProperty(pKey, pValue); //以适合使用 load 方法加载到 Properties 表中的格式, //将此 Properties 表中的属性列表(键和元素对)写入输出流 pps.store(out, "Update " + pKey + " name"); } }
30.2
117
0.62362
376787d3e3b8258c63b118665b3542fecbc1a5e4
1,685
/* * Copyright (C) 2017 Angel Garcia * * 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.xengar.android.movieguide.data; /** * Container for data of a clickable, scrollable image. * It can be a movie imagePath, TV Show imagePath, cast image or movie image. */ public class ImageItem { private final int id; private final String imagePath; private final String backgroundImagePath; private final String title; private final String subtitle; // Constructor public ImageItem(String imagePath, int id, String title, String subtitle, String backgroundImagePath) { this.title = title; this.subtitle = subtitle; this.id = id; this.imagePath = imagePath; this.backgroundImagePath = backgroundImagePath; } // Getters public String getImageTitle() { return title; } public String getImageSubtitle() { return subtitle; } public int getImageId() { return id; } public String getImagePath() { return imagePath; } public String getBackgroundImagePath() { return backgroundImagePath; } }
27.622951
77
0.677151
348b246a952052b8b82f38e3a8e0134bd23ab9ac
1,944
package com.alivc.live.pusher.demo; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.alivc.live.pusher.AlivcLivePushStatsInfo; public class PushTextStatsFragment extends Fragment{ public static final String TAG = "PushTextStatsFragment"; private LogInfoAdapter mAdapter; private RecyclerView mLogRecyclerView; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.push_text_log, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLogRecyclerView = (RecyclerView) view.findViewById(R.id.log_recycler); mAdapter = new LogInfoAdapter(getActivity()); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); mLogRecyclerView.setLayoutManager(layoutManager); mAdapter.setHasStableIds(true); mLogRecyclerView.setAdapter(mAdapter); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } public void updateValue(AlivcLivePushStatsInfo alivcLivePushStatsInfo) { if(mAdapter != null) { mAdapter.updateValue(alivcLivePushStatsInfo); } } }
28.173913
113
0.715535
d7fda731f9503b8d69928cf40bdea39fe5dcba6e
1,293
package com.github.chen0040.elasticsearch.server.configs; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import pl.allegro.tech.embeddedelasticsearch.EmbeddedElastic; import pl.allegro.tech.embeddedelasticsearch.PopularProperties; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; @Configuration public class BeanConfig { @Value("${elasticsearch.tcp_comm_port}") private int tcpPort; @Value("${elasticsearch.cluster_name}") private String esClusterName; @Bean public EmbeddedElastic elasticSearch() throws IOException, InterruptedException { return EmbeddedElastic.builder() .withElasticVersion("5.0.0") .withSetting(PopularProperties.TRANSPORT_TCP_PORT, tcpPort) .withSetting(PopularProperties.CLUSTER_NAME, esClusterName) //.withPlugin("analysis-stempel") .withSetting("http.cors.allow-origin", "*") .withStartTimeout(60L, TimeUnit.SECONDS) .withSetting("http.cors.enabled", true) .withInstallationDirectory(new File("/tmp/es")) .build(); } }
35.916667
85
0.705336
415601da4c4e5267288ae27c1573990daa652d60
4,565
package com.tailf.jnc; import java.util.ArrayList; /** * This class implements a list of prefix mappings, which provides mappings * from namespaces to prefixes. * **/ public class PrefixMap extends ArrayList<Prefix> { private static final long serialVersionUID = 1L; /** * Creates an empty prefix map object. */ public PrefixMap() { } /** * Inserts a prefix initially in the new prefix map. */ public PrefixMap(Prefix p) { add(p); } /** * Inserts an array of prefixes initially in the new prefix map. */ public PrefixMap(Prefix[] prefixes) { for (Prefix p : prefixes) { add(p); } } /** * Nondestructively merges a prefix map with this object. * * @param prefixes The prefix map to merge with. */ public void merge(PrefixMap prefixes) { for (Prefix p : prefixes) { merge(p); } } /** * Non-destructively merges a prefix in the prefix map. * * @param prefix the prefix to add if not already present. */ public void merge(Prefix prefix) { final int index = indexOfName(prefix.name); if (index == -1) { add(prefix); } } /** * Stores the prefixes in the prefix map. Replaces those that already * exists, and add the new ones that doesn't exist. * * @param prefixes Prefix mappings */ public void set(PrefixMap prefixes) { trace("set: " + prefixes); for (Prefix p : prefixes) { set(p); } } /** * Stores a prefix in the prefix map. Replace any old occurrence. * * @param prefix Prefix mapping to be set */ public void set(Prefix prefix) { final int index = indexOfName(prefix.name); if (index == -1) { if (prefix.name.equals("")) { add(0, prefix); // add default prefix first in the prefix map } else { add(prefix); } } else { set(index, prefix); } } /** * Removes a prefix mapping. * * @param prefix Name of prefix mapping to be removed. */ public void remove(String prefix) { final int index = indexOfName(prefix); if (index >= 0) { remove(index); } } /** * Gets the prefix at specified index. * * @param i Index of prefix mapping to get. * @return Prefix mapping */ public Prefix getPrefix(int i) { return super.get(i); } /** * Returns the index of the prefix name in the prefix map. * * @param name The prefix name * @return Index of prefix mapping with specified prefix name */ public int indexOfName(String name) { // trace("indexOfName("+name+")"); for (int i = 0; i < size(); i++) { if (name.equals(getPrefix(i).name)) { return i; } } return -1; } /** * Lookups prefix name in the prefix map. Return the Prefix object. * * @param name The prefix name * @return Prefix mapping */ public Prefix lookup(String name) { // trace("lookup("+name+")"); for (int i = 0; i < size(); i++) { final Prefix p = getPrefix(i); if (name.equals(p.name)) { return p; } } return null; } /** * Lookups namespace and returns prefix for it. * * @param ns The namespace to lookup in this prefix */ public String nsToPrefix(String ns) { // trace("nsToPrefix(\""+ns+"\")"); for (int i = 0; i < size(); i++) { final Prefix p = getPrefix(i); if (p.ns != null && ns.equals(p.value)) { return p.name; } } return null; } /** * Lookups prefix and returns the associated namespace */ public String prefixToNs(String name) { // trace("prefixToNs("+name+")"); for (int i = 0; i < size(); i++) { final Prefix p = getPrefix(i); if (name.equals(p.name)) { return p.value; } } return null; } /* help functions */ /** * Printout trace if 'debug'-flag is enabled. */ private void trace(String s) { if (Element.debugLevel >= Element.DEBUG_LEVEL_PREFIXMAP) { System.err.println("*PrefixMap: " + s); } } }
24.411765
77
0.514786
e1ffca38970f021bc03879209a210439a1308fc2
563
package c.c.k.ctn; import c.c.k.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @Title c.c.k.ctn * @Copyright: Copyright 2019 * @Description: java <br/> * @Created on 2019/7/23 chenck */ @RestController public class HomeController { @Autowired private HelloService helloService; @GetMapping("/hello") public String sayHi(){ return helloService.sayHello(); } }
21.653846
62
0.730018
63e853a0aeda2987a2c98ac4b241de044936d64e
7,094
package com.springx.bootdubbo.starter.cache.core.command; import redis.clients.util.SafeEncoder; import java.util.*; import static com.springx.bootdubbo.starter.cache.core.support.redis.JedisProviderFactory.*; /** * redis操作hashmap * * @author <a href="mailto:505847426@qq.com">carterbrother</a> * @description <br> * @date 2015年12月7日 * @Copyright (c) 2015, springx.com */ public class RedisBinaryHashMap extends RedisCollection { public RedisBinaryHashMap(String key) { super(key); } /** * @param key * @param expireTime 超时时间(秒) 小于等于0 为永久缓存 */ public RedisBinaryHashMap(String key, long expireTime) { super(key, expireTime); } /** * 指定组名 * * @param key * @param groupName */ public RedisBinaryHashMap(String key, String groupName) { super(key, groupName); } /** * @param key * @param groupName 分组名 * @param expireTime 超时时间(秒) 小于等于0 为永久缓存 */ public RedisBinaryHashMap(String key, String groupName, long expireTime) { super(key, groupName, expireTime); } /** * 设置hash缓存 * * @param datas * @return */ public boolean set(Map<String, byte[]> datas) { if (datas == null || datas.isEmpty()) { return false; } Map<byte[], byte[]> newDatas = new HashMap<>(); Set<String> keySet = datas.keySet(); for (String key : keySet) { if (datas.get(key) == null) { continue; } newDatas.put(SafeEncoder.encode(key), datas.get(key)); } boolean result = false; try { if (isCluster(groupName)) { result = getBinaryJedisClusterCommands(groupName).hmset(key, newDatas).equals(RESP_OK); } else { result = getBinaryJedisCommands(groupName).hmset(key, newDatas).equals(RESP_OK); } //设置超时时间 if (result) setExpireIfNot(expireTime); return result; } finally { getJedisProvider(groupName).release(); } } /** * 获取所有值 * value以byte[]数组形式返回 * * @return */ public Map<String, byte[]> getAll() { try { Map<byte[], byte[]> datas = null; Map<String, byte[]> result = new HashMap<>(); if (isCluster(groupName)) { datas = getBinaryJedisClusterCommands(groupName).hgetAll(key); } else { datas = getBinaryJedisCommands(groupName).hgetAll(key); } Iterator<Map.Entry<byte[], byte[]>> it = datas.entrySet().iterator(); while (it.hasNext()) { Map.Entry<byte[], byte[]> entry = it.next(); result.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); } return result; } finally { getJedisProvider(groupName).release(); } } /** * 查看缓存hash是否包含某个key * * @param field * @return */ public boolean containsKey(String field) { try { if (isCluster(groupName)) { return getBinaryJedisClusterCommands(groupName).hexists(key, SafeEncoder.encode(field)); } else { return getBinaryJedisCommands(groupName).hexists(key, SafeEncoder.encode(field)); } } finally { getJedisProvider(groupName).release(); } } /** * 设置ç * * @param field * @param value * @return */ public boolean set(String field, byte[] value) { boolean result = false; if (value == null) { return false; } //返回值(1:新字段被设置,0:已经存在值被更新) try { if (isCluster(groupName)) { result = getBinaryJedisClusterCommands(groupName) .hset(key, SafeEncoder.encode(field), value) >= 0; } else { result = getBinaryJedisCommands(groupName).hset(key, SafeEncoder.encode(field), value) >= 0; } //设置超时时间 if (result) { setExpireIfNot(expireTime); } return result; } finally { getJedisProvider(groupName).release(); } } /** * 设置ç * * @param field * @param value * @return */ public boolean set(String field, Object value) { boolean result = false; if (value == null) { return false; } //返回值(1:新字段被设置,0:已经存在值被更新) try { if (isCluster(groupName)) { result = getBinaryJedisClusterCommands(groupName) .hset(key, SafeEncoder.encode(field), SafeEncoder.encode(value.toString())) >= 0; } else { result = getBinaryJedisCommands(groupName).hset(key, SafeEncoder.encode(field), SafeEncoder.encode(value.toString())) >= 0; } //设置超时时间 if (result) { setExpireIfNot(expireTime); } return result; } finally { getJedisProvider(groupName).release(); } } /** * 移除hash缓存中的指定值 * * @param field * @return */ public boolean remove(String field) { try { if (isCluster(groupName)) { return getBinaryJedisClusterCommands(groupName).hdel(key, SafeEncoder.encode(field)).equals(RESP_OK); } else { return getBinaryJedisCommands(groupName).hdel(key, SafeEncoder.encode(field)).equals(RESP_OK); } } finally { getJedisProvider(groupName).release(); } } /** * 返回长度 * * @return */ public long length() { try { if (isCluster(groupName)) { return getBinaryJedisClusterCommands(groupName).hlen(key); } else { return getBinaryJedisCommands(groupName).hlen(key); } } finally { getJedisProvider(groupName).release(); } } /** * 获取一个值 * * @param field * @return */ @SuppressWarnings("unchecked") public byte[] getOne(String field) { return get(field).get(field); } /** * 获取多个key的值 * * @param fields * @return */ public Map<String, byte[]> get(String... fields) { try { List<byte[]> datas = null; Map<String, byte[]> result = new HashMap<>(); for (String field : fields) { if (isCluster(groupName)) { datas = getBinaryJedisClusterCommands(groupName).hmget(key, SafeEncoder.encode(field)); } else { datas = getBinaryJedisCommands(groupName).hmget(key, SafeEncoder.encode(field)); } result.put(field, datas.get(0)); } return result; } finally { getJedisProvider(groupName).release(); } } }
26.871212
139
0.519735
b75add3ff102335d8baad69b491c32e80babddcc
6,179
package org.egov.wf.service; import com.jayway.jsonpath.JsonPath; import org.egov.common.contract.request.RequestInfo; import org.egov.mdms.model.MasterDetail; import org.egov.mdms.model.MdmsCriteria; import org.egov.mdms.model.MdmsCriteriaReq; import org.egov.mdms.model.ModuleDetail; import org.egov.wf.config.WorkflowConfig; import org.egov.wf.repository.ServiceRequestRepository; import org.egov.wf.util.WorkflowConstants; import org.egov.wf.web.models.ProcessInstanceRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import java.util.*; import static org.egov.wf.util.WorkflowConstants.*; @Service public class MDMSService { private WorkflowConfig config; private ServiceRequestRepository serviceRequestRepository; private WorkflowConfig workflowConfig; private Map<String,Boolean> stateLevelMapping; @Autowired public MDMSService(WorkflowConfig config, ServiceRequestRepository serviceRequestRepository, WorkflowConfig workflowConfig) { this.config = config; this.serviceRequestRepository = serviceRequestRepository; this.workflowConfig = workflowConfig; } public Map<String, Boolean> getStateLevelMapping() { return this.stateLevelMapping; } @Bean public void stateLevelMapping(){ Map<String, Boolean> stateLevelMapping = new HashMap<>(); Object mdmsData = getBusinessServiceMDMS(); List<HashMap<String, Object>> configs = JsonPath.read(mdmsData,JSONPATH_BUSINESSSERVICE_STATELEVEL); for (Map map : configs){ String businessService = (String) map.get("businessService"); Boolean isStatelevel = Boolean.valueOf((String) map.get("isStatelevel")); stateLevelMapping.put(businessService, isStatelevel); } this.stateLevelMapping = stateLevelMapping; } /** * Calls MDMS service to fetch master data * @param requestInfo * @return */ public Object mDMSCall(RequestInfo requestInfo){ MdmsCriteriaReq mdmsCriteriaReq = getMDMSRequest(requestInfo,workflowConfig.getStateLevelTenantId()); Object result = serviceRequestRepository.fetchResult(getMdmsSearchUrl(), mdmsCriteriaReq); return result; } /** * Calls MDMS service to fetch master data * @return */ public Object getBusinessServiceMDMS(){ MdmsCriteriaReq mdmsCriteriaReq = getBusinessServiceMDMSRequest(new RequestInfo(), workflowConfig.getStateLevelTenantId()); Object result = serviceRequestRepository.fetchResult(getMdmsSearchUrl(), mdmsCriteriaReq); return result; } /** * Creates MDMSCriteria * @param requestInfo The RequestInfo of the request * @param tenantId TenantId of the request * @return MDMSCriteria for search call */ private MdmsCriteriaReq getMDMSRequest(RequestInfo requestInfo, String tenantId){ ModuleDetail escalationDetail = getAutoEscalationConfig(); ModuleDetail tenantDetail = getTenants(); List<ModuleDetail> moduleDetails = new LinkedList<>(Arrays.asList(escalationDetail,tenantDetail)); MdmsCriteria mdmsCriteria = MdmsCriteria.builder().moduleDetails(moduleDetails) .tenantId(tenantId) .build(); MdmsCriteriaReq mdmsCriteriaReq = MdmsCriteriaReq.builder().mdmsCriteria(mdmsCriteria) .requestInfo(requestInfo).build(); return mdmsCriteriaReq; } /** * Creates MDMSCriteria * @param requestInfo The RequestInfo of the request * @param tenantId TenantId of the request * @return MDMSCriteria for search call */ private MdmsCriteriaReq getBusinessServiceMDMSRequest(RequestInfo requestInfo, String tenantId){ ModuleDetail wfMasterDetails = getBusinessServiceMasterConfig(); MdmsCriteria mdmsCriteria = MdmsCriteria.builder().moduleDetails(Collections.singletonList(wfMasterDetails)) .tenantId(tenantId) .build(); MdmsCriteriaReq mdmsCriteriaReq = MdmsCriteriaReq.builder().mdmsCriteria(mdmsCriteria) .requestInfo(requestInfo).build(); return mdmsCriteriaReq; } /** * Fetches BusinessServiceMasterConfig from MDMS * @return ModuleDetail for workflow */ private ModuleDetail getBusinessServiceMasterConfig() { // master details for WF module List<MasterDetail> wfMasterDetails = new ArrayList<>(); wfMasterDetails.add(MasterDetail.builder().name(MDMS_BUSINESSSERVICE).build()); ModuleDetail wfModuleDtls = ModuleDetail.builder().masterDetails(wfMasterDetails) .moduleName(MDMS_WORKFLOW).build(); return wfModuleDtls; } /** * Creates MDMS ModuleDetail object for AutoEscalation * @return ModuleDetail for AutoEscalation */ private ModuleDetail getAutoEscalationConfig() { // master details for WF module List<MasterDetail> masterDetails = new ArrayList<>(); masterDetails.add(MasterDetail.builder().name(MDMS_AUTOESCALTION).build()); ModuleDetail wfModuleDtls = ModuleDetail.builder().masterDetails(masterDetails) .moduleName(MDMS_WORKFLOW).build(); return wfModuleDtls; } /** * Creates MDMS ModuleDetail object for tenants * @return ModuleDetail for tenants */ private ModuleDetail getTenants() { // master details for WF module List<MasterDetail> masterDetails = new ArrayList<>(); masterDetails.add(MasterDetail.builder().name(MDMS_TENANTS).build()); ModuleDetail wfModuleDtls = ModuleDetail.builder().masterDetails(masterDetails) .moduleName(MDMS_MODULE_TENANT).build(); return wfModuleDtls; } /** * Returns the url for mdms search endpoint * @return url for mdms search endpoint */ public StringBuilder getMdmsSearchUrl() { return new StringBuilder().append(config.getMdmsHost()).append(config.getMdmsEndPoint()); } }
31.207071
131
0.70513
f94ceb552ab82630ec460f0b4fea8f0fb0af2933
141
package arjuna.tpi.helpers; public class Args { public static Arg arg(String name, String value) { return new Arg(name, value); } }
14.1
51
0.695035
cf21e17e1168de442a4e1111efecba6dec95020d
4,980
package com.mygdx.game.action; import com.badlogic.gdx.math.MathUtils; import com.mygdx.game.actor.BaseActor; import com.mygdx.game.manager.EnumAction; import com.mygdx.game.map.MapLocal; import com.mygdx.game.stage.StageMap; /** * Created by Administrator on 2017/3/29. */ public class ActionMove implements GamepadKey { @Override public void passU(MapLocal mapLocal, BaseActor actor) { // move(mapLocal,actor,0,1); actor.move(0,1); actor.enumAction = EnumAction.MOVE_N; actor.faceTo = EnumAction.FACE_N; } @Override public void passD(MapLocal mapLocal, BaseActor actor) { // move(mapLocal,actor,0,-1); actor.move(0,-1); actor.enumAction = EnumAction.MOVE_S; actor.faceTo = EnumAction.FACE_S; } @Override public void passL(MapLocal mapLocal, BaseActor actor) { // move(mapLocal,actor,-1,0); actor.move(-1,0); actor.enumAction = EnumAction.MOVE_W; actor.faceTo = EnumAction.FACE_W; } @Override public void passR(MapLocal mapLocal, BaseActor actor) { // move(mapLocal,actor,1,0); actor.move(1,0); // actor.addAction(Actions.moveBy(100,100,2)); actor.enumAction = EnumAction.MOVE_E; actor.faceTo = EnumAction.FACE_E; } @Override public void passA(MapLocal mapLocal, BaseActor actor) { // 直接获得物品 // 1、判断地图中物品对象与actor的距离 2、显示最近的物品的名称 3、按键时判断背包大小获取物品 for (int i=0;i<10;i++){ if (actor.items[i].length()<2 && actor.objName.length()>0){ actor.items[i] = actor.objName; mapLocal.removeObj("objs",actor.objName); StageMap.getInstance().addMsg("得到:"+actor.objName); break; }else if (i==10){ StageMap.getInstance().addMsg("包满了,装不下了"); } } } @Override public void passB(MapLocal mapLocal, BaseActor actor) { } @Override public void passX(MapLocal mapLocal, BaseActor actor) { // 互动测试 if (actor.actionState == ToolActions.砍柴){ ToolActions.砍柴.enter(actor); } } @Override public void passY(MapLocal mapLocal, BaseActor actor) { } @Override public void passL1(MapLocal mapLocal, BaseActor actor) { // actor.actionStr = "战斗"; // actor.actionIndex++; actor.put("行动状态","战斗"); // actor.actionStr = actor.get("行动状态"); } @Override public void passL2(MapLocal mapLocal, BaseActor actor) { actor.itemUp(); System.out.print(actor.indexItem); } @Override public void passR1(MapLocal mapLocal, BaseActor actor) { actor.actionIndex--; } @Override public void passR2(MapLocal mapLocal, BaseActor actor) { actor.itemDown(); } @Override public void passStart(MapLocal mapLocal, BaseActor actor) { // moveRand(mapLocal,actor); // moveTo(mapLocal,actor,40,40); } @Override public void passBack(MapLocal mapLocal, BaseActor actor) { } void moveRand(MapLocal mapLocal,BaseActor baseActor){ int rx,ry; rx = MathUtils.random(-1,1); ry = MathUtils.random(-1,1); move(mapLocal,baseActor,rx,ry); } boolean arrive(MapLocal mapLocal,BaseActor baseActor,int x,int y){ int dx,dy; dx = Math.abs(baseActor.lx-x); dy = Math.abs(baseActor.ly-y); return (dx==dy && dx==0); } void moveTo(MapLocal mapLocal,BaseActor baseActor,int x,int y){ int distance; int dx,dy; dx = (int) Math.abs(baseActor.getX()-x); dy = (int) Math.abs(baseActor.getY()-y); if (!arrive(mapLocal,baseActor,x,y)){ if (dx>dy){ if (baseActor.getX()>x){ move(mapLocal,baseActor,-1,0); }else { move(mapLocal,baseActor,1,0); } }else { if (baseActor.getY()>y){ move(mapLocal,baseActor,0,-1); }else { move(mapLocal,baseActor,0,1); } } } } void move(MapLocal mapLocal,BaseActor baseActor,int x,int y){ final int x0,y0; String[] datas; x0 = baseActor.lx + x; y0 = baseActor.ly + y; if(x0>-1 && y0>-1 && x0<16 && y0<16){ // datas=mapLocal.datas[y0][x0].split(","); // if (datas[1].equals("空气")){ baseActor.move(x,y); // if (!datas[2].equals("空气")){ // } // } } else if(x0 == -1){ baseActor.rx-=2; baseActor.lx = 15; } else if(y0== -1){ baseActor.ry-=2; baseActor.ly = 15; } else if(x0 == 16){ baseActor.rx +=2; baseActor.lx = 0; } else if(y0 == 16){ baseActor.ry+=2; baseActor.ly = 0; } } }
31.320755
71
0.548394
c9b51e8499f89da29db6e8242a9346b2936b66b8
1,361
package de.ragedev.purejaxrs; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Scanner; import javax.ws.rs.ext.RuntimeDelegate; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; @SuppressWarnings("restriction") public class MicroServer { private static HttpServer server; public static void main(String[] args) throws IOException { start(); Scanner scanner = new Scanner(System.in); System.out.println("Enter any key and return to stop the MicroServer."); scanner.next(); stop(); scanner.close(); } public static void start() throws IOException { System.out.println("Possible endpoints are " + "\n - http://localhost:8080/helloworld and " + "\n - http://localhost:8080/sayhello?name=yourname"); final InetSocketAddress socketAddress = new InetSocketAddress("localhost", 8080); server = HttpServer.create(socketAddress, 0); final HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new Endpoints(), HttpHandler.class); server.createContext("/", handler); server.start(); System.out.println("MicroServer started."); } public static void stop() { if (server != null) { server.stop(0); System.out.println("MicroServer stopped."); } else throw new IllegalStateException("You must start the server before stopping it."); } }
28.354167
111
0.737693
c0c7fa414c02ae98902ab27bc96e78e1948fc2d8
1,658
/* * Copyright (c) 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.spring.dynamic; import org.springframework.beans.factory.FactoryBean; import reactor.core.dynamic.DynamicReactor; import reactor.core.dynamic.DynamicReactorFactory; /** * @author Jon Brisbin */ public class DynamicReactorFactoryBean<T extends DynamicReactor> implements FactoryBean<T> { private final boolean singleton; private final Class<T> type; private final DynamicReactorFactory<T> reactorFactory; public DynamicReactorFactoryBean(Class<T> type) { this.singleton = false; this.type = type; this.reactorFactory = new DynamicReactorFactory<T>(type); } public DynamicReactorFactoryBean(Class<T> type, boolean singleton) { this.singleton = singleton; this.type = type; this.reactorFactory = new DynamicReactorFactory<T>(type); } @Override public T getObject() throws Exception { return reactorFactory.create(); } @Override public Class<?> getObjectType() { return type; } @Override public boolean isSingleton() { return singleton; } }
27.633333
92
0.736429
badcd4fa93036fe8748ef44458818bc356befcee
4,552
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.metrics.core.impl; import static org.hawkular.metrics.core.api.AvailabilityType.DOWN; import static org.hawkular.metrics.core.api.AvailabilityType.UP; import static org.hawkular.metrics.core.impl.AvailabilityBucketDataPointMatcher.matchesAvailabilityBucketDataPoint; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.hawkular.metrics.core.api.AvailabilityBucketDataPoint; import org.hawkular.metrics.core.api.AvailabilityType; import org.hawkular.metrics.core.api.Buckets; import org.hawkular.metrics.core.api.DataPoint; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableList; /** * @author Thomas Segismont */ public class AvailabilityBucketedOutputMapperTest { private AvailabilityBucketedOutputMapper mapper; @Before public void setup() { Buckets buckets = new Buckets(1, 10, 10); mapper = new AvailabilityBucketedOutputMapper(null, null, buckets); } @Test public void newEmptyPointInstance() throws Exception { assertTrue("Expected an empty instance", mapper.newEmptyPointInstance(1, 100).isEmpty()); } @Test public void testWithOneUp() throws Exception { DataPoint<AvailabilityType> a1 = new DataPoint<>(15, UP); AvailabilityBucketDataPoint actual = mapper.newPointInstance(10, 20, ImmutableList.of(a1)); AvailabilityBucketDataPoint expected = new AvailabilityBucketDataPoint.Builder(10, 20) .setUptimeRatio(1.0) .build(); assertFalse("Expected non empty instance", actual.isEmpty()); assertThat(actual, matchesAvailabilityBucketDataPoint(expected)); } @Test public void testWithOneDown() throws Exception { DataPoint<AvailabilityType> a1 = new DataPoint<>(15, DOWN); AvailabilityBucketDataPoint actual = mapper.newPointInstance(10, 20, ImmutableList.of(a1)); AvailabilityBucketDataPoint expected = new AvailabilityBucketDataPoint.Builder(10, 20) .setDowntimeCount(1) .setDowntimeDuration(10) .setLastDowntime(20) .setUptimeRatio(0.0) .build(); assertFalse("Expected non empty instance", actual.isEmpty()); assertThat(actual, matchesAvailabilityBucketDataPoint(expected)); } @Test public void testWithOneDownOneUp() throws Exception { DataPoint<AvailabilityType> a1 = new DataPoint<>(12, DOWN); DataPoint<AvailabilityType> a2 = new DataPoint<>(18, UP); AvailabilityBucketDataPoint actual = mapper.newPointInstance(10, 20, ImmutableList.of(a1, a2)); AvailabilityBucketDataPoint expected = new AvailabilityBucketDataPoint.Builder(10, 20) .setDowntimeCount(1) .setDowntimeDuration(8) .setLastDowntime(18) .setUptimeRatio(0.2) .build(); assertFalse("Expected non empty instance", actual.isEmpty()); assertThat(actual, matchesAvailabilityBucketDataPoint(expected)); } @Test public void testWithOneUpOneDown() throws Exception { DataPoint<AvailabilityType> a1 = new DataPoint<>(13, UP); DataPoint<AvailabilityType> a2 = new DataPoint<>(17, DOWN); AvailabilityBucketDataPoint actual = mapper.newPointInstance(10, 20, ImmutableList.of(a1, a2)); AvailabilityBucketDataPoint expected = new AvailabilityBucketDataPoint.Builder(10, 20) .setDowntimeCount(1) .setDowntimeDuration(3) .setLastDowntime(20) .setUptimeRatio(0.7) .build(); assertFalse("Expected non empty instance", actual.isEmpty()); assertThat(actual, matchesAvailabilityBucketDataPoint(expected)); } }
42.943396
115
0.702768
999abd4e77146218fb9f52a9433be31cdbea2ea4
131
package p019d.p273h.p276c.p282f; /* renamed from: d.h.c.f.a */ /* compiled from: BannerAdapterApi */ public interface C12860a { }
18.714286
37
0.709924
493a71e0d4e6e021b076ed660f244dc6d9ca2c6e
518
package com.doggogram.backendsvc.services; import io.jsonwebtoken.Claims; import javax.transaction.Transactional; import java.util.Date; import java.util.Optional; import java.util.function.Function; @Transactional public interface JwtTokenService { String generateToken(String user); String getUserFromToken(String token); Date getExpirationDateFromToken(String token); <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver); Optional<Boolean> validateToken(String token); }
28.777778
78
0.795367
cbd84745d7f1973dc116744add1dcf0ab78faf85
4,141
/* * 작성자 : * 작성일 : * 회계 관련 dao * */ package com.spring.Creamy_CRM.Host_dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.spring.Creamy_CRM.VO.AccountVO; import com.spring.Creamy_CRM.VO.IncomeStatementVO; import com.spring.Creamy_CRM.VO.CostofSalesVO; import com.spring.Creamy_CRM.VO.EndingInventoryVO; @Repository public class AccountDAOImpl implements AccountDAO { @Autowired SqlSession sqlSession; // 매입매출 전표 목록 @Override public List<AccountVO> getSlipList(String host_code) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getSlipList(host_code); } // 매입매출 전표 등록 @Override public int insertSlip(AccountVO vo) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.insertSlip(vo); } // 선택된 유형의 매출전표 조회 public List<AccountVO> getSelectList(Map<String, Object> map){ AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getSelectList(map); } // 검색어에 따른 매출전표 조회 public List<AccountVO> getSearchList(Map<String, Object> map){ AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getSearchList(map); } // 매입매출 전표 수정 페이지 @Override public AccountVO getSlipInfo(String slip_code) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getSlipInfo(slip_code); } // 매입매출 전표 수정처리 @Override public int updateSlip(AccountVO vo) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.updateSlip(vo); } // 매입매출 전표 삭제처리 @Override public int deleteSlip(String slip_code) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.deleteSlip(slip_code); } // 영업외 손익 목록 조회 public List<AccountVO> getNOLlist(String host_code){ AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getNOLlist(host_code); } // 선택된 유형의 영업외손익 조회 public List<AccountVO> getNOLselectList(Map<String, Object> map){ AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getNOLselectList(map); } // 검색어에 따른 영업외손익 조회 public List<AccountVO> getNOLsearchList(Map<String, Object> map){ AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getNOLsearchList(map); } // 손익계산서 조회 public IncomeStatementVO getIncome_statement(Map<String, Object> map){ AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getIncome_statement(map); } // 총 매출액 조회 public int getRevenue(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getRevenue(map); } // 1. 기초 재고액 public EndingInventoryVO getEndingInven(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getEndingInven(map); } // 2. 당기 매입액 public CostofSalesVO getStockTotal(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getStockTotal(map); } // 3. 기말 재고액을 구하기 위한 재고 실사 수량 조회 public int TotalInvenCnt(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.TotalInvenCnt(map); } // 직원 지급 급여 총 금액 조회 public int getTotalSalary(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.getTotalSalary(map); } // 매입매출전표에서 복리후생비, 소모품비, 수수료비용 합계 public int[] sumSGA_expenses(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.sumSGA_expenses(map); } // 매입매출전표에서 법인세등, 비용, 수익 합계 public int[] sumNonOperatingLoss(Map<String, Object> map) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.sumNonOperatingLoss(map); } // 손익계산서 등록처리 public int InsertIncomeStatement(IncomeStatementVO vo) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.InsertIncomeStatement(vo); } // 기말재고액 등록처리 public int insertEndingInventory(EndingInventoryVO vo) { AccountDAO dao = sqlSession.getMapper(AccountDAO.class); return dao.insertEndingInventory(vo); } }
26.88961
71
0.750302
142d71f29910a666e6ab3415f581da90350aa3b0
733
package com.yuelchen.shape3d; import org.junit.Assert; import org.junit.Test; public class CubeTest { @Test public void getSurfaceAreaTest1() { Assert.assertEquals(337.5, Cube.getSurfaceArea(7.5), 1); } @Test public void getSurfaceAreaTest2() { Assert.assertEquals(65.34, Cube.getSurfaceArea(3.3), 2); } @Test public void getVolumeTest1() { Assert.assertEquals(421.87, Cube.getVolume(7.5), 2); } @Test public void getVolumeTest2() { Assert.assertEquals(35.93, Cube.getVolume(3.3), 2); } @Test public void getSpaceDiagonal1() { Assert.assertEquals(12.99, Cube.getSpaceDiagonal(7.5), 2); } @Test public void getSpaceDiagonal2() { Assert.assertEquals(5.71, Cube.getSpaceDiagonal(3.3), 2); } }
19.810811
60
0.706685
7cbb1179ded321e5d3f79eafc2b833d2cc7a326b
3,244
/* * Copyright © 2018, lanbery,Lambor Co,. Ltd. All Rights Reserved. * * Copyright Notice * lanbery copyrights this specification. No part of this specification may be reproduced in any form or means, without the prior written consent of lanbery. * * Disclaimer * This specification is preliminary and is subject to change at any time without notice. Lambor assumes no responsibility for any errors contained herein. * */ package io.nbs.commons.helper; import UI.ConstantsUI; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Properties; public class MerkleHashHelper { private static final Logger logger = LoggerFactory.getLogger(MerkleHashHelper.class); private static final String MERKLE_FILE =".merkle"; private static Properties MERKLE_HASH = new Properties(); private MerkleHashHelper(){ InputStream is = null; try{ File f = new File(ConstantsUI.PROFILE_ROOT); if(!f.exists()){ f.mkdirs(); } File mfile = new File(ConstantsUI.PROFILE_ROOT,MERKLE_FILE); if(!mfile.exists()){ mfile.createNewFile(); } is = new BufferedInputStream(new FileInputStream(mfile)); MERKLE_HASH.load(is); is.close(); }catch (IOException ioe){ logger.error("load merkle file."); if(is!=null){ try { is.close(); }catch (IOException ioec){ logger.error("close io error."); } } } } private static class MerkleHolder { static MerkleHashHelper instance = new MerkleHashHelper(); } /** * * @return */ public static MerkleHashHelper getInstance(){ return MerkleHolder.instance; } /** * * @return */ public static Properties getMerkleHash(){ return MERKLE_HASH; } /** * * @param key * @return */ public String getFileName(String key){ return MERKLE_HASH.getProperty(key); } /** * * @param hash * @param name * @param comments * @return * @throws IOException */ public boolean storeMerkleHash(String hash,String name,String comments) throws FileNotFoundException { if(hash==null)return false; if(StringUtils.isBlank(name))name=hash; File merkleFile; FileOutputStream fos; try{ MERKLE_HASH.setProperty(hash,name); merkleFile = new File(ConstantsUI.PROFILE_ROOT+MERKLE_FILE); fos = new FileOutputStream(merkleFile); if(StringUtils.isNotBlank(comments)){ MERKLE_HASH.store(fos,comments); }else { MERKLE_HASH.store(fos,null); } fos.flush(); fos.close(); return true; } catch (FileNotFoundException e) { throw new FileNotFoundException(MERKLE_FILE+" not found."); } catch (IOException e) { e.printStackTrace(); return false; } } }
27.491525
159
0.583539
a81565c0df3334efb2066cbf0c6093406ece4d70
423
package com.xyzniu.fpsgame.programs; import android.content.Context; public class ShaderProgramManager { public static MainShaderProgram mainShaderProgram; public static EndPointShaderProgram endPointShaderProgram; public static void init(Context context) { mainShaderProgram = new MainShaderProgram(context); endPointShaderProgram = new EndPointShaderProgram(context); } }
26.4375
67
0.754137
524fcf045bc0bb1deec2234d616f666a21c81dcc
1,933
/* * Copyright 2009 Max Ishchenko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import net.ishchenko.idea.nginx.annotator.NginxElementVisitor; import net.ishchenko.idea.nginx.psi.NginxDirective; import net.ishchenko.idea.nginx.psi.NginxDirectiveName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NonNls; /** * Created by IntelliJ IDEA. * User: Max * Date: 09.07.2009 * Time: 21:02:29 */ public class NginxDirectiveNameImpl extends NginxElementImpl implements NginxDirectiveName { public NginxDirectiveNameImpl(ASTNode node) { super(node); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof NginxElementVisitor) { ((NginxElementVisitor) visitor).visitDirectiveName(this); } else { visitor.visitElement(this); } } public NginxDirective getDirective() { return (NginxDirective) getNode().getTreeParent().getPsi(); } @Override public String getName() { return getText(); } public PsiElement setName(@NonNls String name) throws IncorrectOperationException { throw new IncorrectOperationException(); } }
30.68254
92
0.730471
6c3e63646ed3d404195a1b609f4609dfde5f0afa
5,181
package us.kbase.typedobj.test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.Random; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.common.service.JsonTokenStream; import us.kbase.common.service.UObject; import us.kbase.typedobj.core.LocalTypeProvider; import us.kbase.typedobj.core.TypeDefId; import us.kbase.typedobj.core.TypeDefName; import us.kbase.typedobj.core.ValidatedTypedObject; import us.kbase.typedobj.core.TypedObjectValidator; import us.kbase.typedobj.db.MongoTypeStorage; import us.kbase.typedobj.db.TypeDefinitionDB; import us.kbase.typedobj.db.TypeStorage; import us.kbase.typedobj.db.test.TypeRegisteringTest; import us.kbase.typedobj.idref.IdReferenceHandlerSet; import us.kbase.typedobj.idref.IdReferenceHandlerSetFactory; public class JsonTokenValidatorTester { private static final long seed = 1234567890L; private static final Random rnd = new Random(seed); public static void main(String[] args) throws Exception { // point the type definition db to point there TypeStorage storage = new MongoTypeStorage(TypeRegisteringTest.createMongoDbConnection()); storage.removeAllData(); TypeDefinitionDB db = new TypeDefinitionDB(storage); // create a validator that uses the type def db String username = "wstester1"; String moduleName = "KBaseNetworks"; String typeName = "Network"; String kbSpec = "module " + moduleName + " {typedef structure {string val;} " + typeName + ";};"; db.requestModuleRegistration(moduleName, username); db.approveModuleRegistrationRequest(username, moduleName, true); db.registerModule(kbSpec, Arrays.asList(typeName), username); db.releaseModule(moduleName, username, false); File f = new File("temp_files/temp_validation.json"); for (int n = 0; n < 1000; n++) { JsonGenerator jgen = new ObjectMapper().getFactory().createGenerator(f, JsonEncoding.UTF8); int buffer = 100 + rnd.nextInt(1000000); jgen.writeStartObject(); jgen.writeFieldName("val_"); jgen.writeString(generateLargeString(rnd, buffer - 1)); jgen.writeFieldName("val"); jgen.writeString(generateLargeString(rnd, buffer)); jgen.writeFieldName("val-"); jgen.writeString(generateLargeString(rnd, buffer + 1)); for (int i = 0; i < 1000; i++) { int len = buffer + rnd.nextInt(buffer); jgen.writeFieldName("\"val" + i); jgen.writeString("test\"" + i + ((i % 10) == 9 ? generateLargeString(rnd, len) : "")); } jgen.close(); long time = System.currentTimeMillis(); JsonTokenStream jp = new JsonTokenStream(f); //, buffer); IdReferenceHandlerSetFactory fac = new IdReferenceHandlerSetFactory(6); IdReferenceHandlerSet<String> han = fac.createHandlers(String.class); han.associateObject("foo"); ValidatedTypedObject report = new TypedObjectValidator( new LocalTypeProvider(db)).validate(new UObject(jp, null), new TypeDefId(new TypeDefName(moduleName, typeName)), han); assertThat(report.isInstanceValid(), is(true)); System.out.println(buffer + "\t" + f.length() + "\t" + (System.currentTimeMillis() - time) + " ms"); jp.setRoot(null); File f2 = new File("temp_files/temp_validation2.json"); jp.writeJson(f2); compareFiles(f, f2, false); } } public static void compareFiles(File f1, File f2, boolean debug) throws IOException { Reader r1 = new FileReader(f1); Reader r2 = new FileReader(f2); compareReaders(r1, r2, debug); r1.close(); r2.close(); } private static void compareReaders(Reader r1, Reader r2, boolean debug) throws IOException { int bufSize = 1000; char[] buf1 = new char[bufSize]; char[] buf2 = new char[bufSize]; long size = 0; while (true) { int c1 = readAsMuchAsPossible(r1, buf1); int c2 = readAsMuchAsPossible(r2, buf2); if (c1 != c2) { if (debug) { System.out.println(new String(buf1, 0, c1)); System.out.println(new String(buf2, 0, c2)); } throw new IllegalStateException("Sources have different sizes: " + (c1 == bufSize ? ">" : "") + (size + c1) + ", " + (c2 == bufSize ? ">" : "") + (size + c2)); } for (int i = 0; i < c1; i++) if (buf1[i] != buf2[i]) { if (debug) { System.out.println(new String(buf1, 0, c1)); System.out.println(new String(buf2, 0, c2)); } throw new IllegalStateException("Sources differ at position " + (size + i)); } size += c1; if (c1 < bufSize) break; } } private static int readAsMuchAsPossible(Reader r, char[] buf) throws IOException { int pos = 0; while (true) { int count = r.read(buf, pos, buf.length - pos); if (count < 0) break; pos += count; if (pos == buf.length) break; } return pos; } private static String generateLargeString(Random rnd, int len) { char[] data = new char[len]; for (int i = 0; i < len; i++) data[i] = (char)(32 + rnd.nextInt(95)); String largeValue = new String(data); return largeValue; } }
36.230769
103
0.700637
f4cf194470813e5ee7909a08efc57ea01df7f237
810
package com.oxchains.themis.repo.entity.order; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; /** * @author anonymity * @create 2018-08-01 11:06 **/ @Data @Entity @Table(name = "order_pri_key") public class OrderPriKey { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * ID */ private Long userId; /** * 订单 */ private String orderId; /** * 私钥/未处理 */ private String priKey; /** * 私钥/最终的 */ private String finalPriKey; public OrderPriKey() { } public OrderPriKey(Long userId, String orderId, String priKey) { this.userId = userId; this.orderId = orderId; this.priKey = priKey; } }
16.875
68
0.611111
490b0d72f5f8cc7c15e93ad2199aec4309428704
2,028
package frc.robot; import com.ctre.phoenix.motorcontrol.can.TalonSRX; import com.ctre.phoenix.motorcontrol.ControlMode; import edu.wpi.first.wpilibj.Joystick; public class Intake { TalonSRX intakeMotor, intakeArm; /** * Constructor class defining the motor for the robots intake system * @param intakeMotorID ID of the intake motor * @param intakermID ID of the motor for the intake arm */ public Intake (int intakeMotorID, int intakeArmID) { intakeMotor = new TalonSRX(intakeMotorID); intakeArm = new TalonSRX(intakeArmID); } /** * Method to set the inversion status of the intake motor * @param intakeMotorInverted Boolean for the inversion status of the intake motor * @param intakeArmInverted Boolean for the inversion status of the intake arm motor */ public void setInversion (boolean intakeMotorInverted, boolean intakeArmInverted) { intakeMotor.setInverted(intakeMotorInverted); intakeArm.setInverted(intakeArmInverted); } /** * Method to run the intake * @param power Unspecified power to run the intake arm motor */ public void intakeIn (double power) { intakeMotor.set(ControlMode.PercentOutput, Math.abs(power)); } /** * Method to run the intake in reverse * @param power2 Unspecified negative power for the intake arm motor */ public void intakeOut (double power2) { intakeMotor.set(ControlMode.PercentOutput, -Math.abs(power2)); } /** * Code to move the intake arm up or down * @param intakePower Inputted power, based on which button is input */ public void moveArm (double intakePower) { intakeArm.set(ControlMode.PercentOutput, intakePower); } /** * Method to stop the intake motor */ public void stop () { intakeMotor.set(ControlMode.PercentOutput, 0); } public void stopArm () { intakeArm.set(ControlMode.PercentOutput, 0); } }
25.037037
88
0.672091
9e5b4eefbc4b996ad2aee18d8934bf12957d273c
1,240
/** * Copyright (c) 2017 Dell Inc., or its subsidiaries. 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 */ package io.pravega.controller.store.stream; import io.pravega.test.common.AssertExtensions; import org.junit.Test; import static org.junit.Assert.assertEquals; public class VersionTest { @Test public void intVersionSerializationTest() { Version.IntVersion version = new Version.IntVersion(10); assertEquals(version, Version.IntVersion.fromBytes(version.toBytes())); } @Test public void unSupportedVersionException() { TestVersion version = new TestVersion(); AssertExtensions.assertThrows(UnsupportedOperationException.class, version::asIntVersion); } @Test public void testAsVersionType() { Version version = new Version.IntVersion(100); Version.IntVersion intVersion = version.asIntVersion(); assertEquals(100, intVersion.getIntValue()); } static class TestVersion extends Version.UnsupportedVersion { } }
31
98
0.708871
9422d04eed2a5b79f4a34cc56544fb0e0df9f3fe
279
package netty.rpc.server; /** * @author: 程序员七哥 * @date: 2021-12-19 * @description: 服务端启动类 */ public class RpcServerStarter { public static void main(String[] args) throws Exception { // 发布服务 new RpcServer().publish("netty.rpc.server.provider"); } }
18.6
61
0.637993
0b38f81fdc8a3812bdc9bb5efbb8e1bf45956255
9,463
package com.restsecure; import com.restsecure.core.util.NameValueList; import com.restsecure.core.http.NameAndValue; import com.restsecure.validation.matchers.IsAnyValue; import com.restsecure.validation.matchers.IsNameValueListContaining; import com.restsecure.validation.matchers.JsonMatcher; import org.hamcrest.Matcher; import java.util.function.Function; import static org.hamcrest.Matchers.equalTo; public class Matchers { /** * Creates a matcher who always returns the true * * @return IsAnyValue */ public static <T> Matcher<T> anyValue() { return new IsAnyValue<>(); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name that satisfies the specified matcher.<br> * For example: * <pre>assertThat(multiValueList, containsName(containsString("myName")))</pre> * * @param nameMatcher the matcher that must be satisfied by at least one name * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsName(Matcher<String> nameMatcher) { return new IsNameValueListContaining<>(nameMatcher, Function.identity(), anyValue()); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name that is equal to the specified name.<br> * For example: * <pre>assertThat(multiValueList, containsName("myName"))</pre> * * @param name the name that at least one element must have * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsName(String name) { return new IsNameValueListContaining<>(equalTo(name), Function.identity(), anyValue()); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one value that satisfies the specified matcher.<br> * For example: * <pre>assertThat(multiValueList, containsValue(equalTo("myValue")))</pre> * * @param valueMatcher the matcher that must be satisfied by at least one value * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsValue(Matcher<String> valueMatcher) { return new IsNameValueListContaining<>(anyValue(), Function.identity(), valueMatcher); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one value that is equal to the specified value.<br> * For example: * <pre>assertThat(multiValueList, containsValue("myValue"))</pre> * * @param value the value that at least one element must have * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsValue(String value) { return new IsNameValueListContaining<>(anyValue(), Function.identity(), equalTo(value)); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair(nameAndValue))</pre> * * @param pair the name and value pair that at least one element must have * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsPair(NameAndValue pair) { return new IsNameValueListContaining<>(equalTo(pair.getName()), Function.identity(), equalTo(pair.getValue())); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair("myName", "myValue"))</pre> * * @param name the name that at least one element must have * @param value the value that at least one element must have * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsPair(String name, String value) { return new IsNameValueListContaining<>(equalTo(name), Function.identity(), equalTo(value)); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair("myName", Integer::parseInt, lessThan(200)))</pre> * * @param name the name that at least one element must have * @param parsingFunction the function that converts the value to the needed type * @param valueMatcher the matcher that must be satisfied by at least one value * @return IsMultiValueListContaining */ public static <T extends NameAndValue, E> Matcher<NameValueList<T>> containsPair(String name, Function<String, E> parsingFunction, Matcher<? super E> valueMatcher) { return new IsNameValueListContaining<>(equalTo(name), parsingFunction, valueMatcher); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair("myName", containsString("myValue")))</pre> * * @param name the name that at least one element must have * @param valueMatcher the matcher that must be satisfied by at least one value * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsPair(String name, Matcher<String> valueMatcher) { return new IsNameValueListContaining<>(equalTo(name), Function.identity(), valueMatcher); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair(containsString("myName"), "myValue"))</pre> * * @param nameMatcher the matcher that must be satisfied by at least one name * @param value the value that at least one element must have * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsPair(Matcher<String> nameMatcher, String value) { return new IsNameValueListContaining<>(nameMatcher, Function.identity(), equalTo(value)); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair("myName", Integer::parseInt, lessThan(200)))</pre> * * @param nameMatcher the matcher that must be satisfied by at least one name * @param parsingFunction the function that converts the value to the needed type * @param valueMatcher the matcher that must be satisfied by at least one value * @return IsMultiValueListContaining */ public static <T extends NameAndValue, E> Matcher<NameValueList<T>> containsPair(Matcher<String> nameMatcher, Function<String, E> parsingFunction, Matcher<? super E> valueMatcher) { return new IsNameValueListContaining<>(nameMatcher, parsingFunction, valueMatcher); } /** * Creates a matcher for {@link NameValueList} matching when the examined {@link NameValueList} contains * at least one name and value pair that is equal to the specified pair.<br> * For example: * <pre>assertThat(multiValueList, containsPair("myName", Integer::parseInt, lessThan(200)))</pre> * * @param nameMatcher the matcher that must be satisfied by at least one name * @param valueMatcher the matcher that must be satisfied by at least one value * @return IsMultiValueListContaining */ public static <T extends NameAndValue> Matcher<NameValueList<T>> containsPair(Matcher<String> nameMatcher, Matcher<String> valueMatcher) { return new IsNameValueListContaining<>(nameMatcher, Function.identity(), valueMatcher); } /** * Creates a matcher for json path value matching when the examined value satisfied at specified matcher<br> * For example: * <pre>assertThat(jsonString, valueByPathIs("user.age", lessThan(20)))</pre> * * @param path json path * @param valueMatcher the matcher that must be satisfied by value * @return IsMultiValueListContaining */ public static JsonMatcher valueByPathIs(String path, Matcher<?> valueMatcher) { return new JsonMatcher(path, valueMatcher); } }
49.031088
142
0.679911
79f16b6176367f5064bc7d1815831c448541c17a
4,810
package de.mcmdev.betterprotocol.common.protocol; import com.github.steveice10.packetlib.packet.BufferedPacket; import com.github.steveice10.packetlib.packet.DefaultPacketHeader; import com.github.steveice10.packetlib.packet.Packet; import com.github.steveice10.packetlib.packet.PacketHeader; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.lang.reflect.Constructor; /** * A registry that maps packet id's to their respective {@link Packet} classes Implementations are * dependent on a version of MCProtocolLib * * <p>Implementations for all versions are in common to support multi-version platforms like * BungeeCord */ public abstract class AbstractProtocolRegistry { private final BiMap<Integer, Class<? extends Packet>> incoming = HashBiMap.create(); private final BiMap<Integer, Class<? extends Packet>> outgoing = HashBiMap.create(); private final PacketHeader packetHeader = new DefaultPacketHeader(); public PacketHeader getPacketHeader() { return packetHeader; } public final void registerIncoming(int id, Class<? extends Packet> packet) { this.incoming.put(id, packet); } public final void registerOutgoing(int id, Class<? extends Packet> packet) { this.outgoing.put(id, packet); } public final Packet createIncomingPacket(int id) { Class<? extends Packet> packet = this.incoming.get(id); if (packet == null) { throw new IllegalArgumentException("Invalid packet id: " + id); } else { try { Constructor<? extends Packet> constructor = packet.getDeclaredConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return constructor.newInstance(); } catch (NoSuchMethodError var4) { throw new IllegalStateException( "Packet \"" + id + ", " + packet.getName() + "\" does not have a no-params constructor for instantiation."); } catch (Exception var5) { throw new IllegalStateException( "Failed to instantiate packet \"" + id + ", " + packet.getName() + "\".", var5); } } } public final int getIncomingId(Class<? extends Packet> packetClass) { Integer packetId = this.incoming.inverse().get(packetClass); if (packetId == null) { throw new IllegalArgumentException( "Unregistered outgoing packet class: " + packetClass.getName()); } else { return packetId; } } public final int getIncomingId(Packet packet) { return packet instanceof BufferedPacket ? this.getIncomingId(((BufferedPacket) packet).getPacketClass()) : this.getIncomingId(packet.getClass()); } public final int getOutgoingId(Class<? extends Packet> packetClass) { Integer packetId = this.outgoing.inverse().get(packetClass); if (packetId == null) { throw new IllegalArgumentException( "Unregistered outgoing packet class: " + packetClass.getName()); } else { return packetId; } } public final int getOutgoingId(Packet packet) { return packet instanceof BufferedPacket ? this.getIncomingId(((BufferedPacket) packet).getPacketClass()) : this.getOutgoingId(packet.getClass()); } public final Packet createOutgoingPacket(int id) { Class<? extends Packet> packet = this.outgoing.get(id); if (packet == null) { throw new IllegalArgumentException("Invalid packet id: " + id); } else { try { Constructor<? extends Packet> constructor = packet.getDeclaredConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return constructor.newInstance(); } catch (NoSuchMethodError var4) { throw new IllegalStateException( "Packet \"" + id + ", " + packet.getName() + "\" does not have a no-params constructor for instantiation."); } catch (Exception var5) { throw new IllegalStateException( "Failed to instantiate packet \"" + id + ", " + packet.getName() + "\".", var5); } } } }
38.790323
98
0.57526
867261279bdef19709e7f67b3612756f0cdae8c5
2,073
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: server-protobuf/izou.proto package org.intellimate.server.proto; public final class IzouOuterClass { private IzouOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } static final com.google.protobuf.Descriptors.Descriptor internal_static_intellimate_Izou_descriptor; static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_intellimate_Izou_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\032server-protobuf/izou.proto\022\013intellimat" + "e\":\n\004Izou\022\n\n\002id\030\001 \001(\005\022\017\n\007version\030\002 \001(\t\022\025" + "\n\rdownload_link\030\003 \001(\tB \n\034org.intellimate" + ".server.protoP\001b\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_intellimate_Izou_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_intellimate_Izou_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_intellimate_Izou_descriptor, new java.lang.String[] { "Id", "Version", "DownloadLink", }); } // @@protoc_insertion_point(outer_class_scope) }
39.865385
101
0.729378
149463bd6e7dc48bd148aafdadbf9ee6e1d8768a
4,409
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.remoting.transport.netty; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * NettyHandler */ @Sharable public class NettyHandler extends SimpleChannelHandler { private final Map<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); // <ip:port, channel> private final URL url; private final ChannelHandler handler; public NettyHandler(URL url, ChannelHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.url = url; this.handler = handler; } public Map<String, Channel> getChannels() { return channels; } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { if (channel != null) { channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()), channel); } handler.connected(channel); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { channels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress())); handler.disconnected(channel); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { // handler 接收到消息 ; 直接委托给传入的 handler进行执行; 这里为HeaderExchangeHandler handler.received(channel, e.getMessage()); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } } @Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { super.writeRequested(ctx, e); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { handler.sent(channel, e.getMessage()); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { handler.caught(channel, e.getCause()); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } } }
37.364407
121
0.69721
ef36c623692749d15a4db799edc2bdd51326475e
778
package com.twu.biblioteca; /** * Created by nsarsur on 9/21/16. */ public class Book { private String title; private String author; private int year; private boolean checkout; public Book(String title, String author, int year) { this.title = title; this.author = author; this.year = year; this.checkout = false; } public String getTitle() { return title; } public String getAuthor() { return author; } public int getYear() { return year; } public boolean isCheckout() { return checkout; } public void setCheckout(boolean checkout) { this.checkout = checkout; } public boolean getCheckout() { return checkout; } }
17.288889
56
0.583548
29b5befe90b01f5af6c737326da11373746a355b
332
package cloud.timo.TimoCloud.api.events.base; import cloud.timo.TimoCloud.api.events.Event; import cloud.timo.TimoCloud.api.objects.BaseObject; import java.net.InetAddress; public interface BasePublicAddressChangeEvent extends Event { BaseObject getBase(); InetAddress getOldValue(); InetAddress getNewValue(); }
19.529412
61
0.783133
6a498e8079204723a44253b2bb449cbc13247bdc
7,283
package com.jove.demo.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; 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.SessionAttributes; import com.jove.demo.models.CodeMaster; import com.jove.demo.models.Estimation; import com.jove.demo.models.RoomCategory; import com.jove.demo.models.RoomType; import com.jove.demo.models.User; import com.jove.demo.services.CodeMasterService; import com.jove.demo.services.EstimationService; import com.jove.demo.services.RoomCategoryService; import com.jove.demo.services.RoomTypeService; @Controller @SessionAttributes({ "user", "estimation", "pageType" }) public class EstimationController { private static final String PAGE_MODEL_NEW = "NEW"; private static final String PAGE_MODEL_EDIT = "EDIT"; private static final String PAGE_MODEL_DETAIL = "DETAIL"; private static final Logger logger = LoggerFactory.getLogger(EstimationController.class); @Autowired CodeMasterService codeMasterService; @Autowired RoomCategoryService roomCategoryService; @Autowired RoomTypeService roomTypeService; @Autowired private HomeController homeController; @Autowired private EstimationService estService; @RequestMapping(value = "/estimation-1", method = RequestMethod.POST) public String estimationStepOne(@RequestParam String action, @Validated Estimation reqEstimation, BindingResult result, Model model) { logger.debug("estimation 1 controller -> estimation step 2 page init"); if (action.equals("prev")) { return homeController.home(model); } else { String pageType = (String) model.getAttribute("pageType"); if (pageType == null || pageType.equals("")) { pageType = PAGE_MODEL_NEW; } model.addAttribute("pageType", pageType); return estimationStepTwoInit(reqEstimation, model); } } @RequestMapping(value = "/estimation-2", method = RequestMethod.POST) public String estimationStepTwo(@RequestParam String action, @RequestParam String pageStatus, @Validated Estimation reqEstimation, Model model) { String pageType = (String) model.getAttribute("pageType"); if (pageStatus.equals("false")) { // input page logger.debug("estimation 2 controller - input page"); if (action.equals("prev")) { return estimationStepOneInit(model); } else { return estimationStepThreeInit(reqEstimation, model); } } else { // confirm page logger.debug("estimation 2 controller - confirm page"); int estimationId = 0; if (action.equals("prev")) { return estimationStepTwoInit(reqEstimation, model); } else { if (pageType.equals(PAGE_MODEL_EDIT)) { estimationId = reqEstimation.getEstimationId(); estService.update(reqEstimation); } else if (pageType.equals(PAGE_MODEL_NEW)) { estimationId = estService.insert(reqEstimation); } else { logger.error("系统异常,错误代码0x000001,请与系统管理员联系。"); } } User user = (User) model.getAttribute("user"); if (user == null || user.getUserName() == null || user.getUserName().equals("")) { logger.error("session过期,请重新登录。"); } Estimation estimation = new Estimation(); estimation = new Estimation(); estimation.setUserId(user.getUserId()); model.addAttribute("estimation", estimation); return estimationSuccess(estimationId, model); } } @RequestMapping(value = "/estimation-search", method = RequestMethod.GET) public String estimationLists(Model model) { logger.debug("estimation list page init"); List<Estimation> estLists = estService.selectToSearchResult(); model.addAttribute("estLists", estLists); return "estimation-list"; } @RequestMapping(value = "/estimation/detail/{id}", method = RequestMethod.GET) public String estimationDetail(@PathVariable int id, Model model) { Estimation estimation = estService.selectOne(id); model.addAttribute("pageType", PAGE_MODEL_DETAIL); model.addAttribute("estimation", estimation); return estimationStepThreeInit(estimation, model); } @RequestMapping(value = "/estimation/edit/{id}", method = RequestMethod.GET) public String estimationEdit(@PathVariable int id, Model model) { Estimation estimation = estService.selectOne(id); model.addAttribute("pageType", PAGE_MODEL_EDIT); model.addAttribute("estimation", estimation); return estimationStepTwoInit(estimation, model); } @RequestMapping(value = "/estimation/del/{id}", method = RequestMethod.GET) public String estimationDel(@PathVariable int id, Model model) { estService.del(id); return estimationLists(model); } // 共同方法 protected String estimationStepOneInit(Model model) { // 准备下个画面(estimation-step-1)的初始数据 // 画面项目显示数据,默认选择可以在这里设置 Estimation estimation = (Estimation) model.getAttribute("estimation"); if (estimation == null) { logger.debug("estimation is null"); User user = (User) model.getAttribute("user"); if (user == null || user.getUserName() == null || user.getUserName().equals("")) { logger.error("session过期,请重新登录。"); } estimation = new Estimation(); estimation.setUserId(user.getUserId()); } // 户型 List<RoomType> roomTypes = roomTypeService.getAll(); // 装修状况的Category 1 List<CodeMaster> codeMasters = codeMasterService.getByCategory(1); model.addAttribute("roomTypes", roomTypes); model.addAttribute("codeMasters", codeMasters); model.addAttribute("estimation", estimation); return "estimation-step-1"; } private String estimationStepTwoInit(@Validated Estimation reqEstimation, Model model) { logger.debug("estimation step 2 page init"); Estimation estimation = (Estimation) model.getAttribute("estimation"); if (estimation == null) { logger.error("estimation is null"); } estimation.setRoomId(reqEstimation.getRoomId()); estimation.setInteriorDecoration(reqEstimation.getInteriorDecoration()); // 装修服务 List<RoomCategory> roomCategories = roomCategoryService.selectAll(); model.addAttribute("roomCategories", roomCategories); model.addAttribute("estimation", estimation); model.addAttribute("pageStatus", "false"); return "estimation-step-2"; } private String estimationStepThreeInit(@Validated Estimation reqEstimation, Model model) { logger.debug("estimation step 3 page init"); // 装修服务 List<RoomCategory> roomCategories = roomCategoryService.selectAll(); model.addAttribute("roomCategories", roomCategories); model.addAttribute("estimation", reqEstimation); model.addAttribute("pageStatus", "true"); return "estimation-step-2"; } private String estimationSuccess(int estimationId, Model model) { logger.debug("estimation successpage init"); // String pageType = (String) model.getAttribute("pageType"); model.addAttribute("estimationId", estimationId); // model.addAttribute("pageType", pageType); return "estimation-success"; } }
35.70098
98
0.753398
872d5ab969976b4d13442b06abb87c1905f804e1
2,565
package io.github.kshitij_jain.circularindicatorview; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.AppCompatButton; import android.view.View; import io.github.kshitij_jain.indicatorview.IndicatorView; public class MainActivity extends AppCompatActivity { private ViewPager mViewPager; private IndicatorView mIndicatorView; private ViewPagerAdapter mViewPagerAdapter; private AppCompatButton mButtonSkip; private AppCompatButton mButtonNext; private Integer viewsCount = 4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); mIndicatorView.setPageIndicators(viewsCount); setupViewPager(); mButtonNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int current = getItem(+1); if (current < viewsCount) { mViewPager.setCurrentItem(current); } } }); } private void initViews() { mViewPager = (ViewPager) findViewById(R.id.view_pager); mButtonSkip = (AppCompatButton) findViewById(R.id.button_skip); mButtonNext = (AppCompatButton) findViewById(R.id.button_next); mIndicatorView = (IndicatorView) findViewById(R.id.indicator_view); } private void setupViewPager() { mViewPagerAdapter = new ViewPagerAdapter(viewsCount); mViewPager.setAdapter(mViewPagerAdapter); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mIndicatorView.setCurrentPage(position); if (position == viewsCount - 1) { mButtonNext.setText("Start"); mButtonSkip.setVisibility(View.GONE); } else { mButtonNext.setText("Next"); mButtonSkip.setVisibility(View.VISIBLE); } } @Override public void onPageScrollStateChanged(int state) { } }); } private int getItem(int i) { return mViewPager.getCurrentItem() + i; } }
30.176471
102
0.635867
5e0697f4185324412c7db3c4cda5f63ab6527000
133
package ru.usedesk.knowledgebase_gui.external; public interface IUsedeskOnSearchQueryListener { void onSearchQuery(String s); }
22.166667
48
0.819549
72d0a0bc770418343ec1b6aef61325aa2b723b6b
234
package mass3d.springframework.mass3dpetclinic.services; import mass3d.springframework.mass3dpetclinic.model.PetType; /** * Created by Hamza on 29/04/2021. */ public interface PetTypeService extends CrudService<PetType, Long> { }
23.4
68
0.799145
965252b9a86293150c0addc16091750c3b25db54
3,947
package org.reldb.wrapd.sqldb; import org.reldb.toolbox.il8n.Msg; import org.reldb.toolbox.il8n.Str; import javax.lang.model.SourceVersion; import java.util.List; import java.util.Vector; /** * Convert SQL text with optional parameters specified as ? or {name} to * SQL text with only ? parameters, and obtain a list of parameter names, * where a generated parameter name will correspond to each ?, and the specified * name will be for each {name}. */ public class SQLParameterConverter { private static final Msg ErrMissingEndBrace = new Msg("Missing end ''}'' in parameter def started at position {0} in {1}", SQLParameterConverter.class); private static final Msg ErrDuplicateParameterName = new Msg("Attempt to define duplicate parameter name {0}.", SQLParameterConverter.class); private static final Msg ErrInvalidIdentifier = new Msg("Parameter name {0} is not a valid Java identifier.", SQLParameterConverter.class); private static final Msg ErrInvalidIdentifierCharacter = new Msg("Parameter name {0} must not contain ''.''.", SQLParameterConverter.class); private static final char ParmChar = '?'; private static final char ParmNameLeftDelimiter = '{'; private static final char ParmNameRightDelimiter = '}'; private String sqlText; private final Vector<String> parameterNames = new Vector<>(); private void addParameterName(String rawName) { var name = rawName.trim(); if (name.contains(".")) throw new IllegalArgumentException(Str.ing(ErrInvalidIdentifierCharacter, name)); if (!SourceVersion.isName(name)) throw new IllegalArgumentException(Str.ing(ErrInvalidIdentifier, name)); if (parameterNames.contains(name)) throw new IllegalArgumentException(Str.ing(ErrDuplicateParameterName, name)); parameterNames.add(name); } private void addAutomaticParameterName() { addParameterName("p" + parameterNames.size()); } /** * Create a SQL parameter converter. * * @param sqlText SQL query text. Parameters may be specified as ? or {name}. If {name} is used, it will * appear as a corresponding Java method name. If ? is used, it will be named pn, where n * is a unique number in the given definition. Use getSQLText() after generate() to obtain final * SQL text with all {name} converted to ? for subsequent evaluation. */ public SQLParameterConverter(String sqlText) { this.sqlText = sqlText; } /** * Generate the revised SQL and parameter name list. * * @throws IllegalArgumentException is thrown if the parameter specification is invalid. */ public void process() { StringBuffer sql = new StringBuffer(sqlText); for (int start = 0; start < sql.length(); start++) { if (sql.charAt(start) == ParmChar) addAutomaticParameterName(); else if (sql.charAt(start) == ParmNameLeftDelimiter) { var startNamePos = start + 1; var endBracePos = sql.indexOf(String.valueOf(ParmNameRightDelimiter), startNamePos); if (endBracePos == -1) throw new IllegalArgumentException(Str.ing(ErrMissingEndBrace, start, sql)); addParameterName(sql.substring(startNamePos, endBracePos)); sql.replace(start, endBracePos + 1, String.valueOf(ParmChar)); start++; } } sqlText = sql.toString(); } /** * Get SQL text. May be modified by process(). * * @return SQL text. */ public String getSQLText() { return sqlText; } /** * Get the parameter names obtained by process(). * * @return List of parameter names, in the order of appearance. */ public List<String> getParameterNames() { return parameterNames; } }
40.27551
156
0.654674
c2d4c2538db445d47b65ef3a14ea89dd7c1a6b3d
700
package com.learning.awspring.config; import static com.learning.awspring.utils.AppConstants.PROFILE_PROD; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Configuration(proxyBeanMethods = false) @Profile({PROFILE_PROD}) public class AwsConfig { @Bean @Primary public AmazonS3 amazonS3Client() { AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard(); return builder.build(); } }
30.434783
73
0.798571
468c3bee87e405dcdcc52910527b30e7e50edac7
1,861
package com.example.qrcodeteam30.controllerclass; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Handle anything related to cryptography (hash, encrypt, decrypt) * TO DO: Implement an encrypt/decrypt algorithm for QR Code content (planned using AES-256) */ public class MyCryptographyController { /** * Hash a string to SHA-256 hex representation * @param input * @return SHA-256 hex representation of the input string * @throws NoSuchAlgorithmException */ static public String hashSHA256(String input) throws NoSuchAlgorithmException { try { final var digest = MessageDigest.getInstance("SHA-256"); final byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8)); final var hexString = new StringBuilder(); for (byte b : hash) { final var hex = Integer.toHexString(0xff & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch(Exception e){ throw new RuntimeException(e); } } /** * Encrypt a string * @param strToEncrypt * @return encrypted string */ public static String encrypt(String strToEncrypt) { String str = null; try { str = MyCryptographyController.hashSHA256(strToEncrypt); } catch (NoSuchAlgorithmException e) { str = "default"; } return str; } /** * Decrypt a string, which is encrypted by the method encrypt * @param strToDecrypt * @return decrypted String */ public static String decrypt(String strToDecrypt) { return strToDecrypt; } }
30.508197
92
0.619559
700b3a4617ec4a49379273b6693eb2db5d36c6ad
4,278
/* * #%L * BigDataViewer core classes with minimal dependencies * %% * Copyright (C) 2012 - 2015 BigDataViewer authors * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 HOLDERS 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. * #L% */ package bdv.tools.brightness; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import bdv.util.BoundedValue; /** * A {@link JSlider} with a {@link JSpinner} next to it, both modifying the same * {@link BoundedValue value}. */ public class SliderPanel extends JPanel implements BoundedValue.UpdateListener { private static final long serialVersionUID = 6444334522127424416L; private final JSlider slider; private final JSpinner spinner; private final BoundedValue model; /** * Create a {@link SliderPanel} to modify a given {@link BoundedValue value}. * * @param name * label to show next to the slider. * @param model * the value that is modified. */ public SliderPanel( final String name, final BoundedValue model, final int spinnerStepSize ) { super(); setLayout( new BorderLayout( 10, 10 ) ); slider = new JSlider( SwingConstants.HORIZONTAL, model.getRangeMin(), model.getRangeMax(), model.getCurrentValue() ); spinner = new JSpinner(); spinner.setModel( new SpinnerNumberModel( model.getCurrentValue(), model.getRangeMin(), model.getRangeMax(), spinnerStepSize ) ); slider.addChangeListener( new ChangeListener() { @Override public void stateChanged( final ChangeEvent e ) { final int value = slider.getValue(); model.setCurrentValue( value ); } } ); spinner.addChangeListener( new ChangeListener() { @Override public void stateChanged( final ChangeEvent e ) { final int value = ( ( Integer ) spinner.getValue() ).intValue(); model.setCurrentValue( value ); } } ); if ( name != null ) { final JLabel label = new JLabel( name, SwingConstants.CENTER ); label.setAlignmentX( Component.CENTER_ALIGNMENT ); add( label, BorderLayout.WEST ); } add( slider, BorderLayout.CENTER ); add( spinner, BorderLayout.EAST ); this.model = model; model.setUpdateListener( this ); } public void setNumColummns( final int cols ) { ( ( JSpinner.NumberEditor ) spinner.getEditor() ).getTextField().setColumns( cols ); } @Override public void update() { final int value = model.getCurrentValue(); final int min = model.getRangeMin(); final int max = model.getRangeMax(); if (slider.getMaximum() != max || slider.getMinimum() != min) { slider.setMinimum( min ); slider.setMaximum( max ); final SpinnerNumberModel spinnerModel = ( SpinnerNumberModel ) spinner.getModel(); spinnerModel.setMinimum( min ); spinnerModel.setMaximum( max ); } slider.setValue( value ); spinner.setValue( value ); } }
32.165414
131
0.727443
57746c50c5d8286fa81d091121461263cbe9a172
476
package com.qmplus.v3.api.models.request; import java.util.List; public class LDAPQueryRequest extends BaseRequest { private String searchBase; private List<String> filters; public String getSearchBase() { return searchBase; } public void setSearchBase(String searchBase) { this.searchBase = searchBase; } public List<String> getFilters() { return filters; } public void setFilters(List<String> filters) { this.filters = filters; } }
19.04
51
0.718487
bd1fb31b242826d3e738713da0d40bdd9f8f58e8
22,426
package uk.co.jemos.podam.typeManufacturers; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.api.DataProviderStrategy; import uk.co.jemos.podam.api.ObjectStrategy; import uk.co.jemos.podam.api.PodamUtils; import uk.co.jemos.podam.common.*; import javax.validation.Constraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.atomic.AtomicReference; /** * Type Manufacturer utility class. * * Created by tedonema on 01/07/2015. * * @since 6.0.0.RELEASE */ public abstract class TypeManufacturerUtil { /** The application logger */ private static final Logger LOG = LoggerFactory.getLogger(TypeManufacturerUtil.class); /** * It returns a {@link AttributeStrategy} if one was specified in * annotations, or {@code null} otherwise. * * @param strategy * The data provider strategy * @param annotations * The list of annotations, irrelevant annotations will be removed * @param attributeType * Type of attribute expected to be returned * @return {@link AttributeStrategy}, if {@link PodamStrategyValue} or bean * validation constraint annotation was found among annotations * @throws IllegalAccessException * if attribute strategy cannot be instantiated * @throws InstantiationException * if attribute strategy cannot be instantiated * @throws SecurityException * if access security is violated * @throws InvocationTargetException * if invocation failed * @throws IllegalArgumentException * if illegal argument provided to a constructor */ public static AttributeStrategy<?> findAttributeStrategy(DataProviderStrategy strategy, List<Annotation> annotations, Class<?> attributeType) throws InstantiationException, IllegalAccessException, SecurityException, IllegalArgumentException, InvocationTargetException { List<Annotation> localAnnotations = new ArrayList<Annotation>(annotations); Iterator<Annotation> iter = localAnnotations.iterator(); while (iter.hasNext()) { Annotation annotation = iter.next(); if (annotation instanceof PodamStrategyValue) { PodamStrategyValue strategyAnnotation = (PodamStrategyValue) annotation; return strategyAnnotation.value().newInstance(); } /* Podam annotation is present, this will be handled later by type manufacturers */ if (annotation.annotationType().getAnnotation(PodamAnnotation.class) != null) { return null; } /* Find real class out of proxy */ Class<? extends Annotation> annotationClass = annotation.getClass(); if (Proxy.isProxyClass(annotationClass)) { Class<?>[] interfaces = annotationClass.getInterfaces(); if (interfaces.length == 1) { @SuppressWarnings("unchecked") Class<? extends Annotation> tmp = (Class<? extends Annotation>) interfaces[0]; annotationClass = tmp; } } AttributeStrategy<?> attrStrategy = strategy.getStrategyForAnnotation(annotationClass); if (null != attrStrategy) { return attrStrategy; } if (annotation.annotationType().getAnnotation(Constraint.class) != null) { if (annotation instanceof NotNull || annotation.annotationType().getName().equals("org.hibernate.validator.constraints.NotEmpty") || annotation.annotationType().getName().equals("org.hibernate.validator.constraints.NotBlank")) { /* We don't need to do anything for NotNull constraint */ iter.remove(); } else if (!NotNull.class.getPackage().equals(annotationClass.getPackage())) { LOG.warn("Please, register AttributeStratergy for custom " + "constraint {}, in DataProviderStrategy! Value " + "will be left to null", annotation); } } else { iter.remove(); } } AttributeStrategy<?> retValue = null; if (!localAnnotations.isEmpty() && !Collection.class.isAssignableFrom(attributeType) && !Map.class.isAssignableFrom(attributeType) && !attributeType.isArray()) { retValue = new BeanValidationStrategy(attributeType); } return retValue; } /** * Finds suitable static constructors for POJO instantiation * <p> * This method places required and provided types for object creation into a * map, which will be used for type mapping. * </p> * * @param factoryClass * Factory class to produce the POJO * @param pojoClass * Typed class * @return an array of suitable static constructors found */ public static Method[] findSuitableConstructors(final Class<?> factoryClass, final Class<?> pojoClass) { // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = factoryClass.getDeclaredMethods(); List<Method> constructors = new ArrayList<Method>(); // A candidate factory method is a method which returns the // Class type for (Method candidateConstructor : declaredMethods) { if (candidateConstructor.getReturnType().equals(pojoClass)) { if (Modifier.isStatic(candidateConstructor.getModifiers()) || !factoryClass.equals(pojoClass)) { constructors.add(candidateConstructor); } } } return constructors.toArray(new Method[constructors.size()]); } /** * Fills type agruments map * <p> * This method places required and provided types for object creation into a * map, which will be used for type mapping. * </p> * * @param typeArgsMap * a map to fill * @param pojoClass * Typed class * @param genericTypeArgs * Type arguments provided for a generics object by caller * @return Array of unused provided generic type arguments * @throws IllegalStateException * If number of typed parameters doesn't match number of * provided generic types */ public static Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { TypeVariable<?>[] typeArray = pojoClass.getTypeParameters(); List<TypeVariable<?>> typeParameters = new ArrayList<TypeVariable<?>>(Arrays.asList(typeArray)); List<Type> genericTypes = new ArrayList<Type>(Arrays.asList(genericTypeArgs)); Iterator<TypeVariable<?>> iterator = typeParameters.iterator(); Iterator<Type> iterator2 = genericTypes.iterator(); while (iterator.hasNext()) { Type genericType = (iterator2.hasNext() ? iterator2.next() : null); /* Removing types, which are already in typeArgsMap */ if (typeArgsMap.containsKey(iterator.next().getName())) { iterator.remove(); /* Removing types, which are type variables */ if (genericType instanceof TypeVariable) { iterator2.remove(); } } } if (typeParameters.size() > genericTypes.size()) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + Arrays.toString(typeArray) + ", provided " + Arrays.toString(genericTypeArgs); throw new IllegalArgumentException(msg); } final Method[] suitableConstructors = TypeManufacturerUtil.findSuitableConstructors(pojoClass, pojoClass); for (Method constructor : suitableConstructors) { TypeVariable<Method>[] ctorTypeParams = constructor.getTypeParameters(); if (ctorTypeParams.length == genericTypes.size()) { for (int i = 0; i < ctorTypeParams.length; i++) { Type foundType = genericTypes.get(i); typeArgsMap.put(ctorTypeParams[i].getName(), foundType); } } } for (int i = 0; i < typeParameters.size(); i++) { Type foundType = genericTypes.remove(0); typeArgsMap.put(typeParameters.get(i).getName(), foundType); } Type[] genericTypeArgsExtra; if (genericTypes.size() > 0) { genericTypeArgsExtra = genericTypes.toArray(new Type[genericTypes.size()]); } else { genericTypeArgsExtra = PodamConstants.NO_TYPES; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (int i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } /** * Searches for annotation with information about collection/map size * and filling strategies * * @param strategy * a data provider strategy * @param annotations * a list of annotations to inspect * @param collectionElementType * a collection element type * @param elementStrategyHolder * a holder to pass found element strategy back to the caller, * can be null * @param keyStrategyHolder * a holder to pass found key strategy back to the caller, * can be null * @return * A number of element in collection or null, if no annotation was * found * @throws InstantiationException * A strategy cannot be instantiated * @throws IllegalAccessException * A strategy cannot be instantiated */ public static Integer findCollectionSize( DataProviderStrategy strategy, List<Annotation> annotations, Class<?> collectionElementType, Holder<AttributeStrategy<?>> elementStrategyHolder, Holder<AttributeStrategy<?>> keyStrategyHolder) throws InstantiationException, IllegalAccessException { // If the user defined a strategy to fill the collection elements, // we use it Size size = null; for (Annotation annotation : annotations) { if (annotation instanceof PodamCollection) { PodamCollection collectionAnnotation = (PodamCollection) annotation; if (null != elementStrategyHolder) { Class<? extends AttributeStrategy<?>> attributeStrategy = collectionAnnotation.collectionElementStrategy(); if (null == attributeStrategy || ObjectStrategy.class.isAssignableFrom(attributeStrategy)) { attributeStrategy = collectionAnnotation.mapElementStrategy(); } if (null != attributeStrategy) { elementStrategyHolder.setValue(attributeStrategy.newInstance()); } } if (null != keyStrategyHolder) { Class<? extends AttributeStrategy<?>> attributeStrategy = collectionAnnotation.mapKeyStrategy(); if (null != attributeStrategy) { keyStrategyHolder.setValue(attributeStrategy.newInstance()); } } return collectionAnnotation.nbrElements(); } else if (annotation instanceof Size) { size = (Size) annotation; } } Integer nbrElements = strategy .getNumberOfCollectionElements(collectionElementType); if (null != size) { if (nbrElements > size.max()) { nbrElements = size.max(); } if (nbrElements < size.min()) { nbrElements = size.min(); } } return nbrElements; } /** * Utility to merge actual types with supplied array of generic type * substitutions * * @param attributeType * actual type of object * @param genericAttributeType * generic type of object * @param suppliedTypes * an array of supplied types for generic type substitution * @param typeArgsMap * a map relating the generic class arguments ("&lt;T, V&gt;" for * example) with their actual types * @return An array of merged actual and supplied types with generic types * resolved */ public static Type[] mergeActualAndSuppliedGenericTypes( Class<?> attributeType, Type genericAttributeType, Type[] suppliedTypes, Map<String, Type> typeArgsMap) { TypeVariable<?>[] actualTypes = attributeType.getTypeParameters(); if (actualTypes.length <= suppliedTypes.length) { return suppliedTypes; } Type[] genericTypes = null; if (genericAttributeType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) genericAttributeType; genericTypes = paramType.getActualTypeArguments(); } else if (genericAttributeType instanceof WildcardType) { WildcardType wildcardType = (WildcardType) genericAttributeType; genericTypes = wildcardType.getLowerBounds(); if (ArrayUtils.isEmpty(genericTypes)) { genericTypes = wildcardType.getUpperBounds(); } } List<Type> resolvedTypes = new ArrayList<Type>(); List<Type> substitutionTypes = new ArrayList<Type>(Arrays.asList(suppliedTypes)); for (int i = 0; i < actualTypes.length; i++) { Type type = null; if (actualTypes[i] instanceof TypeVariable) { type = typeArgsMap.get(((TypeVariable<?>)actualTypes[i]).getName()); } else if (actualTypes[i] instanceof WildcardType) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(PodamConstants.NO_TYPES); type = TypeManufacturerUtil.resolveGenericParameter(actualTypes[i], typeArgsMap, methodGenericTypeArgs); } if ((type == null) && (genericTypes != null)) { if (genericTypes[i] instanceof Class) { type = genericTypes[i]; } else if (genericTypes[i] instanceof WildcardType) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(PodamConstants.NO_TYPES); type = resolveGenericParameter(genericTypes[i], typeArgsMap, methodGenericTypeArgs); } else if (genericTypes[i] instanceof ParameterizedType) { type = genericTypes[i]; } else { LOG.debug("Skipping type {} {}", actualTypes[i], genericTypes[i]); } } if (type != null) { resolvedTypes.add(type); if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) { substitutionTypes.remove(0); } } } Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]); Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]); return ArrayUtils.addAll(resolved, supplied); } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ public static Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType = null; //Safe copy Map<String, Type> localMap = new HashMap<String, Type>(typeArgsMap); methodGenericTypeArgs.set(PodamConstants.NO_TYPES); if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } else if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = localMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, localMap, methodGenericTypeArgs); } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); Type[] actualTypeArgs = pType.getActualTypeArguments(); if (!typeArgsMap.isEmpty()) { for (int i = 0; i < actualTypeArgs.length; i++) { Class<?> tmp = resolveGenericParameter(actualTypeArgs[i], localMap, methodGenericTypeArgs); if (tmp != actualTypeArgs[i]) { /* If actual type argument has its own arguments, * we will loose them now, so we will leave type unresolved * until lower levels of type resolution */ if (ArrayUtils.isEmpty(methodGenericTypeArgs.get())) { actualTypeArgs[i] = tmp; } } } } methodGenericTypeArgs.set(actualTypeArgs); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (ArrayUtils.isNotEmpty(bounds)) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (ArrayUtils.isNotEmpty(bounds)) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], localMap, methodGenericTypeArgs); } } if (parameterType == null) { LOG.warn("Unrecognized type {}. Will use Object instead", paramType); parameterType = Object.class; } return parameterType; } /** * It retrieves the value for the {@link PodamStrategyValue} annotation with * which the attribute was annotated * * @param attributeType * The attribute type, used for type checking * @param annotations * Annotations attached to the attribute * @param attributeStrategy * The {@link AttributeStrategy} to use * @return The value for the {@link PodamStrategyValue} annotation with * which the attribute was annotated * @throws IllegalArgumentException * If the type of the data strategy defined for the * {@link PodamStrategyValue} annotation is not assignable to * the annotated attribute. This de facto guarantees type * safety. */ public static Object returnAttributeDataStrategyValue(Class<?> attributeType, List<Annotation> annotations, AttributeStrategy<?> attributeStrategy) throws IllegalArgumentException { if (null == attributeStrategy) { return null; } Object retValue = attributeStrategy.getValue(attributeType, annotations); if (retValue != null) { Class<?> desiredType = attributeType.isPrimitive() ? PodamUtils.primitiveToBoxedType(attributeType) : attributeType; if (!desiredType.isAssignableFrom(retValue.getClass())) { String errMsg = "The AttributeStrategy " + attributeStrategy.getClass().getName() + " produced value of type " + retValue.getClass().getName() + " incompatible with attribute type " + attributeType.getName(); throw new IllegalArgumentException(errMsg); } else { LOG.debug("The parameter {} will be filled using the following strategy {}", attributeType, attributeStrategy); } } return retValue; } }
41.839552
139
0.57857
c61eabbe0df5fc6194552a74780b4c892780c35a
12,181
// =========================================================================== // // // // Copyright 2011 Anton Dubrau and McGill University. // // // // 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 natlab.tame.callgraph; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import natlab.CompilationProblem; import natlab.Parse; import natlab.toolkits.analysis.ColonExprSimplification; import natlab.tame.classes.ClassRepository; import natlab.tame.simplification.LambdaSimplification; import natlab.toolkits.Context; import natlab.toolkits.analysis.varorfun.VFPreorderAnalysis; import natlab.toolkits.filehandling.GenericFile; import natlab.toolkits.path.FileEnvironment; import natlab.toolkits.path.FunctionReference; import natlab.toolkits.rewrite.Simplifier; import ast.ClassDef; import ast.Function; import ast.FunctionList; import ast.Program; import ast.Script; /** * A SimpleFunctionCollection is a collection of static functions. The * collection of functions is done by this object. We refer to parsing as * 'collecting', since we need to parse, resolve names as functions or variables * and explore the path to find functions in one pass. * * Given a main function, all functions that may be used during execution are in * this collection. This can only be ensured if certain dynamic Matlab builtins * are not used (thus this is part of the Static package): - cd into directories * which have requried matlab functions - eval, ... - calls to builtin(..) - any * creation of function handles to these builtins * */ public class SimpleFunctionCollection extends HashMap<FunctionReference, StaticFunction> implements FunctionCollection { private static final long serialVersionUID = 1L; private HashSet<GenericFile> loadedFiles = new HashSet<GenericFile>(); // files // that // were // loaded // so // far private FunctionReference main = null; // denotes which function is the // entry point private FileEnvironment fileEnvironment; private static boolean DEBUG = false; private ClassRepository classRepository; public static boolean convertColonToRange = false; // Determines whether to // run transformation // which converts // ColonExpr to // RangeExpr. /** * The function collection gets created via a path environment object This * will collect all the files, starting from the main function ('primary * function') */ public SimpleFunctionCollection(FileEnvironment fileEnvironment) { super(); this.fileEnvironment = fileEnvironment; // build class repository this.classRepository = new ClassRepository(fileEnvironment); // get main file (entrypoint) main = fileEnvironment.getMainFunctionReference(); // collect ArrayList<CompilationProblem> errors = new ArrayList<CompilationProblem>(); collect(main, errors); } /** * creates a deep copy of this function collection */ public SimpleFunctionCollection(SimpleFunctionCollection other) { super(); this.loadedFiles.addAll(other.loadedFiles); this.main = other.main; this.fileEnvironment = other.fileEnvironment; this.classRepository = other.classRepository; for (FunctionReference ref : other.keySet()) { this.put(ref, other.get(ref).clone()); } } /*** public stuff ***********************************************************************/ public FunctionReference getMain() { return main; } /*** Collecting files *******************************************************************/ public boolean collect(FunctionReference ref) { return collect(ref, new ArrayList<CompilationProblem>()); } /** * adds the matlab functions from the given filename to the collection * * @return returns true on success */ public boolean collect(FunctionReference funcRef, ArrayList<CompilationProblem> errList) { if (DEBUG) System.out.println("collecting " + funcRef); // was the filename already loaded? if (loadedFiles.contains(funcRef.getFile())) return true; if (funcRef.isBuiltin) return true; Program program = Parse.parseMatlabFile(funcRef.getFile(), errList); if (program == null) { throw new UnsupportedOperationException("cannot parse file " + funcRef + ":\n" + errList); } program.setFile(funcRef.getFile()); // check whether the matlab file has a good type if (program instanceof Script) { System.err .println("The tamer does not suport scripts at this point."); // TODO return false; } else if (program instanceof ClassDef) { System.err .println("The tamer does not support classes at this point."); // TODO - also add the class to the class repository } else if (!(program instanceof FunctionList)) { System.err .println("The tamer encountered Matlab file of unknown/unsupported type " + program.getClass() + "."); } // We reduce lambda expressions at this point, because they create extra // functions if (convertColonToRange) { ColonExprSimplification.analyze(program); } program = (Program) Simplifier.simplify( program, new VFPreorderAnalysis(program, fileEnvironment .getFunctionOrScriptQuery(funcRef.path)), LambdaSimplification.class); loadedFiles.add(funcRef.getFile()); boolean success = true; // turn functions into static functions, and go through their function // references recursively FunctionList functionList = (FunctionList) program; for (Function functionAst : functionList.getFunctions()) { // create/add static function FunctionReference ref = new FunctionReference( functionAst.getName().getID(), funcRef.getFile()); Context context = fileEnvironment.getContext(functionAst, funcRef.getFile()); StaticFunction function = new StaticFunction(functionAst, ref, context); this.put(ref, function); // recursively load referenced functions success = success && resolveFunctionsAndCollect(function, errList); } // TODO we should collect used siblings and get rid of unused ones return success; } /** * resolves all calls to other functions within given function, and collects * functions not in this collection */ private boolean resolveFunctionsAndCollect(StaticFunction function, ArrayList<CompilationProblem> errList) { boolean success = true; LinkedList<String> unfoundFunctions = new LinkedList<String>(); // collect references to other functions - update symbol table, // recursively collect for (String otherName : function.getCalledFunctions().keySet()) { FunctionReference ref = function.getCalledFunctions() .get(otherName); if (ref == null) { unfoundFunctions.add(otherName); success = false; } if (success) { success = success && collect(ref, errList); } } if (unfoundFunctions.size() != 0) { // TODO - should we do anything here? Just throw error if it's no an // incremental collection if (!(this instanceof IncrementalFunctionCollection)) { throw new UnsupportedOperationException("reference to " + unfoundFunctions + " in " + function.getName() + " not found"); } } return success; } /** * inlines all functions into the main function */ public void inlineAll() { inlineAll(new HashSet<FunctionReference>(), getMain()); System.out.println("finished inlining all"); } // inlines all calls inside the given function // throws a unspported operation if there is an attempt to inline a function // that is alraedy in the context -- cannot inline recursive functions private void inlineAll(Set<FunctionReference> context, FunctionReference function) { // error check if (context.contains(function)) { throw new UnsupportedOperationException( "trying to inline recursive function " + function); } if (!containsKey(function)) { throw new UnsupportedOperationException( "trying to inline function " + function + ", which is not loaded"); } if (function.isBuiltin()) return; // add this call to the context context.add(function); // inline all called functions recursively for (FunctionReference ref : get(function).getCalledFunctions() .values()) { if (!ref.isBuiltin()) { // inline recursively System.out.println("go inline " + ref); inlineAll(context, ref); } } // inline the calls to the given function get(function).inline(this); // remove this context context.remove(function); } /** * returns a single inlined function representing this function collection. * Does not alter the the function collection. Only works for non-recursive * callgraphs. */ public Function getAsInlinedFunction() { return getAsInlinedStaticFunction().getAst(); } /** * returns a single inlined StaticFunction representing this function * collection. Does not alter the function collection. Only works for * non-recursive callgraphs. */ public StaticFunction getAsInlinedStaticFunction() { SimpleFunctionCollection c = new SimpleFunctionCollection(this); c.inlineAll(); return c.get(c.getMain()); } /** * returns all function references that are either in this function * collection or that are being referred to by and function in this * collection */ public HashSet<FunctionReference> getAllFunctionReferences() { HashSet<FunctionReference> result = new HashSet<FunctionReference>(); for (FunctionReference ref : this.keySet()) { result.add(ref); result.addAll(this.get(ref).getCalledFunctions().values()); } return result; } /** * returns all function references to builtins among the whole call graph */ public HashSet<FunctionReference> getAllFunctionBuiltinReferences() { HashSet<FunctionReference> result = new HashSet<FunctionReference>(); for (FunctionReference ref : this.keySet()) { for (FunctionReference ref2 : this.get(ref).getCalledFunctions() .values()) { if (ref2.isBuiltin()) result.add(ref2); } } return result; } public String getPrettyPrinted() { String s = ""; for (FunctionReference f : this.keySet()) { s += ("\n" + this.get(f)); } return s; } @Override public ClassRepository getClassRepository() { return this.classRepository; } @Override public List<StaticFunction> getAllFunctions() { List<StaticFunction> functionList = new ArrayList<StaticFunction>(); for (FunctionReference ref : this.keySet()) { functionList.add(this.get(ref)); } return functionList; } }
34.802857
92
0.644528
eb515fc677ce9557b8c89bb05f1ee4a0cb89ff57
2,101
package com.gempukku.libgdx.graph.pipeline.producer.node; import com.badlogic.gdx.utils.Array; import com.gempukku.libgdx.graph.data.FieldType; import com.gempukku.libgdx.graph.data.GraphNodeInput; public class GraphNodeInputImpl<T extends FieldType> implements GraphNodeInput<T> { private String id; private String name; private boolean acceptingMultiple; private Array<T> acceptedTypes; private boolean required; private boolean mainConnection; public GraphNodeInputImpl(String id, String name, T... acceptedType) { this(id, name, false, acceptedType); } public GraphNodeInputImpl(String id, String name, boolean required, T... acceptedType) { this(id, name, required, false, acceptedType); } public GraphNodeInputImpl(String id, String name, boolean required, boolean mainConnection, T... acceptedType) { this(id, name, required, mainConnection, false, acceptedType); } public GraphNodeInputImpl(String id, String name, boolean required, boolean mainConnection, boolean acceptingMultiple, T... acceptedType) { this.id = id; this.name = name; this.required = required; this.mainConnection = mainConnection; this.acceptingMultiple = acceptingMultiple; this.acceptedTypes = new Array<>(acceptedType); } @Override public boolean isRequired() { return required; } @Override public boolean isMainConnection() { return mainConnection; } @Override public String getFieldId() { return id; } @Override public String getFieldName() { return name; } @Override public boolean isAcceptingMultiple() { return acceptingMultiple; } @Override public Array<T> getAcceptedPropertyTypes() { return acceptedTypes; } @Override public boolean acceptsInputTypes(Array<T> inputTypes) { for (T inputType : inputTypes) { if (!acceptedTypes.contains(inputType, true)) return false; } return true; } }
27.644737
143
0.669681
359633a7e051850b29104a2cdfed9628817471b7
3,072
/* * Copyright 2015-2021 Micro Focus or one of its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hpe.caf.languagedetection.cld2; import com.hpe.caf.languagedetection.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /** * Created by smitcona on 30/11/2015. */ public class Cld2Tester { public static void main(String[] args) throws LanguageDetectorException, IOException { /** * Whether to return multiple languages or just the top language */ boolean multiLang = true; /** * Pass in the filename from command line and it gets read in e.g. "C:\\Users\\smitcona\\Desktop\\emailGerman.txt" */ // byte[] bytes = getAllData(args[0]); byte[] bytes = Files.readAllBytes(Paths.get(args[0])); /** * Settings file takes either: * <li>(multilang) -e.g. (true)</li> * <li>(multilang, "hints") -e.g. (false, "ENGLISH")</li> * <li>("encoding", multilang, "hints") -e.g. ("utf8", true, "en", "fr")</li> */ LanguageDetectorSettings settings = new LanguageDetectorSettings(multiLang); // LanguageDetectorSettings settings = new LanguageDetectorSettings(multiLang,"en", "it"); /** * Provider to provide a detector implementation */ LanguageDetectorProvider provider = new Cld2DetectorProvider(); /** * Detector implementation */ LanguageDetector detector = provider.getLanguageDetector(); /** * this is the final result from the language detection, and you pass in the bytes from the text file and settings */ LanguageDetectorResult result = detector.detectLanguage(bytes, settings); DetectedLanguage[] d = result.getLanguages().toArray(new DetectedLanguage[result.getLanguages().size()]); /** * output the results */ for (int i = 0; i < d.length; i++) { System.out.println("" + i + ": " + d[i].getLanguageCode()); System.out.println("" + i + ": " + d[i].getLanguageName()); System.out.println("" + i + ": " + d[i].getConfidencePercentage()); } /** * Get languages Collection into an array */ // if(result.getLanguageDetectorStatus()==LanguageDetectorStatus.COMPLETED) { // } else { // System.out.println("Language detection failed. Make sure supplied text file encoding is UTF-8. \n"); // } } }
35.72093
122
0.624349
18477798471d74b5c5d95a98a03532c136827b8c
976
public class Question91 { public int numDecodings(String s) { if(s.charAt(0)=='0') return 0; if(s.length()==1) return 1; int[] result=new int[s.length()]; result[0]=1; if(s.charAt(1)=='0') { if(s.charAt(0)>'2') return 0; result[1]=1; } else if(10*(s.charAt(0)-'0')+s.charAt(1)-'0'>26){ result[1]=1; } else result[1]=2; for(int i=2;i<s.length();i++){ if(s.charAt(i)=='0'){ if(10*(s.charAt(i-1)-'0')+s.charAt(i)-'0'>26||s.charAt(i-1)=='0') return 0; result[i]=result[i-2]; } else if(s.charAt(i-1)=='0') result[i]=result[i-1]; else if(10*(s.charAt(i-1)-'0')+s.charAt(i)-'0'>26){ result[i]=result[i-1]; } else result[i]=result[i-2]+result[i-1]; } return result[s.length()-1]; } }
30.5
81
0.415984
321ac71fb5ff5beb925ddecc08b3e66aeb5c5722
103
package edu.berkeley.cs.succinct.util; public interface Source { int length(); int get(int i); }
12.875
38
0.699029
f5895f07749402371af0308499bfd46bcb3ad634
1,795
package me.deepak.interview.queue; import java.util.ArrayDeque; import java.util.Deque; /* * https://leetcode.com/problems/sliding-window-maximum/ * https://youtu.be/39grPZtywyQ * https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/ */ public class SlidingWindowMaximum { public int[] maxSlidingWindow(int[] a, int k) { if (a == null || a.length == 0) { return new int[0]; } int n = a.length; int[] result = new int[n - k + 1]; // Create a Double Ended Queue, that will store indexes of array elements. // The queue will store indexes of useful elements in every window and it will // maintain decreasing order of values from front to rear in Queue. Deque<Integer> deque = new ArrayDeque<>(); // Process first k (or first window) elements of array for (int i = 0; i < k; i++) { // For every element, the previous smaller elements are useless so // remove them from Queue while (!deque.isEmpty() && a[deque.peekLast()] < a[i]) { deque.removeLast(); } // Add new element at rear of queue deque.addLast(i); } for (int i = k; i < n; i++) { // The element at the front of the queue is the largest element of // previous window result[i - k] = a[deque.peekFirst()]; // Remove all elements smaller than the currently // being added element (remove useless elements) while (!deque.isEmpty() && a[deque.peekLast()] < a[i]) { deque.removeLast(); } // Remove the elements which are out of this window if (!deque.isEmpty() && deque.peekFirst() == i - k) { deque.removeFirst(); } // Add current element at the rear of Queue deque.addLast(i); } // add the maximum element of last window to result result[n - k] = a[deque.peekFirst()]; return result; } }
28.046875
91
0.656267
9d6b827072bdf8b165d233da82e6ff0b13501387
2,694
package com.cambrian.mall.auth.controller; import com.alibaba.fastjson.TypeReference; import com.cambrian.common.constant.AuthServerConstants; import com.cambrian.common.to.MemberEntityDTO; import com.cambrian.mall.auth.config.WeiboOAuth2Properties; import com.cambrian.mall.auth.feign.MemberFeignService; import com.cambrian.mall.auth.to.WeiboAccessTokenDTO; import lombok.val; import org.springframework.http.*; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpSession; /** * @author kuma 2021-01-04 */ @Controller @RequestMapping("/oauth2.0") public class Auth2Controller { private final WeiboOAuth2Properties weiboOAuth2Properties; private final RestTemplate restTemplate; private final MemberFeignService memberClient; public Auth2Controller(WeiboOAuth2Properties weiboOauth2Properties, RestTemplate restTemplate, MemberFeignService memberClient) { this.weiboOAuth2Properties = weiboOauth2Properties; this.restTemplate = restTemplate; this.memberClient = memberClient; } @GetMapping("/weibo/success") public String webbo(@RequestParam("code") String code, HttpSession session) { // 1. 获取 access token val param = weiboOAuth2Properties.buildTokenParam(code); val header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_FORM_URLENCODED); val httpEntity = new HttpEntity<>(param, header); ResponseEntity<WeiboAccessTokenDTO> accessToken = restTemplate.postForEntity(weiboOAuth2Properties.tokenUrl(), httpEntity, WeiboAccessTokenDTO.class); if (accessToken.getStatusCode() != HttpStatus.OK) { return "redirect:http://auth.2cmall.com/signin.html"; } val token = accessToken.getBody(); // 2. 调用远程服务查询用户信息 try { val result = memberClient.oauth2Signin(token); if (!result.isSuccess()) { return "redirect:http://auth.2cmall.com/signin.html"; } MemberEntityDTO user = result.get("social_user", new TypeReference<MemberEntityDTO>() { }); session.setAttribute(AuthServerConstants.SESSION_KEY_LOGIN_USER, user); // 3. 跳回首页 return "redirect:http://2cmall.com"; } catch (Exception e) { return "redirect:http://auth.2cmall.com/signin.html"; } } }
39.043478
116
0.70193
b33b7ab8931c775fc8fec0fcdc449dc2e71c3ca2
24,376
/* Copyright (C) 2016 New York University This file is part of Data Polygamy which is released under the Revised BSD License See file LICENSE for full license details. */ package edu.nyu.vida.data_polygamy.ct; import edu.nyu.vida.data_polygamy.ct.ReebGraphData.Arc; import edu.nyu.vida.data_polygamy.utils.Utilities; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; public class SimplifyFeatures implements Serializable { private static final long serialVersionUID = 1L; public class Feature implements Serializable { private static final long serialVersionUID = 1L; public int v; public int br; public MyIntList arcs = new MyIntList(); public float wt; public float exFn; public float avgFn; public float sadFn; public byte type; } public Feature [] brFeatures; ArrayList<Feature> features = new ArrayList<Feature>(); SimplifyCT sim; ArrayList<Integer> criticalPts; int lastSaddle; private int countFeatures(boolean max) { ReebGraphData data = sim.data; int no = 0; for(int i = 0;i < sim.order.length;i ++) { Branch br = sim.branches[sim.order.array[i]]; if(max) { if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { no ++; } } else { if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { no ++; } } } return no; } private int countFeatures(boolean max, float th) { ReebGraphData data = sim.data; int no = 0; for(int i = 0;i < sim.order.length;i ++) { Branch br = sim.branches[sim.order.array[i]]; float fn = data.nodes[br.to].fn - data.nodes[br.from].fn; if(max) { if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { if(fn >= th) { no ++; } } } else { if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { if(fn >= th) { no ++; } } } } return no; } HashSet<Integer> featureSet = new HashSet<Integer>(); HashMap<Integer, Integer> cps; private void initFeatures(boolean max) { int nf = brFeatures.length; if(nf > sim.order.length) { nf = sim.order.length; brFeatures = new Feature[nf]; } int pos = sim.order.length - 1; ReebGraphData data = sim.data; lastSaddle = -1; if(max) { for(int i = 0;i < data.noNodes;i ++) { if(data.nodes[i].type == ReebGraphData.SADDLE) { lastSaddle = i; break; } } } else { for(int i = data.noNodes - 1;i >= 0;i --) { if(data.nodes[i].type == ReebGraphData.SADDLE) { lastSaddle = i; break; } } } // Added by Harish lastSaddle = -1; cps = new HashMap<Integer, Integer>(); boolean root = true; int no = 0; while(no < nf) { int bno = sim.order.get(pos); Branch br = sim.branches[bno]; if(max) { if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { cps.put(br.to, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.to].v; brFeatures[no].exFn = data.nodes[br.to].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.from].fn; if(root) { if(lastSaddle == -1) { // single edge brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.from].fn; } else { brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[lastSaddle].fn; brFeatures[no].sadFn = data.nodes[lastSaddle].fn; } root = false; } no ++; } } else { if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { cps.put(br.from, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.from].v; brFeatures[no].exFn = data.nodes[br.from].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.to].fn; if(root) { if(lastSaddle == -1) { // single edge brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.to].fn; }else { brFeatures[no].wt = data.nodes[lastSaddle].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[lastSaddle].fn; } root = false; } no ++; } } pos --; } } private void getFeatures(boolean max) { for(int i = 0;i < sim.branches.length;i ++) { if(sim.removed[i]) { continue; } Branch br = sim.branches[i]; int fno = -1; if(max && cps.get(br.to) != null) { fno = cps.get(br.to); } else if(!max && cps.get(br.from) != null) { fno = cps.get(br.from); } if(fno == -1) { continue; } brFeatures[fno].br = i; featureSet.add(i); } } boolean less(int v1, int v2) { if(sim.data.nodes[v1].fn < sim.data.nodes[v2].fn) { return true; } if(sim.data.nodes[v1].fn > sim.data.nodes[v2].fn) { return false; } if(v1 < v2) { return true; } return false; } private void populateFeature(int f, boolean max) { int bno = brFeatures[f].br; ArrayList<Integer> queue = new ArrayList<Integer>(); queue.add(bno); while(queue.size() > 0) { int b = queue.remove(0); if(b != bno && featureSet.contains(b)) { Utilities.er("Can this now happen??"); continue; } Branch br = sim.branches[b]; brFeatures[f].arcs.addAll(br.arcs); for(int i = 0;i < br.children.length;i ++) { int bc = br.children.get(i); queue.add(bc); } } } public void simplify(int noFeatures, String rg, String simrg, boolean maxAsFeature, Function fn) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); System.out.println("Finished simplification"); int totalFeatures = countFeatures(maxAsFeature); noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeatures(maxAsFeature); sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn,totalFeatures, noFeatures); getFeatures(maxAsFeature); for(int i = 0;i < brFeatures.length;i ++) { populateFeature(i, maxAsFeature); } System.out.println("Updated features"); } /** * * @param rg * @param simrg * @param maxAsFeature * @param fn * @param th Assumes that the values are normalized between 0 and 1 */ public void simplify(String rg, String simrg, boolean maxAsFeature, Function fn, float th) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); System.out.println("Finished simplification"); int totalFeatures = countFeatures(maxAsFeature); int noFeatures = countFeatures(maxAsFeature, th); System.out.println("No. of features: " + noFeatures); brFeatures = new Feature[noFeatures]; initFeatures(maxAsFeature); sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn,totalFeatures, noFeatures); getFeatures(maxAsFeature); for(int i = 0;i < brFeatures.length;i ++) { populateFeature(i, maxAsFeature); } System.out.println("Updated features"); } double [] fn; double [] ct; double [] ex; int [] exv; public class MyArrays implements Serializable { private static final long serialVersionUID = 1L; private static final int INSERTIONSORT_THRESHOLD = 7; public void sort(int [] a) { int [] aux = clone(a); mergeSort(aux, a, 0, a.length, 0); } private int [] clone(int [] a) { int[] aux = new int[a.length]; for(int i = 0;i < a.length;i ++) { aux[i] = a[i]; } return aux; } private void mergeSort(int[] src, int[] dest, int low, int high, int off) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for (int i = low; i < high; i++) for (int j = i; j > low && compare(dest[j - 1], dest[j]) > 0; j--) swap(dest, j, j - 1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1; mergeSort(dest, src, low, mid, -off); mergeSort(dest, src, mid, high, -off); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (compare(src[mid - 1], src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for (int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && compare(src[p], src[q]) <= 0) dest[i] = src[p++]; else dest[i] = src[q++]; } } private void swap(int[] x, int a, int b) { int t = x[a]; x[a] = x[b]; x[b] = t; } } public int compare(int o1, int o2) { Arc arc1 = sim.data.arcs[o1]; Arc arc2 = sim.data.arcs[o2]; int v1 = arc1.from; int v2 = arc2.from; if(sim.data.nodes[v1].fn < sim.data.nodes[v2].fn || (sim.data.nodes[v1].fn == sim.data.nodes[v2].fn && sim.data.nodes[v1].v < sim.data.nodes[v2].v)) { return -1; } return 1; } public void writePersistence(String perFile, String extremaFile) { try { PrintStream pr = new PrintStream(perFile); PrintStream er = new PrintStream(extremaFile); float max = brFeatures[0].wt; for(int i = 1;i < brFeatures.length;i ++) { max = Math.max(max,brFeatures[i].wt); } // boundary case if(brFeatures.length == 2) { exType[0] = CTAlgorithm.MAXIMUM | CTAlgorithm.MINIMUM; } for(int i = 0;i < brFeatures.length;i ++) { float per = (max == 0)?1:brFeatures[i].wt / max; double pp = 0; if(ct != null && ct[i] != 0) { pp = fn[i] / ct[i]; } if(per > 1) { Utilities.er("!!!!!!!!!!!!!!!!!!!!!!!"); } pr.println(i + " " + per + " " + brFeatures[i].wt + " " + brFeatures[i].exFn + " " + pp + " " + exType[i]); // er.println(i + " " + brFeatures[i].v); er.println(i + " " + exv[i] + " " + exType[i]); } pr.close(); er.close(); } catch (Exception e) { e.printStackTrace(); } } /***************************************************************************************************************************************/ public void simplify(int noFeatures, String rg, String simrg, Function fn) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); System.out.println("Finished simplification"); int totalFeatures = sim.order.length; noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeatures(); for(int i = 0;i < brFeatures.length;i ++) { populateFeature(i); } System.out.println("Updated features"); } public void simplify(String rg, String simrg, Function fn, float th) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); // System.out.println("Finished simplification"); int totalFeatures = sim.order.length; int noFeatures = countFeatures(th); noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeatures(); for(int i = 0;i < brFeatures.length;i ++) { populateFeature(i); } // System.out.println("Updated features"); } public void simplify(ReebGraphData rgData, String simrg, Function fn, float th) { sim = new SimplifyCT(); sim.setInput(rgData); sim.simplify(fn); // System.out.println("Finished simplification"); int totalFeatures = sim.order.length; int noFeatures = countFeatures(th); noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeatures(); for(int i = 0;i < brFeatures.length;i ++) { populateFeature(i); } // System.out.println("Updated features"); } public Feature [] getFeatures() { return brFeatures; } private int countFeatures(float th) { ReebGraphData data = sim.data; int no = 0; for(int i = 0;i < sim.order.length;i ++) { Branch br = sim.branches[sim.order.array[i]]; float fn = data.nodes[br.to].fn - data.nodes[br.from].fn; if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { if(fn >= th) { no ++; } } else if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { if(fn >= th) { no ++; } } } return (no == 0)?1:no; } public void simplifyNoPart(String rg, String simrg, Function fn, float th) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); System.out.println("Finished simplification"); int totalFeatures = sim.order.length; int noFeatures = countFeaturesNoPart(th); noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeaturesNoPart(); sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn,totalFeatures, noFeatures); getFeaturesNoPart(); for(int i = 0;i < brFeatures.length;i ++) { populateFeatureNoPart(i); } System.out.println("Updated features"); } public void simplifyNoPart(int noFeatures, String rg, String simrg, Function fn) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); System.out.println("Finished simplification"); int totalFeatures = sim.order.length; // int noFeatures = countFeaturesNoPart(th); noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeaturesNoPart(); sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn,totalFeatures, noFeatures); getFeaturesNoPart(); for(int i = 0;i < brFeatures.length;i ++) { populateFeatureNoPart(i); } System.out.println("Updated features"); } private void getFeaturesNoPart() { for(int i = 0;i < sim.branches.length;i ++) { if(sim.removed[i]) { continue; } Branch br = sim.branches[i]; int fno = -1; if(cps.get(br.to) != null) { fno = cps.get(br.to); } if(cps.get(br.from) != null) { fno = cps.get(br.from); } if(fno == -1) { continue; } brFeatures[fno].br = i; featureSet.add(i); } } private int countFeaturesNoPart(float th) { ReebGraphData data = sim.data; int no = 0; for(int i = 0;i < sim.order.length;i ++) { Branch br = sim.branches[sim.order.array[i]]; float fn = data.nodes[br.to].fn - data.nodes[br.from].fn; if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { if(fn >= th) { no ++; } } if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { if(fn >= th) { no ++; } } } if(no == 0) { no = 2; } return no; } private void initFeatures() { featureSet.clear(); int nf = brFeatures.length; if(nf > sim.order.length) { nf = sim.order.length; brFeatures = new Feature[nf]; } int pos = sim.order.length - 1; ReebGraphData data = sim.data; cps = new HashMap<Integer, Integer>(); int root = 0; int no = 0; while(no < nf) { int bno = sim.order.get(pos); Branch br = sim.branches[bno]; if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { featureSet.add(bno); cps.put(br.to, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.to].v; brFeatures[no].exFn = data.nodes[br.to].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.from].fn; brFeatures[no].type = CTAlgorithm.MAXIMUM; if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { brFeatures[no].type |= CTAlgorithm.MINIMUM; root ++; } brFeatures[no].br = bno; no ++; } else if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { featureSet.add(bno); cps.put(br.from, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.from].v; brFeatures[no].exFn = data.nodes[br.from].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.to].fn; brFeatures[no].br = bno; brFeatures[no].type = CTAlgorithm.MINIMUM; no ++; } pos --; } if(root != 1) { if(root > 1) { Utilities.er("Can there be more than one root???"); } else { Utilities.er("Where has the root gone missing"); } } } private void initFeaturesNoPart() { featureSet.clear(); int nf = brFeatures.length; if(nf > sim.order.length) { nf = sim.order.length; brFeatures = new Feature[nf]; } int pos = sim.order.length - 1; ReebGraphData data = sim.data; cps = new HashMap<Integer, Integer>(); int root = 0; int no = 0; while(no < nf) { int bno = sim.order.get(pos); Branch br = sim.branches[bno]; if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { featureSet.add(bno); cps.put(br.to, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.to].v; brFeatures[no].exFn = data.nodes[br.to].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.from].fn; brFeatures[no].type = CTAlgorithm.MAXIMUM; if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { // brFeatures[no].type |= CTAlgorithm.MINIMUM; root ++; } brFeatures[no].br = bno; no ++; } if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { featureSet.add(bno); cps.put(br.from, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.from].v; brFeatures[no].exFn = data.nodes[br.from].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.to].fn; brFeatures[no].br = bno; brFeatures[no].type = CTAlgorithm.MINIMUM; no ++; } pos --; } if(root != 1) { if(root > 1) { Utilities.er("Can there be more than one root???"); } else { Utilities.er("Where has the root gone missing"); } } } private void populateFeature(int f) { int bno = brFeatures[f].br; ArrayList<Integer> queue = new ArrayList<Integer>(); queue.add(bno); while(queue.size() > 0) { int b = queue.remove(0); if(b!= bno && featureSet.contains(b)) { continue; } Branch br = sim.branches[b]; brFeatures[f].arcs.addAll(br.arcs); for(int i = 0;i < br.children.length;i ++) { int bc = br.children.get(i); queue.add(bc); } } } private void populateFeatureNoPart(int f) { int bno = brFeatures[f].br; ArrayList<Integer> queue = new ArrayList<Integer>(); queue.add(bno); while(queue.size() > 0) { int b = queue.remove(0); if(b!= bno && featureSet.contains(b)) { continue; } Branch br = sim.branches[b]; brFeatures[f].arcs.addAll(br.arcs); for(int i = 0;i < br.children.length;i ++) { int bc = br.children.get(i); queue.add(bc); } } } byte [] exType; public void updatePartition(String part, String simpart) { int [] arcMap = new int[sim.data.noArcs]; Arrays.fill(arcMap, -1); // fn = new double[sim.data.noArcs]; // ct = new double[sim.data.noArcs]; ex = new double[brFeatures.length]; exv = new int[brFeatures.length]; exType = new byte[brFeatures.length]; Arrays.sort(brFeatures, new Comparator<Feature>() { @Override public int compare(Feature o1, Feature o2) { if(o2.wt > o1.wt) { return 1; } return -1; } }); for(int i = 0;i < brFeatures.length;i ++) { for(int j = 0;j < brFeatures[i].arcs.length;j ++) { int arc = brFeatures[i].arcs.get(j); arcMap[arc] = i; } ex[i] = brFeatures[i].exFn; exv[i] = brFeatures[i].v; exType[i] = brFeatures[i].type; } try { BufferedReader reader = new BufferedReader(new FileReader(part)); PrintWriter p = new PrintWriter(simpart); int n = Integer.parseInt(reader.readLine().trim()); p.println(n); for(int i = 0;i < n;i ++) { int e = Integer.parseInt(reader.readLine().trim()); int newe = -1; if(e != -1) { newe = arcMap[e]; } // boundary condition if(brFeatures.length == 2) { newe = 0; } p.println(newe); } reader.close(); p.close(); } catch (Exception e) { e.printStackTrace(); } } public int [] getUpdatedPartition(String part) { int [] arcMap = new int[sim.data.noArcs]; Arrays.fill(arcMap, -1); ex = new double[brFeatures.length]; exv = new int[brFeatures.length]; exType = new byte[brFeatures.length]; Arrays.sort(brFeatures, new Comparator<Feature>() { @Override public int compare(Feature o1, Feature o2) { if(o2.wt > o1.wt) { return 1; } return -1; } }); for(int i = 0;i < brFeatures.length;i ++) { for(int j = 0;j < brFeatures[i].arcs.length;j ++) { int arc = brFeatures[i].arcs.get(j); arcMap[arc] = i; } ex[i] = brFeatures[i].exFn; exv[i] = brFeatures[i].v; exType[i] = brFeatures[i].type; } try { BufferedReader reader = new BufferedReader(new FileReader(part)); int n = Integer.parseInt(reader.readLine().trim()); int [] reg = new int[n]; for(int i = 0;i < n;i ++) { int e = Integer.parseInt(reader.readLine().trim()); int newe = -1; if(e != -1) { newe = arcMap[e]; } // boundary condition if(brFeatures.length == 2) { newe = 0; } reg[i] = newe; } reader.close(); return reg; } catch (Exception e) { e.printStackTrace(); } return null; } /////////// public void simplifyRootChildren(String rg, String simrg, Function fn, float th) { sim = new SimplifyCT(); sim.setInput(rg); sim.simplify(fn); System.out.println("Finished simplification"); int totalFeatures = sim.order.length; int noFeatures = countFeaturesRootChildren(th); noFeatures = Math.min(noFeatures, totalFeatures); brFeatures = new Feature[noFeatures]; initFeaturesRootChildren(); for(int i = 0;i < brFeatures.length;i ++) { populateFeature(i); } System.out.println("Updated features"); } private int countFeaturesRootChildren(float th) { ReebGraphData data = sim.data; int no = 0; int root = sim.order.array[sim.order.length - 1]; if(sim.branches[root].parent != -1) { Utilities.er("incorrect root!! don't be lazy and write code properly"); } for(int i = 0;i < sim.order.length;i ++) { Branch br = sim.branches[sim.order.array[i]]; if(br.parent == root) { float fn = data.nodes[br.to].fn - data.nodes[br.from].fn; if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { if(fn >= th) { no ++; } } else if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { if(fn >= th) { no ++; } } } } return (no == 0)?1:no; } private void initFeaturesRootChildren() { featureSet.clear(); int nf = brFeatures.length; if(nf > sim.order.length) { nf = sim.order.length; brFeatures = new Feature[nf]; } int pos = sim.order.length - 1; ReebGraphData data = sim.data; cps = new HashMap<Integer, Integer>(); int root = 0; int rootBr = sim.order.array[sim.order.length - 1]; int no = 0; while(no < nf) { int bno = sim.order.get(pos); Branch br = sim.branches[bno]; if(rootBr == bno || br.parent == rootBr) { if(data.nodes[br.to].type == ReebGraphData.MAXIMUM) { featureSet.add(bno); cps.put(br.to, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.to].v; brFeatures[no].exFn = data.nodes[br.to].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.from].fn; brFeatures[no].type = CTAlgorithm.MAXIMUM; if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { brFeatures[no].type |= CTAlgorithm.MINIMUM; root ++; } brFeatures[no].br = bno; no ++; } else if(data.nodes[br.from].type == ReebGraphData.MINIMUM) { featureSet.add(bno); cps.put(br.from, no); brFeatures[no] = new Feature(); brFeatures[no].v = data.nodes[br.from].v; brFeatures[no].exFn = data.nodes[br.from].fn; brFeatures[no].wt = data.nodes[br.to].fn - data.nodes[br.from].fn; brFeatures[no].sadFn = data.nodes[br.to].fn; brFeatures[no].br = bno; brFeatures[no].type = CTAlgorithm.MINIMUM; no ++; } } pos --; } if(root != 1) { if(root > 1) { Utilities.er("Can there be more than one root???"); } else { Utilities.er("Where has the root gone missing"); } } } }
25.959531
152
0.606129
36d31bcf8733c028544edb2f7cba27064fb03ea4
728
package io.renren.modules.test.controller; import io.renren.common.annotation.SysLog; import io.renren.common.utils.R; import io.renren.modules.test.entity.DataSourceEntity; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/dbsource/manage") public class DataSourceManagerController { @SysLog("添加数据源") @RequestMapping("/add") @RequiresPermissions("dbsource:manage:add") public R addDatasource(@RequestBody DataSourceEntity dbsource){ return R.ok(); } }
28
67
0.788462
907a3a759387638c9820e8c214b02988ca63d293
526
package com.fgw.mall.member.feign; import com.fgw.mall.common.utils.CommonResult; import com.fgw.mall.common.utils.PageUtils; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.Map; @FeignClient("mall-order") public interface OrderFeignService { @PostMapping("/order/order/list/withitems") CommonResult<PageUtils> listWithItems(@RequestBody Map<String, Object> params); }
30.941176
83
0.807985
9bcfc39db1d6e528b2ce5ff7f88dc3ae899f703b
1,254
package org.burroloco.donkey.error.transform; import au.net.netstorm.boost.sniper.marker.HasFixtures; import au.net.netstorm.boost.sniper.marker.LazyFields; import au.net.netstorm.boost.spider.api.runtime.Nu; import org.burroloco.butcher.fixture.checker.file.FileChecker; import static org.burroloco.butcher.fixture.checker.type.Occurrence.ONCE; import org.burroloco.butcher.util.file.FileCleaner; import org.burroloco.donkey.data.cake.Slice; import org.burroloco.donkey.glue.testcase.DonkeyTestCase; import org.burroloco.util.wire.Dna; import java.io.File; public class SwallowingBurperMolecularTest extends DonkeyTestCase implements LazyFields, HasFixtures { private static final File REPORT = new File("gen/demo/log/transform-errors.log"); private Burper subject; FileChecker fileChecker; FileCleaner fileCleaner; Slice slice; Dna dna; Nu nu; public void fixtures() { fileCleaner.clean(REPORT); dna.strand(Burper.class, SwallowingBurper.class); subject = nu.nu(Burper.class); } public void testErrorLogging() { RuntimeException e = new RuntimeException("random: " + slice); subject.error(slice, e); fileChecker.check(REPORT, ONCE, "random: \\{\\}"); } }
34.833333
102
0.743222
5cfa678ea69f971d0d62dc67361dc90163eb561b
3,303
package me.zhengjie; import com.alibaba.fastjson.JSONObject; import com.google.gson.JsonObject; import org.openqa.selenium.WebElement; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import org.testng.annotations.AfterClass; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; import java.net.URL; import java.util.List; import java.util.Map; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class AppDemo { private AppiumDriver driver; @BeforeClass public void setup() throws Exception { DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(CapabilityType.BROWSER_NAME, ""); cap.setCapability("platformName", "Android"); //指定测试平台 // cap.setCapability("deviceName", "127.0.0.1:62001"); //指定测试机的ID,通过adb命令`adb devices`获取 // cap.setCapability("platformVersion", "7"); cap.setCapability("deviceName", "192.168.0.101:5555"); //将上面获取到的包名和Activity名设置为值 // cap.setCapability("appPackage", "com.niwodai.universityloan"); /// cap.setCapability("appActivity", "com.niwodai.loan.lead.WelComeAcV349"); // //A new session could not be created的解决方法 // cap.setCapability("appWaitActivity", "com.meizu.flyme.calculator.Calculator"); // //每次启动时覆盖session,否则第二次后运行会报错不能新建session // cap.setCapability("sessionOverride", true); try { cap.setCapability("app", "D:\\apkdownload\\toutiao_unsigned_signed.apk"); driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap); driver.installApp("app"); }catch(Exception ex){ System.out.println(ex); } System.out.println("------------------"); } @Test public void plus() throws Exception { Thread.sleep(6000); // int width = driver.manage().window().getSize().width; // int height = driver.manage().window().getSize().height; // int x0 = (int)(width * 0.8); // 起始x坐标 // int x1 = (int)(height * 0.2); // 终止x坐标 // int y = (int)(height * 0.5); // y坐标 // for (int i=0; i<5; i++) { // driver.swipe(x0, y, x1, y, 500); // Thread.sleep(1000); // } // // driver.findElementById("com.youdao.calculator:id/guide_button").click(); // for (int i=0; i<6; i++) { // driver.findElementByXPath("//android.webkit.WebView[@text='Mathbot Editor']").click(); // Thread.sleep(1000); // } // // String btn_xpath = "//*[@resource-id='com.youdao.calculator:id/view_pager_keyboard']/android.widget.GridView/android.widget.FrameLayout[%d]/android.widget.FrameLayout"; // driver.findElementByXPath(String.format(btn_xpath, 7)).click(); // driver.findElementByXPath(String.format(btn_xpath, 10)).click(); // driver.findElementByXPath(String.format(btn_xpath, 8)).click(); // Thread.sleep(3000); // List<WebElement> webList1 = driver.findElements("/"); // JsonObject json = driver.getSettings(); // Map<String,Object> maps = driver.getAppStringMap(); } @AfterClass public void tearDown() throws Exception { driver.quit(); } }
37.11236
178
0.640327
6078c8326ffd208ade316136b85d53dca01f09e5
2,330
/* * @copyright : ToXSL Technologies Pvt. Ltd. < www.toxsl.com > * @author : Shiv Charan Panjeta < shiv@toxsl.com > * All Rights Reserved. * Proprietary and confidential : All information contained herein is, and remains * the property of ToXSL Technologies Pvt. Ltd. and its partners. * Unauthorized copying of this file, via any medium is strictly prohibited. */ package com.handlUser.app.utils; import android.content.Context; import android.graphics.Typeface; import android.os.Build; import android.util.Log; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class TypefaceUtil { /** * Using reflection to override default typeface * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN * * @param context to work with assets * @param defaultFontNameToOverride for example "monospace" * @param customFontFileNameInAssets file name of the font from assets */ public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) { final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Map<String, Typeface> newMap = new HashMap<String, Typeface>(); newMap.put("serif", customFontTypeface); try { final Field staticField = Typeface.class .getDeclaredField("sSystemFontMap"); staticField.setAccessible(true); staticField.set(null, newMap); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } else { try { final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride); defaultFontTypefaceField.setAccessible(true); defaultFontTypefaceField.set(null, customFontTypeface); } catch (Exception e) { Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride); } } } }
41.607143
160
0.669528
4ed976775459acab59e0906f8f49e9f3151f63ac
633
package org.dinhware.bot.adapter.core; import org.dinhware.bot.adapter.Listener; import org.dinhware.bot.adapter.ListenerType; import org.dinhware.bot.event.HostEvent; import org.dinhware.bot.objects.EventType; import java.util.Map; /** * Created by: Niklas * Date: 20.01.2018 * Alias: Dinh * Time: 11:40 */ @ListenerType(type = EventType.HOSTTARGET) public abstract class HostAdapter implements Listener { @Override public void dispatch(Map<String, String> tags, String[] arguments, String line) { onHost(new HostEvent(tags, arguments, line)); } protected abstract void onHost(HostEvent event); }
23.444444
85
0.736177
2c1767cdc6f539e4abdf76f7c56e5241a3ea2d78
893
/* Copyright 2017 Rice University 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. */ // THIS FILE IS A PART OF THE TESTPACK MAVEN INTEGRATION AND SHOULD NOT BE MODIFIED FOR TESTPACK CREATION. /** * When maven tests are run ensure that the pass program passes the test suite. */ public class PassProgramTest extends TestSuite { @Override protected PassProgram makeTestable() { return new PassProgram(); } }
29.766667
106
0.774916
210e3e62bad2ccc2af17f4decf383669c41772a3
745
package com.zys.design.pattern.builder; import java.time.LocalDate; /** * @Description 产品头部 * @Author leo * @Date 2020/8/24 14:44 */ public class Header { /** * 文件名 */ private String fileName; /** * 创建时间 */ private LocalDate createDate; public Header(String fileName, LocalDate createDate) { this.fileName = fileName; this.createDate = createDate; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public LocalDate getCreateDate() { return createDate; } public void setCreateDate(LocalDate createDate) { this.createDate = createDate; } }
18.170732
58
0.613423
9cf99bea80829085e6eceb14a6722ba6bb9de5fc
8,022
package org.sturrock.cassette.cassettej; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public abstract class ContentAddressableStoreTest { protected static ContentAddressableStore cas; private String helloWorldString = "Hello World"; // Precomputed sha1 hash of "Hello World" protected Hash helloWorldHash = new Hash("0A4D55A8D778E5022FAB701977C5D840BBC486D0"); // Precomputed gzip byte array of "Hello World" private byte[] helloWorldEncodedBytes = { 31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 87, 8, -49, 47, -54, 73, 1, 0, 86, -79, 23, 74, 11, 0, 0, 0 }; private String goodbyeWorldString = "Goodbye World"; protected Hash goodbyeWorldHash = new Hash("D409B5D36068592A1C06C29FC3B7F16839398793"); private Hash writeHelloWorld() throws IOException { return writeString(helloWorldString, new LinkedList<ContentEncoding>()); } private Hash writeHelloWorld(ContentEncoding contentEncoding) throws IOException { List<ContentEncoding> contentEncodings = new LinkedList<ContentEncoding>(); contentEncodings.add(contentEncoding); return writeString(helloWorldString, contentEncodings); } private Hash writeString(String string) throws IOException { return writeString(string, new LinkedList<ContentEncoding>()); } private Hash writeString(String string, ContentEncoding contentEncoding) throws IOException { List<ContentEncoding> contentEncodings = new LinkedList<ContentEncoding>(); contentEncodings.add(contentEncoding); return writeString(string, contentEncodings); } private Hash writeString(String string, List<ContentEncoding> contentEncodings) throws IOException { byte[] bytes = string.getBytes(StandardCharsets.UTF_8); try (InputStream stream = new ByteArrayInputStream(bytes);) { Hash hash = cas.write(stream, contentEncodings); return hash; } } @Before public void setUp() throws IOException { } @After public void tearDown() throws IOException { } @Test public void testWrite() throws IOException { Hash actual; actual = writeHelloWorld(); assertEquals(helloWorldHash, actual); } @Test public void testEncodedWrite() throws IOException { Hash actual; actual = writeHelloWorld(new GZIPContentEncoding()); assertEquals(helloWorldHash, actual); } @Test public void testContains() throws IOException { writeHelloWorld(); // Now cas should contain some content with this hash assertEquals(true, cas.contains(helloWorldHash)); // And shouldn't contain this hash assertEquals(false, cas.contains(goodbyeWorldHash)); writeString(goodbyeWorldString); // And now it should assertEquals(true, cas.contains(goodbyeWorldHash)); } @Test public void testEncodedContains() throws IOException { ContentEncoding encoding = new GZIPContentEncoding(); writeHelloWorld(encoding); // Now cas should contain some content with this hash assertEquals(true, cas.contains(helloWorldHash, encoding)); // And shouldn't contain this hash assertEquals(false, cas.contains(goodbyeWorldHash, encoding)); writeString(goodbyeWorldString, encoding); // And now it should assertEquals(true, cas.contains(goodbyeWorldHash, encoding)); } @Test public void testGetContentLength() throws IOException { writeHelloWorld(); // The content length should be 11 (Hello World) assertEquals(helloWorldString.length(), cas.getContentLength(helloWorldHash)); } @Test public void testEncodedGetContentLength() throws IOException { writeHelloWorld(new GZIPContentEncoding()); // The content length should be 11 (Hello World) assertEquals(helloWorldString.length(), cas.getContentLength(helloWorldHash)); // The encoded content length should be 48 (gzipped Hello World) assertEquals(helloWorldEncodedBytes.length, cas.getContentLength(helloWorldHash, new GZIPContentEncoding())); } @Test public void testGetHashes() throws IOException { List<Hash> hashes; hashes = cas.getHashes(); // Should only be nothing in there assertEquals(0, hashes.size()); writeHelloWorld(); hashes = cas.getHashes(); // Should only be one piece of content assertEquals(1, hashes.size()); // The hash should be the same as above assertEquals(helloWorldHash, hashes.get(0)); writeString(goodbyeWorldString); hashes = cas.getHashes(); assertEquals(2, hashes.size()); } @Test public void testRead() throws IOException { writeHelloWorld(); try (InputStream stream = cas.read(helloWorldHash);) { if (stream == null) fail("Content not found"); String content = new String(readFully(stream), StandardCharsets.UTF_8); // Content should be Hello World assertEquals(helloWorldString, content); } } @Test public void testEncodedRead() throws IOException { ContentEncoding encoding = new GZIPContentEncoding(); writeHelloWorld(encoding); try (InputStream stream = cas.read(helloWorldHash, encoding);) { if (stream == null) fail("Content not found"); try (InputStream decodedStream = encoding.decode(stream);) { String content = new String(readFully(decodedStream), StandardCharsets.UTF_8); // Content should be Hello World assertEquals(helloWorldString, content); } } } @Test public void testDelete() throws IOException { writeHelloWorld(new GZIPContentEncoding()); writeString(goodbyeWorldString); List<Hash> hashes; hashes = cas.getHashes(); // Should two pieces of content assertEquals(2, hashes.size()); Hash hash = hashes.get(0); cas.delete(hash); hashes = cas.getHashes(); // Now should be only one piece of content assertEquals(1, hashes.size()); hashes = cas.getHashes(); hash = hashes.get(0); cas.delete(hash); hashes = cas.getHashes(); // Now should be no content assertEquals(0, hashes.size()); } private static byte[] readFully(InputStream inputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, length); } return baos.toByteArray(); } @Test public void testContentAddedListener() throws IOException { ContentAddressableStoreListenerTestAdded contentAddressableStoreListenerTest = new ContentAddressableStoreListenerTestAdded(); cas.addListener(contentAddressableStoreListenerTest); writeHelloWorld(); ContentAddressableStoreEvent event = contentAddressableStoreListenerTest.getEvent(); Hash expectedHash = helloWorldHash; Hash actualHash = event.getHash(); assertEquals(expectedHash, actualHash); ContentAddressableStore expectedSource = cas; ContentAddressableStore actualSource = (ContentAddressableStore) event.getSource(); assertEquals(expectedSource, actualSource); // Must remove the listener as don't want it firing in other tests. cas.removeListener(contentAddressableStoreListenerTest); } @Test public void testContentRemovedListener() throws IOException { ContentAddressableStoreListenerTestRemoved contentAddressableStoreListenerTest = new ContentAddressableStoreListenerTestRemoved(); writeHelloWorld(); cas.addListener(contentAddressableStoreListenerTest); cas.delete(helloWorldHash); ContentAddressableStoreEvent event = contentAddressableStoreListenerTest.getEvent(); Hash expectedHash = helloWorldHash; Hash actualHash = event.getHash(); assertEquals(expectedHash, actualHash); ContentAddressableStore expectedSource = cas; ContentAddressableStore actualSource = (ContentAddressableStore) event.getSource(); assertEquals(expectedSource, actualSource); // Must remove the listener as don't want it firing in other tests. cas.removeListener(contentAddressableStoreListenerTest); } }
31.70751
132
0.761531
cddb46716cd46fb240dee1f1ceec5d1cada82cf1
1,146
package coneforest.psylla.core; import coneforest.psylla.*; /** * A representation of {@code iterable}, a type of an object that can be * iterated over. * * @param <T> a type of elements returned by the iterator. */ @Type("iterable") public interface PsyIterable<T extends PsyObject> extends PsyStreamable<T>, Iterable<T> { default public PsyArray psyToArray() throws PsyException { final var oArray=new PsyArray(); for(final T o: this) oArray.psyAppend(o); return oArray; } default public PsyFormalStream<T> psyStream() { return new PsyStream(java.util.stream.StreamSupport.<T>stream(spliterator(), false)); } default public PsyString psyUnite(final PsyTextual oSeparator) throws PsyException { final var separator=oSeparator.stringValue(); final var sb=new StringBuilder(); final java.util.Iterator<T> iterator=iterator(); try { while(iterator.hasNext()) { sb.append(((PsyTextual)iterator.next()).stringValue()); if(iterator.hasNext()) sb.append(separator); } } catch(final ClassCastException e) { throw new PsyTypeCheckException(); } return new PsyString(sb); } }
21.222222
87
0.710297
b0d46f8242b70bec7951c97c9d1f58038427d060
656
package hands.on.grpc; import hands.on.grpc.protobuf.ProtocolBufferMediaType; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; @QuarkusTest public class ProtoResourceTest { @Test public void testBeersEndpoint() { given() .contentType(ProtocolBufferMediaType.APPLICATION_PROTOBUF) .accept(ProtocolBufferMediaType.APPLICATION_PROTOBUF) .body(BeerProtos.GetBeersRequest.newBuilder().build().toByteArray()) .when().post("/api/proto") .then() .statusCode(200); } }
28.521739
84
0.664634
616c95eecc06cef3598ef035d495fb8c766bf812
2,310
package com.example.chaoice3240.firstactivity.repository.user; import com.example.chaoice3240.firstactivity.database.DbMng; import com.example.chaoice3240.firstactivity.database.user.UserEntity; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by luthfihariz on 5/20/17. */ public class UserLocalDataSource implements UserDataSource { @Inject DbMng dbMng; @Inject public UserLocalDataSource() { } @Override public Observable<Boolean> insertUser(UserEntity userEntity) { return Observable.just(userEntity) .observeOn(Schedulers.io()) .flatMap(new Func1<UserEntity, Observable<Boolean>>() { @Override public Observable<Boolean> call(UserEntity userEntity) { dbMng.userDao().insertUsers(userEntity); return Observable.just(true); } }); } @Override public Observable<UserEntity> getUser(String firstName) { return Observable.just(firstName) .observeOn(Schedulers.io()) .flatMap(new Func1<String, Observable<UserEntity>>() { @Override public Observable<UserEntity> call(String firstName) { UserEntity userEntity=dbMng.userDao().searchUserByName(firstName); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return Observable.just(userEntity); } }); } @Override public Observable<UserEntity> getUsers() { return Observable.just("1") .observeOn(Schedulers.io()) .flatMap(new Func1<String, Observable<UserEntity>>() { @Override public Observable<UserEntity> call(String s) { List<UserEntity> userEntities= dbMng.userDao().searchAllUsers(); return Observable.from(userEntities); } }); } }
32.535211
90
0.551515
6f6885359da177c025362bf2508cca49c44b4582
3,849
package com.amaze.filemanager.ui.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; import com.amaze.filemanager.R; /** * Created by Arpit on 30-07-2015. */ public class SizeDrawable extends View { Paint mPaint, mPaint1,mPaint2; RectF rectF; float startangle=-90,angle = 0; float startangle1=-90,angle1 = 0; float startangle2=-90,angle2=0; public SizeDrawable(Context context) { super(context); } int twenty; public SizeDrawable(Context context, AttributeSet attributeSet) { super(context, attributeSet); int strokeWidth = dpToPx(40); rectF=new RectF(getLeft(),getTop(),getRight(),getBottom()); //rectF = new RectF(dpToPx(0), dpToPx(0), dpToPx(200), dpToPx(200)); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(ContextCompat.getColor(getContext(),R.color.accent_indigo)); // mPaint.setStrokeCap(Paint.Cap.BUTT); mPaint.setStrokeWidth(strokeWidth); mPaint1 = new Paint(); mPaint1.setAntiAlias(true); mPaint1.setStyle(Paint.Style.FILL); mPaint1.setColor(ContextCompat.getColor(getContext(),R.color.accent_red)); // mPaint1.setStrokeCap(Paint.Cap.BUTT); mPaint1.setStrokeWidth(strokeWidth); mPaint2 = new Paint(); mPaint2.setAntiAlias(true); mPaint2.setStyle(Paint.Style.FILL); mPaint2.setColor(ContextCompat.getColor(getContext(),R.color.accent_green)); // mPaint2.setStrokeCap(Paint.Cap.BUTT); mPaint2.setStrokeWidth(strokeWidth); twenty = dpToPx(10); } DisplayMetrics displayMetrics; public int dpToPx(int dp) { if (displayMetrics == null) displayMetrics = getResources().getDisplayMetrics(); int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); return px; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // canvas.drawLine((getWidth() - twenty)-2,0,(getWidth() - twenty),0,mPaint1); if(angle2!=0)canvas.drawLine(0,getHeight()- (getHeight() * angle1),0,getHeight()-(getHeight()*angle2),mPaint2); canvas.drawLine(0, getHeight(),0, getHeight()- (getHeight() * angle), mPaint); if(angle1!=0)canvas.drawLine(0,getHeight()- (getHeight() * angle),0,getHeight()-(getHeight()*angle1),mPaint1); /* Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.STROKE); paint.setTextSize(20); canvas.drawText(Math.round(angle * 100)+"%",(getWidth() - twenty)*angle/2, 25,paint); if(angle1>0.20)canvas.drawText(Math.round((angle1-angle)*100)+"%",(getWidth() - twenty)*angle+(getWidth() - twenty)*(angle1-angle)/2, 25,paint); if(angle2>0.20)canvas.drawText(Math.round((angle2-angle1)*100)+"%",(getWidth() - twenty)*angle1+(getWidth() - twenty)*(angle2-angle1)/2, 25,paint); canvas.drawArc(rectF, startangle, angle, true, mPaint); canvas.drawArc(rectF, startangle1, angle1, true, mPaint1); canvas.drawArc(rectF, startangle2, angle2, true, mPaint2); */ } public void setAngle(float angle,float startangle) { this.angle = angle; this.startangle=startangle; } public void setAngle1(float angle,float startangle1) { this.angle1 = angle; this.startangle1=startangle1; } public void setAngle2(float angle2,float startangle2) { this.angle2 = angle2; this.startangle2=startangle2; } }
33.469565
155
0.663549
434888c05a7c53bf0a07e7438d2b198be6f9a931
280
package observer; public class TemperaturAnzeige extends Beobachtbar<Integer> { public void getWert(Integer temperatur) { System.out.println("Anzeige: "); informiereBeobachter(temperatur); System.out.println("Ende Anzeige"); System.out.println(); } }
20
62
0.707143
36ac37e1facd2bd5cfdb72962b26e44a95847aa4
2,880
package net.ros.common.tile.module; import lombok.Builder; import lombok.Getter; import lombok.Setter; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; import net.ros.common.machine.module.IModularMachine; import net.ros.common.machine.module.impl.SteamModule; import net.ros.common.machine.module.ISerializableModule; import net.ros.common.machine.module.ITickableModule; import net.ros.common.machine.module.MachineModule; import net.ros.common.machine.module.impl.FluidStorageModule; @Getter public class SteamBoilerModule extends MachineModule implements ITickableModule, ISerializableModule { @Setter private float maxHeat; @Setter private float currentHeat; private final String waterTank; @Builder public SteamBoilerModule(IModularMachine machine, String waterTank, float maxHeat) { super(machine, "SteamBoilerModule"); this.maxHeat = maxHeat; this.waterTank = waterTank; } @Override public void tick() { if (this.getMachineTile().getWorld().getTotalWorldTime() % 5 == 0) { if (this.currentHeat > this.getMinimumTemp()) this.currentHeat -= 0.1f; else if (this.currentHeat < this.getMinimumTemp()) this.currentHeat = this.getMinimumTemp(); this.sync(); } if (this.currentHeat >= 100) { int toProduce = (int) (1 / Math.E * (this.currentHeat / 10)); FluidStack drained = this.getMachine().getModule(FluidStorageModule.class) .getFluidHandler(this.getWaterTank()).drain(toProduce, true); if (drained != null) toProduce = drained.amount; else toProduce = 0; this.getMachine().getModule(SteamModule.class).getInternalSteamHandler().fillSteam(toProduce, true); if (toProduce != 0 && this.getMachineTile().getWorld().getTotalWorldTime() % 2 == 0) this.currentHeat -= 0.075; this.sync(); } } private int getMinimumTemp() { return (int) (this.getMachineTile().getWorld().getBiome( this.getMachineTile().getPos()).getTemperature(this.getMachineTile().getPos()) * 20); } public int getHeatScaled(int pixels) { final int i = (int) this.getMaxHeat(); if (i == 0) return -1; return (int) Math.min(this.getCurrentHeat() * pixels / i, pixels); } @Override public void fromNBT(NBTTagCompound tag) { this.currentHeat = tag.getFloat("currentHeat"); } @Override public NBTTagCompound toNBT(NBTTagCompound tag) { tag.setFloat("currentHeat", this.currentHeat); return tag; } public void addHeat(float heat) { this.currentHeat += heat; } }
29.387755
112
0.633681
1c4807c3f26bbf50640ce0d40f574a2349c38f1b
7,351
package com.codepath.cdharini.justlistit.model; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Helper with functions to access our database of todo items * Created by dharinic on 8/13/17. */ public class ToDoDatabaseHelper extends SQLiteOpenHelper { private static final String TAG = ToDoDatabaseHelper.class.getSimpleName(); private static final String DATABASE_NAME = "justlistit"; private static final int DATABASE_VERSION = 1; private static final String KEY_ID = "_id"; private static final String KEY_DUEDATE = "duedate"; private static final String KEY_TODOITEM = "item"; private static final String KEY_PRIORITY = "priority"; private static final String TABLE_TODOITEMS = "todoItemsTable"; private static ToDoDatabaseHelper sInstance; public static synchronized ToDoDatabaseHelper getInstance(Context context) { if (sInstance == null) { sInstance = new ToDoDatabaseHelper(context.getApplicationContext()); } return sInstance; } private ToDoDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TODOITEMS_TABLE = "CREATE TABLE " + TABLE_TODOITEMS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TODOITEM + " TEXT," + KEY_PRIORITY + " TEXT," + KEY_DUEDATE + " TEXT" + ")"; db.execSQL(CREATE_TODOITEMS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion != newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODOITEMS); onCreate(db); } } /** * Adds a new entry to the database * @param item ToDoItem to be added */ public void addItem(ToDoItem item) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put(KEY_TODOITEM, item.getTodoItem()); values.put(KEY_DUEDATE, item.getDate()); values.put(KEY_PRIORITY, item.getPriority().toString()); db.insertOrThrow(TABLE_TODOITEMS, null, values); db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, "Error while adding todo to database", e); } finally { db.endTransaction(); } } /** * Deletes entry using database id * @param id Database primary key */ public void deleteItem(long id) { SQLiteDatabase db = getWritableDatabase(); String selection = KEY_ID + " = ?"; db.beginTransaction(); try { db.delete(TABLE_TODOITEMS, selection, new String[] { String.valueOf(id) }); db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, "Error when deleting todo", e); } finally { db.endTransaction(); } } /** * Updates an item in the database * @param id Database primary key * @param editedItem updated Todo * @param priority updated priority * @param date updated due date */ public void updateItem(long id, String editedItem, String priority, String date) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put(KEY_TODOITEM, editedItem); values.put(KEY_PRIORITY, priority); values.put(KEY_DUEDATE, date); String selection = KEY_ID + " = ?"; int count = db.update( TABLE_TODOITEMS, values, selection, new String[] { String.valueOf(id) }); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while editing todo in database"); } finally { db.endTransaction(); } } /** * Retreives entry from DB * @param id Database primary key * @return ToDoItem */ public ToDoItem getItem(long id) { SQLiteDatabase db = getWritableDatabase(); String queryString = String.format("SELECT * FROM %s WHERE %s = ?", TABLE_TODOITEMS, KEY_ID); Cursor cursor = db.rawQuery(queryString, new String[]{String.valueOf(id)}); if (cursor.getCount() == 0) { cursor.close(); return null; } cursor.moveToFirst(); ToDoItem item = parseItemFromCursor(cursor); cursor.close(); return item; } /** * Get ToDoItem given a cursor * @param cursor * @return ToDoItem */ public ToDoItem parseItemFromCursor(Cursor cursor) { String d = cursor.getString(cursor.getColumnIndex(KEY_DUEDATE)); ToDoItem.Priority p = ToDoItem.Priority.valueOf((cursor.getString(cursor.getColumnIndex(KEY_PRIORITY)))); String i = cursor.getString(cursor.getColumnIndex(KEY_TODOITEM)); return new ToDoItem(i, d, p); } /** * Delets all rows in DB */ public void deleteAllItems() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { db.delete(TABLE_TODOITEMS, null, null); db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, "Error while trying to delete all posts and users", e); } finally { db.endTransaction(); } } /** * Gets a Cursor to the items table * @return cursor */ public Cursor getCursorSortByPriority() { SQLiteDatabase db = getWritableDatabase(); String SELECT_ITEMS_QUERY = String.format("SELECT * FROM %s ORDER BY CASE %s WHEN 'HIGH' THEN 1\n" + "WHEN 'MEDIUM' THEN 2\n" + "WHEN 'LOW' THEN 3\n" + "ELSE 4 END", TABLE_TODOITEMS, KEY_PRIORITY); Cursor todoCursor = db.rawQuery(SELECT_ITEMS_QUERY, null); return todoCursor; } /** * Gets all the items in the table * @return list of items in the table */ public List<ToDoItem> getAllItems() { List<ToDoItem> items = new ArrayList<>(); String SELECT_ITEMS_QUERY = String.format("SELECT * FROM %s", TABLE_TODOITEMS); SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(SELECT_ITEMS_QUERY, null); try { if (cursor.moveToFirst()) { do { ToDoItem item = parseItemFromCursor(cursor); items.add(item); } while(cursor.moveToNext()); } } catch (Exception e) { Log.e(TAG, "Error while trying to get posts from database", e); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return items; } }
31.96087
113
0.590668
5ced68949a940a42f7925a3e9640cbf9ef044f11
1,178
package soya.framework.tool.codegen; import soya.framework.commons.util.CodeBuilder; public abstract class JavaCodeBuilderCommand extends JavaCodegenCommand { protected int indent; @Override public String call() throws Exception { CodeBuilder builder = CodeBuilder.newInstance(); printPackage(builder); printClass(builder); indent ++; printBody(builder); indent --; return end(builder); } protected abstract void printBody(CodeBuilder builder); protected void printPackage(CodeBuilder builder) { builder.append("package ").append(packageName).appendLine(";").appendLine(); } protected void printClass(CodeBuilder builder) { builder.append("public class ").append(className).appendLine(" {").appendLine(); } protected void printDefaultConstructor(String modify, CodeBuilder builder) { builder.append(modify, indent).append(" ").append(className).appendLine("() {"); builder.appendLine("}", indent).appendLine(); } protected String end(CodeBuilder builder) { builder.append("}"); return builder.toString(); } }
26.772727
88
0.66893