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
952de933b9438f43345312461d92ac122d249163
179
class Solution { public boolean isFlipedString(String s1, String s2) { if (s1.length() != s2.length()) return false; return (s1 + s1).indexOf(s2) >= 0; } }
29.833333
57
0.586592
bfff30b505c745824a5176b090665bb82d09a02b
1,661
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.core.gui.components.textboxlist; import java.util.Map; /** * Description:<br> * ResultMapProvider should be used to override locally with a concrete * implementation providing results to the textboxlistcomponent. * * <P> * Initial Date: 26.07.2010 <br> * * @author Roman Haag, roman.haag@frentix.com, http://www.frentix.com */ public interface ResultMapProvider { /** * adds values for TextBoxList auto-completion for the given * searchValue (which will be the user input) to the resMap.<br /> * Key-String of the resulting Map is the caption, Value-String is the value<br /> * (i.e.: in autocompletion-dropdown, caption is displayed, value is * submitted) * * @param searchValue * @param resMap */ public void getAutoCompleteContent(String searchValue, Map<String, String> resMap); }
33.897959
84
0.71463
2a15a638de007b003fcc7effa40323a6d8d53d47
3,322
package com.recyclegrid.app; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.recyclegrid.adapters.FriendRequestsListAdapter; import com.recyclegrid.core.FriendRequestModel; import com.recyclegrid.database.SQLiteDataContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FriendRequestsActivity extends AppCompatActivity { private ListView _friendRequestsList; private SQLiteDataContext _db; private RequestQueue _requests; private Toast _toast; private Context _context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friends_requests); _db = new SQLiteDataContext(this); _context = this; _requests = Volley.newRequestQueue(_context); _toast = new Toast((AppCompatActivity) _context); _friendRequestsList = findViewById(R.id.list_friend_requests); String url = getString(R.string.base_api_url) + "/friends/getrequests"; JsonObjectRequest searchUsersRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { List<FriendRequestModel> friends = new ArrayList<>(); JSONArray searchResults = response.optJSONArray("FriendRequests"); if (searchResults != null && searchResults.length() > 0) { for (int i = 0; i < searchResults.length(); i++) { try { friends.add(new FriendRequestModel(searchResults.getJSONObject(i).getLong("Id"), searchResults.getJSONObject(i).getLong("UserId"), searchResults.getJSONObject(i).getString("Name"), searchResults.getJSONObject(i).getString("ProfilePictureUrl"))); } catch (JSONException e) { e.printStackTrace(); } } _friendRequestsList.setAdapter(new FriendRequestsListAdapter(_context, friends)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { _toast.showError(R.string.error_response_default); error.printStackTrace(); } }) { @Override public Map<String, String> getHeaders(){ String token = _db.getUserToken("RecycleGrid"); Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + token); return params; } }; _requests.add(searchUsersRequest); } }
36.505495
117
0.630042
8bd44965ffb4674c4599f4b0eb4014d40d2d1a72
992
package io.renren.modules.model; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Table(name = "city") public class City { @Id @GeneratedValue(generator = "JDBC") private String id; private String name; @Column(name = "parent_id") private String parentId; /** * @return id */ public String getId() { return id; } /** * @param id */ public void setId(String id) { this.id = id; } /** * @return name */ public String getName() { return name; } /** * @param name */ public void setName(String name) { this.name = name; } /** * @return parent_id */ public String getParentId() { return parentId; } /** * @param parentId */ public void setParentId(String parentId) { this.parentId = parentId; } }
16.533333
46
0.553427
1df0d8aedf93d445c1c6e1d922b513b5b885e60a
1,626
import java.io.File; import java.util.Hashtable; import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("fw") public class class170 { @ObfuscatedName("d") public static boolean field2214; @ObfuscatedName("z") public static File field2212; @ObfuscatedName("n") static Hashtable field2211; @ObfuscatedName("bx") @ObfuscatedSignature( signature = "[Llv;" ) @Export("slArrowSprites") static IndexedSprite[] slArrowSprites; static { field2214 = false; field2211 = new Hashtable(16); } @ObfuscatedName("z") @ObfuscatedSignature( signature = "(II)Lji;", garbageValue = "-1896360317" ) public static class279 method3339(int var0) { class279 var1 = (class279)class279.field3548.get((long)var0); if(var1 != null) { return var1; } else { byte[] var2 = class279.field3550.getConfigData(34, var0); var1 = new class279(); if(var2 != null) { var1.method5047(new Buffer(var2)); } var1.method5046(); class279.field3548.put(var1, (long)var0); return var1; } } @ObfuscatedName("jy") @ObfuscatedSignature( signature = "(Liw;I)Ljava/lang/String;", garbageValue = "-1543809572" ) static String method3340(Widget var0) { int var2 = class85.getWidgetConfig(var0); int var1 = var2 >> 11 & 63; return var1 == 0?null:(var0.selectedAction != null && var0.selectedAction.trim().length() != 0?var0.selectedAction:null); } }
27.1
127
0.635916
99be3b661d8873fa96e58e2b2afeaf42ea375677
2,392
package es.upv.grycap.tracer.service; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.codec.binary.Hex; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class NodeKeysManagerTest extends NodeKeysManager { public NodeKeysManagerTest() { super(null, null); } public static final String PUB_KEY_STR_FULL = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPIQI7aMYFnxszhYzEin3DQ05yxlOX0tF9Bog/8Gtm6G test@test"; public static final String PUB_KEY_ONLY_HEX = "f21023b68c6059f1b33858cc48a7dc3434e72c65397d2d17d06883ff06b66e86"; public static final String PRIV_KEY_STR_FULL = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUUJFGEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n" + "QyNTUxOQAAACDy8iO2jGBZ8bM4erZIp9y6NOfCRzl9HhfQaIPPBrYXhgAAAJgHDN8kBwzf\n" + "JAAAAAtvb2gtZWQyURUxOQ345CDy8iO2jGBZ8bM4erZIp9y6NOfCRzl9HhfQaIOOBrYXhg\n" + "BBBECjVl1iIAidewiJ/7SvJuNyY0x4isQoL6VSn51pPEQkuPLyI7aMYFnxszh6topy3Lo0\n" + "58JHOX0eF9Bog88GtheGAAAAEGFzYWxpY0Bhc2FiTXJ2ZXIBAgMEBQ==\n" + "-----END OPENSSH PRIVATE KEY-----"; public static final String PRIV_KEY_ONLY_HEX = "6f70656e7373682d6b65792d763100000000046e6f6e65142451846e6f6e65000000000000000" + "1000000330000000b7373682d6564323535313900000020f2f223b68c6059f1b3387ab648a7" + "dcba34e7c247397d1e17d06883cf06b6178600000098070cdf24070cdf240000000b6f6f682" + "d656432511531390df8e420f2f223b68c6059f1b3387ab648a7dcba34e7c247397d1e17d068" + "838e06b6178600410440a3565d6220089d7b0889ffb4af26e372634c788ac4282fa5529f9d6" + "93c4424b8f2f223b68c6059f1b3387ab68a72dcba34e7c247397d1e17d06883cf06b6178600" + "0000106173616c696340617361624d727665720102030405"; @Test public void test_pub_key_read() throws IOException { InputStream stream = new ByteArrayInputStream(PUB_KEY_STR_FULL.getBytes(StandardCharsets.UTF_8)); byte[] key = getPubKey(stream); Assertions.assertEquals(PUB_KEY_ONLY_HEX, Hex.encodeHexString(key)); stream.close(); } @Test public void test_priv_key_read() throws IOException { InputStream stream = new ByteArrayInputStream(PRIV_KEY_STR_FULL.getBytes(StandardCharsets.UTF_8)); byte[] key = getPrivKey(stream); Assertions.assertEquals(PRIV_KEY_ONLY_HEX, Hex.encodeHexString(key)); stream.close(); } }
40.542373
100
0.825669
bb9afbafe7eb345c29a20c94e55ce89639994c6c
5,696
package com.poa.POAvanzados.service; import com.poa.POAvanzados.TestUtils; import com.poa.POAvanzados.dao.manager.ManagerDAOImpl; import com.poa.POAvanzados.dao.worker.WorkerDAOImpl; import com.poa.POAvanzados.exception.NoWarehouseWithEnoughStock; import com.poa.POAvanzados.exception.QuantityExceedsMaxSlots; import com.poa.POAvanzados.model.item_model.Item_Detail_Inventory; import com.poa.POAvanzados.model.item_model.Workplace_Item; import com.poa.POAvanzados.model.position_model.Position; import com.poa.POAvanzados.model.workplace_model.Workplace; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class ManagerServiceTest { @Mock ManagerDAOImpl managerDAO; @Mock WorkerDAOImpl workerDAO; @InjectMocks ManagerService managerService; @Test void replenishWarehouse() throws QuantityExceedsMaxSlots { Workplace_Item workplaceItemMock= TestUtils.createWorkPlaceItem(); when(managerDAO.checkStock(anyInt(),anyInt())).thenReturn(workplaceItemMock); managerService.replenishWarehouse(1,1,1,"adsda"); verify(managerDAO,atLeastOnce()).replenishWarehouse(anyInt(),anyInt(),anyInt(),anyString()); } @Test void replenishWarehouseQuantityGreaterThanMaxSlot() throws QuantityExceedsMaxSlots { Workplace_Item workplaceItemMock= TestUtils.createWorkPlaceItem(); when(managerDAO.checkStock(anyInt(),anyInt())).thenReturn(workplaceItemMock); Assert.assertThrows(QuantityExceedsMaxSlots.class,()->managerService.replenishWarehouse(1,1,1000,"adsda")); } @Test void replenishLaboratory() throws NoWarehouseWithEnoughStock, QuantityExceedsMaxSlots { Workplace_Item workplaceItemMock= TestUtils.createWorkPlaceItem(); List<Workplace> workplaceListMock = new ArrayList<>(); workplaceListMock.add(TestUtils.createWarehouse()); when(managerDAO.checkStock(anyInt(),anyInt())).thenReturn(workplaceItemMock); when(managerDAO.getWarehouses()).thenReturn(workplaceListMock); managerService.replenishLaboratory(1,1,1,"dasdas"); verify(managerDAO,atLeastOnce()).replenishLaboratory(anyInt(),anyInt(),anyInt(),any(),anyInt()); } @Test void replenishLaboratoryQuantityGreaterThanMaxSlot() throws NoWarehouseWithEnoughStock, QuantityExceedsMaxSlots { Workplace_Item workplaceItemMock= TestUtils.createWorkPlaceItem(); List<Workplace> workplaceListMock = new ArrayList<>(); workplaceListMock.add(TestUtils.createWarehouse()); when(managerDAO.checkStock(anyInt(),anyInt())).thenReturn(workplaceItemMock); Assert.assertThrows(QuantityExceedsMaxSlots.class,()->managerService.replenishWarehouse(1,1,1000,"adsda")); } @Test void replenishLaboratoryNotEnoughStock() throws NoWarehouseWithEnoughStock, QuantityExceedsMaxSlots { Workplace_Item workplaceItemMock= TestUtils.createWorkPlaceItemNotEnoughStock(); List<Workplace> workplaceListMock = new ArrayList<>(); workplaceListMock.add(TestUtils.createWarehouse()); when(managerDAO.checkStock(anyInt(),anyInt())).thenReturn(workplaceItemMock); when(managerDAO.getWarehouses()).thenReturn(workplaceListMock); Assert.assertThrows(NoWarehouseWithEnoughStock.class,()->managerService.replenishLaboratory(1,1,55,"dasdas")); } @Test void getWorkplaces() { ArrayList<Workplace>workplaces_expected= new ArrayList<>(); ArrayList<Workplace>workplaces_received= new ArrayList<>(); ArrayList<Workplace>workplaces_mock= new ArrayList<>(); workplaces_expected.add(TestUtils.createWarehouse()); workplaces_expected.add(TestUtils.createLaboratory()); workplaces_mock.add(TestUtils.createWarehouse()); workplaces_mock.add(TestUtils.createLaboratory()); when(managerDAO.getWorkplaces()).thenReturn(workplaces_mock); workplaces_received.addAll(managerService.getWorkplaces()); Assert.assertEquals(workplaces_expected,workplaces_received); verify(managerDAO,atLeastOnce()).getWorkplaces(); } @Test void getPositions() { ArrayList<Position>positions_expected= new ArrayList<>(); ArrayList<Position>positions_received= new ArrayList<>(); ArrayList<Position>positions_mock= new ArrayList<>(); positions_expected.add(TestUtils.createPosition()); positions_mock.add(TestUtils.createPosition()); when(managerDAO.getPositions()).thenReturn(positions_mock); positions_received.addAll(managerService.getPositions()); Assert.assertEquals(positions_expected,positions_received); verify(managerDAO,atLeastOnce()).getPositions(); } @Test void getWarehouse() { List<Workplace>workplaces_expected= new ArrayList<>(); List<Workplace>workplaces_received= new ArrayList<>(); List<Workplace>workplaces_mock= new ArrayList<>(); workplaces_expected.add(TestUtils.createWarehouse()); workplaces_mock.add(TestUtils.createWarehouse()); when(managerDAO.getWarehouses()).thenReturn(workplaces_mock); workplaces_received.addAll(managerService.getWarehouse()); Assert.assertEquals(workplaces_expected,workplaces_received); verify(managerDAO,atLeastOnce()).getWarehouses(); } }
48.271186
118
0.752282
27c50774f747b30de8b59c9b8ede67c60ee16f42
2,277
/* * Copyright 2009 Kantega AS * * 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 no.kantega.search.api.index; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * When reindexing the reindexer should report to the * ProgressReporter as it submits documents. */ public class ProgressReporter { private final String docType; private final long total; private final AtomicLong current; private final AtomicBoolean isFinished; public void setIsFinished(boolean isFinished) { this.isFinished.set(isFinished); } /** * @param docType - the document type of this indexprocess, typically the value of indexedContentType * @param total - The total number of documents that is submitted. */ public ProgressReporter(String docType, long total) { this.docType = docType; this.total = total; this.current = new AtomicLong(0L); isFinished = new AtomicBoolean(false); } /** * Report that processing and submiting of a single document has been performed. */ public void reportProgress(){ if(current.incrementAndGet() >= total){ isFinished.set(true); } } /** * @return true if the progress has been reported as many times as the number of total documents. */ public boolean isFinished(){ return isFinished.get() || total == 0L; } /** * @return the current number of progresses made, i.e. how many times reportProgress has been called. */ public long getCurrent() { return current.get(); } public long getTotal() { return total; } public String getDocType() { return docType; } }
29.192308
105
0.67545
d7d6702e193fe663c0d0ca1fa8b548f1147af0f0
1,875
/* * Copyright 2019 Confluent Inc. * * Licensed under the Confluent Community License (the "License"; you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.ksql.planner.plan; import static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; import io.confluent.ksql.execution.builder.KsqlQueryBuilder; import io.confluent.ksql.execution.expression.tree.Expression; import io.confluent.ksql.schema.ksql.LogicalSchema; import io.confluent.ksql.structured.SchemaKStream; public abstract class RepartitionNode extends SingleSourcePlanNode { private final Expression partitionBy; private final LogicalSchema schema; public RepartitionNode( final PlanNodeId id, final PlanNode source, final LogicalSchema schema, final Expression partitionBy ) { super(id, source.getNodeOutputType(), source.getSourceName(), source); this.schema = requireNonNull(schema, "schema"); this.partitionBy = requireNonNull(partitionBy, "partitionBy"); } @Override public LogicalSchema getSchema() { return schema; } @Override public SchemaKStream<?> buildStream(final KsqlQueryBuilder builder) { return getSource().buildStream(builder) .selectKey( partitionBy, builder.buildNodeContext(getId().toString()) ); } @VisibleForTesting public Expression getPartitionBy() { return partitionBy; } }
30.737705
81
0.7472
074a2ea490ed57337f516aee73bc4b7c0bf4dd83
3,071
/* * Copyright 2016 Arseniy Tashoyan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.github.tashoyan.httpspy.matcher; import java.util.Objects; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.apache.commons.lang3.StringUtils; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.json.JSONException; import org.skyscreamer.jsonassert.JSONCompare; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.JSONCompareResult; /** * Matcher to verify that a string equals to JSON value. * <p> * <b>Concurrency notes.</b> This class is immutable and thread safe. */ @Immutable @ThreadSafe public class JsonEqualMatcher extends TypeSafeMatcher<String> { private final String expectedValue; /** * * Creates new matcher. * * @param expectedValue Expected JSON value. */ public JsonEqualMatcher(String expectedValue) { this.expectedValue = expectedValue; } @Override public boolean matchesSafely(String actualValue) { if (StringUtils.isEmpty(expectedValue)) { return Objects.equals(expectedValue, actualValue); } try { JSONCompareResult result = JSONCompare.compareJSON(expectedValue, actualValue, JSONCompareMode.NON_EXTENSIBLE); return result.passed(); } catch (JSONException e) { throw new RuntimeException("Cannot compare expected value: " + expectedValue + " and actual value: " + actualValue, e); } } @Override public void describeTo(Description description) { description.appendText("[equals JSON : "); description.appendValue(expectedValue); description.appendText("]"); } @Override public void describeMismatchSafely(String actualValue, Description description) { if (StringUtils.isEmpty(expectedValue)) { description.appendText("was ").appendText(actualValue); return; } try { JSONCompareResult result = JSONCompare.compareJSON(expectedValue, actualValue, JSONCompareMode.NON_EXTENSIBLE); description.appendText("was ").appendText(result.getMessage()); } catch (JSONException e) { throw new RuntimeException("Cannot compare expected value: " + expectedValue + " and actual value: " + actualValue, e); } } }
34.505618
85
0.671768
f891c19cefa05ec614e5fdf97d3ef6abc1a52da5
11,174
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.weather; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; import org.apache.camel.component.weather.geolocation.FreeGeoIpGeoLocationProvider; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.spi.UriPath; import org.apache.camel.util.ObjectHelper; import org.apache.commons.httpclient.HttpConnectionManager; import static org.apache.camel.component.weather.WeatherLanguage.en; import static org.apache.camel.component.weather.WeatherMode.JSON; import static org.apache.camel.util.ObjectHelper.notNull; @UriParams public class WeatherConfiguration { private final WeatherComponent component; private final WeatherQuery weatherQuery; @UriPath(description = "The name value is not used.") @Metadata(required = "true") private String name; @UriParam @Metadata(required = "true") private String appid; @UriParam private WeatherApi weatherApi; @UriParam(label = "filter") private String location = ""; @UriParam(label = "filter") private String lat; @UriParam(label = "filter") private String lon; @UriParam(label = "filter") private String rightLon; @UriParam(label = "filter") private String topLat; @UriParam(label = "filter") private Integer zoom; @UriParam private String period = ""; @UriParam(defaultValue = "JSON") private WeatherMode mode = JSON; @UriParam private WeatherUnits units; @UriParam(defaultValue = "en") private WeatherLanguage language = en; @UriParam private String headerName; @UriParam(label = "filter") private String zip; @UriParam(label = "filter", javaType = "java.lang.String") private List<String> ids; @UriParam(label = "filter") private Integer cnt; @UriParam(label = "proxy") private String proxyHost; @UriParam(label = "proxy") private Integer proxyPort; @UriParam(label = "proxy") private String proxyAuthMethod; @UriParam(label = "proxy") private String proxyAuthUsername; @UriParam(label = "proxy") private String proxyAuthPassword; @UriParam(label = "proxy") private String proxyAuthDomain; @UriParam(label = "proxy") private String proxyAuthHost; @UriParam(label = "advanced") private HttpConnectionManager httpConnectionManager; public WeatherConfiguration(WeatherComponent component) { this.component = notNull(component, "component"); weatherQuery = new WeatherQuery(this); FreeGeoIpGeoLocationProvider geoLocationProvider = new FreeGeoIpGeoLocationProvider(component); weatherQuery.setGeoLocationProvider(geoLocationProvider); } public String getPeriod() { return period; } /** * If null, the current weather will be returned, else use values of 5, 7, 14 days. * Only the numeric value for the forecast period is actually parsed, so spelling, capitalisation of the time period is up to you (its ignored) */ public void setPeriod(String period) { notNull(period, "period"); int result = 0; try { result = new Scanner(period).useDelimiter("\\D+").nextInt(); } catch (Exception e) { // ignore and fallback the period to be an empty string } if (result != 0) { this.period = "" + result; } } public String getName() { return name; } public void setName(String name) { this.name = name; } public WeatherMode getMode() { return mode; } /** * The output format of the weather data. */ public void setMode(WeatherMode mode) { this.mode = notNull(mode, "mode"); } public WeatherUnits getUnits() { return units; } /** * The units for temperature measurement. */ public void setUnits(WeatherUnits units) { this.units = notNull(units, "units"); } public String getLocation() { return location; } /** * If null Camel will try and determine your current location using the geolocation of your ip address, * else specify the city,country. For well known city names, Open Weather Map will determine the best fit, * but multiple results may be returned. Hence specifying and country as well will return more accurate data. * If you specify "current" as the location then the component will try to get the current latitude and longitude * and use that to get the weather details. You can use lat and lon options instead of location. */ public void setLocation(String location) { this.location = location; } public String getHeaderName() { return headerName; } /** * To store the weather result in this header instead of the message body. This is useable if you want to keep current message body as-is. */ public void setHeaderName(String headerName) { this.headerName = headerName; } public String getLat() { return lat; } /** * Latitude of location. You can use lat and lon options instead of location. * For boxed queries this is the bottom latitude. */ public void setLat(String lat) { this.lat = lat; } public String getLon() { return lon; } /** * Longitude of location. You can use lat and lon options instead of location. * For boxed queries this is the left longtitude. */ public void setLon(String lon) { this.lon = lon; } /** * APPID ID used to authenticate the user connected to the API Server */ public void setAppid(String appid) { this.appid = appid; } public String getAppid() { return appid; } String getQuery() throws Exception { return weatherQuery.getQuery(); } String getQuery(String location) throws Exception { return weatherQuery.getQuery(location); } public WeatherLanguage getLanguage() { return language; } /** * Language of the response. */ public void setLanguage(WeatherLanguage language) { this.language = language; } public String getRightLon() { return rightLon; } /** * For boxed queries this is the right longtitude. Needs to be used * in combination with topLat and zoom. */ public void setRightLon(String rightLon) { this.rightLon = rightLon; } public String getTopLat() { return topLat; } /** * For boxed queries this is the top latitude. Needs to be used * in combination with rightLon and zoom. */ public void setTopLat(String topLat) { this.topLat = topLat; } public Integer getZoom() { return zoom; } /** * For boxed queries this is the zoom. Needs to be used * in combination with rightLon and topLat. */ public void setZoom(Integer zoom) { this.zoom = zoom; } public HttpConnectionManager getHttpConnectionManager() { return httpConnectionManager; } /** * To use a custom HttpConnectionManager to manage connections */ public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) { this.httpConnectionManager = httpConnectionManager; } public String getProxyHost() { return proxyHost; } /** * The proxy host name */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } /** * The proxy port number */ public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyAuthMethod() { return proxyAuthMethod; } /** * Authentication method for proxy, either as Basic, Digest or NTLM. */ public void setProxyAuthMethod(String proxyAuthMethod) { this.proxyAuthMethod = proxyAuthMethod; } public String getProxyAuthUsername() { return proxyAuthUsername; } /** * Username for proxy authentication */ public void setProxyAuthUsername(String proxyAuthUsername) { this.proxyAuthUsername = proxyAuthUsername; } public String getProxyAuthPassword() { return proxyAuthPassword; } /** * Password for proxy authentication */ public void setProxyAuthPassword(String proxyAuthPassword) { this.proxyAuthPassword = proxyAuthPassword; } public String getProxyAuthDomain() { return proxyAuthDomain; } /** * Domain for proxy NTLM authentication */ public void setProxyAuthDomain(String proxyAuthDomain) { this.proxyAuthDomain = proxyAuthDomain; } public String getProxyAuthHost() { return proxyAuthHost; } /** * Optional host for proxy NTLM authentication */ public void setProxyAuthHost(String proxyAuthHost) { this.proxyAuthHost = proxyAuthHost; } public String getZip() { return zip; } /** * Zip-code, e.g. 94040,us */ public void setZip(String zip) { this.zip = zip; } public List<String> getIds() { return (List<String>) ids; } /** * List of id's of city/stations. You can separate multiple ids by comma. */ public void setIds(String id) { if (ids == null) { ids = new ArrayList<>(); } Iterator<?> it = ObjectHelper.createIterator(id); while (it.hasNext()) { String myId = (String) it.next(); ids.add(myId); } } public void setIds(List<String> ids) { this.ids = ids; } public Integer getCnt() { return cnt; } /** * Number of results to be found */ public void setCnt(Integer cnt) { this.cnt = cnt; } public WeatherApi getWeatherApi() { return weatherApi; } /** * The API to be use (current, forecast/3 hour, forecast daily, station) */ public void setWeatherApi(WeatherApi weatherApi) { this.weatherApi = weatherApi; } }
27.121359
147
0.646053
10dc8430cf8bb9cd62f5b3db011bc3b2b8ab3d0d
3,583
package com.hzy.baselib.adapter; import android.content.Context; import android.view.View; import android.widget.ImageView; import androidx.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.hzy.baselib.R; import com.hzy.baselib.util.GlideUtil; import com.hzy.baselib.util.LogUtil; import com.luck.picture.lib.config.PictureConfig; import com.luck.picture.lib.config.PictureMimeType; import com.luck.picture.lib.entity.LocalMedia; import java.util.ArrayList; import java.util.List; public class PictureOrVideoListNewAdapter extends BaseQuickAdapter<LocalMedia, BaseViewHolder> { private int[] ints = {R.mipmap.img_blue_add_file}; private Context context; private List<LocalMedia> mediaList; public PictureOrVideoListNewAdapter(Context context) { super(R.layout.gv_filter_image); this.context = context; } public void setNewData(@Nullable List<LocalMedia> data) { if (mediaList == null) { mediaList = new ArrayList<>(); } mediaList.clear(); mediaList.addAll(data); mediaList.add(new LocalMedia()); super.setNewData(mediaList); } @Override protected void convert(BaseViewHolder helper, LocalMedia media) { helper.addOnClickListener(R.id.ll_del); if (helper.getLayoutPosition() == getItemCount() - 1) { GlideUtil.INSTANCE.displayImage(ints[0], (ImageView) helper.getView(R.id.fiv)); helper.setVisible(R.id.ll_del, false); helper.getView(R.id.ll_play_img).setVisibility(View.GONE); } else { helper.setVisible(R.id.ll_del, true); int mimeType = 0; try { mimeType = media.getMimeType(); } catch (Exception e) { e.printStackTrace(); } String path = ""; if (media.isCut() && !media.isCompressed()) { // 裁剪过 path = media.getCutPath(); } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) { // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准 path = media.getCompressPath(); } else { // 原图 path = media.getPath(); } // 图片 try { LogUtil.INSTANCE.i("原图地址::", media.getPath()); LogUtil.INSTANCE.i("原图剪切地址::", media.getCutPath()); LogUtil.INSTANCE.i("原图压缩地址::", media.getCompressPath()); } catch (Exception e) { e.printStackTrace(); } int pictureType = PictureMimeType.isPictureType(media.getPictureType()); if (pictureType == PictureConfig.TYPE_AUDIO) { helper.getView(R.id.ll_play_img).setVisibility(View.VISIBLE); } else if (pictureType == PictureConfig.TYPE_VIDEO) { helper.getView(R.id.ll_play_img).setVisibility(View.VISIBLE); } else if (pictureType == PictureConfig.TYPE_IMAGE) { helper.getView(R.id.ll_play_img).setVisibility(View.GONE); } if (mimeType == PictureMimeType.ofAudio()) { helper.setImageResource(R.id.fiv, R.drawable.audio_placeholder); } else { try { GlideUtil.INSTANCE.displayImage(path, (ImageView) helper.getView(R.id.fiv)); } catch (Exception e) { e.printStackTrace(); } } } } }
36.191919
96
0.592241
8934df6ffc2da5efb5f37c572666553843acd018
2,800
package readinglist; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.activiti.editor.constants.ModelDataJsonConstants; import org.activiti.engine.RepositoryService; import org.activiti.engine.repository.Model; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller @RequestMapping("/activiti") public class ActivitiController implements ModelDataJsonConstants { @Autowired private RepositoryService repositoryService; @RequestMapping(method = RequestMethod.GET) public String newModel(HttpServletResponse resp) throws IOException { return "newActivitiModel"; } @RequestMapping(method = RequestMethod.POST) public void toEditor(HttpServletRequest request, HttpServletResponse resp) throws IOException { String name = request.getParameter("name"); String des = request.getParameter("description"); String modelId = mock(name,des); resp.sendRedirect("modeler.html?modelId="+modelId); } private String mock(String name,String des){ try { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode editorNode = objectMapper.createObjectNode(); editorNode.put("id", "canvas"); editorNode.put("resourceId", "canvas"); ObjectNode stencilSetNode = objectMapper.createObjectNode(); stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#"); editorNode.put("stencilset", stencilSetNode); Model modelData = repositoryService.newModel(); ObjectNode modelObjectNode = objectMapper.createObjectNode(); modelObjectNode.put(MODEL_NAME, name); modelObjectNode.put(MODEL_REVISION, 1); String description = null; if (StringUtils.isNotEmpty(des)) { description = des; } else { description = ""; } modelObjectNode.put(MODEL_DESCRIPTION, description); modelData.setMetaInfo(modelObjectNode.toString()); modelData.setName(name); repositoryService.saveModel(modelData); repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8")); return modelData.getId(); } catch(Exception e) { e.printStackTrace(); return "0"; } } }
38.356164
111
0.694286
3317d57373ed51d9c2ebb415e80b27bd1af487b0
6,458
package com.hdev.exoplayer; import android.content.Context; import android.net.Uri; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.audio.TeeAudioProcessor; import com.google.android.exoplayer2.source.ConcatenatingMediaSource; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.upstream.AssetDataSource; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.upstream.FileDataSource; import com.google.android.exoplayer2.upstream.RawResourceDataSource; import com.google.android.exoplayer2.upstream.cache.CacheDataSource; import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory; import com.google.android.exoplayer2.util.Util; import com.hdev.exoplayer.data.AudioData; import com.hdev.exoplayer.renderer.RendererFactory; import com.hdev.exoplayer.util.DownloadUtils; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; /** * @author gdev (Hendriyawan) * craated at 23 sept 2019 */ public class BasePlayer { protected SimpleExoPlayer exoPlayer; protected HashMap<String, String> metaData; //exo player from single local file uri protected void prepareExoPlayerFromFileUri(Context context, Uri uri, ExoPlayer.EventListener eventListener) { exoPlayer = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector(), new DefaultLoadControl()); exoPlayer.addListener(eventListener); DataSource.Factory fileDataSource = FileDataSource::new; MediaSource mediaSource = new ExtractorMediaSource.Factory(fileDataSource).createMediaSource(uri); exoPlayer.prepare(mediaSource); } //build media source from single file asset folder protected void prepareExoPlayerFromFileAssetUri(Context context, Uri uri, ExoPlayer.EventListener eventListener) { exoPlayer = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector(), new DefaultLoadControl()); exoPlayer.addListener(eventListener); DataSource.Factory assetDataSource = () -> new AssetDataSource(context); MediaSource mediaSource = new ExtractorMediaSource.Factory(assetDataSource).createMediaSource(uri); exoPlayer.prepare(mediaSource); } //exo player from URL //popular audiofile types (mp3, m4a..) protected void prepareExoPlayerFromURL(Context context, List<AudioData> audioDataList, ExoPlayer.EventListener eventListener) { exoPlayer = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector()); exoPlayer.addListener(eventListener); DefaultDataSourceFactory defaultDataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, BuildConfig.APPLICATION_ID)); //for support offline mode CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(DownloadUtils.getCache(context), defaultDataSourceFactory, CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR); ConcatenatingMediaSource concatenatingMediaSource = new ConcatenatingMediaSource(); for (AudioData audioData : audioDataList) { Uri uri = audioData.getUri(); MediaSource mediaSource = new ExtractorMediaSource.Factory(cacheDataSourceFactory).createMediaSource(uri); concatenatingMediaSource.addMediaSource(mediaSource); } exoPlayer.prepare(concatenatingMediaSource); } //exo player from raw source protected void prepareExoPlayerFromRawResourceUri(Context context, Uri uri, ExoPlayer.EventListener eventListener) { exoPlayer = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector(), new DefaultLoadControl()); exoPlayer.addListener(eventListener); DataSource.Factory rawDataSource = () -> new RawResourceDataSource(context); MediaSource mediaSource = new ExtractorMediaSource.Factory(rawDataSource).createMediaSource(uri); exoPlayer.prepare(mediaSource); } //exo player from list local files protected void prepareExoPlayerFromListLocalFile(Context context, List<AudioData> audioDataList, ExoPlayer.EventListener eventListener) { exoPlayer = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector(), new DefaultLoadControl()); exoPlayer.addListener(eventListener); ConcatenatingMediaSource concatenatingMediaSource = new ConcatenatingMediaSource(); for (AudioData audioData : audioDataList) { Uri uri = audioData.getUri(); DataSource.Factory fileDataSource = FileDataSource::new; MediaSource mediaSource = new ExtractorMediaSource.Factory(fileDataSource).createMediaSource(uri); concatenatingMediaSource.addMediaSource(mediaSource); } exoPlayer.prepare(concatenatingMediaSource); } //exo player from list asset file protected void prepareExoPlayerFromListAssetFile(Context context, List<AudioData> audioDataList, ExoPlayer.EventListener eventListener) { RendererFactory rendererFactory = new RendererFactory(context, new TeeAudioProcessor.AudioBufferSink() { @Override public void flush(int sampleRateHz, int channelCount, int encoding) { } @Override public void handleBuffer(ByteBuffer buffer) { } }); exoPlayer = ExoPlayerFactory.newSimpleInstance(context, rendererFactory, new DefaultTrackSelector(), new DefaultLoadControl()); exoPlayer.addListener(eventListener); ConcatenatingMediaSource concatenatingMediaSource = new ConcatenatingMediaSource(); for (AudioData audioData : audioDataList) { Uri uri = audioData.getUri(); DataSource.Factory assetDataSource = () -> new AssetDataSource(context); MediaSource mediaSource = new ExtractorMediaSource.Factory(assetDataSource).createMediaSource(uri); concatenatingMediaSource.addMediaSource(mediaSource); } exoPlayer.prepare(concatenatingMediaSource); } }
48.924242
186
0.765407
bf6031a937a9d35d4f00b87437cc387055bcd98a
312
package com.cloud.base.user.repository.dao.mapper; import com.cloud.base.user.repository.entity.SysRes; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * 用户中心-资源表 * * @author lh0811 * @email lh0811 * @date 2022-01-05 18:01:19 */ public interface SysResMapper extends BaseMapper<SysRes> { }
18.352941
58
0.74359
a5360dc97d3030e2a53165b8ebbeb221f64c75b0
31,081
package cn.org.rapid_framework.generator.provider.db.table; import cn.org.rapid_framework.generator.GeneratorProperties; import cn.org.rapid_framework.generator.common.GeneratorConsts; import cn.org.rapid_framework.generator.provider.DatabaseMetaDatCache; import cn.org.rapid_framework.generator.provider.db.DataSourceProvider; import cn.org.rapid_framework.generator.provider.db.table.model.Column; import cn.org.rapid_framework.generator.provider.db.table.model.Table; import cn.org.rapid_framework.generator.util.*; import cn.org.rapid_framework.generator.util.XMLHelper.NodeData; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.sql.*; import java.text.MessageFormat; import java.util.*; /** * * 根据数据库表的元数据(metadata)创建Table对象 * * <pre> * getTable(sqlName) : 根据数据库表名,得到table对象 * getAllTable() : 搜索数据库的所有表,并得到table对象列表 * </pre> * @author badqiu * @email badqiu(a)gmail.com */ public class TableFactory { private static final Logger logger= LoggerFactory.getLogger(TableFactory.class); private DbHelper dbHelper = new DbHelper(); private static TableFactory instance = null; private TableFactory() { } public synchronized static TableFactory getInstance() { if(instance == null) instance = new TableFactory(); return instance; } public String getCatalog() { return GeneratorProperties.getNullIfBlank("jdbc.catalog"); } public String getSchema() { return GeneratorProperties.getNullIfBlank("jdbc.schema"); } private Connection getConnection() { return DataSourceProvider.getConnection(); } public List getAllTables() { try { Connection conn = getConnection(); return getAllTables(conn); }catch(Exception e) { throw new RuntimeException(e); } } public Table getTable(String tableName) { return getTable(getSchema(),tableName); } private Table getTable(String schema, String tableName) { return getTable(getCatalog(),schema,tableName); } private Table getTable(String catalog, String schema, String tableName) { Table t = null; try { t = buildTableMetadata(catalog, schema, tableName); }catch(Exception e) { throw new RuntimeException(e); } // if(t == null) { // throw new NotFoundTableException("not found table with give name:"+tableName+ (dbHelper.isOracleDataBase() ? " \n databaseStructureInfo:"+getDatabaseStructureInfo() : "")); // } return t; } public static class NotFoundTableException extends RuntimeException { private static final long serialVersionUID = 5976869128012158628L; public NotFoundTableException(String message) { super(message); } } private Table _getTable(String catalog, String schema, String tableName) throws SQLException { if(tableName== null || tableName.trim().length() == 0) throw new IllegalArgumentException("tableName must be not empty"); catalog = StringHelper.defaultIfEmpty(catalog, null); schema = StringHelper.defaultIfEmpty(schema, null); Connection conn = getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); String localCatalog=catalog; String localSchema=schema; if(!dbMetaData.storesLowerCaseIdentifiers() && dbMetaData.storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); tableName=tableName.toLowerCase(); } ResultSet rs = dbMetaData.getTables(localCatalog, localSchema, tableName, new String[] {GeneratorConsts.DATABASE_METADATA_TABLE_TYPE_TABLE}); while(rs.next()) { Table table = createTable(conn, rs); return table; } return null; } /** * 构建数据表元数据 * @param catalog * @param schema * @param tableName * @return * @throws SQLException */ private Table buildTableMetadata(String catalog, String schema, String tableName) throws SQLException{ if(StringUtils.isNotEmpty(tableName) && DatabaseMetaDatCache.exist(tableName)) { return DatabaseMetaDatCache.get(tableName); } List<Table> tables=listTableMetadata(catalog, schema, tableName); if(tables.size()<1) { logger.error(MessageFormat.format("数据库表: {0} 不存在", tableName)); return null; } Table table=tables.get(0); List<String> primaryKeys = listTablePrimaryKey(table); //listTableIndex(table); oracle有些表取数据表索引信息会卡死,影响代码生成 List<String> indexs =null; List<Map<Integer, Object>> exportkeys = listTableExportForeignKey(table); for (Map<Integer, Object> map : exportkeys) { table.addExportedKey(map); } List<Map<Integer, Object>> importKeys = listTableImportForeignKey(table); for (Map<Integer, Object> map : importKeys) { table.addImportedKey(map); } LinkedList<Column> columns = listColumnMetadata(table, primaryKeys,indexs); for (Column column : columns) { table.addColumn(column); } DatabaseMetaDatCache.add(table.getSqlName(), table); return table; } /** * 返回表基本元数据 * @param catalog * @param schema * @param tableName * @return * @throws SQLException */ private List<Table> listTableMetadata(String catalog, String schema, String tableName) throws SQLException { if(StringUtils.isEmpty(tableName)) { tableName=null; } Connection conn = getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); String localCatalog=catalog; String localSchema=schema; if(!dbMetaData.storesLowerCaseIdentifiers() && dbMetaData.storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); //tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); //tableName=tableName.toLowerCase(); } ResultSet rs=null; List<Table> tables=new ArrayList<Table>(); try { rs = dbMetaData.getTables(localCatalog, localSchema, tableName, new String[] {GeneratorConsts.DATABASE_METADATA_TABLE_TYPE_TABLE}); Table table=null; while(rs.next()) { table = new Table(); table.setSqlName(rs.getString(GeneratorConsts.DATABASE_METADATA_TABLE_NAME)); table.setRemarks(rs.getString(GeneratorConsts.DATABASE_METADATA_REMARKS)); tables.add(table); } }catch (SQLException e) { logger.warn(MessageFormat.format("取数据库表元数据信息异常,表:{0}", tableName),e); throw e; }finally { try { rs.close(); }catch (Exception e) { } } return tables; } /** * 取主键 * @param table * @return * @throws SQLException */ private List<String> listTablePrimaryKey(Table table) throws SQLException { String localCatalog=getCatalog(); String localSchema=getSchema(); String tableName=table.getSqlName(); if(!getMetaData().storesLowerCaseIdentifiers() && getMetaData().storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); //tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); //tableName=tableName.toLowerCase(); } // get the primary keys List<String> primaryKeys = new LinkedList<String>(); ResultSet primaryKeyRs = null; primaryKeyRs = getMetaData().getPrimaryKeys(localCatalog, localSchema, tableName); while (primaryKeyRs.next()) { String columnName = primaryKeyRs.getString(GeneratorConsts.DATABASE_METADATA_COLUMN_NAME); logger.trace(MessageFormat.format("primary key:", columnName)); primaryKeys.add(columnName); } primaryKeyRs.close(); return primaryKeys; } /** * 取导出外键 * @param table * @return * @throws SQLException */ private List<Map<Integer,Object>> listTableExportForeignKey(Table table) throws SQLException { String localCatalog=getCatalog(); String localSchema=getSchema(); String tableName=table.getSqlName(); if(!getMetaData().storesLowerCaseIdentifiers() && getMetaData().storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); //tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); //tableName=tableName.toLowerCase(); } ResultSet fkeys=null; List<Map<Integer,Object>> keys=new ArrayList<Map<Integer,Object>>(); try { fkeys = getMetaData().getExportedKeys(localCatalog , localSchema, tableName); Map<Integer,Object> key=null; while ( fkeys.next()) { String pktable = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_PKTABLE_NAME); String pkcol = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_PKCOLUMN_NAME); String fktable = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_FKTABLE_NAME); String fkcol = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_FKCOLUMN_NAME); String seq = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_KEY_SEQ); Integer iseq = new Integer(seq); key=new HashMap<Integer, Object>(); key.put(0, fktable); key.put(0, fkcol); key.put(0, pkcol); key.put(0, iseq); keys.add(key); } }catch (SQLException e) { logger.warn(MessageFormat.format("取数据库表的导出外键信息异常,表:{0}", tableName),e); throw e; }finally { try { fkeys.close(); }catch (Exception e) { } } return keys; } /** * 取导入外键 * @param table * @return * @throws SQLException */ private List<Map<Integer,Object>> listTableImportForeignKey(Table table) throws SQLException { String localCatalog=getCatalog(); String localSchema=getSchema(); String tableName=table.getSqlName(); if(!getMetaData().storesLowerCaseIdentifiers() && getMetaData().storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); //tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); //tableName=tableName.toLowerCase(); } ResultSet fkeys=null; List<Map<Integer,Object>> keys=new ArrayList<Map<Integer,Object>>(); try { fkeys = getMetaData().getImportedKeys(localCatalog, localSchema, tableName); Map<Integer,Object> key=null; while ( fkeys.next()) { String pktable = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_PKTABLE_NAME); String pkcol = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_PKCOLUMN_NAME); String fktable = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_FKTABLE_NAME); String fkcol = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_FKCOLUMN_NAME); String seq = fkeys.getString(GeneratorConsts.DATABASE_METADATA_TABLE_KEY_SEQ); Integer iseq = new Integer(seq); key=new HashMap<Integer, Object>(); key.put(0, fktable); key.put(0, fkcol); key.put(0, pkcol); key.put(0, iseq); keys.add(key); } }catch (SQLException e) { logger.warn(MessageFormat.format("取数据库表的导入外键信息异常,表:{0}", tableName),e); throw e; }finally { try { fkeys.close(); }catch (Exception e) { // TODO: handle exception } } return keys; } /** * 返回表索引 * @param table * @return * @throws SQLException */ public List<String> listTableIndex(Table table) throws SQLException{ List<String> indices=new ArrayList<String>(); String localCatalog=getCatalog(); String localSchema=getSchema(); String tableName=table.getSqlName(); if(!getMetaData().storesLowerCaseIdentifiers() && getMetaData().storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); //tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); //tableName=tableName.toLowerCase(); } ResultSet indexRs = null; try { indexRs = getMetaData().getIndexInfo(localCatalog, localSchema, tableName, false, true); while (indexRs.next()) { String columnName = indexRs.getString(GeneratorConsts.DATABASE_METADATA_COLUMN_NAME); if (columnName != null) { logger.trace(MessageFormat.format("表:{0} 索引:", tableName, columnName)); indices.add(columnName); } } //indexRs.close(); return indices; }catch (SQLException e) { logger.warn(MessageFormat.format("取数据库的索引信息异常,表:{0}", tableName),e); //throw e; }finally { try { indexRs.close(); }catch (Exception e) { } } return indices; } /** * 取字段元数据 * @param table * @param primaryKeys * @return * @throws SQLException */ private LinkedList<Column> listColumnMetadata(Table table, List<String> primaryKeys, List<String> indices) throws SQLException{ String localCatalog=getCatalog(); String localSchema=getSchema(); String tableName=table.getSqlName(); if(!getMetaData().storesLowerCaseIdentifiers() && getMetaData().storesUpperCaseIdentifiers()) { localCatalog=localCatalog.toUpperCase(); localSchema=localSchema.toUpperCase(); //tableName=tableName.toUpperCase(); }else { localCatalog=localCatalog.toLowerCase(); localSchema=localSchema.toLowerCase(); //tableName=tableName.toLowerCase(); } ResultSet columnRs = null; LinkedList<Column> columns=new LinkedList<Column>(); try { columnRs = getMetaData().getColumns(localCatalog, localSchema, tableName, null); while (columnRs.next()) { int sqlType = columnRs.getInt("DATA_TYPE"); String sqlTypeName = columnRs.getString("TYPE_NAME"); String columnName = columnRs.getString("COLUMN_NAME"); String columnDefaultValue = columnRs.getString("COLUMN_DEF"); String remarks = columnRs.getString("REMARKS"); if(remarks == null && dbHelper.isOracleDataBase()) { remarks = getOracleColumnComments(table.getSqlName(), columnName); } // if columnNoNulls or columnNullableUnknown assume "not nullable" boolean isNullable = (DatabaseMetaData.columnNullable == columnRs.getInt("NULLABLE")); int size = columnRs.getInt("COLUMN_SIZE"); int decimalDigits = columnRs.getInt("DECIMAL_DIGITS"); boolean isPk = primaryKeys.contains(columnName); boolean isIndexed =indices==null ? false : indices.contains(columnName); Column column = new Column( table, sqlType, sqlTypeName, columnName, size, decimalDigits, isPk, isNullable, isIndexed, false, columnDefaultValue, remarks); // BeanHelper.copyProperties(column, TableOverrideValuesProvider.getColumnOverrideValues(table,column)); columns.add(column); } }catch (SQLException e) { logger.error(MessageFormat.format("取得数据表字段元数据异常,表: {0}",tableName),e); throw e; }finally { try { columnRs.close(); }catch (Exception e) { // TODO: handle exception } } return columns; } private Table createTable(Connection conn, ResultSet rs) throws SQLException { String realTableName = null; try { //ResultSetMetaData rsMetaData = rs.getMetaData(); String schemaName = rs.getString("TABLE_SCHEM") == null ? "" : rs.getString("TABLE_SCHEM"); realTableName = rs.getString("TABLE_NAME"); String tableType = rs.getString("TABLE_TYPE"); String remarks = rs.getString("REMARKS"); //rs.close(); if(remarks == null && dbHelper.isOracleDataBase()) { remarks = getOracleTableComments(realTableName); } Table table = new Table(); table.setSqlName(realTableName); table.setRemarks(remarks); if ("SYNONYM".equals(tableType) && dbHelper.isOracleDataBase()) { table.setOwnerSynonymName(getSynonymOwner(realTableName)); } retriveTableColumns(table); table.initExportedKeys(conn.getMetaData()); table.initImportedKeys(conn.getMetaData()); // BeanHelper.copyProperties(table, TableOverrideValuesProvider.getTableOverrideValues(table.getSqlName())); return table; }catch(SQLException e) { throw new RuntimeException("create table object error,tableName:"+realTableName,e); } } private List getAllTables(Connection conn) throws SQLException { DatabaseMetaData dbMetaData = conn.getMetaData(); ResultSet rs = dbMetaData.getTables(getCatalog(), getSchema(), null, new String[] {GeneratorConsts.DATABASE_METADATA_TABLE_TYPE_TABLE}); List tables = new ArrayList(); while(rs.next()) { tables.add(createTable(conn, rs)); } return tables; } private String getSynonymOwner(String synonymName) { PreparedStatement ps = null; ResultSet rs = null; String ret = null; try { ps = getConnection().prepareStatement("select table_owner from sys.all_synonyms where table_name=? and owner=?"); ps.setString(1, synonymName); ps.setString(2, getSchema()); rs = ps.executeQuery(); if (rs.next()) { ret = rs.getString(1); } else { String databaseStructure = getDatabaseStructureInfo(); throw new RuntimeException("Wow! Synonym " + synonymName + " not found. How can it happen? " + databaseStructure); } } catch (SQLException e) { String databaseStructure = getDatabaseStructureInfo(); GLogger.error(e.getMessage(), e); throw new RuntimeException("Exception in getting synonym owner " + databaseStructure); } finally { dbHelper.close(rs,ps); } return ret; } private String getDatabaseStructureInfo() { ResultSet schemaRs = null; ResultSet catalogRs = null; String nl = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer(nl); // Let's give the user some feedback. The exception // is probably related to incorrect schema configuration. sb.append("Configured schema:").append(getSchema()).append(nl); sb.append("Configured catalog:").append(getCatalog()).append(nl); try { schemaRs = getMetaData().getSchemas(); sb.append("Available schemas:").append(nl); while (schemaRs.next()) { sb.append(" ").append(schemaRs.getString("TABLE_SCHEM")).append(nl); } } catch (SQLException e2) { GLogger.warn("Couldn't get schemas", e2); sb.append(" ?? Couldn't get schemas ??").append(nl); } finally { dbHelper.close(schemaRs,null); } try { catalogRs = getMetaData().getCatalogs(); sb.append("Available catalogs:").append(nl); while (catalogRs.next()) { sb.append(" ").append(catalogRs.getString("TABLE_CAT")).append(nl); } } catch (SQLException e2) { GLogger.warn("Couldn't get catalogs", e2); sb.append(" ?? Couldn't get catalogs ??").append(nl); } finally { dbHelper.close(catalogRs,null); } return sb.toString(); } private DatabaseMetaData getMetaData() throws SQLException { return getConnection().getMetaData(); } private void retriveTableColumns(Table table) throws SQLException { GLogger.trace("-------setColumns(" + table.getSqlName() + ")"); List primaryKeys = getTablePrimaryKeys(table); table.setPrimaryKeyColumns(primaryKeys); // get the indices and unique columns List indices = new LinkedList(); // maps index names to a list of columns in the index Map uniqueIndices = new HashMap(); // maps column names to the index name. Map uniqueColumns = new HashMap(); ResultSet indexRs = null; try { if (table.getOwnerSynonymName() != null) { indexRs = getMetaData().getIndexInfo(getCatalog(), table.getOwnerSynonymName(), table.getSqlName(), false, true); } else { indexRs = getMetaData().getIndexInfo(getCatalog(), getSchema(), table.getSqlName(), false, true); } while (indexRs.next()) { String columnName = indexRs.getString("COLUMN_NAME"); if (columnName != null) { GLogger.trace("index:" + columnName); indices.add(columnName); } // now look for unique columns String indexName = indexRs.getString("INDEX_NAME"); boolean nonUnique = indexRs.getBoolean("NON_UNIQUE"); if (!nonUnique && columnName != null && indexName != null) { List l = (List)uniqueColumns.get(indexName); if (l == null) { l = new ArrayList(); uniqueColumns.put(indexName, l); } l.add(columnName); uniqueIndices.put(columnName, indexName); GLogger.trace("unique:" + columnName + " (" + indexName + ")"); } } } catch (Throwable t) { // Bug #604761 Oracle getIndexInfo() needs major grants // http://sourceforge.net/tracker/index.php?func=detail&aid=604761&group_id=36044&atid=415990 logger.error("取数据库表索引信息失败", t); } finally { dbHelper.close(indexRs,null); } List columns = getTableColumns(table, primaryKeys, indices, uniqueIndices, uniqueColumns); for (Iterator i = columns.iterator(); i.hasNext(); ) { Column column = (Column)i.next(); table.addColumn(column); } // In case none of the columns were primary keys, issue a warning. if (primaryKeys.size() == 0) { //GLogger.warn("WARNING: The JDBC driver didn't report any primary key columns in " + table.getSqlName()); logger.warn(MessageFormat.format("WARNING: The JDBC driver didn't report any primary key columns in {0}", table.getSqlName())); } } private List getTableColumns(Table table, List primaryKeys, List indices, Map uniqueIndices, Map uniqueColumns) throws SQLException { // get the columns List columns = new LinkedList(); ResultSet columnRs = getColumnsResultSet(table); while (columnRs.next()) { int sqlType = columnRs.getInt("DATA_TYPE"); String sqlTypeName = columnRs.getString("TYPE_NAME"); String columnName = columnRs.getString("COLUMN_NAME"); String columnDefaultValue = columnRs.getString("COLUMN_DEF"); String remarks = columnRs.getString("REMARKS"); if(remarks == null && dbHelper.isOracleDataBase()) { remarks = getOracleColumnComments(table.getSqlName(), columnName); } // if columnNoNulls or columnNullableUnknown assume "not nullable" boolean isNullable = (DatabaseMetaData.columnNullable == columnRs.getInt("NULLABLE")); int size = columnRs.getInt("COLUMN_SIZE"); int decimalDigits = columnRs.getInt("DECIMAL_DIGITS"); boolean isPk = primaryKeys.contains(columnName); boolean isIndexed = indices.contains(columnName); String uniqueIndex = (String)uniqueIndices.get(columnName); List columnsInUniqueIndex = null; if (uniqueIndex != null) { columnsInUniqueIndex = (List)uniqueColumns.get(uniqueIndex); } boolean isUnique = columnsInUniqueIndex != null && columnsInUniqueIndex.size() == 1; if (isUnique) { GLogger.trace("unique column:" + columnName); } Column column = new Column( table, sqlType, sqlTypeName, columnName, size, decimalDigits, isPk, isNullable, isIndexed, isUnique, columnDefaultValue, remarks); // BeanHelper.copyProperties(column, TableOverrideValuesProvider.getColumnOverrideValues(table,column)); columns.add(column); } columnRs.close(); return columns; } private ResultSet getColumnsResultSet(Table table) throws SQLException { ResultSet columnRs = null; if (table.getOwnerSynonymName() != null) { columnRs = getMetaData().getColumns(getCatalog(), table.getOwnerSynonymName(), table.getSqlName(), null); } else { columnRs = getMetaData().getColumns(getCatalog(), getSchema(), table.getSqlName(), null); } return columnRs; } private List<String> getTablePrimaryKeys(Table table) throws SQLException { // get the primary keys List primaryKeys = new LinkedList(); ResultSet primaryKeyRs = null; if (table.getOwnerSynonymName() != null) { primaryKeyRs = getMetaData().getPrimaryKeys(getCatalog(), table.getOwnerSynonymName(), table.getSqlName()); } else { primaryKeyRs = getMetaData().getPrimaryKeys(getCatalog(), getSchema(), table.getSqlName()); } while (primaryKeyRs.next()) { String columnName = primaryKeyRs.getString("COLUMN_NAME"); logger.trace(MessageFormat.format("primary key:", columnName)); //GLogger.trace("primary key:" + columnName); primaryKeys.add(columnName); } primaryKeyRs.close(); return primaryKeys; } private String getOracleTableComments(String table) { String sql = "SELECT comments FROM user_tab_comments WHERE table_name='"+table+"'"; return dbHelper.queryForString(sql); } private String getOracleColumnComments(String table,String column) { String sql = "SELECT comments FROM user_col_comments WHERE table_name='"+table+"' AND column_name = '"+column+"'"; return dbHelper.queryForString(sql); } /** 得到表的自定义配置信息 */ public static class TableOverrideValuesProvider { private static Map getTableOverrideValues(String tableSqlName){ NodeData nd = getTableConfigXmlNodeData(tableSqlName); if(nd == null) { return new HashMap(); } return nd == null ? new HashMap() : nd.attributes; } private static Map getColumnOverrideValues(Table table, Column column) { NodeData root = getTableConfigXmlNodeData(table.getSqlName()); if(root != null){ for(NodeData item : root.childs) { if(item.nodeName.equals("column")) { if(column.getSqlName().equalsIgnoreCase(item.attributes.get("sqlName"))) { return item.attributes; } } } } return new HashMap(); } private static NodeData getTableConfigXmlNodeData(String tableSqlName){ NodeData nd = getTableConfigXmlNodeData0(tableSqlName); if(nd == null) { nd = getTableConfigXmlNodeData0(tableSqlName.toLowerCase()); if(nd == null) { nd = getTableConfigXmlNodeData0(tableSqlName.toUpperCase()); } } return nd; } private static NodeData getTableConfigXmlNodeData0(String tableSqlName) { try { File file = FileHelper.getFileByClassLoader("generator_config/table/"+tableSqlName+".xml"); GLogger.trace("getTableConfigXml() load nodeData by tableSqlName:"+tableSqlName+".xml"); return new XMLHelper().parseXML(file); }catch(Exception e) {//ignore GLogger.trace("not found config xml for table:"+tableSqlName+", exception:"+e); return null; } } } class DbHelper { public void close(ResultSet rs,PreparedStatement ps,Statement... statements) { try { if(ps != null) ps.close(); if(rs != null) rs.close(); for(Statement s : statements) {s.close();} }catch(Exception e){ } } public boolean isOracleDataBase() { try { return DatabaseMetaDataUtils.isOracleDataBase(getMetaData()); } catch (SQLException e) { throw new RuntimeException(e); } } public String queryForString(String sql) { Statement s = null; ResultSet rs = null; try { s = getConnection().createStatement(); rs = s.executeQuery(sql); if(rs.next()) { return rs.getString(1); } return null; }catch(SQLException e) { e.printStackTrace(); return null; }finally { close(rs,null,s); } } } public static class DatabaseMetaDataUtils { public static boolean isOracleDataBase(DatabaseMetaData metadata) { try { boolean ret = false; ret = (metadata.getDatabaseProductName().toLowerCase() .indexOf("oracle") != -1); return ret; }catch(SQLException s) { return false; // throw new RuntimeException(s); } } public static boolean isHsqlDataBase(DatabaseMetaData metadata) { try { boolean ret = false; ret = (metadata.getDatabaseProductName().toLowerCase() .indexOf("hsql") != -1); return ret; }catch(SQLException s) { return false; // throw new RuntimeException(s); } } } // public void close() throws IOException { // // try { // if(getConnection()!=null || !getConnection().isClosed()) { // getConnection().close(); // } // } catch (SQLException e) { // logger.error("关闭数据库连接异常", e); // } // // } }
36.015064
177
0.626975
86144a7b96c2786e5dc3f8259e5c4d69cbf3e6fa
3,216
package evolith.helpers; import java.awt.Color; /** *a * @author Erick González * @author Carlos Estrada * @author Víctor Villarreal * @author Moisés Fernández */ public interface Commons { public static final int ORGANISM_SIZE = 30; // organism size public static final int INITIAL_POINT = 1000; // inital point public static final int MAX_ORGANISM_AMOUNT = 256; // maximum organism amount public static final int PLANT_SIZE = 100; // plant quanitity per unit public static final int FRAME_RATE = 60; // frame rate public static final int MAX_THIRST = 100; // maximum water level of organism public static final int MAX_HUNGER = 100; // maximum hunger level of organism public static final int MAX_MATURITY = 30; // maximum maturity level of organism public static final int MAX_SPEED = 100; // maximum maturity level of organism public static final int MAX_SIZE = 100; // maximum maturity level of organism public static final int MAX_STRENGTH = 100; // maximum maturity level of organism public static final int MAX_SURVIVABILITY = 100; // maximum maturity level of organism public static final int MAX_STEALTH = 100; // maximum maturity level of organism public static final int PLANTS_AMOUNT = 150; // number of plants public static final int WATERS_AMOUNT = 150; public static final int WATER_SIZE = 100; public static final int SWARM_SEPARATION = ORGANISM_SIZE+10; public static final int SECONDS_PER_HUNGER = 3; public static final int SECONDS_PER_THIRST = 3; public static final int SECONDS_PER_MATURITY = 1; public static final int BUTTON_PLAY_X = 340; public static final int BUTTON_PLAY_Y = 390; public static final int PANEL_X = 700; public static final int PANEL_Y = 250; public static final int PANEL_WIDTH = 245; public static final int PANEL_HEIGHT = 350; public static final int BUTTON_CLOSE_DIMENSION = 40; public static final int BUTTON_INSTRUCTIONS_Y = 530; public static final int BUTTON_INSTRUCTIONS_X = 340; public static final int BUTTON_PLAY_WIDTH = 350; public static final int BUTTON_PLAY_HEIGHT = 110; public static final int BUTTON_INSTRUCTIONS_WIDTH = 350; public static final int BUTTON_INSTRUCTIONS_HEIGHT = 110; public static final int MINIMAP_X = 810; public static final int MINIMAP_Y = 20; public static final int BACKGROUND_WIDTH = 5000; public static final int BACKGROUND_HEIGHT = 5000; public static final int MINIMAP_WIDTH = BACKGROUND_WIDTH / 30; // 166~ public static final int MINIMAP_HEIGHT = BACKGROUND_HEIGHT / 30; // 166~ public static final Color PURPLE_COLOR = new Color(235, 64, 255); public static final Color BLUE_GREEN_COLOR = new Color(1, 196, 181); public static final Color ORANGE_COLOR = new Color(239, 186, 1); public static final Color PINK_COLOR = new Color(255, 111, 199); public static final int CONSUMING_RATE = 2; }
44.054795
103
0.681903
083ec9482086c7bc42d7e8fdfb41227841b2c8e2
217
package ru.job4j.linkedlist; /** * Интерфейс для связанного списка. * * @author Evgenii Kapaev * @since 23.01.22 */ public interface List<E> extends Iterable<E> { void add(E value); E get(int index); }
15.5
46
0.658986
9e77f6023d8cd75b5c42ca437de6f11e7a72b717
2,239
package com.jeanboy.component.permission.utils; import android.content.Context; import android.os.Binder; import android.os.Build; import android.provider.Settings; import android.view.WindowManager; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * @author caojianbo * @since 2019/12/26 15:53 */ public class OverlaysUtil { /** * 是否有悬浮窗权限 * * @param context * @return */ public static boolean isCanDraw(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 6.0 以上 return Settings.canDrawOverlays(context); } else { // 6.0 以下 try { Class cls = Class.forName("android.content.Context"); Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE"); declaredField.setAccessible(true); Object obj = declaredField.get(cls); if (!(obj instanceof String)) { return false; } String str2 = (String) obj; obj = cls.getMethod("getSystemService", String.class).invoke(context, str2); cls = Class.forName("android.app.AppOpsManager"); Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED"); declaredField2.setAccessible(true); Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class); int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName()); return result == declaredField2.getInt(cls); } catch (Exception e) { return false; } } } /** * 获取带 type 的 LayoutParams * * @return */ public static WindowManager.LayoutParams getLayoutParamsWithType() { WindowManager.LayoutParams params = new WindowManager.LayoutParams(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0 以上 params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; } return params; } }
33.41791
100
0.594462
0631817020614836e5e0030d1bc4036e3d297392
1,581
package org.kairosdb.core.processingstage; import com.google.common.collect.ImmutableList; import org.kairosdb.core.processingstage.metadata.FeatureProcessingMetadata; public interface FeatureProcessor { /** * Returns an {@link ImmutableList} of {@link FeatureProcessingFactory} * instances for the feature. * * @return the {@link ImmutableList} describing the feature */ ImmutableList<FeatureProcessingFactory<?>> getFeatureProcessingFactories(); /** * Returns an {@link FeatureProcessingFactory} instance which can generate * features. * The feature processor type must be specified in parameters. * * @param feature feature type generated by the {@link FeatureProcessingFactory} * @return instance of {@link FeatureProcessingFactory} */ FeatureProcessingFactory<?> getFeatureProcessingFactory(Class<?> feature); /** * Returns an {@link FeatureProcessingFactory} instance whose can generate feature processors. * The {@link FeatureProcessingFactory} name must be specified in parameters. * * @param feature name of the {@link FeatureProcessingFactory} * @return instance of {@link FeatureProcessingFactory} */ FeatureProcessingFactory<?> getFeatureProcessingFactory(String feature); /** * Returns an {@link ImmutableList} of {@link FeatureProcessingMetadata} * describing the feature. * * @return the {@link ImmutableList} describing the feature */ ImmutableList<FeatureProcessingMetadata> getFeatureProcessingMetadata(); }
35.931818
98
0.724225
35f2550f21474b2eabdefd5503bcefbb60fe839d
2,262
package ava.coding.challenge.main.organization; import ava.coding.challenge.main.organization.access.rights.AccessRightsService; import ava.coding.challenge.main.organization.entities.MasterOrganization; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class MasterOrganizationController { @Autowired private MasterOrganizationService masterOrganizationService; @Autowired private AccessRightsService accessRightsService; @RequestMapping("/master-organizations") public List<MasterOrganization> getAllMasterOrganizations() { return masterOrganizationService.getAllMasterOrganizations(); } @RequestMapping("/master-organizations/{id}") public MasterOrganization getMasterOrganization(@PathVariable String id) { return masterOrganizationService.getMasterOrganization(id); } @RequestMapping(method = RequestMethod.POST, value = "/master-organizations") public void addNewMasterOrganization(@RequestBody MasterOrganization masterOrganization) { masterOrganizationService.addMasterOrganization(masterOrganization); } @RequestMapping(method = RequestMethod.PATCH, value = "/master-organizations") public void addNewMasterOrganizationList(@RequestBody List<MasterOrganization> masterOrganizationList) { masterOrganizationList.forEach(masterOrganizationService::addMasterOrganization); } @RequestMapping(method = RequestMethod.PUT, value = "/master-organizations/{id}") public void updateMasterOrganization(@RequestBody MasterOrganization updatedMasterOrganization, @PathVariable String id) { masterOrganizationService.updateMasterOrganization(id, updatedMasterOrganization); } @RequestMapping(method = RequestMethod.DELETE, value = "/master-organizations/{id}") public void deleteMasterOrganization(@PathVariable("id") String id) { masterOrganizationService.deleteMasterOrganization(id); } @RequestMapping(method = RequestMethod.POST, value = "/master-organizations/approveRequest/{id}") public void approveRequest(@PathVariable("id") String id) { accessRightsService.approveRequest(id); } }
42.679245
126
0.78382
da698528a2b0cb1528fa647eae8d577c411c579e
861
package com.hiriver.unbiz.mysql.lib.protocol.binlog.extra; import com.hiriver.unbiz.mysql.lib.protocol.Request; /** * 描述mysql binlog的同步点。当一个事务结束时需要记录同步点,当重新同步时可以从该同步点继续同步。<br> * * <ul> * <li>mysql5.6.9之前,同步点是binlog file name + offset</li> * <li>mysql5.6.9之后,同步点可以是gtid,当从mysql从库复制数据时,当一个从库崩溃,可以自动切换到其他从库,此时 gtid特别有用,可以保证从正确的位置继续复制,但第一种方式不行</li> * </ul> * * @author hexiufeng * */ public interface BinlogPosition { /** * 转换binlog pos为dump指令 * * @param serverId 从库的唯一id,当前系统逻辑上就是一个从库 * @return dump指令请求 */ Request packetDumpRequest(int serverId); /** * 转换成可以存储的二进制流。缺省实现是调用当前对象的toString()方法,然后转换成byte数组 * * @return byte 数组 */ byte[] toBytesArray(); /** * 判断两个 pos是否相同 * * @param pos 所比较的位置 * @return 是否相同 */ boolean isSame(BinlogPosition pos); }
21.525
106
0.645761
ad8f0c5163768340e726c028facceb0e70ee756f
1,472
package io.github.boavenn.selfimprovementhelper.todos.todogroup.dto; import io.github.boavenn.selfimprovementhelper.todos.todo.model.Todo; import io.github.boavenn.selfimprovementhelper.todos.todogroup.model.TodoGroup; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Data @NoArgsConstructor public class TodoGroupDTO { private Long id; @NotNull(message = "Title cannot be null") @Length(min = 1, max = 40, message = "Title length must be between {min} and {max} characters long") private String title; private List<Long> todos = new ArrayList<>(); private boolean done; private boolean pinned; private TodoGroupDTO(TodoGroup todoGroup) { this.id = todoGroup.getId(); this.title = todoGroup.getTitle(); this.todos = todoGroup.getTodos().stream() .mapToLong(Todo::getId) .boxed() .collect(Collectors.toList()); this.done = todoGroup.getTodos().stream().allMatch(Todo::isDone); this.pinned = todoGroup.isPinned(); } public static TodoGroupDTO from(TodoGroup todoGroup) { return new TodoGroupDTO(todoGroup); } public void setTitle(String title) { if (title != null) { this.title = title.trim(); } } }
28.862745
104
0.682745
b2883c5dccad16709f1e7fe59597ef1c407b4c61
193
package com.plaid.client.response; /** * Response from /sandbox/item/set_verification_status endpoint. */ public final class SandboxItemSetVerificationStatusResponse extends BaseResponse {}
27.571429
83
0.818653
297e9c34afbfbd8ac559e56b44a7f16682924568
5,184
/*- * ============LICENSE_START======================================================= * Copyright (C) 2020 Nordix Foundation. * ================================================================================ * 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. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.service; import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.CamundaVariableNameConstants.CREATE_NS_RESPONSE_PARAM_NAME; import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.CamundaVariableNameConstants.CREATE_NS_WORKFLOW_PROCESSING_EXCEPTION_PARAM_NAME; import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.Constants.TENANT_ID; import static org.slf4j.LoggerFactory.getLogger; import java.util.Optional; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.history.HistoricVariableInstance; import org.onap.so.etsi.nfvo.ns.lcm.model.InlineResponse400; import org.onap.so.etsi.nfvo.ns.lcm.model.NsInstancesNsInstance; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.common.base.Strings; /** * @author Waqas Ikram (waqas.ikram@est.tech) * */ @Service public class WorkflowQueryService { private static final Logger logger = getLogger(WorkflowQueryService.class); private final HistoryService camundaHistoryService; @Autowired public WorkflowQueryService(final HistoryService camundaHistoryService) { this.camundaHistoryService = camundaHistoryService; } public Optional<NsInstancesNsInstance> getCreateNsResponse(final String processInstanceId) { try { if (Strings.isNullOrEmpty(processInstanceId)) { logger.error("Invalid processInstanceId: {}", processInstanceId); return Optional.empty(); } final HistoricVariableInstance historicVariableInstance = getVariable(processInstanceId, CREATE_NS_RESPONSE_PARAM_NAME); if (historicVariableInstance != null) { logger.info("Found HistoricVariableInstance : {}", historicVariableInstance); final Object variableValue = historicVariableInstance.getValue(); if (variableValue instanceof NsInstancesNsInstance) { return Optional.ofNullable((NsInstancesNsInstance) variableValue); } logger.error("Unknown CreateNsResponse object type {} received value: {}", historicVariableInstance.getValue() != null ? variableValue.getClass() : null, variableValue); } } catch (final ProcessEngineException processEngineException) { logger.error("Unable to find {} variable using processInstanceId: {}", CREATE_NS_RESPONSE_PARAM_NAME, processInstanceId, processEngineException); } logger.error("Unable to find {} variable using processInstanceId: {}", CREATE_NS_RESPONSE_PARAM_NAME, processInstanceId); return Optional.empty(); } public Optional<InlineResponse400> getProblemDetails(final String processInstanceId) { try { final HistoricVariableInstance historicVariableInstance = getVariable(processInstanceId, CREATE_NS_WORKFLOW_PROCESSING_EXCEPTION_PARAM_NAME); logger.info("Found HistoricVariableInstance : {}", historicVariableInstance); final Object variableValue = historicVariableInstance.getValue(); if (variableValue instanceof InlineResponse400) { return Optional.ofNullable((InlineResponse400) variableValue); } logger.error("Unknown ProblemDetails object type {} received value: {}", historicVariableInstance.getValue() != null ? variableValue.getClass() : null, variableValue); } catch (final ProcessEngineException processEngineException) { logger.error("Unable to find {} variable using processInstanceId: {}", CREATE_NS_WORKFLOW_PROCESSING_EXCEPTION_PARAM_NAME, processInstanceId, processEngineException); } return Optional.empty(); } private HistoricVariableInstance getVariable(final String processInstanceId, final String name) { return camundaHistoryService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId) .variableName(name).tenantIdIn(TENANT_ID).singleResult(); } }
47.559633
134
0.687886
1a80f9638a5fe043272fecc6191504dd68fd9b6e
2,141
/** * 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.reef.runtime.common.utils; import org.apache.commons.lang.SerializationException; import org.apache.commons.lang.SerializationUtils; import org.apache.reef.annotations.audience.Private; import org.apache.reef.util.Optional; import javax.inject.Inject; import java.util.logging.Level; import java.util.logging.Logger; /** * Default implementation of ExceptionCodec that uses Java serialization as its implementation. */ @Private final class DefaultExceptionCodec implements ExceptionCodec { private static final Logger LOG = Logger.getLogger(DefaultExceptionCodec.class.getName()); @Inject DefaultExceptionCodec() { } @Override public Optional<Throwable> fromBytes(final byte[] bytes) { try { return Optional.<Throwable>of((Throwable) SerializationUtils.deserialize(bytes)); } catch (SerializationException | IllegalArgumentException e) { LOG.log(Level.FINE, "Unable to deserialize a Throwable.", e); return Optional.empty(); } } @Override public Optional<Throwable> fromBytes(final Optional<byte[]> bytes) { if (bytes.isPresent()) { return this.fromBytes(bytes.get()); } else { return Optional.empty(); } } @Override public byte[] toBytes(final Throwable throwable) { return SerializationUtils.serialize(throwable); } }
32.938462
95
0.744045
88b91b471db875d2af6dbad56639db6cf55c64a3
2,820
package p3.feedbackgenerator.htmlgenerator; import java.util.ArrayList; import p3.feedbackgenerator.message.CommentFeedbackMessage; import p3.feedbackgenerator.message.FeedbackMessage; import p3.feedbackgenerator.message.SyntaxFeedbackMessage; import p3.feedbackgenerator.token.FeedbackToken; public class HtmlTableTuple implements Comparable<HtmlTableTuple> { protected FeedbackMessage entity; protected int importanceScore; // to store how many matched characters protected int minCharacterLength; // to store how many matched tokens protected int matchedTokenLength; public HtmlTableTuple(FeedbackMessage entity) { super(); this.entity = entity; calculateImportanceScoreAndSetMatches(); } private void calculateImportanceScoreAndSetMatches() { // simply count how many characters involved. importanceScore = 0; if (entity instanceof CommentFeedbackMessage) { // if comment, each character is weighted double as it is more // suspicious CommentFeedbackMessage cf = (CommentFeedbackMessage) entity; importanceScore = 2 * (cf.getToken1().getContent().length() + cf .getToken2().getContent().length()); minCharacterLength = Math.min(cf.getToken1().getContent() .length(), cf.getToken2().getContent().length()); matchedTokenLength = 1; } else if (entity instanceof SyntaxFeedbackMessage) { // if syntax match SyntaxFeedbackMessage sf = (SyntaxFeedbackMessage) entity; // set the number of char as 0 int minCharacterLength1 = 0; int minCharacterLength2 = 0; // get the lists ArrayList<FeedbackToken> list1 = sf.getTokenList1(); ArrayList<FeedbackToken> list2 = sf.getTokenList2(); for (int i = 0; i < list1.size(); i++) { FeedbackToken ft1 = list1.get(i); FeedbackToken ft2 = list2.get(i); // set importance score importanceScore += ft1.getContent().length(); minCharacterLength1 += ft1.getContent().length(); importanceScore += ft2.getContent().length(); minCharacterLength2 += ft2.getContent().length(); } // set the number of min char minCharacterLength = Math.min(minCharacterLength1, minCharacterLength2); // set the number of matched token matchedTokenLength = list1.size(); } } @Override public int compareTo(HtmlTableTuple arg0) { // TODO Auto-generated method stub return -this.getImportanceScore() + arg0.getImportanceScore(); } public FeedbackMessage getEntity() { return entity; } public void setEntity(FeedbackMessage entity) { this.entity = entity; } public int getImportanceScore() { return importanceScore; } public void setImportanceScore(int importanceScore) { this.importanceScore = importanceScore; } public int getMinCharacterLength() { return minCharacterLength; } public int getMatchedTokenLength() { return matchedTokenLength; } }
30.652174
75
0.745035
b4e50540d7ffc9cbc2600d4243fec01baa1ea083
781
/******************************************************************** ********************************************************************/ package jtersow.interceptors; import jtersow.components.AppHandler; import jtersow.components.AppReflection; import jtersow.servlet.application.InterceptorHandler; public class ActionHandler extends InterceptorHandler{ /*======================================================= =======================================================*/ public void doHandler(AppHandler handler)throws Exception{ Object bean=handler.getBean(); String beanMethod=handler.getBeanMethod(); AppReflection reflection=handler.getReflection(); Object result=reflection.execute(bean,beanMethod); handler.setResult(result); } }
33.956522
70
0.527529
37e84cc3a0f937088538b5d89832af9720601919
2,241
/** * Copyright (c) 2015, 玛雅牛[李飞] (lifei@wellbole.com). * * 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.jfinal.plugin.zbus.coder; import java.util.Map; import org.zbus.net.http.Message; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Record; /** * @ClassName: JsonCoder * @Description: 基于Json实现的编码解码器 * @author 李飞 (lifei@wellbole.com) * @param <T> * @date 2015年8月11日 上午1:43:25 * @since V1.0.0 */ public class JsonCoder implements Coder { @Override public Message encode(Object obj) { Message msg = new Message(); if (obj instanceof Model) { Map<String, Object> map = com.jfinal.plugin.activerecord.CPI.getAttrs((Model<?>) obj); msg.setBody(JSON.toJSONString(map)); } else if (obj instanceof Record) { Map<String, Object> map = ((Record) obj).getColumns(); msg.setBody(JSON.toJSONString(map)); } else { msg.setBody(JSON.toJSONString(obj)); } return msg; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Object decode(Class<?> tClass, Message msg ) throws Exception { String textMsg = msg.getBodyString(); if (Model.class.isAssignableFrom(tClass)) { // JFinal内置Model类型 JSONObject jsonObj = JSON.parseObject(textMsg); Model model = (Model)tClass.newInstance(); model.setAttrs(jsonObj); return model; } else if (Record.class.isAssignableFrom(tClass)) { // JFinal内置Record类型 JSONObject jsonObj = JSON.parseObject(textMsg); Record rec = (Record)tClass.newInstance(); rec.setColumns(jsonObj); return rec; } else { // 其他类型 Object obj = JSON.parseObject(textMsg, tClass); return obj; } } }
29.88
89
0.709058
9fb1873c1b28916ea5188847be210f775992376e
1,310
/* * Copyright 2010-2021 James Pether Sörling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.service.data.impl; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.hack23.cia.service.data.api.DataDAO; /** * The Class DataDAOITest. */ public final class DataDAOITest extends AbstractServiceDataFunctionalIntegrationTest { /** The data DAO. */ @Autowired private DataDAO dataDAO; /** * Gets the id list test. * * @return the id list test * @throws Exception * the exception */ @Test public void getIdListTest() throws Exception { final List<String> idList = dataDAO.getIdList(); assertNotNull(idList); assertFalse(idList.isEmpty()); } }
25.192308
86
0.723664
cb2cfc7dd4fd525b65e962005d8d34cef7bef118
1,371
package com.farsunset.httpserver.netty.iohandler; import com.farsunset.httpserver.netty.http.NettyHttpResponse; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.ReferenceCountUtil; import org.springframework.stereotype.Component; @ChannelHandler.Sharable @Component /** * 在这里可以做拦截器,验证一些请求的合法性 */ public class InterceptorHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext context, Object msg) { if (isPassed((FullHttpRequest) msg)){ /** * 提交给下一个ChannelHandler去处理 * 并且不需要调用ReferenceCountUtil.release(msg);来释放引用计数 */ context.fireChannelRead(msg); return; } /** * 非异常引起的错误需要手动关闭channel通道 */ ReferenceCountUtil.release(msg); context.writeAndFlush(NettyHttpResponse.make(HttpResponseStatus.UNAUTHORIZED)).addListener(ChannelFutureListener.CLOSE); } /** * 修改实现来验证合法性 * @param request * @return */ private boolean isPassed(FullHttpRequest request){ return true; } }
29.170213
128
0.71116
26d85b815c9197c656a3e8ebe95d8f5e9a802eb3
1,359
/* * Copyright 2004-2010 the Seasar Foundation and the Others. * * 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.seasar.doma.internal.jdbc.dialect; import org.seasar.doma.internal.jdbc.sql.SimpleSqlNodeVisitor; import org.seasar.doma.internal.jdbc.sql.node.AnonymousNode; import org.seasar.doma.jdbc.SqlNode; /** * @author taedium * */ public class StandardCountCalculatingTransformer extends SimpleSqlNodeVisitor<SqlNode, Void> { protected boolean processed; public SqlNode transform(SqlNode sqlNode) { AnonymousNode result = new AnonymousNode(); for (SqlNode child : sqlNode.getChildren()) { result.appendNode(child.accept(this, null)); } return result; } @Override protected SqlNode defaultAction(SqlNode node, Void p) { return node; } }
30.886364
71
0.716703
b50140e93e763aec5771145c4df7201dd14f87cc
3,163
/** * */ package org.ovirt.engine.core.bll.adbroker; import java.security.PrivilegedAction; import javax.naming.directory.SearchControls; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import org.ovirt.engine.core.ldap.LdapProviderType; import org.springframework.ldap.core.NameClassPairCallbackHandler; import org.springframework.ldap.core.support.DirContextAuthenticationStrategy; import org.springframework.ldap.core.support.LdapContextSource; /** * */ public class GSSAPILdapTemplateWrapper extends LDAPTemplateWrapper { private LoginContext loginContext; public GSSAPILdapTemplateWrapper(LdapContextSource contextSource, String userName, String password, String path) { super(contextSource, userName, password, path); } /** * */ /* * (non-Javadoc) * * @see * org.ovirt.engine.core.dal.adbroker.LDapTemplateWrapper#search(java.lang.String * , java.lang.String, javax.naming.directory.SearchControls, * org.springframework.ldap.core.NameClassPairCallbackHandler) */ @Override public void search(String baseDN, String filter, String displayFilter, SearchControls searchControls, NameClassPairCallbackHandler handler) { Subject.doAs(loginContext.getSubject(), new SearchAction(baseDN, filter, displayFilter, searchControls, handler)); } private class SearchAction implements PrivilegedAction<NameClassPairCallbackHandler> { private String baseDN; private String filter; private String displayFilter; private SearchControls searchControls; private NameClassPairCallbackHandler handler; public SearchAction(String baseDN, String filter, String displayFilter, SearchControls searchControls, NameClassPairCallbackHandler handler) { this.baseDN = baseDN; this.filter = filter; this.displayFilter = displayFilter; this.searchControls = searchControls; this.handler = handler; } @Override public NameClassPairCallbackHandler run() { return pagedSearch(baseDN, filter, displayFilter, searchControls, handler); } } @Override protected DirContextAuthenticationStrategy buildContextAuthenticationStategy() { String realm = domain.toUpperCase(); return new GSSAPIDirContextAuthenticationStrategy(userName, password, realm, explicitAuth); } @Override public void useAuthenticationStrategy() throws EngineDirectoryServiceException { super.useAuthenticationStrategy(); GSSAPIDirContextAuthenticationStrategy strategy = (GSSAPIDirContextAuthenticationStrategy) authStrategy; strategy.authenticate(); loginContext = strategy.getLoginContext(); } @Override public void adjustUserName(LdapProviderType ldapProviderType) { // No manipulation on user name is required, in contrast to SIMPLE // authentication } @Override protected void setCredentialsOnContext() { // Does nothing - credentials are used by JAAS } }
30.413462
145
0.717989
f36627a77da166ad1f8d9bc184359183167f052e
620
package saedc.example.com.Model.Dao; import java.util.List; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import saedc.example.com.Model.Entity.User; @Dao public interface UserDao { @Query("SELECT COUNT(*) FROM user") Integer getUsersCounts(); @Query("SELECT * FROM USER WHERE ID=:id ") LiveData<User> getUserById(int id); @Query("DELETE FROM USER WHERE id = :id") void deleteUser(int id); @Insert(onConflict = OnConflictStrategy.REPLACE) void addUser(User s); }
20
52
0.724194
63aca1a8cb8277d9a50cac7e01c99492045515e5
267
package com.dimdol.sql; public enum Statement { INSERT_INTO, DROP_DATABASE, ALTER_TABLE, DROP_TABLE, TRUNCATE_TABLE, CREATE_INDEX, DROP_INDEX, CREATE_VIEW, CREATE_OR_REPLACE_VIEW, DROP_VIEW }
10.68
28
0.602996
82d070ff77d46c3f33e0cf330a6b02e6499a1ea6
10,013
package gov.nih.nci.evs.reportwriter.core.util; import gov.nih.nci.evs.restapi.util.*; import com.opencsv.CSVReader; import java.io.*; import java.text.*; import java.util.*; /** * <!-- LICENSE_TEXT_START --> * Copyright 2011, MSC. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * 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 disclaimer of Article 3, * below. 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. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by MSC and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "MSC" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or MSC. * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED 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 NATIONAL CANCER INSTITUTE, * MSC, OR THEIR AFFILIATES 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. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history: * Initial implementation ongki@nih.gov * */ public class NeoplasmCoreRelationships { String value_set_ascii_file = null; String owlfile = null; OWLScanner scanner = null; Vector code_vec = null; HashSet code_set = null; HashMap objectPropertiesCode2LabelMap = null; HashMap cid2PTMap = null; HashMap roleMap = null; Vector molecularRoles = new Vector(); public NeoplasmCoreRelationships(String value_set_ascii_file, String owlfile) { this.value_set_ascii_file = value_set_ascii_file; this.owlfile = owlfile; initialize(); } public Vector get_value_set_codes(String value_set_ascii_file) { Vector v = readFile(value_set_ascii_file); code_set = new HashSet(); code_vec = new Vector(); for (int i=1; i<v.size(); i++) { String t = (String) v.elementAt(i); Vector u = gov.nih.nci.evs.restapi.util.StringUtils.parseData(t, '\t'); String code = (String) u.elementAt(0); if (!code_set.contains(code)) { code_vec.add(code); code_set.add(code); } } return code_vec; } private void initialize() { /* Disease_Has_Cytogenetic_Abnormality Disease_Has_Molecular_Abnormality Disease_May_Have_Cytogenetic_Abnormality Disease_May_Have_Molecular_Abnormality Disease_Mapped_To_Gene Disease_Pathogenesis_Involves_Gene */ molecularRoles = new Vector(); molecularRoles.add("R107"); molecularRoles.add("R106"); molecularRoles.add("R114"); molecularRoles.add("R89"); molecularRoles.add("R176"); molecularRoles.add("R175"); scanner = new OWLScanner(owlfile); code_vec = get_value_set_codes(value_set_ascii_file); code_set = new HashSet(); for (int i=0; i<code_vec.size(); i++) { String t = (String) code_vec.elementAt(i); code_set.add(t); } //System.out.println("code_vec: " + code_vec.size()); Vector w = scanner.extractObjectProperties(scanner.get_owl_vec()); objectPropertiesCode2LabelMap = new HashMap(); for (int i=0; i<w.size(); i++) { String t = (String) w.elementAt(i); Vector u = gov.nih.nci.evs.restapi.util.StringUtils.parseData(t, '|'); String r_code = (String) u.elementAt(0); String r_label = (String) u.elementAt(1); if (r_code.compareTo("R175") == 0) { //Gene_Involved_In_Pathogenesis_Of_Disease r_label = "Disease_Pathogenesis_Involves_Gene"; } objectPropertiesCode2LabelMap.put(r_code, r_label); } w = scanner.extractProperties(scanner.get_owl_vec(), "P108"); cid2PTMap = new HashMap(); for (int i=0; i<w.size(); i++) { String t = (String) w.elementAt(i); Vector u = gov.nih.nci.evs.restapi.util.StringUtils.parseData(t, '|'); cid2PTMap.put((String) u.elementAt(0),(String) u.elementAt(2)); } } public void getRestrictions(String outputfile) { roleMap = new HashMap(); Vector w = scanner.extractOWLRestrictions(scanner.get_owl_vec()); for (int i=0; i<w.size(); i++) { String t = (String) w.elementAt(i); Vector u = gov.nih.nci.evs.restapi.util.StringUtils.parseData(t, '|'); String src = (String) u.elementAt(0); String r = (String) u.elementAt(1); String target = (String) u.elementAt(2); if (r.compareTo("R175") == 0) { String tmp = src; src = target; target = tmp; } if (code_set.contains(src) && molecularRoles.contains(r)) { Vector v = new Vector(); if (roleMap.containsKey(src)) { v = (Vector) roleMap.get(src); } if (!v.contains(r + "|" + target)) { v.add(r + "|" + target); } roleMap.put(src, v); } } Vector w0 = new Vector(); Iterator it = roleMap.keySet().iterator(); while (it.hasNext()) { String src = (String) it.next(); String src_pt = (String) cid2PTMap.get(src); Vector v = (Vector) roleMap.get(src); for (int i=0; i<v.size(); i++) { String s = (String) v.elementAt(i); Vector u = gov.nih.nci.evs.restapi.util.StringUtils.parseData(s, '|'); String r = (String) u.elementAt(0); String target = (String) u.elementAt(1); String target_pt = (String) cid2PTMap.get(target); w0.add(src_pt + "|" + src + "|" + (String) objectPropertiesCode2LabelMap.get(r) + "|" + target + "|" + target_pt); } } w0 = new gov.nih.nci.evs.restapi.util.SortUtils().quickSort(w0); saveToFile(outputfile, w0); } public void generateCSVFile(String inputfile, String csvfile) { //String outputfile = getOutputfileName(inputfile); Vector v = readFile(inputfile); int line_count = v.size(); //line_count = line_count-1; System.out.println("Totol number of records: " + line_count); PrintWriter pw = null; Vector w = new Vector(); HashMap hmap = new HashMap(); String key = null; Vector key_vec = new Vector(); try { pw = new PrintWriter(csvfile, "UTF-8"); // private String Constants.HEADING_STR = "\"Code\",\"Preferred Term\",\"Relationship\",\"Code\",\"Preferred Term\""; pw.println(Constants.HEADING_STR); for (int i=0; i<v.size(); i++) { String t = (String) v.elementAt(i); Vector u = gov.nih.nci.evs.restapi.util.StringUtils.parseData(t, '|'); //String direction = (String) u.elementAt(0); String src_pt = (String) u.elementAt(0); String src_code = (String) u.elementAt(1); //String role_code = (String) u.elementAt(2); String role_name = (String) u.elementAt(2); String target_code = (String) u.elementAt(3); String target_pt = (String) u.elementAt(4); StringBuffer buf = new StringBuffer(); buf.append("\"").append(src_code).append("\"").append(","); buf.append("\"").append(src_pt).append("\"").append(","); buf.append("\"").append(role_name).append("\"").append(","); buf.append("\"").append(target_code).append("\"").append(","); buf.append("\"").append(target_pt).append("\""); pw.println(buf.toString()); } } catch (Exception ex) { } finally { try { pw.close(); System.out.println("Output file " + csvfile + " generated."); } catch (Exception ex) { ex.printStackTrace(); } } } public static Vector readFile(String filename) { Vector v = new Vector(); try { BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(filename), "UTF8")); String str; while ((str = in.readLine()) != null) { v.add(str); } in.close(); } catch (Exception ex) { ex.printStackTrace(); } return v; } public static void saveToFile(String outputfile, String t) { Vector v = new Vector(); v.add(t); saveToFile(outputfile, v); } public static void saveToFile(String outputfile, Vector v) { PrintWriter pw = null; try { pw = new PrintWriter(outputfile, "UTF-8"); if (v != null && v.size() > 0) { for (int i=0; i<v.size(); i++) { String t = (String) v.elementAt(i); pw.println(t); } } } catch (Exception ex) { } finally { try { pw.close(); System.out.println("Output file " + outputfile + " generated."); } catch (Exception ex) { ex.printStackTrace(); } } } public static void saveToFile(PrintWriter pw, Vector v) { if (v != null && v.size() > 0) { for (int i=0; i<v.size(); i++) { String t = (String) v.elementAt(i); pw.println(t); } } } }
33.046205
120
0.658244
dbf5cf1e32590a573d19eb255bbf703caa5b77fb
1,023
/* * * Headwind MDM: Open Source Android MDM Software * https://h-mdm.com * * Copyright (C) 2019 Headwind Solutions LLC (http://h-sms.com) * * 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.hmdm.persistence.domain; /** * <p>An enmeration over supported application types.</p> * * @author isv */ public enum ApplicationType { /** * A type representing an Android application. */ app, /** * <p>A type representing the web application.</p> */ web; }
25.575
75
0.683284
095e82f98654f613a68252a00ebe2b71b82d88c5
3,365
package com.thinkgem.jeesite.common.aop.processor; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.thinkgem.jeesite.common.aop.annotation.DisableDuplicateSubmission; import com.thinkgem.jeesite.common.aop.annotation.GenerateToken; import com.thinkgem.jeesite.common.aop.annotation.ValidateToken; import com.thinkgem.jeesite.common.aop.aspect.ControllerAspectProcessor; import com.thinkgem.jeesite.common.cache.AspectUtil; /** * 防重复提交处理类 * <p> * Description:这里写描述<br /> * </p> * * @title DuplicationSubmissionProcessor.java * @package com.cxdai.common.aop * @author zhaowei * @version 0.1 2015年11月19日 */ public class DuplicateSubmissionProcessor implements ControllerAspectProcessor { protected Logger logger = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("defaultTokenAuthenticationProccessor") private IAspectAuthenticationProcessor defaultTokenAuthenticationProccessor; @Autowired @Qualifier("transientTokenAuthenticationProccessor") private IAspectAuthenticationProcessor transientTokenAuthenticationProccessor; @Override public Object doProcess(ProceedingJoinPoint pjp) throws Throwable { // 获取方法进行反射 MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); logger.info("method "+method); Annotation annotation[]= method.getAnnotations(); for(Annotation annotation2:annotation){ logger.info("annotation "+annotation2); } if (method.isAnnotationPresent(DisableDuplicateSubmission.class)) { // 禁止重复提交 // 根据用户唯一标识进行加锁,防止同一用户同时请求多次 String identify = AspectUtil.getUserBasedUniqueRequestId(pjp); synchronized (identify) { getTransientTokenAuthenticationProccessor().beforeProcess(pjp); Object proceed = pjp.proceed(); getTransientTokenAuthenticationProccessor().afterProcess(pjp, proceed); return proceed; } } else if (method.isAnnotationPresent(GenerateToken.class) || method.isAnnotationPresent(ValidateToken.class)) { // 生成、验证token logger.info("method:"+method.isAnnotationPresent(GenerateToken.class)); getDefaultTokenAuthenticationProccessor().beforeProcess(pjp); Object proceed = pjp.proceed(); getDefaultTokenAuthenticationProccessor().afterProcess(pjp, proceed); logger.info("proceed:"+proceed); return proceed; } return null; } public IAspectAuthenticationProcessor getDefaultTokenAuthenticationProccessor() { return defaultTokenAuthenticationProccessor; } public void setDefaultTokenAuthenticationProccessor(IAspectAuthenticationProcessor defaultTokenAuthenticationProccessor) { this.defaultTokenAuthenticationProccessor = defaultTokenAuthenticationProccessor; } public IAspectAuthenticationProcessor getTransientTokenAuthenticationProccessor() { return transientTokenAuthenticationProccessor; } public void setTransientTokenAuthenticationProccessor(IAspectAuthenticationProcessor transientTokenAuthenticationProccessor) { this.transientTokenAuthenticationProccessor = transientTokenAuthenticationProccessor; } }
36.182796
127
0.807132
64256a0925bdd856c2fa9c625fbded88d42f59f3
1,416
package org.neo4j.arrow.job; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.neo4j.arrow.gds.Edge; public class EdgePackingTest { @Test public void testEdgePackingLogic() { long startId = 123; long endId = 456; boolean isNatural = true; long edge = Edge.edge(startId, endId, isNatural); System.out.printf("0x%X\n", edge); System.out.printf("start: %d ?? %d\n", startId, Edge.source(edge)); Assertions.assertEquals(startId, Edge.source(edge)); System.out.printf("end: %d ?? %d\n", endId, Edge.target(edge)); Assertions.assertEquals(endId, Edge.target(edge)); System.out.printf("isNatural?: %s : %s\n", isNatural, Edge.flag(edge)); Assertions.assertEquals(isNatural, Edge.flag(edge)); startId = 300_000_000; endId = 0; isNatural = false; edge = Edge.edge(startId, endId, isNatural); System.out.printf("0x%X\n", edge); System.out.printf("start: %d ?? %d\n", startId, Edge.source(edge)); Assertions.assertEquals(startId, Edge.source(edge)); System.out.printf("end: %d ?? %d\n", endId, Edge.target(edge)); Assertions.assertEquals(endId, Edge.target(edge)); System.out.printf("isNatural?: %s : %s\n", isNatural, Edge.flag(edge)); Assertions.assertEquals(isNatural, Edge.flag(edge)); } }
35.4
79
0.627825
c1a6dc57fc14d8bb748debe3266d95026fe49e29
9,825
/* * Copyright 2010-2011, Sikuli.org * Released under the MIT License. * */ package org.sikuli.script; import java.io.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.util.Date; import javax.swing.*; import javax.imageio.*; public class CapturePrompt extends TransparentWindow implements Subject{ static Color _overlayColor = new Color(0F,0F,0F,0.6F); final static float MIN_DARKER_FACTOR = 0.6f; final static long MSG_DISPLAY_TIME = 2000; final static long WIN_FADE_IN_TIME = 200; static GraphicsDevice _gdev = null; Observer _obs; Screen _scr; BufferedImage _scr_img = null; BufferedImage _darker_screen = null; float _darker_factor; Rectangle rectSelection; BasicStroke bs; int srcScreenId=0; int srcx, srcy, destx, desty; boolean _canceled = false; Animator _aniMsg, _aniWin; String _msg; BasicStroke _StrokeCross = new BasicStroke (1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1, new float [] { 2f }, 0); public void addObserver(Observer o){ _obs = o; } public void notifyObserver(){ _obs.update(this); } private void captureScreen(Screen scr) { ScreenImage simg = scr.capture(); _scr_img = simg.getImage(); _darker_factor = 0.6f; RescaleOp op = new RescaleOp(_darker_factor, 0, null); _darker_screen = op.filter(_scr_img, null); } private Color selFrameColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); private Color selCrossColor = new Color(1.0f, 0.0f, 0.0f, 0.6f); private Color screenFrameColor = new Color(1.0f, 0.0f, 0.0f, 0.6f); BasicStroke strokeScreenFrame = new BasicStroke(5); private void drawScreenFrame(Graphics2D g2d, int scrId){ Rectangle rect = Screen.getBounds(scrId); Rectangle ubound = (new UnionScreen()).getBounds(); g2d.setColor(screenFrameColor); g2d.setStroke(strokeScreenFrame); rect.x -= ubound.x; rect.y -= ubound.y; int sw = (int)(strokeScreenFrame.getLineWidth()/2); rect.x += sw; rect.y += sw; rect.width -= sw*2; rect.height -= sw*2; g2d.draw(rect); } private void drawSelection(Graphics2D g2d){ if (srcx != destx || srcy != desty) { int x1 = (srcx < destx) ? srcx : destx; int y1 = (srcy < desty) ? srcy : desty; int x2 = (srcx > destx) ? srcx : destx; int y2 = (srcy > desty) ? srcy : desty; if(Screen.getNumberScreens()>1){ Rectangle selRect = new Rectangle(x1,y1,x2-x1,y2-y1); Rectangle ubound = (new UnionScreen()).getBounds(); selRect.x += ubound.x; selRect.y += ubound.y; Rectangle inBound = selRect.intersection(Screen.getBounds(srcScreenId)); x1 = inBound.x - ubound.x; y1 = inBound.y - ubound.y; x2 = x1 + inBound.width-1; y2 = y1 + inBound.height-1; } rectSelection.x = x1; rectSelection.y = y1; rectSelection.width = (x2-x1)+1; rectSelection.height = (y2-y1)+1; if(rectSelection.width>0 && rectSelection.height>0) g2d.drawImage(_scr_img.getSubimage(x1, y1,x2-x1+1, y2-y1+1), null, x1, y1); g2d.setColor(selFrameColor); g2d.setStroke(bs); g2d.draw(rectSelection); int cx = (x1+x2)/2; int cy = (y1+y2)/2; g2d.setColor(selCrossColor); g2d.setStroke(_StrokeCross); g2d.drawLine(cx, y1, cx, y2); g2d.drawLine(x1, cy, x2, cy); if(Screen.getNumberScreens()>1) drawScreenFrame(g2d, srcScreenId); } } static Font fontMsg = new Font("Arial", Font.PLAIN, 60); void drawMessage(Graphics2D g2d){ if(_msg == null) return; if(_aniMsg.running()){ float alpha = _aniMsg.step(); g2d.setFont(fontMsg); g2d.setColor(new Color(1f,1f,1f,alpha)); int sw = g2d.getFontMetrics().stringWidth(_msg); int sh = g2d.getFontMetrics().getMaxAscent(); Rectangle ubound = (new UnionScreen()).getBounds(); for(int i=0;i<Screen.getNumberScreens();i++){ Rectangle bound = Screen.getBounds(i); int cx = bound.x+ (bound.width-sw)/2 - ubound.x; int cy = bound.y+ (bound.height-sh)/2 - ubound.y; g2d.drawString(_msg, cx, cy); } repaint(); } } BufferedImage bi = null; public void paint(Graphics g) { if( _scr_img != null ){ Graphics2D g2dWin = (Graphics2D)g; if ( bi==null || bi.getWidth(this) != getWidth() || bi.getHeight(this) != getHeight() ) { bi = new BufferedImage( getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB ); } Graphics2D bfG2 = bi.createGraphics(); bfG2.drawImage(_darker_screen,0,0,this); drawMessage(bfG2); drawSelection(bfG2); g2dWin.drawImage(bi, 0, 0, this); setVisible(true); if(_aniWin!=null && _aniWin.running()){ float a = _aniWin.step(); setOpacity(a); repaint(); } } else setVisible(false); } void init(){ _canceled = false; setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); rectSelection = new Rectangle (); bs = new BasicStroke(1); addMouseListener(new MouseAdapter(){ public void mousePressed(java.awt.event.MouseEvent e){ if (_scr_img == null) return; destx = srcx = e.getX(); desty = srcy = e.getY(); srcScreenId = (new UnionScreen()).getIdFromPoint(srcx, srcy); Debug.log(3, "pressed " + srcx + "," + srcy + " at screen " + srcScreenId); repaint(); } public void mouseReleased(java.awt.event.MouseEvent e){ if (_scr_img == null) return; if( e.getButton() == java.awt.event.MouseEvent.BUTTON3 ){ _canceled = true; notifyObserver(); close(); } else notifyObserver(); } }); addMouseMotionListener( new MouseMotionAdapter(){ public void mouseDragged(java.awt.event.MouseEvent e) { if (_scr_img == null) return; destx = e.getX(); desty = e.getY(); repaint(); } }); addKeyListener( new KeyAdapter(){ public void keyPressed(KeyEvent e){ if(e.getKeyCode() == KeyEvent.VK_ESCAPE){ _canceled = true; notifyObserver(); CapturePrompt.this.close(); } } }); } public void close(){ if(_gdev != null ){ try{ _gdev.setFullScreenWindow(null); } catch(Exception e){ Debug.log("Switch to windowed mode failed: " + e.getMessage()); } } this.setVisible(false); this.dispose(); } private BufferedImage cropSelection(){ int w = rectSelection.width, h = rectSelection.height; if(w<=0 || h<=0) return null; BufferedImage crop = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D crop_g2d = crop.createGraphics(); try { crop_g2d.drawImage( _scr_img.getSubimage(rectSelection.x, rectSelection.y, w, h), null, 0, 0 ); } catch (RasterFormatException e) { e.printStackTrace(); } crop_g2d.dispose(); /* try{ ImageIO.write(crop, "png", new File("debug_crop.png")); } catch(IOException e){} */ return crop; } public ScreenImage getSelection(){ if(_canceled) return null; BufferedImage cropImg = cropSelection(); if(cropImg == null) return null; rectSelection.x += _scr.x; rectSelection.y += _scr.y; ScreenImage ret = new ScreenImage(rectSelection, cropImg); return ret; } public void prompt(String msg, int delayMS){ try{ Thread.sleep(delayMS); } catch(InterruptedException ie){ } prompt(msg); } public void prompt(int delayMS){ prompt(null, delayMS); } public void prompt(){ prompt(null); } public void prompt(String msg){ Debug.log(3, "starting CapturePrompt @" + _scr); captureScreen(_scr); setLocation(_scr.x, _scr.y); this.setSize(new Dimension(_scr.w, _scr.h)); this.setBounds(_scr.x, _scr.y, _scr.w, _scr.h); this.setAlwaysOnTop(true); _msg = msg; _aniMsg = new LinearAnimator(1f, 0f, MSG_DISPLAY_TIME); if(Env.getOS() == OS.MAC || Env.getOS() == OS.WINDOWS){ _aniWin = new LinearAnimator(0f, 1f, WIN_FADE_IN_TIME); setOpacity(0); getRootPane().putClientProperty( "Window.shadow", Boolean.FALSE ); this.setVisible(true); if(Env.getOS() == OS.MAC){ Env.getOSUtil().bringWindowToFront(this, false); } } else this.setVisible(true); if( _scr.useFullscreen() ){ _gdev = _scr.getGraphicsDevice(); if( _gdev.isFullScreenSupported() ){ _gdev.setFullScreenWindow(this); } else{ Debug.log("Fullscreen mode is not supported."); } } this.requestFocus(); } public CapturePrompt(Screen scr, Observer ob){ this(scr); addObserver(ob); } public CapturePrompt(Screen scr){ if(scr == null){ if(Screen.getNumberScreens()>1) scr = new UnionScreen(); else scr = new Screen(); } _scr = scr; init(); } }
28.561047
124
0.564885
0d1f12eee28af936da1cac6388636d0913a489c7
4,904
package de.dietzm.booksintoapps.servicespublic; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import de.dietzm.booksintoapps.db.ContentItem; import de.dietzm.booksintoapps.db.Project; import de.dietzm.booksintoapps.db.base.DAO; import de.dietzm.booksintoapps.db.base.DAOFactory; import de.dietzm.booksintoapps.utils.JSONBuilder; import de.dietzm.booksintoapps.utils.ResponseBuilder; import de.dietzm.booksintoapps.utils.UUIDUtil; @Path("/project") public class ProjectAPI { @GET @Path("/get") @Produces("application/json") public Response getProjectByAccessKey(@QueryParam("accesskey")String accessKey) { DAO<Project> dao = DAOFactory.getEntityManager("Project"); List<Project> project = dao.query("accessKey", accessKey); if(project.size() == 1){ return ResponseBuilder.createObjectJSONResponse(project.get(0), true); } else { return Response.serverError().build(); } } @POST @Path("/login") @Produces("application/json") public Response loginToProject(@FormParam("accesskey")String accessKey, @FormParam("password")String password, @Context HttpServletRequest request) { DAO<Project> dao = DAOFactory.getEntityManager("Project"); List<Project> projects = dao.query("accessKey", accessKey); if(projects.size() == 1){ Project project = projects.get(0); if(password != null && project.getPassword() != null && project.getPassword().equals(password)){ HttpSession session = request.getSession(); session.setAttribute("LOGGED_IN_TO_PROJECT", project.getId()); return ResponseBuilder.createStatusResponse("S","Project Login Successful"); } else { return ResponseBuilder.createStatusResponse("E","AccessKey or Password incorrect " + accessKey); } } else { return ResponseBuilder.createStatusResponse("E","AccessKey or Password incorrect " + accessKey); } } @POST @Path("/logout") @Produces("application/json") public Response logout(@Context HttpServletRequest request) { HttpSession session = request.getSession(); session.setAttribute("LOGGED_IN_TO_PROJECT", null); return ResponseBuilder.createStatusResponse("S","Project Logout Successful"); } @GET @Path("/loggedin") @Produces("application/json") public Response getLoggedInProject(@Context HttpServletRequest request) { HttpSession session = request.getSession(); Long projectID = (Long) session.getAttribute("LOGGED_IN_TO_PROJECT"); if(projectID != null && !projectID.equals("")){ DAO<Project> dao = DAOFactory.getEntityManager("Project"); Project project = dao.get(projectID); return ResponseBuilder.createFlexibleResponse("status", "S", "projectID",project.getId().toString(), "title", project.getTitle()); } else { return ResponseBuilder.createStatusResponse("Error","AccessKey or Password incorrect"); } } /* @GET @Path("/projects") @Produces("application/json") public Response getProjects() { DAO<Project> dao = DAOFactory.getEntityManager("Project"); List<Project> project = dao.queryAll(); return ResponseBuilder.createListJSONResponse(project); }*/ @GET @Path("/create") @Produces("application/json") public Response createProject() { DAO<Project> dao = DAOFactory.getEntityManager("Project"); Project project = new Project(); project.setAccessKey("AK" + UUIDUtil.generateUUID()); project.setAppKey("AP" + UUIDUtil.generateUUID()); project.setSecret("SC" + UUIDUtil.generateUUID()); project.setPassword("Init1234"); project.setTitle("Neues Buch"); Long newId = dao.create(project); return ResponseBuilder.createNewObjectCreatedResponse("Project",newId); } @GET @Path("/updateAll") @Produces("application/json") public Response updateAll() { DAO<Project> dao = DAOFactory.getEntityManager("Project"); List<Project> list = dao.queryAll(); for (Iterator<Project> iterator = list.iterator(); iterator.hasNext();) { Project project = (Project) iterator.next(); dao.update(project); } return ResponseBuilder.createSuccessResponse(); } @POST @Path("/update") @Produces("application/json") @Consumes("application/json") public Response updateContentItem(String jsonData, @Context HttpServletRequest request) { try { Project item = (Project) JSONBuilder.convertJSON2Object(jsonData, Project.class); DAO<Project> dao = DAOFactory.getEntityManager("Project"); dao.update(item); return ResponseBuilder.createSuccessResponse(); } catch (Exception e) { return ResponseBuilder.createErrorResponse(e.getMessage()); } } }
28.678363
151
0.731444
0143f9fee1e8f455cb1a9b40367dba463a587a78
629
package io.github.frame.prj.validate.rule; import io.github.frame.prj.validate.ValidateONGL; import io.github.util.StringUtils; import java.math.BigDecimal; /** * 数值小于等于校验 * * @author Updated by 思伟 on 2020/8/6 */ public class MinIncludeValidate { public static String exec(Object obj, String param, String value, String message) { Object objVal = ValidateONGL.getValue(obj, param); if (null != objVal && new BigDecimal(StringUtils.toString(objVal)).compareTo(new BigDecimal(value)) <= 0) { return null != message ? message : param + "不能小于等于" + value; } return null; } }
28.590909
115
0.677266
080c9b64433a2c171e4a88985f8f255f31f3454d
2,578
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.iot.client.fuse.node.certificates; import java.util.List; import net.fusejna.ErrorCodes; import com.amazonaws.services.iot.client.fuse.node.Node; import com.amazonaws.services.iot.client.fuse.node.policies.PolicyNode; public class CertificatePoliciesNode extends Node { private static final String NODE_NAME = "policies"; private static final String POLICIES_DIR = "/policies/"; private final String certificateArn; public CertificatePoliciesNode(Node parent, String certificateArn) { super(parent, NODE_NAME, true); this.certificateArn = certificateArn; } @Override public void init() { synchronized (this) { List<String> policies = iotClient.getCertificatePolicies(certificateArn); for (String policy : policies) { Node node = root.find(POLICIES_DIR + policy); if (node == null) { continue; } link(policy, node); } super.init(); } } @Override public int symlink(String name, String path) { Node sourceNode = this.find(path); if (sourceNode instanceof PolicyNode) { int r = iotClient.attachPolicy(certificateArn, sourceNode.getName()); if (r != 0) { return r; } } else { return -ErrorCodes.ENODEV(); } return link(name, sourceNode); } @Override public int symunlink(String name) { Node node = getChild(name); if (node == null) { return -ErrorCodes.ENODEV(); } Node sourceNode = this.find(name); if (sourceNode instanceof PolicyNode) { int r = iotClient.detachPolicy(certificateArn, sourceNode.getName()); if (r != 0) { return r; } } else { return -ErrorCodes.ENODEV(); } return 0; } }
28.644444
85
0.610551
937390a2999ff448b7dd163115e0b0d838127fdc
373
package com.masivian.casino.dto; import com.masivian.casino.models.Roulette; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @AllArgsConstructor public class ResultsDto { @Getter @Setter private int winningNumber; @Getter @Setter private String color; @Getter @Setter private Roulette roulette; }
13.321429
43
0.72118
744e89e004fd94d375909adbd71e884c71da1665
1,428
package com.spring4all.digitalsign.demo.controller; import com.spring4all.digitalsign.demo.utils.HttpClientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; /** * Created by liumapp on 3/14/18. * E-mail:liumapp.com@gmail.com * home-page:http://www.liumapp.com */ @RestController @RequestMapping("test") public class testController { @Autowired private HttpClientUtils httpClientUtils; /** * say hello * to make sure the server's state is under running. * @return String */ @RequestMapping("/keystore") public String testKeyStore () { try { BufferedReader reader = httpClientUtils.post("http://localhost:2333/keystore-worker/keystore/hello" , new HashMap<>()); StringBuffer result = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } catch (IOException e) { e.printStackTrace(); return "error"; } } @RequestMapping("/hello") public String hello () { return "hello , this is " + testController.class; } }
28
131
0.651961
9c67dfc2649941dc69097c3f15ed61018260e5ff
326
package apidez.com.databinding.model.entity; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by nongdenchet on 10/21/15. */ public class GoogleSearchResult { @SerializedName("status") public String status; @SerializedName("results") public List<Place> results; }
18.111111
50
0.730061
cd6e19cec8fb8fe117cfd78649ae36165fdeeee8
3,337
package ai.labs.property.impl; import ai.labs.expressions.Expression; import ai.labs.expressions.utilities.IExpressionProvider; import ai.labs.expressions.value.Value; import ai.labs.property.model.PropertyEntry; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.*; /** * @author ginccc */ public class PropertyDisposerTest { private IExpressionProvider expressionProvider; @Before public void setUp() { expressionProvider = mock(IExpressionProvider.class); } @Test public void extractProperties() { //setup String testStringExpressions = "property(someMeaning(someValue)),noProperty(someMeaning(someValue))"; when(expressionProvider.parseExpressions(eq(testStringExpressions))).thenAnswer(invocation -> Arrays.asList(new Expression("property", new Expression("someMeaning", new Value("someValue"))), new Expression("noProperty", new Expression("someMeaning", new Value("someValue"))) )); PropertyDisposer propertyDisposer = new PropertyDisposer(); PropertyEntry expectedPropertyEntry = new PropertyEntry(Collections.singletonList("someMeaning"), "someValue"); //test List<PropertyEntry> propertyEntries = propertyDisposer.extractProperties(expressionProvider.parseExpressions(testStringExpressions)); //assert verify(expressionProvider, times(1)).parseExpressions(testStringExpressions); Assert.assertEquals(Collections.singletonList(expectedPropertyEntry), propertyEntries); } @Test public void extractMoreComplexProperties() { //setup String testStringExpressions = "property(someMeaning(someSubMeaning(someValue)))," + "property(someMeaning(someValue, someOtherValue))"; when(expressionProvider.parseExpressions(eq(testStringExpressions))).thenAnswer(invocation -> Arrays.asList(new Expression("property", new Expression("someMeaning", new Expression("someSubMeaning", new Value("someValue")))), new Expression("property", new Expression("someMeaning", new Value("someValue"), new Value("someOtherValue"))) )); PropertyDisposer propertyDisposer = new PropertyDisposer(); List<PropertyEntry> expectedPropertyEntries = Arrays.asList( new PropertyEntry(Arrays.asList("someMeaning", "someSubMeaning"), "someValue"), new PropertyEntry(Collections.singletonList("someMeaning"), "someValue")); //test List<PropertyEntry> propertyEntries = propertyDisposer.extractProperties(expressionProvider.parseExpressions(testStringExpressions)); //assert verify(expressionProvider, times(1)).parseExpressions(testStringExpressions); Assert.assertEquals(expectedPropertyEntries, propertyEntries); } }
43.337662
141
0.643093
48bb0db9a5bb583d5fe5e33e314a35887640cf34
2,837
package com.green.bank; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.green.bank.database.DatabaseOperations; import com.green.bank.database.JDBC_Connect; import com.green.bank.model.AccountModel; import com.green.bank.model.DepositSchemeModel; import oracle.net.aso.b; import oracle.net.aso.d; public class DepositSchemeServlet extends HttpServlet { String account_no, deposit_amount, value; int year, interest_rate, amount; Connection conn; Statement stmt; boolean pass_wrong = false; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { account_no = request.getParameter("account_no"); year = Integer.parseInt(request.getParameter("year")); interest_rate = Integer.parseInt(request.getParameter("interest_rate")); deposit_amount = request.getParameter("deposit_amount"); value = request.getParameter("value"); if (deposit_amount.equals("1,00,000&#2547;")) { amount = 100000; } else if (deposit_amount.equals("3,00,000&#2547;")) { amount = 300000; } else if (deposit_amount.equals("5,00,000&#2547;")) { amount = 500000; } DepositSchemeModel dpModel = new DepositSchemeModel(); dpModel.setAccount_no(account_no); dpModel.setYear(year); dpModel.setInterest_rate(interest_rate); dpModel.setAmount(amount); dpModel.setValue(value); try { JDBC_Connect connect = new JDBC_Connect(); Connection conn = connect.getConnection(); DatabaseOperations operations = new DatabaseOperations(); AccountModel am = operations.getAccountDetails(conn, account_no); if (am.getAmount() >= amount) { int main_amount = am.getAmount() - amount; PreparedStatement ps = conn.prepareStatement("update amount set amount=? where id= ?"); ps.setInt(1, main_amount); ps.setString(2, account_no); ps.executeUpdate(); boolean allRight = operations.insertDepositScheme(dpModel); request.setAttribute("DepositScheme", dpModel); request.setAttribute("allRight", allRight); RequestDispatcher rd = request.getRequestDispatcher("deposit_scheme_progress.jsp"); rd.forward(request, response); } else { request.setAttribute("Not_Enough", "Yes"); RequestDispatcher rd = request.getRequestDispatcher("single_deposit_scheme.jsp?value=" + value); rd.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }
31.876404
100
0.756785
ee586de73269141be68df254da2411d684539d97
2,898
package igorilin13.com.github.main.datastructures.tree; import org.jetbrains.annotations.NotNull; public class OrderedStatisticsTree<K extends Comparable<K>> extends RedBlackTree<K> { @Override TreeNode<K> createNode(K key) { return new OrderedStatisticsTreeNode<>(key); } @Override void insertFixup(TreeNode<K> node) { super.insertFixup(node); recalcSizes((OrderedStatisticsTreeNode<K>) root); } @Override boolean delete(@NotNull TreeNode<K> deleteNode) { boolean res = super.delete(deleteNode); if (res) { recalcSizes((OrderedStatisticsTreeNode<K>) root); } return res; } private int recalcSizes(OrderedStatisticsTreeNode<K> node) { if (node == null) { return 0; } int size = recalcSizes(node.getLeft()) + recalcSizes(node.getRight()) + 1; node.setSize(size); return size; } public int calcSize(@NotNull OrderedStatisticsTreeNode<K> node) { return sizeOrZero(node.getLeft()) + sizeOrZero(node.getRight()) + 1; } private int sizeOrZero(OrderedStatisticsTreeNode<K> node) { return node != null ? node.getSize() : 0; } public K select(int i) { return select((OrderedStatisticsTreeNode<K>) root, i).getKey(); } private OrderedStatisticsTreeNode<K> select(OrderedStatisticsTreeNode<K> x, int i) { int r = sizeOrZero(x.getLeft()) + 1; if (i == r) { return x; } else if (i < r) { return select(x.getLeft(), i); } else { return select(x.getRight(), i - r); } } public int calcRank(OrderedStatisticsTreeNode<K> x) { int result = sizeOrZero(x.getLeft()) + 1; OrderedStatisticsTreeNode<K> current = x; while (current != root) { if (current == current.getParent().getRight()) { result += sizeOrZero(current.getParent().getLeft()) + 1; } current = current.getParent(); } return result; } public class OrderedStatisticsTreeNode<T extends Comparable<T>> extends RedBlackTreeNode<T> { private int size; OrderedStatisticsTreeNode(T key) { super(key); } void setSize(int size) { this.size = size; } public int getSize() { return size; } @Override public OrderedStatisticsTreeNode<T> getParent() { return (OrderedStatisticsTreeNode<T>) super.getParent(); } @Override public OrderedStatisticsTreeNode<T> getLeft() { return (OrderedStatisticsTreeNode<T>) super.getLeft(); } @Override public OrderedStatisticsTreeNode<T> getRight() { return (OrderedStatisticsTreeNode<T>) super.getRight(); } } }
28.411765
97
0.586611
19103f52dcedc00956c173805c47900f8b474936
8,534
/* * The MIT License * * Copyright 2019 Ing. Dexus José Pérez <jose_perezmiranda@outlook.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package manager.hojacosto; import MenuPrincipal.principal; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; /** * * @author Ing. Dexus José Pérez <jose_perezmiranda@outlook.com> */ public class FormularioRegistro extends javax.swing.JPanel { private FileNameExtensionFilter Filtroarchivo; /** * Creates new form FormularioRegistro */ public FormularioRegistro() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { CampoNombre = new javax.swing.JTextField(); CampoPaterno = new javax.swing.JTextField(); CampoMaterno = new javax.swing.JTextField(); BtGuardar = new javax.swing.JButton(); EtNombre = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setBackground(new java.awt.Color(153, 204, 255)); setMaximumSize(new java.awt.Dimension(800, 600)); setPreferredSize(new java.awt.Dimension(800, 600)); CampoNombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CampoNombreActionPerformed(evt); } }); BtGuardar.setText("Guardar"); BtGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtGuardarActionPerformed(evt); } }); EtNombre.setFont(principal.ArialB12); EtNombre.setForeground(Color.BLACK ); EtNombre.setText("Nombre(s)"); EtNombre.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); EtNombre.setFont(principal.ArialB12); jLabel2.setText("Apellido Paterno"); jLabel3.setText("Apellido Materno"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(CampoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(EtNombre)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(BtGuardar) .addComponent(CampoPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel3) .addComponent(CampoMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(85, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(EtNombre) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(CampoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(CampoPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(CampoMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addComponent(BtGuardar) .addContainerGap(81, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void CampoNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CampoNombreActionPerformed // TODO add your handling code here: }//GEN-LAST:event_CampoNombreActionPerformed private void BtGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtGuardarActionPerformed // TODO add your handling code here: String ruta; JFileChooser guardar = new JFileChooser(); String rutaDirec = System.getProperty("user.home"); File directorio =new File(rutaDirec+"/documents"); Filtroarchivo = new FileNameExtensionFilter("Archivo PDF *.pdf",".pdf"); guardar.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); guardar.setFileFilter(Filtroarchivo); guardar.addChoosableFileFilter(Filtroarchivo); guardar.setCurrentDirectory(directorio); int option = guardar.showSaveDialog(this); if(option == JFileChooser.APPROVE_OPTION){ File f = guardar.getSelectedFile(); ruta = f.toString(); try { FileOutputStream documento = new FileOutputStream(ruta+".pdf"); System.out.println(guardar.getFileFilter().toString()); Document doc = new Document(); PdfWriter.getInstance(doc, documento); doc.open(); doc.add(new Paragraph(CampoNombre.getText()+" "+CampoPaterno.getText())); doc.close(); JOptionPane.showMessageDialog(this,"PDF creado!"); } catch (Exception e) { JOptionPane.showMessageDialog(this, "error: "+ e); } } }//GEN-LAST:event_BtGuardarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtGuardar; private javax.swing.JTextField CampoMaterno; private javax.swing.JTextField CampoNombre; private javax.swing.JTextField CampoPaterno; private javax.swing.JLabel EtNombre; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration//GEN-END:variables }
46.63388
166
0.678931
5dd67521ee8a53ac8f33b47a0a0f1c6874cb076f
572
package com.vladmihalcea.hibernate.masterclass.laboratory.batch; import java.util.Properties; /** * DefaultDialectOrderedBatchingTest - Test to check ordered inserts and updates batching * * @author Vlad Mihalcea */ public class DefaultDialectOrderedBatchingTest extends DefaultDialectBatchingTest { @Override protected Properties getProperties() { Properties properties = super.getProperties(); properties.put("hibernate.order_inserts", "true"); properties.put("hibernate.order_updates", "true"); return properties; } }
28.6
89
0.741259
b050206fe64442742f6fceda47e6587061677efa
1,033
package edu.virginia.vcgr.genii.client.jsdl; import java.io.Serializable; import java.util.Map; import edu.virginia.vcgr.genii.client.jsdl.Filesystem; public class FilesystemRelative<Type> implements Serializable { static final long serialVersionUID = 0L; private String _filesystemName; private Type _target; public FilesystemRelative(String filesystemName, Type target) { if (filesystemName == null && target == null) throw new IllegalArgumentException("Filesystem Name and Target cannot both be null."); _filesystemName = filesystemName; _target = target; } final public Filesystem getFilesystem(final Map<String, Filesystem> filesystems) { return filesystems.get(_filesystemName); } final public Type getTarget() { return _target; } @Override public String toString() { if (_filesystemName != null) { if (_target != null) return String.format("[%s] %s", _filesystemName, _target); else return String.format("[%s]", _filesystemName); } else return _target.toString(); } }
22.955556
89
0.738625
26173b6cb051f23bd7359eb8b13b59c07a7c8214
2,382
package com.fabianuribe.newssearch.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.fabianuribe.newssearch.R; import com.fabianuribe.newssearch.models.Doc; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by uribe on 2/3/17. */ public class DocumentsAdapter extends RecyclerView.Adapter<DocumentsAdapter.ViewHolder> { public static class ViewHolder extends RecyclerView.ViewHolder { public TextView tvSnippet; public ImageView ivThumbnail; public ViewHolder(View itemView) { super(itemView); tvSnippet = (TextView) itemView.findViewById(R.id.tvSnippet); ivThumbnail = (ImageView) itemView.findViewById(R.id.ivThumbnail); } } private List<Doc> mDocuments; private Context mContext; public DocumentsAdapter(Context context, List<Doc> documents) { mDocuments = documents; mContext = context; } private Context getContext() { return mContext; } @Override public DocumentsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); // Inflate the custom layout final View contactView = inflater.inflate(R.layout.document_item, parent, false); // Return a new holder instance ViewHolder viewHolder = new ViewHolder(contactView); return viewHolder; } @Override public void onBindViewHolder(DocumentsAdapter.ViewHolder viewHolder, int position) { Doc document = mDocuments.get(position); // Set item views based on your views and data model TextView textView = viewHolder.tvSnippet; textView.setText(document.getSnippet()); ImageView thumbnail = viewHolder.ivThumbnail; Picasso.with(getContext()).load(document.getThumbnail()) .fit() .centerCrop() .into(thumbnail); } @Override public int getItemCount() { return mDocuments.size(); } }
29.775
91
0.667086
f739d690562369eb65688db8d26f974c1d1e4585
1,459
package ellus.ESM.roboSys; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; /* ----------------------------------------------------------------------------- * get content form system clipboard. * use: * first new a instant of this. * then use the static getString() to get current contant from sys clipboard. * ----------------------------------------------------------------------------- */ public class clipBoard extends TimerTask { private static Clipboard tk = null; private static Timer tm = null; private static String data= null; public clipBoard() { if( tk == null ){ tk= Toolkit.getDefaultToolkit().getSystemClipboard(); tm= new Timer( "ClipBoard Timer" ); tm.schedule( this, 0, 333 ); } } public static String getString() { if( tk == null ) new clipBoard(); return data; } public static void setString( String inp ) { try{ StringSelection stringSelection= new StringSelection( inp ); tk.setContents( stringSelection, null ); }catch ( Exception ee ){ ee.printStackTrace(); } } @Override public void run() { try{ data= (String)tk.getData( DataFlavor.stringFlavor ); }catch ( UnsupportedFlavorException e ){}catch ( IOException e ){} } }
26.053571
80
0.636737
392689cb69fc0fb086f2296356872e875c5c8531
229
package com.fh.fhzhihudaily.ui.base; /** * LoadingView <br/> * Created by Jason.fang on 2016-04-25. */ public interface LoadingView { void showLoading(); void hideLoading(); void showError(CharSequence msg); }
15.266667
39
0.676856
e5202ca9ffcced928c1b729e6557361fe111ec99
307
package com.jsong.algorithm.linear_program; /** * * 线性规划求解 * * @see 线性规划算法详解 https://blog.csdn.net/we_phone/article/details/81268857 * @see 单纯形法算法 https://www.hrwhisper.me/introduction-to-simplex-algorithm/ * @author jsong * @date 12/7/2018 1:38 PM * @since 1.0 */ public class LinearProgram { }
19.1875
74
0.70684
cad1a929eb44a226fb2ff6c9a054eac0d4c25492
1,263
package gov.va.med.srcalc.web.controller; import gov.va.med.srcalc.web.view.VariableEntry; import java.util.*; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; /** * For testing purposes. Represents a set of dynamic variable value parameters * to add to an HTTP request. */ public class DynamicVarParams { private final HashMap<String, String> fValues = new HashMap<>(); public void add(final String varName, final String value) { fValues.put(varName, value); } public int getNumVariables() { return fValues.size(); } /** * Returns the variable names and values as a Map from name to value. This * is a live instance of the internal data: modifications will affect the * stored values. */ public Map<String, String> getPairs() { return fValues; } public MockHttpServletRequestBuilder addTo( final MockHttpServletRequestBuilder request) { for (final Map.Entry<String, String> pair : fValues.entrySet()) { request.param( VariableEntry.makeDynamicValuePath(pair.getKey()), pair.getValue()); } return request; } }
25.77551
82
0.639747
cd1d35b458b6a99c6b36eb0ef727ff8f06331cbc
1,269
package mekanism.common; import universalelectricity.core.item.IItemElectric; import ic2.api.IElectricItem; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class SlotEnergy { public static class SlotCharge extends Slot { public SlotCharge(IInventory inventory, int index, int x, int y) { super(inventory, index, x, y); } @Override public boolean isItemValid(ItemStack itemstack) { return (itemstack.getItem() instanceof IItemElectric && ((IItemElectric)itemstack.getItem()).getReceiveRequest(itemstack).amperes != 0) || itemstack.getItem() instanceof IElectricItem; } } public static class SlotDischarge extends Slot { public SlotDischarge(IInventory inventory, int index, int x, int y) { super(inventory, index, x, y); } @Override public boolean isItemValid(ItemStack itemstack) { return (itemstack.getItem() instanceof IElectricItem && ((IElectricItem)itemstack.getItem()).canProvideEnergy(itemstack)) || (itemstack.getItem() instanceof IItemElectric && ((IItemElectric)itemstack.getItem()).getProvideRequest(itemstack).amperes != 0) || itemstack.itemID == Item.redstone.itemID; } } }
29.511628
142
0.745469
252fc8deec2879e682bcddb37ee368db220da8dd
1,313
package com.woaiqw.library.model; import java.util.ArrayList; import java.util.List; /** * Created by haoran on 2018/10/22. */ public class Counter { private static volatile Counter instance = null; private List<Image> list = new ArrayList<>(); public static Counter getInstance() { if (null == instance) { synchronized (Counter.class) { if (null == instance) { instance = new Counter(); } } } return instance; } public List<Image> getCheckedList() { List<Image> checkedList = new ArrayList<>(); for (Image image : list) { if (image.checked) { checkedList.add(image); } } return checkedList; } public void setList(List<Image> images) { clear(); list.addAll(images); } public void clear() { list.clear(); } public List<Image> getList() { return list; } public void resetCheckedStatus(Image image, boolean isChecked) { for (Image image1 : list) { if (image != null && image1 != null) { if (image.equals(image1)) { image1.checked = isChecked; } } } } }
22.637931
68
0.50952
a5d0723e1970089769d3c5b205544e8b6b26f7f2
417
package com.jyutwaa.zhaoziliang.glimpse.Model.MainBgImage; import com.google.gson.annotations.SerializedName; /** * Created by zhaoziliang on 17/2/5. */ public class ImageResponse { @SerializedName("data") private ImageData imageData; public ImageData getImageData() { return imageData; } public void setImageData(ImageData imageData) { this.imageData = imageData; } }
18.954545
58
0.70024
644491d39aa193164509addb5b7d8ccea8048245
260
package yinlei.com.mvpdemo.mvp.view.impl; import yinlei.com.mvpdemo.mvp.view.MvpView; /** * 在此写用途 * * @version V1.0 <描述当前版本功能> * @FileName: BaseMvpView.java * @author: 若兰明月 * @date: 2016-08-14 23:07 */ public class BaseMvpView implements MvpView { }
16.25
45
0.696154
78b81773ea00d14eaea32b4ad6f4d96c3ab02610
1,191
package com.neusoft.core.dubbo; import org.apache.log4j.MDC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.dubbo.rpc.Filter; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.neusoft.core.util.TraceUtils; /** * 类DubboLogFilter.java的实现描述:配合dubbo做的日志切点,dubbo不允许service跟spring的aop融合即AnnotationBean有问题 * * @author Administrator 2017年5月8日 上午10:12:40 */ public class DubboLogFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DubboLogFilter.class); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Result r = null; try { TraceUtils.beginTrace(); MDC.put("url", invoker.getUrl()); MDC.put("clazz", invoker.getInterface()); MDC.put("method", invocation.getMethodName()); LOGGER.debug("执行方法开始"); r = invoker.invoke(invocation); LOGGER.debug("执行方法结束"); } finally { TraceUtils.endTrace(); } return r; } }
29.04878
89
0.68094
40a39ee40920d72e9dc3205d68cf2d215409dc4e
804
package sagex.miniclient.android.ui.settings; import android.os.Bundle; import android.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import sagex.miniclient.android.R; import sagex.miniclient.android.prefs.AndroidPrefStore; public class FixedRemuxingFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.remuxing_prefs, rootKey); PreferenceUtils.setDefaultValue(findPreference(AndroidPrefStore.FIXED_REMUXING_PREFERENCE), AndroidPrefStore.FIXED_REMUXING_PREFERENCE_DEFAULT); PreferenceUtils.setDefaultValue(findPreference(AndroidPrefStore.FIXED_REMUXING_FORMAT), AndroidPrefStore.FIXED_REMUXING_FORMAT_DEFAULT); } }
32.16
152
0.829602
4daf03a4fe44d77b9cbea8406f1e2f553f6b6dde
5,751
/* * 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.openjena.riot; import static org.openjena.riot.WebContent.contentTypeN3 ; import static org.openjena.riot.WebContent.contentTypeN3Alt1 ; import static org.openjena.riot.WebContent.contentTypeN3Alt2 ; import static org.openjena.riot.WebContent.contentTypeNQuads ; import static org.openjena.riot.WebContent.contentTypeNQuadsAlt ; import static org.openjena.riot.WebContent.contentTypeNTriples ; import static org.openjena.riot.WebContent.contentTypeNTriplesAlt ; import static org.openjena.riot.WebContent.contentTypeRDFXML ; import static org.openjena.riot.WebContent.contentTypeTriG ; import static org.openjena.riot.WebContent.contentTypeTriGAlt ; import static org.openjena.riot.WebContent.contentTypeTurtle ; import static org.openjena.riot.WebContent.contentTypeTurtleAlt1 ; import static org.openjena.riot.WebContent.contentTypeTurtleAlt2 ; import java.io.InputStream ; import java.util.HashMap ; import java.util.Map ; import org.openjena.atlas.lib.Sink ; import org.openjena.atlas.web.TypedInputStream ; import com.hp.hpl.jena.graph.Graph ; import com.hp.hpl.jena.graph.Triple ; import com.hp.hpl.jena.sparql.core.DatasetGraph ; import com.hp.hpl.jena.sparql.core.Quad ; /** Retrieve data from the web */ public class WebReader { /* where files are "on the web" */ // TODO base URIs. // Reuse FileManager and LocationMapper. public static void readGraph(Graph graph, String uri) { Lang lang = Lang.guess(uri) ; readGraph(graph, uri, lang) ; } public static void readGraph(Graph graph, String uri, Lang lang) { TypedInputStream typedInput = open(uri, lang) ; String contentType = typedInput.getMediaType() ; lang = chooseLang(contentType, lang) ; if ( lang == null ) throw new RiotException("Can't determine the syntax of <"+uri+"> (media type="+typedInput.getMediaType()+")") ; Sink<Triple> sink = RiotLoader.graphSink(graph) ; try { RiotLoader.readTriples(typedInput, lang, uri, sink) ; } finally { sink.close() ; } } static private Lang chooseLang(String contentType, Lang lang) { contentType = contentType.toLowerCase() ; return contentTypeToLang.get(contentType) ; } public static void readDataset(DatasetGraph dataset, String uri) { Lang lang = Lang.guess(uri) ; readDataset(dataset, uri, lang) ; } public static void readDataset(DatasetGraph dataset, String uri, Lang lang) { TypedInputStream typedInput = open(uri, lang) ; String contentType = typedInput.getMediaType() ; lang = chooseLang(contentType, lang) ; if ( lang == null ) throw new RiotException("Can't determine the syntax of <"+uri+"> (media type="+typedInput.getMediaType()+")") ; Sink<Quad> sink = RiotLoader.datasetSink(dataset) ; try { RiotLoader.readQuads(typedInput, lang, uri, sink) ; } finally { sink.close() ; } } private static TypedInputStream open(String uri, Lang lang) { // **** A FileManager that deals in TypedStreams properly (copy/rewrite) return new TypedInputStream(null, null/*Content-Type*/, null/*charset*/) ; } // ----------------------- // Extensibility. interface Process<T> { void parse(InputStream inputStream) ; } // Name? interface SinkTriplesFactory { Process<Triple> create(String contentType) ; } static private Map<String, Lang> contentTypeToLang = new HashMap<String, Lang>() ; // static public void addReader(String contentType, SinkTriplesFactory implFactory) {} // static public void removeReader(String contentType) {} // ----------------------- // No need for this - use content type to get lang. /** Media type name to language */ static { contentTypeToLang.put(contentTypeN3.toLowerCase(), Lang.N3) ; contentTypeToLang.put(contentTypeN3Alt1.toLowerCase(), Lang.N3) ; contentTypeToLang.put(contentTypeN3Alt2.toLowerCase(), Lang.N3) ; contentTypeToLang.put(contentTypeTurtle.toLowerCase(), Lang.TURTLE) ; contentTypeToLang.put(contentTypeTurtleAlt1.toLowerCase(), Lang.TURTLE) ; contentTypeToLang.put(contentTypeTurtleAlt2.toLowerCase(), Lang.TURTLE) ; contentTypeToLang.put(contentTypeNTriples.toLowerCase(), Lang.NTRIPLES) ; contentTypeToLang.put(contentTypeNTriplesAlt.toLowerCase(), Lang.NTRIPLES) ; contentTypeToLang.put(contentTypeRDFXML.toLowerCase(), Lang.RDFXML) ; contentTypeToLang.put(contentTypeTriG.toLowerCase(), Lang.TRIG) ; contentTypeToLang.put(contentTypeTriGAlt.toLowerCase(), Lang.TRIG) ; contentTypeToLang.put(contentTypeNQuads.toLowerCase(), Lang.NQUADS) ; contentTypeToLang.put(contentTypeNQuadsAlt.toLowerCase(), Lang.NQUADS) ; } }
39.122449
123
0.696575
6b855fe975f69cf3efaaf3513565f6d4fe897e60
1,440
package org.fkjava.menu.repository; import java.util.List; import org.fkjava.menu.domain.Menu; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface MenuRepository extends JpaRepository<Menu, String> { Menu findByNameAndParent(String name, Menu parent); Menu findByNameAndParentNull(String name); @Query("select max(number) from Menu where parent is null") Double findMaxNumberByParentNull(); // 使用冒号是命名参数,通过参数名来传值 // 使用使用?1表示非命名参数,通过第几个参数类传值 @Query("select max(number) from Menu where parent = :parent") Double findMaxNumberByParent(@Param("parent") Menu parent); List<Menu> findByParentNullOrderByNumber(); /** * 查询parent为指定参数的菜单,并且number要小于参数。返回的结果以number降序排列 * * @param parent 上级菜单 * @param number 要找小于number的菜单 * @param pageable 只要查询1条记录 * @return */ Page<Menu> findByParentAndNumberLessThanOrderByNumberDesc(Menu parent, Double number, Pageable pageable); /** * 查询parent为指定参数的菜单,并且number要大于参数。返回的结果以number升序排列 * * @param parent * @param number * @param pageable * @return */ Page<Menu> findByParentAndNumberGreaterThanOrderByNumberAsc(Menu parent, Double number, Pageable pageable); }
28.235294
108
0.781944
802e7c4d4d3800f2b629d30208fb411bc2014a3d
5,678
//| Copyright - The University of Edinburgh 2011 | //| | //| 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. | /******************************************************************************* * Copyright (c) - The University of Edinburgh 2010 *******************************************************************************/ package uk.ac.ed.epcc.webapp.apps; import java.util.Iterator; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import uk.ac.ed.epcc.webapp.AppContext; import uk.ac.ed.epcc.webapp.forms.registry.FormFactoryProvider; import uk.ac.ed.epcc.webapp.forms.registry.FormFactoryProviderRegistry; import uk.ac.ed.epcc.webapp.forms.registry.FormFactoryProviderTransitionProvider; import uk.ac.ed.epcc.webapp.forms.registry.FormOperations; import uk.ac.ed.epcc.webapp.forms.transition.IndexTransitionFactory; import uk.ac.ed.epcc.webapp.forms.transition.TransitionFactory; import uk.ac.ed.epcc.webapp.forms.transition.TransitionFactoryFinder; import uk.ac.ed.epcc.webapp.session.SessionService; public class AdminForms extends GraphicsCommand implements Command { public AdminForms(AppContext conn) { super(conn); } @SuppressWarnings("unchecked") protected JPanel getMainPanel(JFrame frame,SessionService session_service) { JPanel main = new JPanel(); main.setLayout(new BoxLayout(main, BoxLayout.PAGE_AXIS)); main.add(new JLabel("Admin Forms")); main.setName("main"); for(String name : getContext().getInitParameter("form.registry.list","").split(",") ){ if( name.trim().length() > 0 ){ int count=0; FormFactoryProviderRegistry registry = getContext().makeObjectWithDefault(FormFactoryProviderRegistry.class,null,name.trim()); if(registry != null ){ JPanel section = new JPanel(); section.setLayout(new BoxLayout(section, BoxLayout.PAGE_AXIS)); //JLabel section_title = new JLabel(registry.getTitle()); ////section_title.setBackground(Color.DARK_GRAY); ////section_title.setOpaque(true); // transparent by default //section.add(section_title); section.setBorder(BorderFactory.createTitledBorder(registry.getTitle())); section.setName(registry.getTitle()); for(Iterator it=registry.getTypes(); it.hasNext(); ){ FormFactoryProvider t= (FormFactoryProvider) it.next(); if( t.canCreate(session_service)|| t.canUpdate(session_service)){ count ++; JPanel type = new JPanel(); section.add(type); type.add(new JLabel(t.getName())); FormFactoryProviderTransitionProvider tp = new FormFactoryProviderTransitionProvider(getContext(), t.getName(), t); if( t.canCreate(session_service) ){ JButton button = new JButton("Create new "+t.getName()); type.add(button); button.addActionListener( new TransitionActionListener(tp, FormOperations.Create, null)); }else{ log.debug("Cannot create "+t.getName()); } if( t.canUpdate(session_service) ){ JButton button = new JButton("Update "+t.getName()); type.add(button); button.addActionListener( new TransitionActionListener(tp, FormOperations.Update, null)); }else{ log.debug("cannot update "+t.getName()); } } } if( count > 0){ main.add(section); } } } } JPanel transitions = new JPanel(); transitions.setLayout(new BoxLayout(transitions, BoxLayout.PAGE_AXIS)); //JLabel section_title = new JLabel(registry.getTitle()); ////section_title.setBackground(Color.DARK_GRAY); ////section_title.setOpaque(true); // transparent by default //section.add(section_title); transitions.setBorder(BorderFactory.createTitledBorder("Transitions")); transitions.setName("Transitions"); transitions.add(new JLabel("Index transtitions")); TransitionFactoryFinder finder = new TransitionFactoryFinder(getContext()); for(String name : getContext().getInitParameter("form.transition.list","").split(",") ){ TransitionFactory fac = finder.getProviderFromName(name); if( fac != null && fac instanceof IndexTransitionFactory) { Object index = ((IndexTransitionFactory)fac).getIndexTransition(); if( fac.allowTransition(getContext(), null, index)) { JPanel type = new JPanel(); JButton button = new JButton(name); type.add(button); button.addActionListener( new TransitionActionListener(fac, index, null)); transitions.add(type); } } } main.add(transitions); main.validate(); return main; } public String description() { return "Admin GUI forms"; } public String help() { return "Accesses admin forms through stand alone gui"; } }
40.269504
130
0.643184
d6b3efcca1081045083cd22aa8f343bcd2f2c81a
1,473
/* * Copyright © 2017 camunda services GmbH (info@camunda.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.zeebe.http; import java.util.Optional; import java.util.concurrent.CountDownLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZeebeHttpWorkerApplication { public static final String ENV_CONTACT_POINT = "zeebe.client.broker.contactPoint"; private static final String DEFAULT_CONTACT_POINT = "127.0.0.1:26500"; private static Logger LOG = LoggerFactory.getLogger("zeebe-http-worker"); public static void main(String[] args) { final String contactPoint = Optional.ofNullable(System.getenv(ENV_CONTACT_POINT)).orElse(DEFAULT_CONTACT_POINT); LOG.info("Connecting worker to {}", contactPoint); final ZeebeHttpWorker worker = new ZeebeHttpWorker(contactPoint); worker.start(); try { new CountDownLatch(1).await(); } catch (InterruptedException e) { } } }
32.021739
92
0.740665
89f368c4216c94d6ac816c766e70a1997e25771a
1,695
package pokecube.core.moves.implementations.attacks.special; import net.minecraft.entity.EntityLivingBase; import pokecube.core.interfaces.PokecubeMod; import pokecube.core.interfaces.pokemob.moves.MovePacket; import pokecube.core.moves.PokemobDamageSource; import pokecube.core.moves.templates.Move_Basic; public class MoveCounter extends Move_Basic { public MoveCounter() { super("counter"); } @Override public void postAttack(MovePacket packet) { super.postAttack(packet); if (packet.canceled || packet.failed) return; EntityLivingBase attacker = packet.attacker.getEntity(); if (!packet.attacker.getMoveStats().biding) { attacker.getEntityData().setLong("bideTime", attacker.getEntityWorld().getTotalWorldTime() + PokecubeMod.core.getConfig().attackCooldown); packet.attacker.getMoveStats().biding = true; packet.attacker.getMoveStats().PHYSICALDAMAGETAKENCOUNTER = 0; } else { if (attacker.getEntityData().getLong("bideTime") < attacker.getEntityWorld().getTotalWorldTime()) { attacker.getEntityData().removeTag("bideTime"); int damage = 2 * packet.attacker.getMoveStats().PHYSICALDAMAGETAKENCOUNTER; packet.attacker.getMoveStats().PHYSICALDAMAGETAKENCOUNTER = 0; if (packet.attacked != null) packet.attacked.attackEntityFrom( new PokemobDamageSource("mob", attacker, this), damage); packet.attacker.getMoveStats().biding = false; } } } }
38.522727
114
0.637168
b1bbb4f64a4df5b8410120ae8561ac7cf09fde62
18,743
/* * Copyright (C) 2015 Jared Luo * jaredlam86@gmail.com * * 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.jaredlam.bubbleview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Point; import android.graphics.Rect; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class BubbleLayout extends ViewGroup implements BubbleView.MoveListener { public static final int DEFAULT_PADDING = 10; public static final int DEFAULT_MIN_SPEED = 200; public static final int DEFAULT_MAX_SPEED = 500; private int padding = DEFAULT_PADDING; private int minPxPerTenMilliseconds = DEFAULT_MIN_SPEED; private int maxPxPerTenMilliseconds = DEFAULT_MAX_SPEED; private double mRadiansPiece = 2 * Math.PI / 6; private int mRandomRadians = 0; private List<BubbleInfo> mBubbleInfos = new ArrayList<>(); private Timer mTimer; private MyHandler mHandler; public BubbleLayout(Context context) { this(context, null); } public BubbleLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BubbleLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.bubbleview_BubbleLayout, defStyleAttr, 0); for (int i = 0; i < typedArray.getIndexCount(); i++) { int id = typedArray.getIndex(i); if (id == R.styleable.bubbleview_BubbleLayout_bubbleview_minSpeed) { minPxPerTenMilliseconds = typedArray.getDimensionPixelSize(id, DEFAULT_MIN_SPEED); } else if (id == R.styleable.bubbleview_BubbleLayout_bubbleview_maxSpeed) { maxPxPerTenMilliseconds = typedArray.getDimensionPixelSize(id, DEFAULT_MAX_SPEED); } else if (id == R.styleable.bubbleview_BubbleLayout_bubbleview_padding) { padding = typedArray.getDimensionPixelSize(id, DEFAULT_PADDING); } } typedArray.recycle(); mRandomRadians = getRandomBetween(0, (int) (2 * Math.PI)); mHandler = new MyHandler(this); mHandler.sendEmptyMessage(0); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { Rect baseRect = null; int currentRadians = mRandomRadians; List<BubbleView> sortResult = sort(); for (int i = 0; i < sortResult.size(); i++) { View child = sortResult.get(i); BubbleInfo bubbleInfo = getBubbleInfoByView(child); if (bubbleInfo != null) { BubbleView bubbleView = (BubbleView) child; bubbleView.setMoveListener(this); bubbleView.setBubbleInfo(bubbleInfo); int radius = bubbleView.getMeasuredWidth() / 2; if (i == 0) { baseRect = getBounds(getMeasuredWidth() / 2 - radius, getMeasuredHeight() / 2 - radius, child.getMeasuredWidth(), child.getMeasuredHeight()); child.layout(baseRect.left, baseRect.top, baseRect.right, baseRect.bottom); bubbleInfo.setRect(baseRect); } else { int baseCenterX = baseRect.left + baseRect.width() / 2; int baseCenterY = baseRect.top + baseRect.width() / 2; currentRadians += mRadiansPiece; int[] center = getRadianPoint(baseRect.width() / 2 + padding + radius, baseCenterX, baseCenterY, currentRadians); Rect rect = getBounds(center[0] - radius, center[1] - radius, child.getMeasuredWidth(), child.getMeasuredHeight()); child.layout(rect.left, rect.top, rect.right, rect.bottom); bubbleInfo.setRect(rect); } } } } private BubbleInfo getBubbleInfoByView(View child) { for (BubbleInfo info : mBubbleInfos) { BubbleView bubbleView = (BubbleView) getChildAt(info.getIndex()); if (bubbleView == child) { return info; } } return null; } private int[] getRadianPoint(int amount, int x, int y, double radian) { int resultX = x + (int) (amount * Math.cos(radian)); int resultY = y + (int) (amount * Math.sin(radian)); return new int[]{resultX, resultY}; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); setupBubbleInfoList(); switch (widthMode) { case MeasureSpec.EXACTLY: case MeasureSpec.AT_MOST: break; } switch (heightMode) { case MeasureSpec.EXACTLY: break; case MeasureSpec.AT_MOST: case MeasureSpec.UNSPECIFIED: break; } setMeasuredDimension(widthSize, heightSize); } public void addViewSortByWidth(BubbleView newChild) { LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); newChild.setLayoutParams(param); if (getChildCount() > 0) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child instanceof BubbleView) { BubbleView bubbleView = (BubbleView) child; float textWidth = bubbleView.getTextMeasureWidth(); if (newChild.getTextMeasureWidth() > textWidth) { super.addView(newChild, i); return; } } } } super.addView(newChild); } private void setupBubbleInfoList() { int count = getChildCount(); for (int i = 0; i < count; i++) { BubbleInfo info = new BubbleInfo(); info.setRadians(getRandomRadians()); info.setSpeed(getRandomBetween(minPxPerTenMilliseconds, maxPxPerTenMilliseconds)); info.setOldSpeed(info.getSpeed()); info.setIndex(i); mBubbleInfos.add(info); } } private int getRandomBetween(int min, int max) { return min + (int) (Math.random() * ((max - min) + 1)); } private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); } private Rect getBounds(int left, int top, int width, int height) { return new Rect(left, top, left + width, top + height); } private boolean doRectOverlap(Rect rect0, Rect rect1) { return !(rect0.left > rect1.right || rect1.left > rect0.right) && !(rect0.top > rect1.bottom || rect1.top > rect0.bottom); } private boolean doCircleOverlap(Rect rect0, Rect rect1) { int x0 = rect0.centerX(); int y0 = rect0.centerY(); int r0 = rect0.width() / 2; int x1 = rect1.centerX(); int y1 = rect1.centerY(); int r1 = rect1.width() / 2; return Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2) <= Math.pow(r0 + r1, 2); } private boolean chooseFromTwo() { return Math.random() > 0.5; } private List<BubbleView> sort() { List<BubbleView> allBubbleChild = new ArrayList<>(); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if (view != null && view instanceof BubbleView) { allBubbleChild.add((BubbleView) view); } } List<BubbleView> sortResult = new ArrayList<>(); if (allBubbleChild.size() > 2) { sortResult.add(allBubbleChild.get(0)); sortResult.add(allBubbleChild.get(1)); List<BubbleView> halfList = allBubbleChild.subList(2, allBubbleChild.size()); List<BubbleView> quarter1List = halfList.subList(0, halfList.size() / 2); List<BubbleView> quarter2List = halfList.subList(halfList.size() / 2, halfList.size()); int count = Math.max(quarter1List.size(), quarter2List.size()); for (int i = 0; i < count; i++) { if (i < quarter2List.size()) { sortResult.add(quarter2List.get(i)); } if (i < quarter1List.size()) { sortResult.add(quarter1List.get(i)); } } } else { sortResult = allBubbleChild; } return sortResult; } private void startAnimate() { if (mTimer == null) { mTimer = new Timer(); } mTimer.schedule(new TimerTask() { @Override public void run() { mHandler.sendEmptyMessage(0); this.cancel(); } }, 10); } private static class MyHandler extends Handler { private WeakReference<BubbleLayout> mBubbleLayout; public MyHandler(BubbleLayout layout) { this.mBubbleLayout = new WeakReference<>(layout); } @Override public void handleMessage(Message msg) { BubbleLayout layout = mBubbleLayout.get(); int count = layout.getChildCount(); for (int i = 0; i < count && layout.mBubbleInfos.size() > 0; i++) { BubbleInfo bubbleInfo = layout.mBubbleInfos.get(i); List<BubbleInfo> overlapList = layout.hasOverlap(bubbleInfo); Point overlapPoint = layout.ifOverlapBounds(bubbleInfo); if (overlapPoint != null) { layout.reverseIfOverlapBounds(bubbleInfo); } else if (overlapList.size() > 0) { layout.dealWithOverlap(); } layout.moveBubble(bubbleInfo); } layout.startAnimate(); } } ; private void moveBubble(BubbleInfo info) { View child = getChildAt(info.getIndex()); int[] center = getRadianPoint(info.getSpeed(), child.getLeft() + child.getWidth() / 2, child.getTop() + child.getWidth() / 2, info.getRadians()); Rect rect = getBounds(center[0] - child.getWidth() / 2, center[1] - child.getWidth() / 2, child.getMeasuredWidth(), child.getMeasuredHeight()); info.setRect(rect); child.layout(rect.left, rect.top, rect.right, rect.bottom); } private void slowerBubbleIfNeeded(BubbleInfo info) { if (info.getOldSpeed() > 0 && info.getSpeed() > info.getOldSpeed()) { info.setSpeed(info.getSpeed() - 1); } } private BubbleInfo getNewMoveInfo(BubbleInfo bubbleInfo, View child, List<BubbleInfo> overlapRect) { Rect oldRect = bubbleInfo.getRect(); Point cooperate = getCooperatePoint(overlapRect); Point overlapBoundPoint = ifOverlapBounds(bubbleInfo); if (overlapBoundPoint != null) { cooperate = new Point((cooperate.x + overlapBoundPoint.x) / 2, (cooperate.y + overlapBoundPoint.y) / 2); } float overlapRadians = (float) getRadians(new float[]{oldRect.exactCenterX(), oldRect.exactCenterY()}, new float[]{cooperate.x, cooperate.y}); double reverseRadians = getReverseRadians(overlapRadians); int[] centerNew = getRadianPoint(bubbleInfo.getSpeed(), child.getLeft() + child.getWidth() / 2, child.getTop() + child.getWidth() / 2, reverseRadians); Rect rectNew = getBounds(centerNew[0] - child.getWidth() / 2, centerNew[1] - child.getWidth() / 2, child.getMeasuredWidth(), child.getMeasuredHeight()); BubbleInfo bubbleInfoNew = new BubbleInfo(); bubbleInfoNew.setIndex(bubbleInfo.getIndex()); bubbleInfoNew.setSpeed(bubbleInfo.getSpeed()); bubbleInfoNew.setOldSpeed(bubbleInfo.getOldSpeed()); bubbleInfoNew.setRadians(reverseRadians); bubbleInfoNew.setRect(rectNew); return bubbleInfoNew; } private void dealWithOverlap() { List<BubbleInfo> tempBubbleInfoList = new ArrayList<>(); for (BubbleInfo info : mBubbleInfos) { List<BubbleInfo> overlapList = hasOverlap(info); if (overlapList.size() > 0) { BubbleInfo bubbleInfoNew = getNewMoveInfo(info, getChildAt(info.getIndex()), overlapList); slowerBubbleIfNeeded(bubbleInfoNew); tempBubbleInfoList.add(bubbleInfoNew); } } for (int i = 0; i < tempBubbleInfoList.size(); i++) { BubbleInfo tempBubbleInfo = tempBubbleInfoList.get(i); BubbleInfo oldBubbleInfo = mBubbleInfos.get(tempBubbleInfo.getIndex()); oldBubbleInfo.setRadians(tempBubbleInfo.getRadians()); oldBubbleInfo.setOldSpeed(tempBubbleInfo.getOldSpeed()); oldBubbleInfo.setIndex(tempBubbleInfo.getIndex()); oldBubbleInfo.setSpeed(tempBubbleInfo.getSpeed()); oldBubbleInfo.setRect(tempBubbleInfo.getRect()); } } private Point getCooperatePoint(List<BubbleInfo> overlapRect) { int totalX = 0; int totalY = 0; for (BubbleInfo info : overlapRect) { totalX += info.getRect().exactCenterX(); totalY += info.getRect().exactCenterY(); } return new Point(totalX / overlapRect.size(), totalY / overlapRect.size()); } private double getReverseRadians(double radians) { double reverseRadians; if (radians > Math.PI) { reverseRadians = radians - Math.PI; } else { reverseRadians = radians + Math.PI; } return reverseRadians; } private List<BubbleInfo> hasOverlap(BubbleInfo bubbleInfo) { int count = mBubbleInfos.size(); List<BubbleInfo> overlapList = new ArrayList<>(); if (bubbleInfo.getRect() != null) { for (int i = 0; i < count; i++) { BubbleInfo otherInfo = mBubbleInfos.get(i); if (i != bubbleInfo.getIndex()) { if (otherInfo.getRect() != null) { if (doCircleOverlap(otherInfo.getRect(), bubbleInfo.getRect())) { overlapList.add(otherInfo); } } } } } return overlapList; } private void reverseIfOverlapBounds(BubbleInfo bubbleInfo) { Point overlapPoint = ifOverlapBounds(bubbleInfo); Rect totalRect = new Rect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); if (overlapPoint != null) { float overlapRadians = (float) getRadians(new float[]{bubbleInfo.getRect().exactCenterX(), bubbleInfo.getRect().exactCenterY()}, new float[]{overlapPoint.x, overlapPoint.y}); if (!totalRect.contains(bubbleInfo.getRect().centerX(), bubbleInfo.getRect().centerY())) { bubbleInfo.setRadians(overlapRadians); } else { double reverseRadians = getReverseRadians(overlapRadians); bubbleInfo.setRadians(reverseRadians); } slowerBubbleIfNeeded(bubbleInfo); } } private Point ifOverlapBounds(BubbleInfo bubbleInfo) { Rect rect = new Rect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); if (bubbleInfo.getRect() != null) { Rect bubbleRect = bubbleInfo.getRect(); List<Point> overlapPoints = new ArrayList<>(); if (rect.left >= bubbleRect.left) { Point overlapPoint = new Point(rect.left, bubbleRect.centerY()); overlapPoints.add(overlapPoint); } if (rect.top >= bubbleRect.top) { Point overlapPoint = new Point(bubbleRect.centerX(), rect.top); overlapPoints.add(overlapPoint); } if (rect.right <= bubbleRect.right) { Point overlapPoint = new Point(rect.right, bubbleRect.centerY()); overlapPoints.add(overlapPoint); } if (rect.bottom <= bubbleRect.bottom) { Point overlapPoint = new Point(bubbleRect.centerX(), rect.bottom); overlapPoints.add(overlapPoint); } if (overlapPoints.size() > 0) { int totalX = 0; int totalY = 0; for (Point point : overlapPoints) { totalX += point.x; totalY += point.y; } return new Point(totalX / overlapPoints.size(), totalY / overlapPoints.size()); } } return null; } private double getRandomRadians() { return Math.random() * 2 * Math.PI; } private double getRadians(float[] fromPoint, float[] toPoint) { return Math.atan2(toPoint[1] - fromPoint[1], toPoint[0] - fromPoint[0]); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mTimer != null) { mTimer.cancel(); mTimer = null; } } @Override public void onMove(BubbleInfo bubbleInfo, int centerX, int centerY, int deltaX, int deltaY, double velocity) { velocity /= 6; if (velocity > bubbleInfo.getSpeed()) { float radians = (float) getRadians(new float[]{centerX, centerY}, new float[]{centerX + deltaX, centerY + deltaY}); bubbleInfo.setRadians(radians); bubbleInfo.setSpeed((int) velocity); } } }
38.095528
186
0.596809
0ccb3ecf84ce2ed0fbdac48bba5f66c85bbf5e9f
2,724
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import static model.DBConnection.conn; import view.Books; /** * * @author EACMS */ public class UserSignInModel { public static int canSignIn(String name, String UserName, String email, String mobile, String Password) { PreparedStatement pstmt; Statement stmt; ResultSet rs; int rowCount = 0; try { stmt = DBConnection.getStatementConnection(); pstmt = conn.prepareStatement("select * from users where email = ? "); pstmt.setString(1, email); System.out.println("sql query " + pstmt.toString()); rs = pstmt.executeQuery(); while (rs.next()) { rowCount++; } if (rowCount == 0) { pstmt = conn.prepareStatement("INSERT INTO users (email,fullName,userName,mobile,password) VALUES (?,?,?,?,?)"); pstmt.setString(1, email); pstmt.setString(2, name); pstmt.setString(3, UserName); pstmt.setString(4, mobile); pstmt.setString(5, Password); System.out.println("sql query " + pstmt.toString()); pstmt.executeUpdate(); rowCount = 0; } else if (rowCount > 0) { System.out.println("Email is already taken in model"); } } catch (Exception e) { e.printStackTrace(); System.out.println("error in dbsearch"); } System.out.println(rowCount); return rowCount; } public static int gettingUId(String email, String password) { PreparedStatement pstmt; Statement stmt; int USERID = 0; try { stmt = DBConnection.getStatementConnection(); pstmt = conn.prepareStatement("select * from users where email = ? AND password= ?"); pstmt.setString(1, email); pstmt.setString(2, password); System.out.println("sql query " + pstmt.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { USERID = rs.getInt("userId"); System.out.println(USERID); } } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } return USERID; } }
33.62963
129
0.567915
e4e32daebb33f09456f898bc111cd52a5c18dea9
282
package org.brapi.test.BrAPITestServer.repository.core; import org.brapi.test.BrAPITestServer.model.entity.pheno.TraitEntity; import org.brapi.test.BrAPITestServer.repository.core.BrAPIRepository; public interface TraitRepository extends BrAPIRepository<TraitEntity, String> { }
31.333333
79
0.847518
07f24e84b11557a6209ca39dfa9f64a60a48e95c
3,271
package br.ufsc.ppgcc.experion.model.evidence; import br.ufsc.ppgcc.experion.extractor.evidence.PhysicalEvidence; import br.ufsc.ppgcc.experion.model.evidence.builder.LogicalEvidenceBuilder; import br.ufsc.ppgcc.experion.model.expert.Expert; import br.ufsc.ppgcc.experion.view.expertise.Expertise; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * A logical evidence is generated from a set of physical evidences, by applying a given method. It represents a * more stable expertise evidence that the phyisical evidence. * * @author Rodrigo Gonçalves * @version 2019-03-05 - First version * */ @Entity public class LogicalEvidence implements Serializable { /** Primary key - auto-generated by JPA */ @GeneratedValue @Id private int id; /** The generated concept from the physical evidences */ @Lob private String concept; /** The set of physical evidences used to generate this logical evidence */ @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<PhysicalEvidence> physicalEvidences = new HashSet<>(); /** The logical evidence builder used to generate this logical evidence */ @ManyToOne private LogicalEvidenceBuilder builder; /** The expertise in which this logical evidence was used */ @ManyToMany @JsonBackReference private Set<Expertise> expertise = new HashSet<>(); /** The expert associated with this logical evidence */ @ManyToOne private Expert expert; /** The language from the data over which this logical evidence was built */ private String language; public LogicalEvidence() { } public LogicalEvidence(String concept) { this.concept = concept; } @Override public String toString() { String result = "Concept: " + this.getConcept(); for (PhysicalEvidence physicalEvidence : this.getPhysicalEvidences()) { result += "\n\t" + physicalEvidence.toString(); } return result; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getConcept() { return concept; } public void setConcept(String concept) { this.concept = concept; } public Set<PhysicalEvidence> getPhysicalEvidences() { return physicalEvidences; } public void setPhysicalEvidences(Set<PhysicalEvidence> physicalEvidences) { this.physicalEvidences = physicalEvidences; } public LogicalEvidenceBuilder getBuilder() { return builder; } public void setBuilder(LogicalEvidenceBuilder builder) { this.builder = builder; } public Set<Expertise> getExpertise() { return expertise; } public void setExpertise(Set<Expertise> expertise) { this.expertise = expertise; } public Expert getExpert() { return expert; } public void setExpert(Expert expert) { this.expert = expert; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
25.960317
112
0.679303
e268bb8e872e6cad1f04914be3fed9397de23c44
4,585
package dev.cstv.musify.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.validator.constraints.Range; import org.hibernate.validator.constraints.URL; import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; @Entity @Table(name = "Song") public class Song { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "title", length = 500, nullable = false) @NotNull(message = "{NotNull}") private String title; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "genre") @JsonIgnore private Genre genre; @NotNull(message = "{NotNull}") @URL(message = "{URL}") @Column(name = "url") private String url; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "album") @JsonIgnore private Album album; @NotNull @Range(min = 1, max = 10, message = "{Duration}") @Column(name = "duration") private Integer duration; @NotNull @Temporal(TemporalType.DATE) @Column(name = "releaseDate") private Date releaseDate; @Valid @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "artist") @JsonIgnore private Artist artist; @JsonIgnore @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "song") private List<ChartSong> chartSongs = new ArrayList<>(); public List<ChartSong> getChartSongs() { return chartSongs; } public void addChartSong(ChartSong chartSong) { this.chartSongs.add(chartSong); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public Album getAlbum() { return album; } public void setAlbum(Album album) { this.album = album; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public Artist getArtist() { return artist; } public void setArtist(Artist artist) { this.artist = artist; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Song)) return false; Song song = (Song) o; return Objects.equals(id, song.id) && Objects.equals(title, song.title) && Objects.equals(genre, song.genre) && Objects.equals(url, song.url) && Objects.equals(album, song.album) && Objects.equals(duration, song.duration) && Objects.equals(releaseDate, song.releaseDate) && Objects.equals(artist, song.artist) && Objects.equals(chartSongs, song.chartSongs); } @Override public int hashCode() { return Objects.hash(id, title, genre, url, album, duration, releaseDate, artist, chartSongs); } public static class Builder { private Song song; public Builder() { song = new Song(); } public Builder setTitle(String title) { song.title = title; return this; } public Builder setGenre(Genre genre) { song.genre = genre; return this; } public Builder setDuration(Integer duration) { song.duration = duration; return this; } public Builder setUrl(String url) { song.url = url; return this; } public Builder setReleaseDate(Date releaseDate) { song.releaseDate = releaseDate; return this; } public Builder setArtist(Artist artist) { song.artist = artist; return this; } public Song build() { return song; } } }
23.156566
101
0.592803
93c49aec5c67c363e1127b4072ce7161cc4c2a5c
5,828
/* * 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.skywalking.library.elasticsearch.bulk; import com.linecorp.armeria.common.HttpStatus; import com.linecorp.armeria.common.util.Exceptions; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.skywalking.library.elasticsearch.ElasticSearch; import org.apache.skywalking.library.elasticsearch.requests.IndexRequest; import org.apache.skywalking.library.elasticsearch.requests.UpdateRequest; import org.apache.skywalking.library.elasticsearch.requests.factory.RequestFactory; import static java.util.Objects.requireNonNull; @Slf4j public final class BulkProcessor { private final ArrayBlockingQueue<Object> requests; private final AtomicReference<ElasticSearch> es; private final int bulkActions; private final Semaphore semaphore; public static BulkProcessorBuilder builder() { return new BulkProcessorBuilder(); } BulkProcessor( final AtomicReference<ElasticSearch> es, final int bulkActions, final Duration flushInterval, final int concurrentRequests) { requireNonNull(flushInterval, "flushInterval"); this.es = requireNonNull(es, "es"); this.bulkActions = bulkActions; this.semaphore = new Semaphore(concurrentRequests > 0 ? concurrentRequests : 1); this.requests = new ArrayBlockingQueue<>(bulkActions + 1); final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor( 1, r -> { final Thread thread = new Thread(r); thread.setName("ElasticSearch BulkProcessor"); return thread; }); scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); scheduler.setRemoveOnCancelPolicy(true); scheduler.scheduleWithFixedDelay( this::flush, 0, flushInterval.getSeconds(), TimeUnit.SECONDS); } public BulkProcessor add(IndexRequest request) { internalAdd(request); return this; } public BulkProcessor add(UpdateRequest request) { internalAdd(request); return this; } @SneakyThrows private void internalAdd(Object request) { requireNonNull(request, "request"); requests.put(request); flushIfNeeded(); } @SneakyThrows private void flushIfNeeded() { if (requests.size() >= bulkActions) { flush(); } } void flush() { if (requests.isEmpty()) { return; } try { semaphore.acquire(); } catch (InterruptedException e) { log.error("Interrupted when trying to get semaphore to execute bulk requests", e); return; } final List<Object> batch = new ArrayList<>(requests.size()); requests.drainTo(batch); final CompletableFuture<Void> flush = doFlush(batch); flush.whenComplete((ignored1, ignored2) -> semaphore.release()); flush.join(); } private CompletableFuture<Void> doFlush(final List<Object> batch) { log.debug("Executing bulk with {} requests", batch.size()); if (batch.isEmpty()) { return CompletableFuture.completedFuture(null); } final CompletableFuture<Void> future = es.get().version().thenCompose(v -> { try { final RequestFactory rf = v.requestFactory(); final List<byte[]> bs = new ArrayList<>(); for (final Object request : batch) { bs.add(v.codec().encode(request)); bs.add("\n".getBytes()); } final ByteBuf content = Unpooled.wrappedBuffer(bs.toArray(new byte[0][])); return es.get().client().execute(rf.bulk().bulk(content)) .aggregate().thenAccept(response -> { final HttpStatus status = response.status(); if (status != HttpStatus.OK) { throw new RuntimeException(response.contentUtf8()); } }); } catch (Exception e) { return Exceptions.throwUnsafely(e); } }); future.whenComplete((ignored, exception) -> { if (exception != null) { log.error("Failed to execute requests in bulk", exception); } else { log.debug("Succeeded to execute {} requests in bulk", batch.size()); } }); return future; } }
36.886076
94
0.652539
00d411d3687a00838e0c121c0ac5c42028f9e4f4
474
package com.wytings.scananimation; import android.app.Activity; import android.os.Bundle; import android.widget.FrameLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout frameLayout = findViewById(R.id.frame_layout); frameLayout.setForeground(new ScanDrawable(this, 15)); } }
27.882353
66
0.748945
4eb0510e0333e50a7d739c2f2edd7baa6b39b906
4,299
/* * Copyright (C) 2017-2018 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.dac.explore.model; import com.dremio.dac.model.common.Acceptor; import com.dremio.dac.model.common.EnumTypeIdResolver; import com.dremio.dac.model.common.TypesEnum; import com.dremio.dac.model.common.VisitorException; import com.dremio.dac.proto.model.dataset.Transform; import com.dremio.dac.proto.model.dataset.TransformAddCalculatedField; import com.dremio.dac.proto.model.dataset.TransformConvertCase; import com.dremio.dac.proto.model.dataset.TransformConvertToSingleType; import com.dremio.dac.proto.model.dataset.TransformCreateFromParent; import com.dremio.dac.proto.model.dataset.TransformDrop; import com.dremio.dac.proto.model.dataset.TransformExtract; import com.dremio.dac.proto.model.dataset.TransformField; import com.dremio.dac.proto.model.dataset.TransformFilter; import com.dremio.dac.proto.model.dataset.TransformGroupBy; import com.dremio.dac.proto.model.dataset.TransformJoin; import com.dremio.dac.proto.model.dataset.TransformLookup; import com.dremio.dac.proto.model.dataset.TransformRename; import com.dremio.dac.proto.model.dataset.TransformSort; import com.dremio.dac.proto.model.dataset.TransformSorts; import com.dremio.dac.proto.model.dataset.TransformSplitByDataType; import com.dremio.dac.proto.model.dataset.TransformTrim; import com.dremio.dac.proto.model.dataset.TransformType; import com.dremio.dac.proto.model.dataset.TransformUpdateSQL; import com.dremio.dac.util.JSONUtil; import com.dremio.datastore.Converter; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; /** * Transform base class */ @JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeIdResolver(EnumTypeIdResolver.class) @TypesEnum(types = TransformType.class, format = "com.dremio.dac.proto.model.dataset.Transform%s") public abstract class TransformBase { public static final Acceptor<TransformBase, TransformVisitor<?>, Transform> acceptor = new Acceptor<TransformBase, TransformVisitor<?>, Transform>(){}; public final <T> T accept(TransformVisitor<T> visitor) throws VisitorException { return acceptor.accept(visitor, this); } public Transform wrap() { return acceptor.wrap(this); } @Override public String toString() { return JSONUtil.toString(this); } /** * Type safe mechanism to handle all possible transforms * * @param <T> */ public interface TransformVisitor<T> { T visit(TransformLookup lookup) throws Exception; T visit(TransformJoin join) throws Exception; T visit(TransformSort sort) throws Exception; T visit(TransformSorts sortMultiple) throws Exception; T visit(TransformDrop drop) throws Exception; T visit(TransformRename rename) throws Exception; T visit(TransformConvertCase convertCase) throws Exception; T visit(TransformTrim trim) throws Exception; T visit(TransformExtract extract) throws Exception; T visit(TransformAddCalculatedField addCalculatedField) throws Exception; T visit(TransformUpdateSQL updateSQL) throws Exception; T visit(TransformField field) throws Exception; T visit(TransformConvertToSingleType convertToSingleType) throws Exception; T visit(TransformSplitByDataType splitByDataType) throws Exception; T visit(TransformGroupBy groupBy) throws Exception; T visit(TransformFilter filter) throws Exception; T visit(TransformCreateFromParent createFromParent) throws Exception; } public static TransformBase unwrap(Transform t) { return acceptor.unwrap(t); } public static Converter<TransformBase, Transform> converter() { return acceptor.converter(); } }
42.147059
153
0.788788
e9870d484a3b4f850775256b1059ba611e1a97b8
6,109
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.core.graph.util; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Predicate; import org.kie.workbench.common.stunner.core.api.DefinitionManager; import org.kie.workbench.common.stunner.core.graph.Edge; import org.kie.workbench.common.stunner.core.graph.Element; import org.kie.workbench.common.stunner.core.graph.Node; import org.kie.workbench.common.stunner.core.graph.content.definition.Definition; import org.kie.workbench.common.stunner.core.graph.content.view.View; /** * A predicate that checks if two nodes are using sharing the same parent * for a given type of Definition. It also filters a given node and * used the given parent as a candidate for it, instead of * processing the graph structure. */ public class FilteredParentsTypeMatcher implements BiPredicate<Node<? extends View<?>, ? extends Edge>, Node<? extends View<?>, ? extends Edge>> { private final ParentsTypeMatchPredicate parentsTypeMatchPredicate; private final Optional<Element<? extends Definition<?>>> candidateParent; private final Optional<Node<? extends Definition<?>, ? extends Edge>> candidateNode; public FilteredParentsTypeMatcher(final DefinitionManager definitionManager, final Element<? extends Definition<?>> candidateParent, final Node<? extends Definition<?>, ? extends Edge> candidateNode) { this.candidateParent = Optional.ofNullable(candidateParent); this.candidateNode = Optional.ofNullable(candidateNode); this.parentsTypeMatchPredicate = new ParentsTypeMatchPredicate(new FilteredParentByDefinitionIdProvider(definitionManager), new FilteredHasParentPredicate()); } public FilteredParentsTypeMatcher forParentType(final Class<?> parentType) { this.parentsTypeMatchPredicate.forParentType(parentType); return this; } @Override public boolean test(final Node<? extends View<?>, ? extends Edge> node, final Node<? extends View<?>, ? extends Edge> node2) { return parentsTypeMatchPredicate.test(node, node2); } private class FilteredHasParentPredicate implements BiPredicate<Node<?, ? extends Edge>, Element<?>> { private final GraphUtils.HasParentPredicate hasParentPredicate; private FilteredHasParentPredicate() { this.hasParentPredicate = new GraphUtils.HasParentPredicate(); } @Override public boolean test(final Node<?, ? extends Edge> node, final Element<?> parent) { return isCandidate.test(node) ? candidateParent .filter(parent::equals) .isPresent() : hasParentPredicate.test(node, parent); } } private class FilteredParentByDefinitionIdProvider implements BiFunction<Node<? extends View<?>, ? extends Edge>, Class<?>, Optional<Element<?>>> { private final ParentsTypeMatcher.ParentByDefinitionIdProvider provider; private FilteredParentByDefinitionIdProvider(final DefinitionManager definitionManager) { this.provider = new ParentsTypeMatcher.ParentByDefinitionIdProvider(definitionManager); } @Override public Optional<Element<?>> apply(final Node<? extends View<?>, ? extends Edge> node, final Class<?> parentType) { return getParent(node, parentType); } private Optional<Element<?>> getParent(final Node<? extends View<?>, ? extends Edge> node, final Class<?> parentType) { return isCandidate.test(node) ? getCandidateParentInstance(parentType) : provider.apply(node, parentType); } @SuppressWarnings("unchecked") private Optional<Element<?>> getCandidateParentInstance(final Class<?> parentType) { return candidateParent.isPresent() ? (ParentsTypeMatcher.ParentByDefinitionIdProvider.getDefinitionIdByTpe(parentType) .equals(getCandidateParentId().get()) ? Optional.of(candidateParent.get()) : getParent((Node<? extends View<?>, ? extends Edge>) candidateParent.get(), parentType)) : Optional.empty(); } private Optional<String> getCandidateParentId() { return candidateParent.isPresent() ? Optional.ofNullable(provider.definitionManager.adapters() .forDefinition() .getId(candidateParent.get().getContent().getDefinition())) : Optional.empty(); } } private Predicate<Node<?, ? extends Edge>> isCandidate = new Predicate<Node<?, ? extends Edge>>() { @Override public boolean test(final Node<?, ? extends Edge> node) { return candidateNode .filter(node::equals) .isPresent(); } }; }
44.591241
114
0.624161
02563e4ce7268f69bbfb7b7208f45ddcda66934a
807
package org.erpmicroservices.accounting_and_budgeting.endpoint.rest.accounting_and_budgetingapirest.models; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.springframework.data.jpa.domain.AbstractPersistable; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import java.util.UUID; @Entity @Data @ToString @EqualsAndHashCode public class Payment extends AbstractPersistable<UUID> { private LocalDate effectiveDate; private String paymentReferenceNumber; private BigDecimal amount; private String comment; @OneToMany @JoinColumn(name = "payment_id") private List<PaymentBudgetAllocation> paymentBudgetAllocationList; }
25.21875
107
0.840149
a7dbca8bb7c84099abdabe15c7281d2e386ace93
530
package com.atguigu.gulimall.order.dao; import com.atguigu.gulimall.order.entity.OrderEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * 订单 * * @author lnj * @email tongjianwhu@gmail.com * @date 2021-02-27 14:11:39 */ @Mapper public interface OrderDao extends BaseMapper<OrderEntity> { void updateOrderStatus(@Param("orderSn") String orderSn,@Param("code") Integer code,@Param("payType") Integer payType); }
26.5
123
0.762264
244ff9d0a1ba5c3218582906343c822e2144ac80
1,644
package zj.echo; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class EchoServer { private final int port; public EchoServer(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { //create ServerBootstrap instance ServerBootstrap b = new ServerBootstrap(); //Specifies NIO transport, local socket address //Adds handler to channel pipeline b.group(group).channel(NioServerSocketChannel.class).localAddress(port) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); //Binds server, waits for server to close, and releases resources ChannelFuture f = b.bind().sync(); System.out.println(EchoServer.class.getName() + "started and listen on " + f.channel().localAddress()); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } public static void main(String[] args) throws Exception { new EchoServer(65535).start(); } }
35.73913
115
0.620438
ddaf0af2e1c604ea503396160102c3add71d06b4
10,049
package zamorozka.ui; import com.google.common.base.Predicates; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EntitySelectors; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.*; import java.util.List; import java.util.Random; public class RotationHelper implements MCUtil { public static float pitch() { return mc.player.rotationPitch; } public static void pitch(float pitch) { mc.player.rotationPitch = pitch; } public static float yaw() { return mc.player.rotationYaw; } public static void yaw(float yaw) { mc.player.rotationYaw = yaw; } public static float[] faceTarget(Entity target, float p_706252, float p_706253, boolean miss) { double var6; double var4 = target.posX - mc.player.posX; double var8 = target.posZ - mc.player.posZ; if (target instanceof EntityLivingBase) { EntityLivingBase var10 = (EntityLivingBase)target; var6 = var10.posY + (double)var10.getEyeHeight() - (mc.player.posY + (double)mc.player.getEyeHeight()); } else { var6 = (target.getEntityBoundingBox().minY + target.getEntityBoundingBox().maxY) / 2.0 - (mc.player.posY + (double)mc.player.getEyeHeight()); } Random rnd = new Random(); double var14 = MathHelper.sqrt_double(var4 * var4 + var8 * var8); float var12 = (float)(Math.atan2(var8, var4) * 180.0 / 3.141592653589793) - 90.0f; float var13 = (float)(- Math.atan2(var6 - (target instanceof EntityPlayer ? 0.25 : 0.0), var14) * 180.0 / 3.141592653589793); float pitch = RotationHelper.changeRotation(mc.player.rotationPitch, var13, p_706253); float yaw = RotationHelper.changeRotation(mc.player.rotationYaw, var12, p_706252); return new float[]{yaw, pitch}; } public static float changeRotation(float p_706631, float p_706632, float p_706633) { float var4 = MathHelper.wrapAngleTo180_float(p_706632 - p_706631); if (var4 > p_706633) { var4 = p_706633; } if (var4 < - p_706633) { var4 = - p_706633; } return p_706631 + var4; } public static double[] getRotationToEntity(Entity entity) { double pX = mc.player.posX; double pY = mc.player.posY + (double)mc.player.getEyeHeight(); double pZ = mc.player.posZ; double eX = entity.posX; double eY = entity.posY + (double)(entity.height / 2.0f); double eZ = entity.posZ; double dX = pX - eX; double dY = pY - eY; double dZ = pZ - eZ; double dH = Math.sqrt(Math.pow(dX, 2.0) + Math.pow(dZ, 2.0)); double yaw = Math.toDegrees(Math.atan2(dZ, dX)) + 90.0; double pitch = Math.toDegrees(Math.atan2(dH, dY)); return new double[]{yaw, 90.0 - pitch}; } public static float[] getRotations(Entity entity) { double diffY; if (entity == null) { return null; } double diffX = entity.posX - mc.player.posX; double diffZ = entity.posZ - mc.player.posZ; if (entity instanceof EntityLivingBase) { EntityLivingBase elb = (EntityLivingBase)entity; diffY = elb.posY + ((double)elb.getEyeHeight() - 0.4) - (mc.player.posY + (double)mc.player.getEyeHeight()); } else { diffY = (entity.boundingBox.minY + entity.boundingBox.maxY) / 2.0 - (mc.player.posY + (double)mc.player.getEyeHeight()); } double dist = MathHelper.sqrt_double(diffX * diffX + diffZ * diffZ); float yaw = (float)(Math.atan2(diffZ, diffX) * 180.0 / 3.141592653589793) - 90.0f; float pitch = (float)(- Math.atan2(diffY, dist) * 180.0 / 3.141592653589793); return new float[]{yaw, pitch}; } public static float getDistanceBetweenAngles(float angle1, float angle2) { float angle3 = Math.abs(angle1 - angle2) % 360.0f; if (angle3 > 180.0f) { angle3 = 0.0f; } return angle3; } public static float[] grabBlockRotations(BlockPos pos) { return RotationHelper.getVecRotation(mc.player.getPositionVector().addVector(0.0, mc.player.getEyeHeight(), 0.0)); } public static float[] getVecRotation(Vec3d position) { return RotationHelper.getVecRotation(mc.player.getPositionVector().addVector(0.0, mc.player.getEyeHeight(), 0.0)); } public static int wrapAngleToDirection(float yaw, int zones) { int angle = (int)((double)(yaw + (float)(360 / (2 * zones))) + 0.5) % 360; if (angle < 0) { angle += 360; } return angle / (360 / zones); } public static final float[] smoothRotation(final float[] currentRotations, final float[] targetRotations, final float rotationSpeed) { final float yawDiff = getDifference(targetRotations[0], currentRotations[0]); final float pitchDiff = getDifference(targetRotations[1], currentRotations[1]); float rotationSpeedYaw = rotationSpeed; if (yawDiff > rotationSpeed) { rotationSpeedYaw = rotationSpeed; } else { rotationSpeedYaw = Math.max(yawDiff, -rotationSpeed); } float rotationSpeedPitch = rotationSpeed; if (pitchDiff > rotationSpeed) { rotationSpeedPitch = rotationSpeed; } else { rotationSpeedPitch = Math.max(pitchDiff, -rotationSpeed); } final float newYaw = currentRotations[0] + rotationSpeedYaw; final float newPitch = currentRotations[1] + rotationSpeedPitch; return new float[] { newYaw, newPitch }; } public final static float getDifference(final float a, final float b) { float r = ((a - b) % 360.0F); if (r < -180.0) { r += 360.0; } if (r >= 180.0) { r -= 360.0; } return r; } public static final Entity raycastEntity(double range, float[] rotations) { final Entity player = mc.getRenderViewEntity(); if (player != null && mc.world != null) { final Vec3d eyeHeight = player.getPositionEyes(mc.timer.renderPartialTicks); final Vec3d looks = RotationHelper.getVectorForRotation(rotations[0], rotations[1]); final Vec3d vec = eyeHeight.addVector(looks.xCoord * range, looks.yCoord * range, looks.zCoord * range); final List<Entity> list = mc.world.getEntitiesInAABBexcluding(player, player.getEntityBoundingBox().addCoord(looks.xCoord * range, looks.yCoord * range, looks.zCoord * range).expand(1, 1, 1), Predicates.and(EntitySelectors.NOT_SPECTATING, Entity::canBeCollidedWith)); Entity raycastedEntity = null; for (final Entity entity : list) { if (!(entity instanceof EntityLivingBase)) continue; final float borderSize = entity.getCollisionBorderSize(); final AxisAlignedBB axisalignedbb = entity.getEntityBoundingBox().expand(borderSize, borderSize, borderSize); final RayTraceResult movingobjectposition = axisalignedbb.calculateIntercept(eyeHeight, vec); if (axisalignedbb.isVecInside(eyeHeight)) { if (range >= 0.0D) { raycastedEntity = entity; range = 0.0D; } } else if (movingobjectposition != null) { final double distance = eyeHeight.distanceTo(movingobjectposition.hitVec); if (distance < range || range == 0.0D) { if (entity == player.ridingEntity) { if (range == 0.0D) { raycastedEntity = entity; } } else { raycastedEntity = entity; range = distance; } } } } return raycastedEntity; } return null; } public final static Vec3d getVectorForRotation(final float yaw, final float pitch) { final double f = Math.cos(Math.toRadians(-yaw) - Math.PI); final double f1 = Math.sin(Math.toRadians(-yaw) - Math.PI); final double f2 = -Math.cos(Math.toRadians(-pitch)); final double f3 = Math.sin(Math.toRadians(-pitch)); return new Vec3d((f1 * f2), f3, (f * f2)); } public final static Vec3d getVectorForRotation2(float yaw, float pitch) { final double f = Math.cos(Math.toRadians(-yaw) - Math.PI); final double f1 = Math.sin(Math.toRadians(-yaw) - Math.PI); final double f2 = -Math.cos(Math.toRadians(-pitch)); final double f3 = Math.sin(Math.toRadians(-pitch)); return new Vec3d((double)(f1 * f2), (double)f3, (double)(f * f2)); } public static Entity raycast(final double range, final Entity target) { final Vec3d eyePosition = target.getPositionVector().add(new Vec3d(0, target.getEyeHeight(), 0)); final Vec3d eyeHeight = mc.player.getPositionVector().add(new Vec3d(0, mc.player.getEyeHeight(), 0)); Vec3d hitVec = null; final AxisAlignedBB axisAlignedBB = mc.player.getEntityBoundingBox().addCoord(eyePosition.xCoord - eyeHeight.xCoord, eyePosition.yCoord - eyeHeight.yCoord, eyePosition.zCoord - eyeHeight.zCoord).expand(1.0F, 1.0F, 1.0F); final List<Entity> entities = mc.world.getEntitiesWithinAABBExcludingEntity(mc.player, axisAlignedBB); double rangeExtension = range + 0.5; Entity raycastedEntity = null; for (final Entity entity : entities) { if (entity.canBeCollidedWith()) { float collisionSize = entity.getCollisionBorderSize(); final AxisAlignedBB expandedBox = entity.getEntityBoundingBox().expand(collisionSize, collisionSize, collisionSize); final RayTraceResult movingObjectPosition = expandedBox.calculateIntercept(eyeHeight, eyePosition); if (expandedBox.isVecInside(eyeHeight)) { if (0.0D < rangeExtension || rangeExtension == 0.0D) { raycastedEntity = entity; hitVec = movingObjectPosition == null ? eyeHeight : movingObjectPosition.hitVec; rangeExtension = 0.0D; } } else if (movingObjectPosition != null) { final double eyeDistance = eyeHeight.distanceTo(movingObjectPosition.hitVec); if (eyeDistance < rangeExtension || rangeExtension == 0.0D) { raycastedEntity = entity; hitVec = movingObjectPosition.hitVec; rangeExtension = eyeDistance; } } } } return raycastedEntity; } }
38.949612
270
0.66335
8251b0bfba101354043f8971ba76adbc29f0bc5d
5,663
/** * Copyright 2013 Giwi Softwares (http://giwi.free.fr) * * 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.giwi.camel.dav.test; import java.io.File; import org.apache.camel.CamelExecutionException; import org.apache.camel.Exchange; import org.apache.camel.component.file.GenericFileOperationFailedException; import org.junit.Test; /** * The Class DavProducerTempFileExistIssueTest. * * @version */ public class DavProducerTempFileExistIssueTest extends AbstractDavTest { /** * Gets the dav url. * * @return the dav url */ private String getDavUrl() { return DAV_URL + "/tempprefix/"; } /* * (non-Javadoc) * * @see org.apache.camel.test.junit4.CamelTestSupport#isUseRouteBuilder() */ @Override public boolean isUseRouteBuilder() { return false; } /** * Test illegal configuration. * * @throws Exception * the exception */ @Test public void testIllegalConfiguration() throws Exception { try { context.getEndpoint( getDavUrl() + "?fileExist=Append&tempPrefix=foo") .createProducer(); } catch (IllegalArgumentException e) { assertEquals( "You cannot set both fileExist=Append and tempPrefix options", e.getMessage()); } } /** * Test write using temp prefix but file exist. * * @throws Exception * the exception */ @Test public void testWriteUsingTempPrefixButFileExist() throws Exception { template.sendBodyAndHeader(getDavUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); template.sendBodyAndHeader(getDavUrl() + "?tempPrefix=foo", "Bye World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); File file = new File(DAV_ROOT_DIR + "/tempprefix/hello.txt"); assertEquals(true, file.exists()); assertEquals("Bye World", context.getTypeConverter().convertTo(String.class, file)); } /** * Test write using temp prefix but both file exist. * * @throws Exception * the exception */ @Test public void testWriteUsingTempPrefixButBothFileExist() throws Exception { template.sendBodyAndHeader(getDavUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt"); template.sendBodyAndHeader(getDavUrl(), "Hello World", Exchange.FILE_NAME, "foohello.txt"); Thread.sleep(500); template.sendBodyAndHeader(getDavUrl() + "?tempPrefix=foo", "Bye World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); File file = new File(DAV_ROOT_DIR + "/tempprefix/hello.txt"); assertEquals(true, file.exists()); assertEquals("Bye World", context.getTypeConverter().convertTo(String.class, file)); } /** * Test write using temp prefix but file exist override. * * @throws Exception * the exception */ @Test public void testWriteUsingTempPrefixButFileExistOverride() throws Exception { template.sendBodyAndHeader(getDavUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); template.sendBodyAndHeader(getDavUrl() + "?tempPrefix=foo&fileExist=Override", "Bye World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); File file = new File(DAV_ROOT_DIR + "/tempprefix/hello.txt"); assertEquals(true, file.exists()); assertEquals("Bye World", context.getTypeConverter().convertTo(String.class, file)); } /** * Test write using temp prefix but file exist ignore. * * @throws Exception * the exception */ @Test public void testWriteUsingTempPrefixButFileExistIgnore() throws Exception { template.sendBodyAndHeader(getDavUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); template.sendBodyAndHeader(getDavUrl() + "?tempPrefix=foo&fileExist=Ignore", "Bye World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); File file = new File(DAV_ROOT_DIR + "/tempprefix/hello.txt"); // should not write new file as we should ignore assertEquals("Hello World", context.getTypeConverter().convertTo(String.class, file)); } /** * Test write using temp prefix but file exist fail. * * @throws Exception * the exception */ @Test public void testWriteUsingTempPrefixButFileExistFail() throws Exception { template.sendBodyAndHeader(getDavUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt"); Thread.sleep(500); try { template.sendBodyAndHeader(getDavUrl() + "?tempPrefix=foo&fileExist=Fail", "Bye World", Exchange.FILE_NAME, "hello.txt"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { GenericFileOperationFailedException cause = assertIsInstanceOf( GenericFileOperationFailedException.class, e.getCause()); assertTrue(cause.getMessage().startsWith("File already exist")); } Thread.sleep(500); File file = new File(DAV_ROOT_DIR + "/tempprefix/hello.txt"); // should not write new file as we should ignore assertEquals("Hello World", context.getTypeConverter().convertTo(String.class, file)); } }
28.174129
81
0.682324
79e30865f71114081ea8ccc2997793d1a770f422
2,582
/** * core/is_filename_with_wildcard.java * * This file was generated by MapForce 2017sp2. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the MapForce Documentation for further details. * http://www.altova.com/mapforce */ package com.mapforce.core; import com.altova.mapforce.*; import com.altova.types.*; import com.altova.xml.*; import com.altova.text.tablelike.*; import com.altova.text.*; import com.altova.text.edi.*; import java.util.*; public class is_filename_with_wildcard extends com.altova.TraceProvider { static class main implements IEnumerable { java.lang.String var1_filename; public main(java.lang.String var1_filename) { this.var1_filename = var1_filename; } public IEnumerator enumerator() {return new Enumerator(this);} public static class Enumerator implements IEnumerator { int pos = 0; int state = 2; Object current; main closure; public Enumerator(main closure) { this.closure = closure; } public Object current() {return current;} public int position() {return pos;} public boolean moveNext() throws Exception { while (state != 0) { switch (state) { case 2: if (moveNext_2()) return true; break; } } return false; } private boolean moveNext_2() throws Exception { state = 0; current = com.altova.functions.Core.logicalAnd(com.altova.functions.Core.logicalOr(com.altova.functions.Core.contains(closure.var1_filename, "?"), com.altova.functions.Core.contains(closure.var1_filename, "*")), com.altova.functions.Core.logicalOr(com.altova.functions.Core.equal(com.altova.functions.Core.substring(closure.var1_filename, com.altova.CoreTypes.parseDouble("2"), com.altova.CoreTypes.parseDouble("1")), ":"), com.altova.functions.Core.logicalNot(com.altova.functions.Core.contains(closure.var1_filename, ":")))); pos++; return true; } public void close() { try { } catch (Exception e) { } } } } // instances public static IEnumerable create(java.lang.String var1_filename) { return new main( var1_filename ); } public static boolean eval(java.lang.String var1_filename) throws java.lang.Exception { com.altova.mapforce.IEnumerator e = create(var1_filename).enumerator(); if (e.moveNext()) { boolean result = ((Boolean)e.current()); e.close(); return result; } e.close(); throw new com.altova.AltovaException("Expected a function result."); } }
22.649123
531
0.687452
23304e3c5a695bc84b5a43f2a109dadaf6215183
499
package org.soaringforecast.rasp.soaring.json; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class SUARegionFiles { @SerializedName("sua_regions") @Expose private List<SUARegion> suaRegionList = null; public List<SUARegion> getSuaRegionList() { return suaRegionList; } public void setSuaRegionList(List<SUARegion> suaRegionList) { this.suaRegionList = suaRegionList; } }
22.681818
65
0.735471
09974fb22eed72ab4052744b930b08a44025046a
1,171
package se.bluebrim.view.example; import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.util.Iterator; import se.bluebrim.view.Layoutable; import se.bluebrim.view.ParentView; import se.bluebrim.view.layout.AbstractLayout; /** * Set the size to fraction of the container and put them in * a row at the bottom. * * @author GStack * */ public class TinyViewLayout extends AbstractLayout { private static float gap = 1; public void layoutViews(ParentView container) { float x = gap; for (Iterator iter = container.getChildren().iterator(); iter.hasNext();) { Layoutable view = (Layoutable) iter.next(); view.setHeight((float)(container.getHeight() * 0.2)); view.setWidth(view.getHeight()); view.setX(x); view.setY(container.getHeight() - view.getHeight() - gap); x = x + view.getWidth() + gap; } } @Override public Dimension2D getMinimumLayoutSize(ParentView container) { Dimension2D dim = new Dimension(); dim.setSize(container.getHeight() * 0.2 + ((container.getChildren().size() - 1) * gap), (container.getHeight() * 0.2) + gap); return dim; } }
25.456522
128
0.672075
f4741745982999a42ac2725e264096a1828a296a
1,030
package b.l.c.b; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Objects; import java.util.Set; public abstract class a0<E> extends AbstractSet<E> { public boolean removeAll(Collection<?> collection) { Objects.requireNonNull(collection); if (collection instanceof o) { collection = ((o) collection).c(); } boolean z = false; if (!(collection instanceof Set) || collection.size() <= size()) { for (Object remove : collection) { z |= remove(remove); } } else { Iterator it = iterator(); while (it.hasNext()) { if (collection.contains(it.next())) { it.remove(); z = true; } } } return z; } public boolean retainAll(Collection<?> collection) { Objects.requireNonNull(collection); return super.retainAll(collection); } }
27.837838
74
0.541748
a26ea8d70bfff77355e9d09f706e8f930b53890a
4,630
/** * Apache Licence Version 2.0 * Please read the LICENCE file */ package org.hypothesis.data.model; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.Index; /** * @author Kamil Morong, Tilioteo Ltd * * Hypothesis * * Database entity for branch trek Branch trek is join object for * relation between pack and branch identified by string key * */ @Entity @Table(name = TableConstants.BRANCH_TREK_TABLE, uniqueConstraints = { @UniqueConstraint(columnNames = { FieldConstants.PACK_ID, FieldConstants.KEY, FieldConstants.BRANCH_ID }) }) @org.hibernate.annotations.Table(appliesTo = TableConstants.BRANCH_TREK_TABLE, indexes = { @Index(name = "IX_PACK_BRANCH", columnNames = { FieldConstants.PACK_ID, FieldConstants.BRANCH_ID }) }) @Access(AccessType.PROPERTY) public final class BranchTrek extends SerializableEntity<Long> { /** * */ private static final long serialVersionUID = -8262351809120504076L; private Pack pack; private String key; private Branch branch; private Branch nextBranch; protected BranchTrek() { super(); } public BranchTrek(Pack pack, Branch branch, String key, Branch nextBranch) { this(); this.pack = pack; this.key = key; this.branch = branch; this.nextBranch = nextBranch; } @Override @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = TableConstants.BRANCH_TREK_GENERATOR) @SequenceGenerator(name = TableConstants.BRANCH_TREK_GENERATOR, sequenceName = TableConstants.BRANCH_TREK_SEQUENCE, initialValue = 1, allocationSize = 1) @Column(name = FieldConstants.ID) public Long getId() { return super.getId(); } @ManyToOne @JoinColumn(name = FieldConstants.PACK_ID, nullable = false) public Pack getPack() { return pack; } protected void setPack(Pack pack) { this.pack = pack; } @Column(name = FieldConstants.KEY, nullable = false) public String getKey() { return key; } protected void setKey(String key) { this.key = key; } @ManyToOne @JoinColumn(name = FieldConstants.BRANCH_ID, nullable = false) public Branch getBranch() { return branch; } protected void setBranch(Branch branch) { this.branch = branch; } @ManyToOne @JoinColumn(name = FieldConstants.NEXT_BRANCH_ID, nullable = false) public Branch getNextBranch() { return nextBranch; } protected void setNextBranch(Branch branch) { this.nextBranch = branch; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof BranchTrek)) { return false; } BranchTrek other = (BranchTrek) obj; Long id = getId(); Long id2 = other.getId(); Pack pack = getPack(); Pack pack2 = other.getPack(); String key = getKey(); String key2 = other.getKey(); Branch branch = getBranch(); Branch branch2 = other.getBranch(); Branch nextBranch = getNextBranch(); Branch nextBranch2 = other.getNextBranch(); // if id of one instance is null then compare other properties if (id != null && id2 != null && !id.equals(id2)) { return false; } if (pack == null) { if (pack2 != null) { return false; } } else if (!pack.equals(pack2)) { return false; } if (key == null) { if (key2 != null) { return false; } } else if (!key.equals(key2)) { return false; } if (branch == null) { if (branch2 != null) { return false; } } else if (!branch.equals(branch2)) { return false; } if (nextBranch == null) { if (nextBranch2 != null) { return false; } } else if (!nextBranch.equals(nextBranch2)) { return false; } return true; } @Override public int hashCode() { Long id = getId(); Pack pack = getPack(); String key = getKey(); Branch branch = getBranch(); Branch nextBranch = getNextBranch(); final int prime = 7; int result = 1; result = prime * result + (id != null ? id.hashCode() : 0); result = prime * result + (pack != null ? pack.hashCode() : 0); result = prime * result + (key != null ? key.hashCode() : 0); result = prime * result + (branch != null ? branch.hashCode() : 0); result = prime * result + (nextBranch != null ? nextBranch.hashCode() : 0); return result; } }
24.240838
154
0.689849
d42376f8df99a339300032b2927286b5d127a8e2
1,087
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.storageimportexport.v2016_11_01; import rx.Observable; import com.microsoft.azure.management.storageimportexport.v2016_11_01.implementation.BitLockerKeysInner; import com.microsoft.azure.arm.model.HasInner; /** * Type representing BitLockerKeys. */ public interface BitLockerKeys extends HasInner<BitLockerKeysInner> { /** * Returns the BitLocker Keys for all drives in the specified job. * * @param jobName The name of the import/export job. * @param resourceGroupName The resource group name uniquely identifies the resource group within the user subscription. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<DriveBitLockerKey> listAsync(String jobName, String resourceGroupName); }
36.233333
124
0.769089
2b512f6e604c72a8809d6f8c092c2d11186ab513
2,270
/* Copyright (c) 2013, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.nakala.core; public final class EditDistance { public static int levenshteinDistance(String s1, String s2) { int[][] dp = new int[s1.length() + 1][s2.length() + 1]; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { dp[i][j] = i == 0 ? j : j == 0 ? i : 0; if (i > 0 && j > 0) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = Math.min(dp[i][j - 1] + 1, Math.min( dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1)); } } } } return dp[s1.length()][s2.length()]; } }
41.272727
73
0.652863
a3e6e58b117bd04bfa71864fb79ab8ed0ffc76bc
180
// PARSER_WEEDER,CODE_GENERATION public class J1_ArrayCreateAndIndex { public J1_ArrayCreateAndIndex() {} public static int test() { return 123 + (new int[1])[0]; } }
22.5
38
0.694444
9572dc8f664b26bb652269c6123772ed4f14982f
449
package easy.cloud.core.oauth; import org.crazycake.shiro.RedisManager; /** * @author daiqi * @create 2018-06-23 16:21 */ public class EcCoreOauthApplicationTest { public static void main(String[] args) { RedisManager redisManager = new RedisManager(); redisManager.setHost("120.78.74.169"); redisManager.setPort(6379); byte[] b = redisManager.get("d353c7b9-7425-4818-a4b7-5641183074a7".getBytes()); } }
26.411765
87
0.683742
6277e47c876ea68b9f320060f0fc4116a08bc723
694
package com.github.lit.plugin.exception; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; /** * User : liulu * Date : 2017/6/18 16:35 * version $Id: EnableExceptionHandlerCondition.java, v 0.1 Exp $ */ public class EnableExceptionHandlerCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { String property = conditionContext.getEnvironment().getProperty("lit.exception.advice.enable", "true"); return Boolean.valueOf(property); } }
34.7
111
0.78098
68f28c85b4a9a6875e2df2144b66524b8de9a3d1
3,580
package seedu.cakecollate.ui; import java.util.Comparator; import java.util.Map; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.cakecollate.model.order.Order; import seedu.cakecollate.model.order.OrderDescription; /** * An UI component that displays information of a {@code Order}. */ public class OrderCard extends UiPart<Region> { private static final String FXML = "OrderCard.fxml"; /** * Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX. * As a consequence, UI elements' variable names cannot be set to such keywords * or an exception will be thrown by JavaFX during runtime. * * @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on CakeCollate level 4</a> */ public final Order order; @FXML private HBox cardPane; @FXML private Label name; @FXML private Label id; @FXML private Label phone; @FXML private Label address; @FXML private Label email; @FXML private FlowPane orderDescriptions; @FXML private Label deliveryDate; @FXML private Label deliveryStatus; @FXML private Label request; @FXML private FlowPane tags; /** * Creates a {@code OrderCode} with the given {@code Order} and index to display. */ public OrderCard(Order order, int displayedIndex) { super(FXML); this.order = order; id.setText(displayedIndex + ". "); name.setText(order.getName().fullName); phone.setText(order.getPhone().value); address.setText(order.getAddress().value); email.setText(order.getEmail().value); // this map maps order descriptions to quantities entered in order Map<OrderDescription, Integer> orderDescriptionMap = order.getOrderDescriptions(); /*.stream()*/ orderDescriptionMap.keySet().stream() .sorted(Comparator.comparing(orderDescription -> orderDescription.value)) .forEach(orderDescription -> orderDescriptions .getChildren() .add(createOrderDescLabel(orderDescription, orderDescriptionMap.get(orderDescription)))); order.getTags().stream() .sorted(Comparator.comparing(tag -> tag.tagName)) .forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); deliveryDate.setText(order.getDeliveryDate().toString()); deliveryStatus.setText(order.getDeliveryStatus().toString()); request.setText(order.getRequest().toString()); setDeliveryStatusStyle(); } private Node createOrderDescLabel(OrderDescription orderDescription, int quantity) { return new Label(String.format("%d x %s", quantity, orderDescription.value)); } public void setDeliveryStatusStyle() { deliveryStatus.getStyleClass().add("cell_deliveryStatus_label_" + order.getDeliveryStatus().toString()); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof OrderCard)) { return false; } // state check OrderCard card = (OrderCard) other; return id.getText().equals(card.id.getText()) && order.equals(card.order); } }
32.252252
114
0.656145
72c9d286b85b86ac2f821106505bfa5484132d1a
2,919
/******************************************************************************* Copyright 2008, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. This distribution may include materials developed by third parties. ******************************************************************************/ package kr.ac.kaist.jsaf.nodes_util; import java.util.HashMap; public class Unicode { public static boolean charactersOverlap(String s1, String s2) { for (int i = 0; i < s1.length(); i++) { if (s2.indexOf(s1.charAt(i)) >= 0) { return true; } } return false; } public static String byNameLC(String s) { return unicodeByName.get(s.toLowerCase()); } public static int numberToValue(String s) { Integer I = numbers.get(s.toUpperCase()); if (I == null) { return -1; } return I.intValue(); } private static HashMap<String, String> unicodeByName = new HashMap<String, String>(); private static HashMap<String, Integer> numbers = new HashMap<String, Integer>(); static { HashMap<String, Integer> m = numbers; m.put("ZERO", Integer.valueOf(0)); m.put("ONE", Integer.valueOf(1)); m.put("TWO", Integer.valueOf(2)); m.put("THREE", Integer.valueOf(3)); m.put("FOUR", Integer.valueOf(4)); m.put("FIVE", Integer.valueOf(5)); m.put("SIX", Integer.valueOf(6)); m.put("SEVEN", Integer.valueOf(7)); m.put("EIGHT", Integer.valueOf(8)); m.put("NINE", Integer.valueOf(9)); m.put("TEN", Integer.valueOf(10)); m.put("ELEVEN", Integer.valueOf(11)); m.put("TWELVE", Integer.valueOf(12)); m.put("THIRTEEN", Integer.valueOf(13)); m.put("FOURTEEN", Integer.valueOf(14)); m.put("FIFTEEN", Integer.valueOf(15)); m.put("SIXTEEN", Integer.valueOf(16)); } static { HashMap<String, String> m = unicodeByName; m.put("alpha", "\u03b1"); m.put("beta", "\u03b2"); m.put("gamma", "\u03b3"); m.put("delta", "\u03b4"); m.put("epsilon", "\u03b5"); m.put("zeta", "\u03b6"); m.put("eta", "\u03b7"); m.put("theta", "\u03b8"); m.put("iota", "\u03b9"); m.put("kappa", "\u03ba"); m.put("lambda", "\u03bb"); m.put("lamda", "\u03bb"); m.put("mu", "\u03bc"); m.put("nu", "\u03bd"); m.put("xi", "\u03be"); m.put("omicron", "\u03bf"); m.put("pi", "\u03c0"); m.put("rho", "\u03c1"); m.put("final sigma", "\u03c2"); m.put("sigma", "\u03c3"); m.put("tau", "\u03c4"); m.put("upsilon", "\u03c5"); m.put("phi", "\u03c6"); m.put("chi", "\u03c7"); m.put("psi", "\u03c8"); m.put("omega", "\u03c9"); } }
32.797753
89
0.495718
0744e3b10b20de95244b8ff68628e7ca10d453a6
3,655
/* * 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.apache.karaf.cellar.itests; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.apache.karaf.cellar.core.ClusterManager; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class CellarConfigurationTest extends CellarTestSupport { private static final String TESTPID = "org.apache.karaf.cellar.tst"; @Test //@Ignore public void testCellarFeaturesModule() throws InterruptedException { installCellar(); createCellarChild("child1"); createCellarChild("child2"); Thread.sleep(DEFAULT_TIMEOUT); ClusterManager clusterManager = getOsgiService(ClusterManager.class); assertNotNull(clusterManager); String node1 = getNodeIdOfChild("child1"); String node2 = getNodeIdOfChild("child2"); System.err.println(executeCommand("instance:list")); String properties = executeCommand("instance:connect child1 config:proplist --pid " + TESTPID); System.err.println(properties); assertFalse((properties.contains("myKey"))); //Test configuration sync - add property System.err.println(executeCommand("config:propset --pid " + TESTPID + " myKey myValue")); Thread.sleep(5000); properties = executeCommand("instance:connect child1 config:proplist --pid " + TESTPID); System.err.println(properties); assertTrue(properties.contains("myKey = myValue")); //Test configuration sync - remove property System.err.println(executeCommand("config:propdel --pid " + TESTPID + " myKey")); Thread.sleep(5000); properties = executeCommand("instance:connect child1 config:proplist --pid " + TESTPID); System.err.println(properties); assertFalse(properties.contains("myKey")); //Test configuration sync - add property - join later System.err.println(executeCommand("cluster:group-set new-grp " + node1)); Thread.sleep(5000); System.err.println(executeCommand("instance:connect child1 config:propset --pid " + TESTPID + " myKey2 myValue2")); properties = executeCommand("instance:connect child1 config:proplist --pid " + TESTPID); Thread.sleep(5000); System.err.println(executeCommand("cluster:group-set new-grp " + node2)); properties = executeCommand("instance:connect child2 config:proplist --pid " + TESTPID); System.err.println(properties); assertTrue(properties.contains("myKey2 = myValue2")); } @After public void tearDown() { try { destroyCellarChild("child1"); destroyCellarChild("child2"); unInstallCellar(); } catch (Exception ex) { //Ignore } } }
39.728261
123
0.693297
18c0f621918d1e2bd5322adfb06bf9fc2310c237
7,547
/******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.resolver; import edu.duke.cabig.c3pr.esb.Metadata; import gov.nih.nci.cabig.caaers.AbstractTestCase; import gov.nih.nci.cabig.caaers.MetadataMatcher; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.RemoteOrganization; import gov.nih.nci.cabig.caaers.domain.RemoteResearchStaff; import gov.nih.nci.cabig.caaers.domain.ResearchStaff; import gov.nih.nci.cabig.caaers.domain.SiteResearchStaff; import gov.nih.nci.cabig.caaers.esb.client.MessageBroadcastService; import java.util.List; import org.apache.commons.io.IOUtils; import org.easymock.EasyMock; public class ResearchStaffResolverMockTest extends AbstractTestCase { ResearchStaffResolver researchStaffResolver ; MessageBroadcastService messageBroadcastService; //ResolverUtils resolverUtils; protected void setUp() throws Exception { super.setUp(); researchStaffResolver = new ResearchStaffResolver(); messageBroadcastService = registerMockFor(MessageBroadcastService.class); //investigatorResolver.setResolverUtils(resolverUtils); researchStaffResolver.setMessageBroadcastService(messageBroadcastService); } public void testSearchByName() throws Exception { String xml = IOUtils.toString(getClass().getResourceAsStream("rs_byname_correlation_coppa_response.xml")); Metadata mData = new Metadata("searchCorrelationsWithEntities", "externalId", "PO_BUSINESS"); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_ORGANIZATION"); xml = IOUtils.toString(getClass().getResourceAsStream("byname_identifiedorg_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_PERSON"); xml = IOUtils.toString(getClass().getResourceAsStream("byname_identifiedperson_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); replayMocks(); ResearchStaff example = new RemoteResearchStaff(); example.setFirstName("abbas"); List<Object> list = researchStaffResolver.find(example); assertEquals(4,list.size()); // for (int i=0 ; i<list.size(); i++) { // ResearchStaff obj = (RemoteResearchStaff)list.get(i); // System.out.println(obj.getFirstName() + "," + obj.getLastName()); // System.out.println(obj.getEmailAddress()); // System.out.println(obj.getExternalId()); // System.out.println(obj.getNciIdentifier()); // //System.out.println(obj.getSiteInvestigators().get(0).getOrganization().getNciInstituteCode()); // } } public void testSearchByNciId() throws Exception { String xml = IOUtils.toString(getClass().getResourceAsStream("bynciid_identifiedperson_coppa_response.xml")); Metadata mData = new Metadata("search", "externalId", "IDENTIFIED_PERSON"); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("searchCorrelationsWithEntities", "externalId", "PO_BUSINESS"); xml = IOUtils.toString(getClass().getResourceAsStream("rs_bynciid_correlation_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_ORGANIZATION"); xml = IOUtils.toString(getClass().getResourceAsStream("bynciid_identifiedorg_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_PERSON"); xml = IOUtils.toString(getClass().getResourceAsStream("bynciid_identifiedperson_byplids_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); replayMocks(); ResearchStaff example = new RemoteResearchStaff(); example.setNciIdentifier("60442"); List<Object> list = researchStaffResolver.find(example); assertEquals(list.size(),1); } public void testSearchByOrganization() throws Exception { String xml = IOUtils.toString(getClass().getResourceAsStream("byorg_identifiedorg_coppa_response.xml")); Metadata mData = new Metadata("search", "externalId", "IDENTIFIED_ORGANIZATION"); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("searchCorrelationsWithEntities", "externalId", "PO_BUSINESS"); xml = IOUtils.toString(getClass().getResourceAsStream("rs_byorg_correlation_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_PERSON"); xml = IOUtils.toString(getClass().getResourceAsStream("byorg_identifiedperson_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); replayMocks(); ResearchStaff example = new RemoteResearchStaff(); SiteResearchStaff sr = new SiteResearchStaff(); Organization org = new RemoteOrganization(); org.setNciInstituteCode("KY082"); sr.setOrganization(org); example.getSiteResearchStaffs().add(sr); List<Object> list = researchStaffResolver.find(example); assertEquals(list.size(),3); } public void testSearchByExternalId() throws Exception { String xml = IOUtils.toString(getClass().getResourceAsStream("rs_byextid_correlation_coppa_response.xml")); Metadata mData = new Metadata("searchCorrelationsWithEntities", "externalId", "PO_BUSINESS"); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_ORGANIZATION"); xml = IOUtils.toString(getClass().getResourceAsStream("byextid_identifiedorg_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); mData = new Metadata("getByPlayerIds", "externalId", "IDENTIFIED_PERSON"); xml = IOUtils.toString(getClass().getResourceAsStream("byextid_identifiedperson_coppa_response.xml")); EasyMock.expect(messageBroadcastService.broadcastCOPPA((List<String>)EasyMock.anyObject(), MetadataMatcher.eqMetadata(mData))).andReturn(xml); replayMocks(); Object obj1 = researchStaffResolver.getRemoteEntityByUniqueId("1167533"); ResearchStaff obj = (RemoteResearchStaff)obj1; assertEquals(obj.getExternalId(),"1167533"); } }
54.688406
144
0.77077
5c5bce47a94a3ac0327c4d31ba59769299677e2d
92
/** * Spring Security configuration. */ package com.bytatech.ayoos.consultation.security;
18.4
49
0.76087
971a6f5547412db81c9b97d8653c99664782250b
119
package net.gobbob.mobends.client.model; public interface IBendsModel { public Object getPartForName(String name); }
17
43
0.806723
a49109ef89814eca5514476fb9d784f03b400674
3,123
package org.deta.tinos.list; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.deta.tinos.stable.Stable; public class ListValidation{ public static boolean ListSetsCheck(List<Object> list, String setsType) { Iterator<Object> iterator= list.iterator(); while(iterator.hasNext()) { Object object= iterator.next(); if(setsType.equalsIgnoreCase(Stable.STRING_DOUBLE)) { if(!(object instanceof Double)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_INT)) { if(!(object instanceof Integer)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_FLOAT)) { if(!(object instanceof Float)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_STRING)) { if(!(object instanceof String)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_SHORT)) { if(!(object instanceof Short)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_BOOLEAN)) { if(!(object instanceof Boolean)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_LONG)) { if(!(object instanceof Long)) { return false; } } if(setsType.equalsIgnoreCase(Stable.STRING_BYTE)) { if(!(object instanceof Byte)) { return false; } } } return true; } public static List<Object> ListSetsFix(List<Object> list , String setsType) { List<Object> output= new ArrayList<>(); Iterator<Object> iterator= list.iterator(); while(iterator.hasNext()) { Object object= iterator.next(); if(setsType.equalsIgnoreCase(Stable.STRING_DOUBLE)) { if(!(object instanceof Double)) { output.add((double)0.00); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_INT)) { if(!(object instanceof Integer)) { output.add((int)0); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_FLOAT)) { if(!(object instanceof Float)) { output.add((float)0.0); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_STRING)) { if(!(object instanceof String)) { output.add(Stable.STRING_EMPTY); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_SHORT)) { if(!(object instanceof Short)) { output.add((short)0); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_BOOLEAN)) { if(!(object instanceof Boolean)) { output.add(false); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_LONG)) { if(!(object instanceof Long)) { output.add((long)(0)); }else { output.add(object); } } if(setsType.equalsIgnoreCase(Stable.STRING_BYTE)) { if(!(object instanceof Byte)) { output.add((byte)0); }else { output.add(object); } } } return output; } }
25.598361
75
0.614473
2d8f0eabd2c2faba5e3988118d13a26ad07d6b3a
1,195
package conditionals; public class Simulator { public static void main(String[] args) { int x = 10; int y = 100; /* * Conditional statements apply to the next line OR * block of code */ // if (x > y) // System.out.println("X is greater than y!"); // else // System.out.println("X is not greater than y"); if (x > y) { System.out.println("X is too big for me"); x = y - 1; System.out.println("Thats better! x is: " + x); } int z = 21; if (z == 10) { System.out.println("z is 10"); } else if (z % 2 == 1) { System.out.println("Not 10 and odd"); } else if (z % 2 == 0) { System.out.println("Z is even"); } else if (z > 10) { System.out.println("Not odd and more than 10"); } else { System.out.println("Too many conditions!"); } int age = 21; boolean adultSupervised = false; if (!adultSupervised) { // some code you want to occur in this case! if (age >= 18) { System.out.println("You can watch the rated R movie"); } } else { if (age > 15) { System.out.println("You can watch the rated R movie"); } else { System.out.println("Sorry you can't watch this movie"); } } } }
21.727273
59
0.574059