blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
882716f9ce73ffbcbdd65a427b40cec908966d7e
0a9dec383fa49519facc12399ff6f4c3a277e9ef
/games/app/src/test/java/cucumber/step/hooks/Hooks.java
9f4de6ce0d6f934660273bcb2211b2163ef7a934
[]
no_license
vitors-ciandt/qa-bootcamp
b19cbc37668f7ea0f238fa55bd7374ab1d1fe43a
905bbe3c0cdc59d98046af987dfd699479931921
refs/heads/master
2023-05-18T21:33:41.622370
2021-06-11T18:05:39
2021-06-11T18:05:39
370,364,834
0
0
null
2021-06-11T18:05:39
2021-05-24T13:37:53
JavaScript
UTF-8
Java
false
false
1,460
java
package cucumber.step.hooks; import com.ciandt.games.playingcard.CardSuit; import com.ciandt.games.playingcard.PlayingCard; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.client.WireMock; import cucumber.api.java.Before; import org.springframework.http.MediaType; import java.util.Arrays; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; public class Hooks { @Before public static void setup() throws JsonProcessingException { PlayingCard playingCard1 = new PlayingCard(1, CardSuit.CLUBS); PlayingCard playingCard2 = new PlayingCard(2, CardSuit.HEARTS); PlayingCard playingCard3 = new PlayingCard(3, CardSuit.SPADES); PlayingCard playingCard4 = new PlayingCard(4, CardSuit.DIAMONDS); List<PlayingCard> playingCardList = Arrays.asList(playingCard1, playingCard2, playingCard3, playingCard4); ObjectMapper objectMapper = new ObjectMapper(); String playingCardsStringList = objectMapper.writeValueAsString(playingCardList); WireMock .stubFor(WireMock.get(WireMock.urlMatching("/shuffled")) .willReturn(aResponse() .withHeader("Content-type", MediaType.APPLICATION_JSON_VALUE) .withStatus(200) .withBody(playingCardsStringList))); } }
[ "CIANDT\\[email protected]" ]
891ddd167cca8391bec9ef293c21bdf7ea926839
763eb85e96ef322f51c441b31ea264106999a719
/src/main/java/com/gita/cursomc/domain/ItemPedidoPK.java
2ecb0b5e09c498a057985c9486b0d248fcda01f1
[]
no_license
daniel-ianae/spring-boot-ecommerce-backend
ce152f55b065b376632e56c01d2aec184d705589
bc76c595d52a3894d9a8dcff105a0c648e8addbb
refs/heads/master
2023-02-17T05:48:40.887179
2021-01-15T21:37:03
2021-01-15T21:37:03
328,257,921
0
0
null
null
null
null
UTF-8
Java
false
false
676
java
package com.gita.cursomc.domain; import java.io.Serializable; import javax.persistence.Embeddable; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Embeddable public class ItemPedidoPK implements Serializable{ private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name="pedido_id") private Pedido pedido; @ManyToOne @JoinColumn(name="produto_id") private Produto produto; public Pedido getPedido() { return pedido; } public void setPedido(Pedido pedido) { this.pedido = pedido; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } }
2b0ac3b385363b1bf898b7f4eb3c2b8c046cb7f5
6392035b0421990479baf09a3bc4ca6bcc431e6e
/projects/spring-data-neo4j-071588a4/prev/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/movies/domain/TempMovie.java
74fa0a8ea2728b590954333bc7abf23f469c5512
[]
no_license
ameyaKetkar/RMinerEvaluationTools
4975130072bf1d4940f9aeb6583eba07d5fedd0a
6102a69d1b78ae44c59d71168fc7569ac1ccb768
refs/heads/master
2020-09-26T00:18:38.389310
2020-05-28T17:34:39
2020-05-28T17:34:39
226,119,387
3
1
null
null
null
null
UTF-8
Java
false
false
1,356
java
/* * Copyright (c) [2011-2015] "Pivotal Software, Inc." / "Neo Technology" / "Graph Aware Ltd." * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product may include a number of subcomponents with * separate copyright notices and license terms. Your use of the source * code for these subcomponents is subject to the terms and * conditions of the subcomponent's license, as noted in the LICENSE file. */ package org.springframework.data.neo4j.integration.movies.domain; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; import java.util.HashSet; import java.util.Set; /** * @author Michal Bachman */ //todo merge with movie when tests fixed @NodeEntity(label = "Movie") public class TempMovie extends AbstractEntity { private String title; @Relationship(type = "RATED", direction = Relationship.INCOMING) private Set<Rating> ratings = new HashSet<>(); public TempMovie() { } public TempMovie(String title) { this.title = title; } public String getTitle() { return title; } public void addRating(Rating rating) { ratings.add(rating); } public Set<Rating> getRatings() { return ratings; } }
c848b65a0f9ed258d629a2f9c3a728cdfe934e91
bd4c3c2719452d386ce19d18dc813976428ba9be
/app/src/test/java/cc/biglong/phonenumtextview/ExampleUnitTest.java
07ad48e7150b1016e30cd0fb6f6a15ebd622fa21
[]
no_license
hustlong/PhoneNumTextView
fc5bfeaf0442dfe85a683aba189a1720975ddc66
101cd4139636f561be2018d697831af9d6f95f20
refs/heads/master
2020-12-25T15:08:28.982955
2016-07-29T03:42:19
2016-07-29T03:42:19
64,446,741
1
0
null
null
null
null
UTF-8
Java
false
false
320
java
package cc.biglong.phonenumtextview; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
dfd8daffcbf6d9b4a6eddb14cb54fed6814cb695
1b61c9829cc3a6019f0dd3f17b68d4a6eebba0af
/03-java-spring/03-spring-data-ii/03-dojos-and-ninjas/DojosAndNinjas/src/main/java/com/nlangione/DojosAndNinjas/DojosAndNinjasApplication.java
384126f0829f531cdd5e5b6d33e5dccee4deb62a
[]
no_license
java-september-2021/NathanL-Assignments
6b966d4d64540411d057f112e8d516aa43f39efe
8394f63072790c09c06abdaa06fbda04df45c7e7
refs/heads/master
2023-08-31T04:59:50.782299
2021-10-16T16:46:44
2021-10-16T16:46:44
401,351,645
0
0
null
null
null
null
UTF-8
Java
false
false
337
java
package com.nlangione.DojosAndNinjas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DojosAndNinjasApplication { public static void main(String[] args) { SpringApplication.run(DojosAndNinjasApplication.class, args); } }
bc48ef1e72a115bf9e845794bd0e2f27dbc89a3b
efb09e687dcb2e5e7d59acffd91b30b0af31a475
/shared/src/main/java/edu/ait/stateservice/SpringFoxConfig.java
aa972317c705ce9f5dfb58fb6552ee7dba39605b
[]
no_license
kieranwhooley/Distributed-Microservice-Application
389e04a977bbd05bc5ede1ed2531db7168747c34
e81ca0d204ef97c163f4b861aeb6a9f11ea7cea3
refs/heads/master
2023-06-18T04:47:40.545350
2021-07-20T10:58:14
2021-07-20T10:58:14
387,523,573
0
0
null
null
null
null
UTF-8
Java
false
false
1,232
java
package edu.ait.stateservice; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SpringFoxConfig { public static final Contact CUSTOM_CONTACT = new Contact("Kieran Whooley", "www.ait.ie", "[email protected]"); public static final ApiInfo CUSTOM_API_INFO = new ApiInfoBuilder().title("US State Service") .description("A list of US States") .version("1.0") .contact(CUSTOM_CONTACT) .build(); @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select().apis(RequestHandlerSelectors.basePackage("edu.ait.stateservice")) .paths(PathSelectors.any()) .build() .apiInfo(CUSTOM_API_INFO); } }
222417f72900aed4adb546565e34bea06b8c6043
5844f23eac634fcd72f6c02e21535e7933730aa3
/src/main/java/cn/edu/cup/commondata/DataItem.java
2222cdf51725e98ad5864e9764239b2cfbeefd32
[]
no_license
xpgitcup/commondata
b4d0c51799954610084a6c89b6c6cd6b29fdc900
4dba6c3d6a7fc75ae6bb250ac727e01d2565e798
refs/heads/master
2022-06-26T22:59:54.688030
2020-04-25T00:54:17
2020-04-25T00:54:17
259,161,470
0
0
null
2022-06-17T03:08:40
2020-04-27T00:12:46
Java
UTF-8
Java
false
false
1,430
java
/* * 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 cn.edu.cup.commondata; /** * * @author LiXiaoping */ public class DataItem { private DataValueType dataValueType; private String unit; private String valueString; public DataItem(DataValueType dataValueType, String unit, String valueString) { this.dataValueType = dataValueType; this.unit = unit; } @Override public String toString() { StringBuilder sb = new StringBuilder(); // sb.append("DataItem{unit=").append(unit); // sb.append(", valueString=").append(valueString); // sb.append('}'); sb.append(valueString); if (!unit.isEmpty()) { sb.append("(").append(unit).append(")"); } return sb.toString(); } public DataValueType getDataValueType() { return dataValueType; } public void setDataValueType(DataValueType dataValueType) { this.dataValueType = dataValueType; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getValueString() { return valueString; } public void setValueString(String valueString) { this.valueString = valueString; } }
8abdd5c82cb8cf90fb62950d02ccd6685dc101da
f24bba680b500d92beaab7ce84411bd6271a6b8e
/app/src/main/java/com/e7yoo/e7/fragment/Joke1ListFragment.java
1f193bef44ca1e0834fdc9ef5acc26ac24e0ea7f
[]
no_license
JackSatellite/itlao5-xmb-android
af8f67ea5a7b57a69f9d9457f503a86e41efb26e
8ef1030068dc6d8852e0193b34aea16a7df16ce6
refs/heads/master
2022-04-17T19:20:54.686645
2020-04-10T14:48:36
2020-04-10T14:48:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,200
java
package com.e7yoo.e7.fragment; import android.os.Message; import android.view.View; import com.e7yoo.e7.E7App; import com.e7yoo.e7.R; import com.e7yoo.e7.adapter.JokeListRefreshRecyclerAdapter; import com.e7yoo.e7.adapter.ListRefreshRecyclerAdapter; import com.e7yoo.e7.model.Joke; import com.e7yoo.e7.model.JokeType; import com.e7yoo.e7.net.NetHelper; import com.e7yoo.e7.sql.DbThreadPool; import com.e7yoo.e7.util.Constant; import com.e7yoo.e7.util.IOUtils; import com.e7yoo.e7.util.JokeUtil; import com.e7yoo.e7.util.PreferenceUtil; import com.e7yoo.e7.util.TastyToastUtil; import com.e7yoo.e7.util.UmengUtil; import com.tencent.bugly.crashreport.CrashReport; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by andy on 2018/4/6. */ public class Joke1ListFragment extends ListFragment { public static Joke1ListFragment newInstance() { Joke1ListFragment fragment = new Joke1ListFragment(); return fragment; } private JokeType jokeType = JokeType.JOKE; public Joke1ListFragment setJokeType(JokeType jokeType) { this.jokeType = jokeType; return this; } @Override public void onEventMainThread(Message msg) { if(isDetached()) { return; } switch (msg.what) { case Constant.EVENT_BUS_NET_jokeRand: if(JokeType.JOKE == jokeType) { doMsg(msg); if(isRefresh) { UmengUtil.onEvent(UmengUtil.JOKE_LIST_JOKE_REFRESH); } else { UmengUtil.onEvent(UmengUtil.JOKE_LIST_JOKE_MORE); } } break; case Constant.EVENT_BUS_NET_jokeRand_pic: if(JokeType.PIC == jokeType) { doMsg(msg); if(isRefresh) { UmengUtil.onEvent(UmengUtil.JOKE_LIST_PIC_REFRESH); } else { UmengUtil.onEvent(UmengUtil.JOKE_LIST_PIC_MORE); } } break; } } private void doMsg(Message msg) { if(mSRLayout == null) { return; } mSRLayout.setRefreshing(false); ArrayList<Joke> joke = JokeUtil.parseJokeRand((JSONObject) msg.obj); if(isRefresh) { if(joke != null && joke.size() > 0) { saveDataToDb(joke); refreshData(joke, true); } mRvAdapter.setFooter(ListRefreshRecyclerAdapter.FooterType.END, R.string.loading_up_load_more, false); } else { mRvAdapter.addItemBottom(joke); if(joke != null && joke.size() > 0) { mRvAdapter.setFooter(ListRefreshRecyclerAdapter.FooterType.END, R.string.loading_up_load_more, false); } else { mRvAdapter.setFooter(ListRefreshRecyclerAdapter.FooterType.NO_MORE, R.string.loading_no_more, false); } } } protected void refreshData(List<Joke> jokes, boolean refresh) { if(mDatas == null || refresh) { mDatas = jokes; if(mRvAdapter != null) { mRvAdapter.refreshData(mDatas); } } } @Override protected ListRefreshRecyclerAdapter initAdapter() { JokeListRefreshRecyclerAdapter jokeListRefreshRecyclerAdapter = new JokeListRefreshRecyclerAdapter(getContext()); jokeListRefreshRecyclerAdapter.setShowCollect(true); return jokeListRefreshRecyclerAdapter; } @Override protected void addListener() { ((JokeListRefreshRecyclerAdapter) mRvAdapter).setOnCollectListener(new JokeListRefreshRecyclerAdapter.OnCollectListener() { @Override public void onCollect(View view, Joke joke, int position) { DbThreadPool.getInstance().insertCollect(E7App.mApp, joke); if(mRvAdapter != null) { ((JokeListRefreshRecyclerAdapter) mRvAdapter).remove(position); } TastyToastUtil.toast(getActivity(), R.string.collect_suc); } }); } boolean isRefresh; @Override protected void loadDataFromNet(boolean isRefresh) { this.isRefresh = isRefresh; if(jokeType == null) { jokeType = JokeType.JOKE; } switch (jokeType) { case PIC: NetHelper.newInstance().jokeRand(true); break; case JOKE: NetHelper.newInstance().jokeRand(false); break; case ALL: default: break; } } @Override protected void loadDataFromDb() { String jokeList = PreferenceUtil.getString(getKey(jokeType), null); try { if(jokeList == null) { return; } Object obj = IOUtils.UnserializeStringToObject(jokeList); if(obj != null) { ArrayList<Joke> jokes = (ArrayList<Joke>) obj; refreshData(jokes, false); } } catch (Throwable e) { CrashReport.postCatchedException(e); } } private void saveDataToDb(ArrayList<Joke> jokes) { PreferenceUtil.commitString(getKey(jokeType), IOUtils.SerializeObjectToString(jokes)); } private String getKey(JokeType jokeType) { String preferenceKey; if(jokeType == null) { jokeType = JokeType.JOKE; } switch (jokeType) { case JOKE: preferenceKey = Constant.PREFERENCE_CIRCLE_JOKE_JOKE; break; case PIC: preferenceKey = Constant.PREFERENCE_CIRCLE_JOKE_PIC; break; case ALL: default: preferenceKey = Constant.PREFERENCE_CIRCLE_JOKE_ALL; break; } return preferenceKey; } }
7b46876cf7b821de586ea6c2c1d9866a9d7bd718
933cad9b42d64e43c8c619e172090be7d27e0b4f
/kurumi_java/src/com/iteye/weimingtom/kurumi/model/ArrayRef.java
432f0431d01b83d8a61bde15be4b5d974be87a12
[]
no_license
weimingtom/kurumi
6eff9aa42a0898deb710dd1e5157a612c4c1fda0
b3b893c5948f572b48fb0da88cbbe05cf5054beb
refs/heads/master
2020-05-23T07:55:26.331237
2018-04-07T11:41:46
2018-04-07T11:41:46
80,464,580
1
0
null
null
null
null
UTF-8
Java
false
false
1,503
java
package com.iteye.weimingtom.kurumi.model; import com.iteye.weimingtom.kurumi.port.ClassType; import com.iteye.weimingtom.kurumi.proto.ArrayElement; import com.iteye.weimingtom.kurumi.proto.GCObjectRef; // // ** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $ // ** Global State // ** See Copyright Notice in lua.h // public class ArrayRef implements GCObjectRef, ArrayElement { // ArrayRef is used to reference GCObject objects in an array, the next two members // point to that array and the index of the GCObject element we are referencing private GCObject[] array_elements; private int array_index; // ArrayRef is itself stored in an array and derived from ArrayElement, the next // two members refer to itself i.e. the array and index of it's own instance. private ArrayRef[] vals; private int index; public ArrayRef() { this.array_elements = null; this.array_index = 0; this.vals = null; this.index = 0; } public ArrayRef(GCObject[] array_elements, int array_index) { this.array_elements = array_elements; this.array_index = array_index; this.vals = null; this.index = 0; } public final void set(GCObject value) { array_elements[array_index] = value; } public final GCObject get() { return array_elements[array_index]; } public final void set_index(int index) { this.index = index; } public final void set_array(Object vals) { // don't actually need this this.vals = (ArrayRef[])vals; ClassType.Assert(this.vals != null); } }
ff603ee8fba54751afdc1a9739a113e0a26f4f9e
7d9c023093375fcdaf8bea5ab03e54b2cacbb97a
/src/org/stl/hitme/sysUtil/ui/ListSelecterFragmentTest.java
2906ba1a43e8006113e1efe47a34fdfe57b8600d
[]
no_license
VictorChenLi/HitMeAndroidDemo
bf6f794b00c9b7ce9f3ce7020cb19c8cd7d08cc6
cca08fcfbc639b81a070526af7f3387a0128615b
refs/heads/master
2016-09-06T16:08:32.389359
2014-01-10T00:00:15
2014-01-10T00:00:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,211
java
package org.stl.hitme.sysUtil.ui; //import android.app.ListFragment; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class ListSelecterFragmentTest extends ListFragment { private String listType; @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toast.makeText(this.getActivity(), "The listType is "+getArguments().getString("listType"), Toast.LENGTH_LONG).show(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values); setListAdapter(adapter); } }
6523bc9ac3fad4af8373c049a063e725baaf3f5c
b47e8589e2ea1c27ace9a2b1e18b97b000cad91c
/mediator/Hyppy.java
70ed8294583cd2800c2edfaa21e41a4d4a178e76
[]
no_license
Janne555/metro-suunnittelumallit
1b6135c7cdcd65566e58d76c7268f0df21d7330d
08b1f8b29ad1bc5ad31d1c435fa6ab902cc1993c
refs/heads/master
2021-04-13T06:04:22.547856
2020-05-03T09:27:43
2020-05-03T09:27:43
249,141,972
0
0
null
null
null
null
UTF-8
Java
false
false
495
java
package mediator; public class Hyppy { private double pituus; private int tyyliPisteet; public Hyppy(double pituus, int tyyliPisteet) { this.pituus = pituus; this.tyyliPisteet = tyyliPisteet; } public int getTyyliPisteet() { return tyyliPisteet; } public double getPituus() { return pituus; } public void setPituus(double pituus) { this.pituus = pituus; } public void setTyyliPisteet(int tyyliPisteet) { this.tyyliPisteet = tyyliPisteet; } }
24861046313c2dce0b182a220f893a6b0e8491ce
4e0453e54973bf9ea3dee54075246d2bace43a6f
/SortCompare.java
29db61edabff3b4b552cb1599336c23891f3b9e4
[]
no_license
azeemm94/data-structures-and-algorithms
ee36ec11e3252466513e30acf940c8f885ad8430
1def240f57e6686ede9d26d6c983d035de3f589a
refs/heads/master
2020-04-13T16:47:02.265067
2018-12-27T19:42:26
2018-12-27T19:42:26
163,330,264
0
0
null
null
null
null
UTF-8
Java
false
false
1,935
java
import java.util.*; import java.time.*; import java.lang.*; public class SortCompare { public static void BubbleSort(int[] x,int n) { for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(x[j]>x[j+1]) { int temp=x[j]; x[j]=x[j+1]; x[j+1]=temp; } } } } public static void MergeSort(int[] a, int low, int high) { int N = high - low; if (N <= 1) return; int mid = low + N/2; // recursively sort MergeSort(a, low, mid); MergeSort(a, mid, high); // merge two sorted subarrays int[] temp = new int[N]; int i = low, j = mid; for (int k = 0; k < N; k++) { if (i == mid) temp[k] = a[j++]; else if (j == high) temp[k] = a[i++]; else if (a[j]<a[i]) temp[k] = a[j++]; else temp[k] = a[i++]; } for (int k = 0; k < N; k++) a[low + k] = temp[k]; } public static int[] genRandomArray(int n) { int x[]=new int[n]; for(int i=0;i<n;i++) x[i]=(int)(Math.random() * 100); //Random integers between 0 and 100 return x; } public static void main(String args[]) { int n=10000; int a[]=genRandomArray(n); long startTime = System.currentTimeMillis(); //select either bubble or merge sort here //BubbleSort(a,n); MergeSort(a,0,n); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Total time "+totalTime); } }
0a0cead9792a00e8889a3a53456924fa7ee88bd7
837b961e5f1bc03a0a9bdd38f515465a330faba5
/02-observer/weather-station/src/main/java/weather/StatisticsDisplay.java
fcaa63bd6c63348e7cc443dca7ed506384336759
[]
no_license
bulbo-bolson/design-patterns
8ff05040eb447ccc375c0746fa519a395304717b
7b5f237ff49eb59045778a66e7c27fde14bddccb
refs/heads/master
2021-07-22T01:09:49.481648
2019-12-23T19:33:28
2019-12-23T19:33:28
217,846,079
0
0
null
2020-10-13T18:23:36
2019-10-27T11:38:47
Java
UTF-8
Java
false
false
1,569
java
package weather; import java.util.ArrayList; import java.util.Collections; public class StatisticsDisplay implements Observer, DisplayElement { private ArrayList<Float> temperatures; private Float averageTemperature; private Float maxTemperature; private Float minTemperature; private Subject weatherData; public StatisticsDisplay(Subject weatherData) { this.weatherData = weatherData; this.temperatures = new ArrayList<Float>(); weatherData.registerObserver(this); } public void update(float temperature, float humidity, float pressure) { this.temperatures.add(temperature); this.averageTemperature = calcAverageTemperature(); this.maxTemperature = calcMaxTemperature(); this.minTemperature = calcMinTemperature(); display(); } private Float calcAverageTemperature() { float totalDegrees = 0; for (float temperature : temperatures) { totalDegrees += temperature; } float averageTemperature = totalDegrees / temperatures.size(); return averageTemperature; } private Float calcMaxTemperature() { float maxTemperature = Collections.max(temperatures); return maxTemperature; } private Float calcMinTemperature() { float minTemperature = Collections.min(temperatures); return minTemperature; } public void display() { System.out.println("Avg / Max / Min temperature: " + averageTemperature + "/" + maxTemperature + "/" + minTemperature); } }
67e08ec3f46ee6c156672ade25e2a8ac9d733eb8
408b676a96b46a13d2f58a03734102e9fccde96f
/jdbc/src/test/java/cy/study/springboot/jdbc/JdbcApplicationTests.java
969740e0291a76997652d745daf5e67fe8d8e414
[]
no_license
cyfreeman/springbootstudy
2045a9ecce5d6ff3dd2184a4997205815058b036
585c3d8cb1b09f2a1d894f7cacb3a49e96ec64d4
refs/heads/master
2022-12-14T21:57:39.194777
2020-09-21T09:07:44
2020-09-21T09:07:44
294,562,477
0
0
null
null
null
null
UTF-8
Java
false
false
657
java
package cy.study.springboot.jdbc; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @SpringBootTest class JdbcApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection); System.out.println("关闭了"); connection.close(); } }
1dfb03a8cad4ebfa04015793b6e05ec04c976875
5596faddc0c8a905ff81051f9e26030b77a1fb13
/stareast-framework/src/main/java/com/stareast/framework/web/exception/user/UserPasswordRetryLimitCountException.java
19462c414b7f9d909271e6dbced3e6d4807a564a
[]
no_license
wangy2015/stareast-oracle
8a5759b500115ba01af6e6d8e15cd21bee768d92
2fccd1ef935ada5a42cf4c5caabb72bf8fd354df
refs/heads/master
2022-09-08T09:46:34.479037
2019-08-13T00:57:27
2019-08-13T00:57:27
200,402,961
0
0
null
2022-09-01T23:10:49
2019-08-03T17:28:12
JavaScript
UTF-8
Java
false
false
402
java
package com.stareast.framework.web.exception.user; /** * 用户错误记数异常类 * * @author stareast */ public class UserPasswordRetryLimitCountException extends UserException { private static final long serialVersionUID = 1L; public UserPasswordRetryLimitCountException(int retryLimitCount) { super("user.password.retry.limit.count", new Object[]{retryLimitCount}); } }
22f011d41e6a10ac61539e283b9b8dd6edf5b39b
1c95cdab94478459640fd444def364168e16ffeb
/app/src/main/java/com/example/patrick/aspro/ProfileActivity.java
27ff4b856c26fbab9a0af095a8cb0e11a8f5d0f0
[]
no_license
PatrickEdmac/Aspro
de9711db59ec1ef7d584e6e9b7236663390f4901
89c1b280a64e40e412ca1b9d7163ff92f99aa514
refs/heads/master
2021-01-01T18:09:13.437620
2017-08-27T16:42:13
2017-08-27T16:42:13
98,259,622
0
0
null
null
null
null
UTF-8
Java
false
false
344
java
package com.example.patrick.aspro; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class ProfileActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); } }
ad24784d343fa6b3e7488bf2f4a1d6f8512b9023
d796bd7178e7a2c2217626d35e1f6edd8e1eab1d
/src/main/java/com/trading/system/exception/ExceptionDetails.java
f95483997e19cc4d7918a09aea7d96d676318fe6
[]
no_license
nareshyadav1918/Trading-Server
c0ff7f48f4392f692d8d509bbd40f8e9eabefc8a
40d7b3b5185497b2d3829871cdcca24887d4b47a
refs/heads/master
2022-12-15T02:20:23.766973
2020-09-08T01:40:28
2020-09-08T01:40:28
292,685,110
0
0
null
null
null
null
UTF-8
Java
false
false
1,666
java
package com.trading.system.exception; import java.util.HashMap; import java.util.Map; public class ExceptionDetails { public Map<Integer, String> uiExecptionlist = new HashMap<Integer, String>(); // General public static int FILE_NOT_FOUND = 14010001; public static int DB_CONNECTION_ERROR = 14010002; public static int DB_TRANSACTION_ERROR = 14010003; public static int GENERAL_ERROR = 14010004; public static int UNAPPRECIATED_PARAMS = 14010006; public static int IMAGES_NOT_ABLE_TO_SAVE = 14010007; public static int USER_NOT_FOUND = 14010008; public static int SYMBOL_ID_NOT_EXIST = 14010009; public static int ACCOUNT_ID_NOT_EXIST = 14010010; public ExceptionDetails(){ this.prepareModelException(); } public void prepareModelException() { // General uiExecptionlist.put(FILE_NOT_FOUND, "Failed to find file at location {0}"); uiExecptionlist.put(DB_TRANSACTION_ERROR, "Error while DB transaction"); // general uiExecptionlist.put(DB_CONNECTION_ERROR, "Error while Connecting to DB"); // general uiExecptionlist.put(GENERAL_ERROR, "{0}"); // general uiExecptionlist.put(UNAPPRECIATED_PARAMS, "Unappreciated input parameter"); // general uiExecptionlist.put(IMAGES_NOT_ABLE_TO_SAVE, "Image not able to save"); // general uiExecptionlist.put(USER_NOT_FOUND, "User Not Found"); // general uiExecptionlist.put(SYMBOL_ID_NOT_EXIST, "symbolId is not exist or not valid"); // general uiExecptionlist.put(ACCOUNT_ID_NOT_EXIST, "Account is not exist or not valid"); // general } }
37c63f6d4514bc38d6b7677f745354474fd09cee
932e5a81f91fb67a73c30e18e556fe6da374cd91
/app/src/main/java/checking/app/sample/LoginActivity.java
83a8650b105018fcfd1e81fb77990f3b063ab2f6
[]
no_license
rameshannadhurai/RoomAccounts
c3c97de1159edce506b624e6ea57d1d9c894810c
ea75440ff63448351469e54fc53a79dcc3390180
refs/heads/master
2020-04-13T09:13:21.702784
2018-12-25T19:07:39
2018-12-25T19:07:39
163,105,172
0
0
null
null
null
null
UTF-8
Java
false
false
3,607
java
package checking.app.sample; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import checking.app.sample.helper.CustomDialog; import checking.app.sample.helper.CustomProgressDialog; import checking.app.sample.helper.MyCommon; import checking.app.sample.helper.SharedHelper; import checking.app.sample.pushnotification.Config; public class LoginActivity extends CommonActivity { @BindView(R.id.edit_email) EditText edit_email; @BindView(R.id.edit_password) EditText edit_password; String str_emil = "", str_password = "", str_user = ""; @BindView(R.id.btn_login) Button btn_login; @BindView(R.id.btn_register) Button btn_register; private FirebaseAuth firebaseAuth; private DatabaseReference databaseReference; private CustomProgressDialog customProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_login); ButterKnife.bind(this); firebaseAuth = FirebaseUtils.getFirebaseAuth(); databaseReference = FirebaseUtils.getDatabaseReference(); customProgressDialog = CustomDialog.getInstanse(this); } @OnClick({R.id.btn_register, R.id.btn_login}) public void onClick(View v) { switch (v.getId()) { case R.id.btn_register: startActivity(new Intent(getApplicationContext(), Register.class)); break; case R.id.btn_login: String email = edit_email.getText().toString().trim(); String password = edit_password.getText().toString().trim(); userLoginFunction(email, password); break; default: break; } } public void userLoginFunction(final String email, final String password) { customProgressDialog.show(); firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { customProgressDialog.dismiss(); if (!task.isSuccessful()) { Toast.makeText(getApplicationContext(), "Please Enter Valid Email and Password", Toast.LENGTH_SHORT).show(); } else { startActivity(new Intent(getApplicationContext(), MainActivity.class)); } } }); } private void displayFirebaseRegId() { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); MyCommon.DEVICETOCKEN = pref.getString("regId", null); SharedHelper.putKey(getApplicationContext(), "DEVICEKY", MyCommon.DEVICETOCKEN); Log.e("KEYYYYYYYYYYYYYYYY==>", "Firebase reg id: " + MyCommon.DEVICETOCKEN); } @Override public void networkAvailable() { displayFirebaseRegId(); } @Override public void networkUnavailable() { } }
77d841a2676c9df3197c88d81001c11eceb87f1a
d98de110431e5124ec7cc70d15906dac05cfa61a
/public/source/ors/src/test/java/org/marketcetera/ors/history/EquityReportsHistoryTest.java
b0c6f3ee89375fd89d741bec0220a998efb64756
[]
no_license
dhliu3/marketcetera
367f6df815b09f366eb308481f4f53f928de4c49
4a81e931a044ba19d8f35bdadd4ab081edd02f5f
refs/heads/master
2020-04-06T04:39:55.389513
2012-01-30T06:49:25
2012-01-30T06:49:25
29,947,427
0
1
null
2015-01-28T02:54:39
2015-01-28T02:54:39
null
UTF-8
Java
false
false
2,796
java
package org.marketcetera.ors.history; import org.marketcetera.util.misc.ClassVersion; import org.marketcetera.trade.*; import org.marketcetera.ors.security.SimpleUser; import org.marketcetera.core.position.PositionKey; import org.marketcetera.module.ExpectedFailure; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.util.Date; import java.util.Map; /* $License$ */ /** * Tests {@link ReportHistoryServices} behavior for Equity and unhandled * instruments. * * @author [email protected] * @version $Id: EquityReportsHistoryTest.java 10885 2009-11-17 19:22:56Z klim $ * @since 2.0.0 */ @ClassVersion("$Id: EquityReportsHistoryTest.java 10885 2009-11-17 19:22:56Z klim $") public class EquityReportsHistoryTest extends ReportHistoryTestBase<Equity> { /** * Verifies the behavior when instrument cannot be extracted from the report. * * @throws Exception if there were unexpected errors. */ @Test public void unhandledInstrument() throws Exception { final ExecutionReport report = createExecReport("ord1", null, new Equity("green"), Side.Buy, OrderStatus.Filled, BigDecimal.TEN, BigDecimal.TEN, BigDecimal.TEN, BigDecimal.TEN); //Change the security type so that the instrument is not retrievable anymore. ((FIXMessageSupport) report).getMessage().setField( new quickfix.field.SecurityType(quickfix.field.SecurityType.BANK_NOTES)); Date before = new Date(); sleepForSignificantTime(); new ExpectedFailure<IllegalArgumentException>() { @Override protected void run() throws Exception { sServices.save(report); } }; //verify that no reports were saved. assertEquals(0, sServices.getReportsSince(sViewer, before).length); } @Override protected Equity getInstrument() { return new Equity("ubm"); } @Override protected BigDecimal getInstrumentPosition(Date inDate, Equity inInstrument) throws Exception { return getPosition(inDate, inInstrument); } @Override protected BigDecimal getInstrumentPosition(Date inDate, Equity inInstrument, SimpleUser inUser) throws Exception { return getPosition(inDate, inInstrument, inUser); } @Override protected Map<PositionKey<Equity>, BigDecimal> getInstrumentPositions(Date inDate) throws Exception { return getPositions(inDate); } @Override protected Map<PositionKey<Equity>, BigDecimal> getInstrumentPositions(Date inDate, SimpleUser inUser) throws Exception { return getPositions(inDate, inUser); } }
3b90f4bb853657431cd1942a1c64892e509b8540
542de8f55b46d6b0801889c2747b386c670f1e6e
/src/main/java/net/koreate/staybusan/room/dao/RoomCommentDAO.java
6c5622f9ac5930a66473f42173a2a2cd77a22d79
[]
no_license
rmsdk900/stay_busan_integrated
3e2e477335047ecfba9a9b2dbf2960c4aad68497
bf68104716b1bf3db394cda590a753f5b56fa694
refs/heads/master
2022-12-21T21:28:01.155139
2020-03-29T13:33:49
2020-03-29T13:33:49
242,610,748
0
1
null
2022-12-16T15:25:25
2020-02-23T23:54:37
Java
UTF-8
Java
false
false
2,443
java
package net.koreate.staybusan.room.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import net.koreate.mvc.common.util.Criteria; import net.koreate.staybusan.room.vo.BanCommentVO; import net.koreate.staybusan.room.vo.CommentVO; public interface RoomCommentDAO { // 먼저 총 후기 갯수부터 불러온다. @Select("SELECT count(*) FROM comment WHERE r_no=#{r_no}") int totalCommentCnt(int r_no) throws Exception; // 불러온다. 후기들 @Select("SELECT * FROM comment " + " WHERE r_no=#{r_no}" + " ORDER BY c_origin DESC, c_seq ASC" + " LIMIT #{cri.pageStart}, #{cri.perPageNum}") List<CommentVO> commentList(@Param("r_no") int r_no,@Param("cri") Criteria cri) throws Exception; // 평균 평점 구하기 @Select("SELECT avg(c_star) FROM comment WHERE r_no=#{r_no} AND c_dep=0") Float getStarAvg(int r_no)throws Exception; // 기존 정렬 값들 수정 @Update("UPDATE comment SET c_seq = c_seq+1 WHERE c_origin=#{c_origin} AND c_seq > #{c_seq}") void updateOriginalSeq(CommentVO vo)throws Exception; // 댓글 넣기 @Insert("INSERT INTO comment (r_no, u_no, u_name, c_origin, c_dep, c_seq, c_content, c_regdate) " + " VALUES(#{r_no}, #{u_no}, #{u_name}, #{c_origin}, #{c_dep}, #{c_seq}, #{c_content}, now())") boolean addReply(CommentVO vo) throws Exception; // 댓글 삭제 @Delete("DELETE FROM comment WHERE c_no=#{c_no}") boolean delComment(int c_no)throws Exception; // 댓글 수정 @Update("UPDATE comment SET c_content=#{c_content} WHERE c_no=#{c_no}") void modComment(@Param("c_no") int c_no, @Param("c_content") String c_content)throws Exception; // 댓글 하나만 들고오기 @Select("SELECT * FROM comment WHERE c_no=#{c_no}") CommentVO getComment(int c_no)throws Exception; // 밴 목록에 올리기 @Insert("INSERT INTO ban_comment(c_no, b_c_reporter, b_c_reason, b_c_bad_person, c_content) VALUES(#{c_no}, #{b_c_reporter}, #{b_c_reason}, #{b_c_bad_person}, #{c_content})") void banComment(BanCommentVO vo)throws Exception; // 밴목록에 올린 거 가져오기 @Select("SELECT * FROM ban_comment WHERE c_no=#{c_no}") List<BanCommentVO> getBanComment(int c_no)throws Exception; }
f89833505b8f9d78fdbb9d54c12a64dcc1b4546c
6f00bef165642228a234a4ac62d6606509c379c0
/OrderService/src/main/java/com/ruhail/OrderService/service/impl/InvoiceServiceImpl.java
2bcd79e4a34ee4f665087b2bcfc07f28e616ca1a
[]
no_license
muhammedruhail/microservicelearning
41a05c2615f37ce54b5c9184e594a20c12f8523e
840a03cf1caad91a38851c69a3179e61171ee9a4
refs/heads/master
2022-11-23T14:36:28.802311
2020-07-30T07:49:20
2020-07-30T07:49:20
279,579,895
0
0
null
null
null
null
UTF-8
Java
false
false
1,953
java
package com.ruhail.OrderService.service.impl; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ruhail.OrderService.domain.Invoice; import com.ruhail.OrderService.repository.InvoiceRepository; import com.ruhail.OrderService.service.InvoiceService; /** * Service Implementation for managing Invoice. */ @Service @Transactional public class InvoiceServiceImpl implements InvoiceService { private final Logger log = LoggerFactory.getLogger(InvoiceServiceImpl.class); private final InvoiceRepository invoiceRepository; public InvoiceServiceImpl(InvoiceRepository invoiceRepository) { this.invoiceRepository = invoiceRepository; } /** * Save a invoice. * * @param invoice the entity to save * @return the persisted entity */ @Override public Invoice save(Invoice invoice) { log.debug("Request to save Invoice : {}", invoice); return invoiceRepository.save(invoice); } /** * Get all the invoices. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<Invoice> findAll(Pageable pageable) { log.debug("Request to get all Invoices"); return invoiceRepository.findAll(pageable); } /** * Get one invoice by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<Invoice> findOne(Long id) { log.debug("Request to get Invoice : {}", id); return invoiceRepository.findById(id); } /** * Delete the invoice by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete Invoice : {}", id); invoiceRepository.deleteById(id); } }
0f2d261abe175033b89982f15341009cf7df858e
46166024c76e4802dc912668b67e6ca9f3ba6565
/app/src/main/java/comq/acadview/project/MainActivity1.java
1ee1a8b7519f75cc9ee63da1b048e10cf5436c2f
[]
no_license
tasvir793/project
0f7695e1542e398c9f200c736bb1e24f58db46cd
a87664fca5cb570028351098b63a220da559c053
refs/heads/master
2020-03-23T03:04:39.689987
2018-07-15T07:55:59
2018-07-15T07:55:59
141,008,328
0
0
null
null
null
null
UTF-8
Java
false
false
1,066
java
package comq.acadview.project; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity1 extends AppCompatActivity { ImageView imageView1; ProgressBar progressBar1; TextView textView1; private static int time_out = 3000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main1); imageView1 = findViewById(R.id.imageView1); progressBar1 = findViewById(R.id.progressBar1); textView1=findViewById(R.id.textView1); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(MainActivity1.this, MainActivity2.class); startActivity(intent); finish(); } }, time_out); } }
59f6ae6d2963c38c932f493b3d03fd69ee3c47d4
2ba20c784e38af267784fefa04e73f82bb6ee645
/src/Project4/ListEngine.java
d2e09670d80464ac53b73b71eef0a5fd65283372
[]
no_license
Kat-lc/CarDealershipLinkedLists
a4ede988174cc2f527dfd67ba089dda820b7579a
4443cf3f122f6e77ce8d117177d1b8546e9bc35a
refs/heads/master
2022-03-31T16:19:43.463158
2019-11-22T06:03:44
2019-11-22T06:03:44
222,593,143
0
0
null
null
null
null
UTF-8
Java
false
false
3,517
java
package Project4; import javax.swing.*; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; public class ListEngine extends AbstractListModel { private MySingleLinkedList listAutos; public ListEngine() { super(); listAutos = new MySingleLinkedList (); createList(); } public Auto remove(int i) { Auto unit = listAutos.remove(i); fireIntervalRemoved(this, 0, listAutos.size()); return unit; } public void add (Auto a) { listAutos.add(a); fireIntervalAdded(this, 0, listAutos.size()); } public Auto get (int i) { return listAutos.get(i); } public Object getElementAt(int arg0) { Auto unit = listAutos.get(arg0); return unit.toString(); } public int getSize() { return listAutos.size(); } public void saveDatabase(String filename) { try { FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(listAutos); os.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null,"Error in saving db"); } } public void loadDatabase(String filename) { try { FileInputStream fis = new FileInputStream(filename); ObjectInputStream is = new ObjectInputStream(fis); listAutos = (MySingleLinkedList) is.readObject(); fireIntervalAdded(this, 0, listAutos.size() - 1); is.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(null,"Error in loading db"); } } public void createList() { SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"); GregorianCalendar temp1 = new GregorianCalendar(); GregorianCalendar temp2 = new GregorianCalendar(); GregorianCalendar temp3 = new GregorianCalendar(); GregorianCalendar temp4 = new GregorianCalendar(); GregorianCalendar temp5 = new GregorianCalendar(); GregorianCalendar temp6 = new GregorianCalendar(); try { Date d1 = df.parse("3/20/2019"); temp1.setTime(d1); Date d2 = df.parse("4/20/2019"); temp2.setTime(d2); Date d3 = df.parse("12/20/2018"); temp3.setTime(d3); Date d4 = df.parse("1/20/2019"); temp4.setTime(d4); Date d5 = df.parse("1/20/2010"); temp5.setTime(d5); Date d6 = df.parse("1/20/2020"); temp6.setTime(d6); Car Car1 = new Car(temp1, "Outback", 18000,"LX", false); Car Car2 = new Car(temp2, "Chevy", 11000,"EX", false); Car Car3 = new Car(temp3, "Focus", 19000,"EX", true); Truck Truck1 = new Truck(temp4,"F150",12000,"LX",false); Truck Truck2 = new Truck(temp5,"F250",42000,"LX",false); Truck Truck3 = new Truck(temp6,"F350",2000,"EX",true); add(Truck1); add(Car1); add(Truck2); add(Car2); add(Car3); add(Truck3); System.out.println(listAutos.size()); System.out.println(listAutos.size()); } catch (ParseException e) { throw new RuntimeException("Error in testing, creation of list"); } } }
bf743c3a30c13b84739575f3f4b29a6585a10726
5fa7462dc506c5dee385c2186db9d5ab54436b05
/src/main/java/com/pendownabook/configuration/SecurityConfiguration.java
c48e90153e1f7143b7200f5ba6d37bc99ca7acfe
[]
no_license
Vishvin95/PenDownABook
a61bdf1a56a904f24d5cfed75874c95001b48648
1c4c55b6b5582fb6323e45e50fe473c9a314b061
refs/heads/master
2023-01-27T13:09:48.329132
2020-12-09T18:55:18
2020-12-09T18:55:18
261,965,692
0
0
null
null
null
null
UTF-8
Java
false
false
3,844
java
package com.pendownabook.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.pendownabook.service.UserService; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Autowired private AuthenticationSuccessHandler successHandler; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/registration**", "/js/**","/css/**","/images/**").permitAll() .antMatchers("/webjars/**").permitAll() .antMatchers("/").permitAll() .antMatchers("/home/**").hasAuthority("USER") .antMatchers("/admin/**").hasAuthority("ADMIN") .antMatchers("/publisher/**").hasAuthority("PUBLISHER") .antMatchers(HttpMethod.GET, "/payment/**").permitAll() .antMatchers(HttpMethod.POST, "/payment/**").permitAll() .antMatchers(HttpMethod.GET, "/book/**").permitAll() .antMatchers(HttpMethod.POST, "/book/**").permitAll() .antMatchers(HttpMethod.GET,"/service/**").permitAll() .antMatchers(HttpMethod.GET,"/previewbook/**").permitAll() .antMatchers(HttpMethod.POST,"/previewbook/**").permitAll() .antMatchers(HttpMethod.GET,"/profile/**").permitAll() .antMatchers(HttpMethod.GET, "/genre/**").permitAll() .antMatchers(HttpMethod.GET,"/subscription/**").permitAll() .antMatchers(HttpMethod.GET,"/reviewstatus/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .successHandler(successHandler) .failureUrl("/login?error") .permitAll() .and() .logout() .invalidateHttpSession(true) .clearAuthentication(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .deleteCookies("JSESSIONID") .permitAll(); } @Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager customAuthenticationManager() throws Exception { return authenticationManager(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } }
fb8538cb1acb494f48845bf321e46159c4182dbd
19978124ebb998c355fc62c3fec31e0cd3ca2939
/CazraGraphs/src/cazgraphs/graph/style/TopologyGraphStyle.java
057d35914c36c4562d71ed0f59b2056d560ae6b3
[ "BSD-2-Clause" ]
permissive
Cazra/CazraGraphs
156e072740e27db8fb42cd6ed95203f5fc8ba550
af5524f2b119cf6913f36acffe4ba61e3815f147
refs/heads/master
2016-09-06T13:57:11.042668
2014-02-04T15:00:58
2014-02-04T15:00:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,122
java
package cazgraphs.graph.style; import java.awt.*; import java.util.Map; import cazgraphs.graph.*; /** * A graph style that color codes nodes based on the topology of the graph * starting from some specified node. */ public class TopologyGraphStyle extends DefaultGraphStyle { /** The computed topology for the graph. */ public Map<String, Integer> topology = null; /** The maximum depth of the topology. */ public int maxDepth = -1; public TopologyGraphStyle() { super(); } /** * Selects a color from the HSB color model to represent a particular depth. * Colors towards the red end of the spectrum are shallow. * Colors towards the blue end of the spectrum are deep. */ protected Color getColorForDepth(int depth, boolean isStroke) { if(depth < 0 || depth > maxDepth) { return new Color(0xEEEEEE); } float hue = 0f; if(depth == 0) { hue = 0f; } else { hue = (depth-1)*0.7f/maxDepth; } float sat = 0.3f; if(depth == 0) { sat = 0.0f; } float bright = 1.0f; if(isStroke) { bright = 0.7f; } return Color.getHSBColor(hue, sat, bright); } /** Sets the topological information for the style, given the top node. */ public void setTopology(VertexSprite node) { if(node == null) { topology = null; return; } topology = GraphSolver.simpleTopology(node.getGraph().getGraph(), node.getID()); maxDepth = -1; for(Integer depth : topology.values()) { if(depth > maxDepth) { maxDepth = depth; } } } public Color getVertexStrokeColor(VertexSprite node) { if(topology == null || node.isSelected()) { return super.getVertexStrokeColor(node); } else { Integer depth = topology.get(node.getID()); if(depth == null) { depth = -1; } return getColorForDepth(depth, true); } } public Color getVertexFillColor(VertexSprite node) { if(topology == null || node.isSelected()) { return super.getVertexFillColor(node); } else { Integer depth = topology.get(node.getID()); if(depth == null) { depth = -1; } return getColorForDepth(depth, node.isSink()); } } public Color getEdgeColor(VertexSprite n1, VertexSprite n2) { if(topology == null) { return getColorForDepth(-1, true); } else { Integer depth1 = topology.get(n1.getID()); Integer depth2 = topology.get(n2.getID()); if(depth1 == null) { depth1 = -1; } if(depth2 == null) { depth2 = -1; } int depth = (int) Math.min(depth1, depth2); return getColorForDepth(depth, true); } } public int getEdgeThickness(VertexSprite n1, VertexSprite n2) { if(topology == null) { return super.getEdgeThickness(n1, n2); } else { if(topology.containsKey(n1.getID())) { return super.getEdgeThickness(n1, n2) * 2; } else { return super.getEdgeThickness(n1, n2); } } } }
e8206bea6563399df8419777178751e4afd2baa4
a529d18a65ad5a8e70c18e7b3d53bff8f88a19ac
/app/src/main/java/com/aprr/biotracer/app/MySingleton.java
c6e634d066fb17b1079c7867f4bb521497f3dd21
[]
no_license
doniapr/BioTracer
6a2217c33f59a113f1cac11f599a3ee6115fb4cc
fbb8fed10af93948c047aee2c06424cb9a89b512
refs/heads/master
2020-04-02T16:46:31.706784
2018-10-25T07:31:29
2018-10-25T07:31:29
154,628,052
0
0
null
null
null
null
UTF-8
Java
false
false
1,104
java
package com.aprr.biotracer.app; import android.content.Context; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class MySingleton { private static MySingleton mInstance; private RequestQueue mRequestQueue; private static Context mCtx; private MySingleton(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); } public static synchronized MySingleton getInstance(Context context) { if (mInstance == null) { mInstance = new MySingleton(context); } return mInstance; } private RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in. mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } }
5ba837c4882a99026a1afc64bbd3166a9c5a969d
dc67ccb234b177ffba698e710f817ab0a842a643
/SportsDance/Dance/src/main/java/mr/li/dance/utils/util/IndexViewPager.java
60006b186753634cd2f102f1860c811e9979176a
[]
no_license
15234450670/companys
eb4278a96580481a60b160a94aa5fc85edc6e183
fb214149d67d2bcb7bcf791009e610aa2e1b255a
refs/heads/master
2021-01-01T17:29:00.429502
2018-06-04T07:24:50
2018-06-04T07:25:30
98,080,318
0
0
null
null
null
null
UTF-8
Java
false
false
1,512
java
package mr.li.dance.utils.util; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; /** * 自定义ViewPager禁止左右滑动 */ public class IndexViewPager extends ViewPager { private boolean isCanScroll = false; public IndexViewPager(Context context) { super(context); } public IndexViewPager(Context context, AttributeSet attrs) { super(context, attrs); } public void setScanScroll(boolean isCanScroll) { this.isCanScroll = isCanScroll; } @Override public void scrollTo(int x, int y) { super.scrollTo(x, y); } @Override public boolean onTouchEvent(MotionEvent arg0) { // TODO Auto-generated method stub if (isCanScroll) { return super.onTouchEvent(arg0); } else { return false; } } @Override public void setCurrentItem(int item, boolean smoothScroll) { // TODO Auto-generated method stub super.setCurrentItem(item, smoothScroll); } @Override public void setCurrentItem(int item) { // TODO Auto-generated method stub super.setCurrentItem(item); } @Override public boolean onInterceptTouchEvent(MotionEvent arg0) { // TODO Auto-generated method stub if (isCanScroll) { return super.onInterceptTouchEvent(arg0); } else { return false; } } }
15f1a7a0b3937745c9adb68f8e0f2c1fd5887e18
6129e92df2d3fc39957d5b320141ba25e870d2d1
/centro-backend/src/test/java/com/tecnositaf/centrobackend/utilities/DateUtilitiesTest.java
1f712fde4eb17fa2857bf50f663b3c402809e511
[]
no_license
WilliamZedda/centro-backend
86ef7208d5f3426ca7f256feee9f6d29a06343e7
7e87fd235236ef5e8bfc29b64a7bef231c244239
refs/heads/master
2021-05-19T04:22:09.697041
2020-04-21T15:24:05
2020-04-21T15:24:05
251,526,652
0
0
null
2021-04-26T20:06:58
2020-03-31T07:08:47
Java
UTF-8
Java
false
false
1,080
java
package com.tecnositaf.centrobackend.utilities; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.tecnositaf.centrobackend.CentroBackendApplication; import static org.junit.Assert.*; import java.time.LocalDateTime; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CentroBackendApplication.class) @SpringBootTest @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DateUtilitiesTest { @Test public void calculateStorageYearsSuccess() { LocalDateTime date = LocalDateTime.of(2000, 10, 10, 10, 10, 10); assertSame(20, DateUtilities.calculateStorageYears(date)); } @Test public void calculateStorageYearsFailure() { LocalDateTime date = LocalDateTime.of(2000, 10, 10, 10, 10, 10); assertNotSame(10, DateUtilities.calculateStorageYears(date)); } }
e426c97c68d1b752999c2567990451819aa5a6eb
663c05309a50b671bab51700ece001a1ea670225
/Springboot/src/main/java/com/project/DAO/MongoDbDao.java
d32750597ac89385a2aa15fb5bd636daf0bb1409
[]
no_license
ubunturoxshacker/SpringbootProject
cd4d63026ce8dcaf4c9fdad789e72b7a6309dad5
53864ed1694c7660f4b0d615470068193386f12d
refs/heads/master
2021-01-01T04:13:58.486347
2017-07-13T17:14:01
2017-07-13T17:14:01
97,144,830
0
0
null
2017-07-13T17:14:02
2017-07-13T16:37:26
null
UTF-8
Java
false
false
1,260
java
package com.project.DAO; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class MongoDbDao { private static MongoDbDao mgdb=new MongoDbDao(); private Map vals; private static MongoClient mongoClient=new MongoClient("localhost",27017); public Map<String,String> dbreturn(){ DB db=mongoClient.getDB("mydb"); DBCollection collection=db.getCollection("test"); System.out.println("Connected now getting collection"); BasicDBObject andQuery =new BasicDBObject(); List<BasicDBObject> obj=new ArrayList<BasicDBObject>(); obj.add(new BasicDBObject("Username","Sankalp Kalia")); obj.add(new BasicDBObject("Password","123")); andQuery.put("$and", obj); @SuppressWarnings("unused") DBCursor cursor=collection.find(andQuery); while(cursor.hasNext()){ DBObject resultObj=cursor.next(); vals= resultObj.toMap(); } return vals; } public static MongoDbDao getMongoDbDao(){ return mgdb; } }
e29e45fec6c4d99925332233314e65d163032fe0
f36068d2e8e5b9d8ec24a4013274cc75745fbcb3
/clouddesigner/org.occiware.clouddesigner.occi.hypervisor.edit/src-gen/org/occiware/clouddesigner/occi/hypervisor/provider/UserItemProvider.java
6cee0a9d05abde88e0968384e66951450cd8c600
[]
no_license
activeeon-bot/ecore
82a098aa4b4a2a47d1f476b0ad343b0e2025b6ef
e9011f1c100391e0201e23011edc8cd64b896d4e
refs/heads/master
2021-01-22T17:18:07.882074
2015-09-24T09:51:41
2015-09-24T09:51:41
43,438,428
1
0
null
2015-09-30T14:39:46
2015-09-30T14:39:46
null
UTF-8
Java
false
false
2,589
java
/** */ package org.occiware.clouddesigner.occi.hypervisor.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.occiware.clouddesigner.occi.hypervisor.User; /** * This is the item provider adapter for a {@link org.occiware.clouddesigner.occi.hypervisor.User} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class UserItemProvider extends InterfaceItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public UserItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns User.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/User")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((User)object).getName(); return label == null || label.length() == 0 ? getString("_UI_User_type") : getString("_UI_User_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
b45134028c3632ac13ab803261edaed7a149be4f
46ce1edf2a23307fc9fa27f9c381d79fd271a1b1
/src/main/java/com/xh/comm/entry/UserLoginInfoBeanExample.java
5624062198c59779df471555b096830b4f9b454d
[]
no_license
yu894890489/xhmanager
7070d389cd2bd08ab41fe2d92fce734b4c5b0665
5c50103de9a1f2690b3a2c35a84318428fb9b5bf
refs/heads/master
2020-03-27T00:53:45.123820
2018-08-22T06:26:47
2018-08-22T06:26:47
145,665,300
0
0
null
null
null
null
UTF-8
Java
false
false
24,292
java
package com.xh.comm.entry; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class UserLoginInfoBeanExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public UserLoginInfoBeanExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } protected void addCriterionForJDBCDate(String condition, Date value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value.getTime()), property); } protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } List<java.sql.Date> dateList = new ArrayList<java.sql.Date>(); Iterator<Date> iter = values.iterator(); while (iter.hasNext()) { dateList.add(new java.sql.Date(iter.next().getTime())); } addCriterion(condition, dateList, property); } protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(String value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(String value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(String value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(String value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(String value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(String value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLike(String value) { addCriterion("user_id like", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotLike(String value) { addCriterion("user_id not like", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<String> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<String> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(String value1, String value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(String value1, String value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andLoginTimeIsNull() { addCriterion("login_time is null"); return (Criteria) this; } public Criteria andLoginTimeIsNotNull() { addCriterion("login_time is not null"); return (Criteria) this; } public Criteria andLoginTimeEqualTo(Date value) { addCriterionForJDBCDate("login_time =", value, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeNotEqualTo(Date value) { addCriterionForJDBCDate("login_time <>", value, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeGreaterThan(Date value) { addCriterionForJDBCDate("login_time >", value, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("login_time >=", value, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeLessThan(Date value) { addCriterionForJDBCDate("login_time <", value, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("login_time <=", value, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeIn(List<Date> values) { addCriterionForJDBCDate("login_time in", values, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeNotIn(List<Date> values) { addCriterionForJDBCDate("login_time not in", values, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeBetween(Date value1, Date value2) { addCriterionForJDBCDate("login_time between", value1, value2, "loginTime"); return (Criteria) this; } public Criteria andLoginTimeNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("login_time not between", value1, value2, "loginTime"); return (Criteria) this; } public Criteria andLoginEndTimeIsNull() { addCriterion("login_end_time is null"); return (Criteria) this; } public Criteria andLoginEndTimeIsNotNull() { addCriterion("login_end_time is not null"); return (Criteria) this; } public Criteria andLoginEndTimeEqualTo(Date value) { addCriterionForJDBCDate("login_end_time =", value, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeNotEqualTo(Date value) { addCriterionForJDBCDate("login_end_time <>", value, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeGreaterThan(Date value) { addCriterionForJDBCDate("login_end_time >", value, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("login_end_time >=", value, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeLessThan(Date value) { addCriterionForJDBCDate("login_end_time <", value, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("login_end_time <=", value, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeIn(List<Date> values) { addCriterionForJDBCDate("login_end_time in", values, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeNotIn(List<Date> values) { addCriterionForJDBCDate("login_end_time not in", values, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeBetween(Date value1, Date value2) { addCriterionForJDBCDate("login_end_time between", value1, value2, "loginEndTime"); return (Criteria) this; } public Criteria andLoginEndTimeNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("login_end_time not between", value1, value2, "loginEndTime"); return (Criteria) this; } public Criteria andCreaterIsNull() { addCriterion("creater is null"); return (Criteria) this; } public Criteria andCreaterIsNotNull() { addCriterion("creater is not null"); return (Criteria) this; } public Criteria andCreaterEqualTo(String value) { addCriterion("creater =", value, "creater"); return (Criteria) this; } public Criteria andCreaterNotEqualTo(String value) { addCriterion("creater <>", value, "creater"); return (Criteria) this; } public Criteria andCreaterGreaterThan(String value) { addCriterion("creater >", value, "creater"); return (Criteria) this; } public Criteria andCreaterGreaterThanOrEqualTo(String value) { addCriterion("creater >=", value, "creater"); return (Criteria) this; } public Criteria andCreaterLessThan(String value) { addCriterion("creater <", value, "creater"); return (Criteria) this; } public Criteria andCreaterLessThanOrEqualTo(String value) { addCriterion("creater <=", value, "creater"); return (Criteria) this; } public Criteria andCreaterLike(String value) { addCriterion("creater like", value, "creater"); return (Criteria) this; } public Criteria andCreaterNotLike(String value) { addCriterion("creater not like", value, "creater"); return (Criteria) this; } public Criteria andCreaterIn(List<String> values) { addCriterion("creater in", values, "creater"); return (Criteria) this; } public Criteria andCreaterNotIn(List<String> values) { addCriterion("creater not in", values, "creater"); return (Criteria) this; } public Criteria andCreaterBetween(String value1, String value2) { addCriterion("creater between", value1, value2, "creater"); return (Criteria) this; } public Criteria andCreaterNotBetween(String value1, String value2) { addCriterion("creater not between", value1, value2, "creater"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterionForJDBCDate("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterionForJDBCDate("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterionForJDBCDate("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterionForJDBCDate("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterionForJDBCDate("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterionForJDBCDate("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterionForJDBCDate("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdaterIsNull() { addCriterion("updater is null"); return (Criteria) this; } public Criteria andUpdaterIsNotNull() { addCriterion("updater is not null"); return (Criteria) this; } public Criteria andUpdaterEqualTo(String value) { addCriterion("updater =", value, "updater"); return (Criteria) this; } public Criteria andUpdaterNotEqualTo(String value) { addCriterion("updater <>", value, "updater"); return (Criteria) this; } public Criteria andUpdaterGreaterThan(String value) { addCriterion("updater >", value, "updater"); return (Criteria) this; } public Criteria andUpdaterGreaterThanOrEqualTo(String value) { addCriterion("updater >=", value, "updater"); return (Criteria) this; } public Criteria andUpdaterLessThan(String value) { addCriterion("updater <", value, "updater"); return (Criteria) this; } public Criteria andUpdaterLessThanOrEqualTo(String value) { addCriterion("updater <=", value, "updater"); return (Criteria) this; } public Criteria andUpdaterLike(String value) { addCriterion("updater like", value, "updater"); return (Criteria) this; } public Criteria andUpdaterNotLike(String value) { addCriterion("updater not like", value, "updater"); return (Criteria) this; } public Criteria andUpdaterIn(List<String> values) { addCriterion("updater in", values, "updater"); return (Criteria) this; } public Criteria andUpdaterNotIn(List<String> values) { addCriterion("updater not in", values, "updater"); return (Criteria) this; } public Criteria andUpdaterBetween(String value1, String value2) { addCriterion("updater between", value1, value2, "updater"); return (Criteria) this; } public Criteria andUpdaterNotBetween(String value1, String value2) { addCriterion("updater not between", value1, value2, "updater"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterionForJDBCDate("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterionForJDBCDate("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterionForJDBCDate("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterionForJDBCDate("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterionForJDBCDate("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterionForJDBCDate("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterionForJDBCDate("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
cee374cce7ba746009afd1f7fbf122be63281f28
3a7cd8f93dd17491544b3e3bb11af455940122d0
/mall14/user/src/main/java/org/lele/user/service/MUserService.java
9ffbb821baa085f9fcae047d2a0c73081c3f357d
[]
no_license
jcl666-github/lel-mall
2bb4078eed29d9df41407adf0613afff18c1fa73
f184d450168e1083c31cd1954e0115aa7310aa5a
refs/heads/master
2022-11-11T16:56:23.350429
2020-06-06T02:23:05
2020-06-06T02:23:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
187
java
package org.lele.user.service; import com.baomidou.mybatisplus.extension.service.IService; import org.lele.common.entity.MUser; public interface MUserService extends IService<MUser> { }
ec4c11bac0e5f130b9597ba113a25c6808ba3d5a
6ad575568324c4bf731e7a4ddb5490cfd10d9217
/src/com/springdemo/mvc/Customer.java
03961b3fe37517845ab463d971a22740e0044ac0
[]
no_license
rhonniel/spring-mvc-demo
4508d1b5611ac7ed6aa0a0c548d2d5571fa4cc6b
c629cd10d2941ff92a8f6b5cd3fb2289d77f8efa
refs/heads/master
2020-04-12T12:59:09.462265
2019-01-05T20:50:11
2019-01-05T20:50:11
162,508,233
1
0
null
null
null
null
UTF-8
Java
false
false
1,507
java
package com.springdemo.mvc; import com.springdemo.mvc.customValidation.CourseCode; import javax.validation.constraints.*; public class Customer { private String firstName; @NotNull(message = "is required") @Size(min=1, message = "is required") private String lastName; @NotNull(message = "is required") @Min(value=0, message = "must be greater than or equal to zero") @Max(value=10, message = "must be less than or equal to 10") private Integer freePasses; @Pattern(regexp = "^[a-zA-Z0-9]{5}", message = "only 5 chars/digits") private String postalCode; @CourseCode(value = "ñaña", message = "ñaaaaaaa") private String courseCode; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public Integer getFreePasses() { return freePasses; } public void setFreePasses(Integer freePasses) { this.freePasses = freePasses; } public String getCourseCode() { return courseCode; } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } }
c0ce09934e9118ee90a65cd735b333080576fc70
87e640c4e5d72d13c571cbecb65aa7d29192155e
/app/src/test/java/shopify/app/shopifyme/ExampleUnitTest.java
2dbbed9626dbaffd901100e9ea6facc76a6517dc
[]
no_license
saurabhmisal/vanhackaton-shopify-challange
1c91f03bd16400ba05225907e4b60c9cc7cd8c0d
7496ca0777f0860025261e9c0d424541405d3969
refs/heads/master
2020-03-26T05:09:46.788731
2016-05-22T21:52:21
2016-05-22T21:52:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
314
java
package shopify.app.shopifyme; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
73823bc4f3bb5529a4ded631b6000134ebe92beb
89b4b60796b5ed68b62368a2944356e1e58280ef
/practice/MyLineChart.java
5790c91decafe86962b210e64c1cd56be6852822
[]
no_license
zjpierson/PA1
3b57114a692edaacfea9ab3242802de587b90098
3ac6b26e3016f7cd54555143032e72f02811baf4
refs/heads/master
2021-01-10T01:50:37.406972
2016-03-14T17:55:09
2016-03-14T17:55:09
51,414,445
0
0
null
null
null
null
UTF-8
Java
false
false
2,526
java
import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import org.jfree.chart.plot.*; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.*; import java.util.*; public class MyLineChart extends ApplicationFrame { public MyLineChart( String applicationTitle , String chartTitle ) { super(applicationTitle); JFreeChart lineChart = ChartFactory.createXYLineChart( chartTitle, "Time","Temperature", createDataset1(), PlotOrientation.VERTICAL, true,true,false); ChartPanel chartPanel = new ChartPanel( lineChart ); chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) ); setContentPane( chartPanel ); pack(); setVisible(true); boolean Dataset1 = true; while(true) { try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } if(Dataset1) { lineChart.getXYPlot().setDataset(createDataset2()); Dataset1 = false; } else { lineChart.getXYPlot().setDataset(createDataset1()); Dataset1 = true; } } } private XYDataset createDataset1( ) { XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries Temperature = new XYSeries("Temperature"); Temperature.add( 15 , 1 ); Temperature.add( 30 , 2 ); Temperature.add( 60 , 3 ); Temperature.add( 120 , 4 ); Temperature.add( 200 , 5 ); dataset.addSeries(Temperature); return dataset; } private XYDataset createDataset2( ) { XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries Temperature = new XYSeries("Temperature"); Temperature.add( 0 , 1 ); Temperature.add( 30 , 2 ); Temperature.add( 60 , 3 ); Temperature.add( 90 , 4 ); Temperature.add( 120 , 5 ); dataset.addSeries(Temperature); return dataset; } public static void main( String[ ] args ) { MyLineChart chart = new MyLineChart( "School Vs Years" , "Numer of Schools vs years"); // chart.pack( ); // RefineryUtilities.centerFrameOnScreen( chart ); // chart.setVisible( true ); } }
ba4783332807efd73ec0985672b158fee21413d4
0c4e08d41ef6e6fdf6be2fc739f9fc2735e35308
/gae/pis/src/com/pis/controllers/UserController.java
5d43af4b75c508f3cabb5b7f5e2e6b091d1e0f4c
[]
no_license
daixufeng/pis4me
455bffba2fa8ae8a8919c9569350d0dcbc3b2783
d463f39f1e52428e8e30a2a0ed1af0d522c26b0c
refs/heads/master
2021-01-10T12:43:41.044113
2019-06-14T02:15:04
2019-06-14T02:15:04
48,839,697
0
1
null
null
null
null
UTF-8
Java
false
false
7,330
java
package com.pis.controllers; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.google.appengine.api.datastore.Entity; import com.pis.domain.EntityFactory; import com.pis.domain.MyEntities; import com.pis.domain.MyEntity; import com.pis.domain.Page; import com.pis.domain.ViewPager; import com.pis.service.CategoryService; import com.pis.service.DictionaryService; import com.pis.service.UserService; @Controller public class UserController { private UserService userService; public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } private CategoryService categoryService; public CategoryService getCategoryService() { return categoryService; } public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } private DictionaryService dictionaryService; public DictionaryService dictionaryService() { return dictionaryService; } public void setDictionaryService(DictionaryService dictionaryService) { this.dictionaryService = dictionaryService; } @RequestMapping(value = "/user", method = RequestMethod.GET) public ModelAndView user(HttpServletRequest request, Model model) { return search(1, request, model); } @RequestMapping(value = "/dologin", method = RequestMethod.POST) public String dologin(HttpServletRequest request) { String userName = request.getParameter("username").trim(); String password = request.getParameter("password").trim(); Map<String, Object> user = userService.getUserByName(userName); if (user != null && user.get("password").equals(password)) { request.getSession().setAttribute("PIS_LOGON_USER", user); return "redirect:/login"; } else return "index"; } @RequestMapping(value = "/user/changepasword", method = RequestMethod.GET) public String changePassword() { return "account/changepasword"; } @RequestMapping(value = "/user/index/{index}", method = RequestMethod.GET) public ModelAndView search(@PathVariable int index, HttpServletRequest request, Model model) { int pageSize = 15; Map<String, Object> params = EntityFactory.getCriteriaFromRequest( request, MyEntities.User.class); Map<String, Object> filterMap = new HashMap<String, Object>(); Map<String, Object> likeMap = new HashMap<String, Object>(); Map<String, Object> sortMap = new HashMap<String, Object>(); if (params.get("username") != null && params.get("username") != "") filterMap.put("UserName", params.get("username")); if (params.get("email") != null && params.get("email") != "") filterMap.put("Email", params.get("email")); if (params.get("categoryid") != null && params.get("categoryid") != "") filterMap.put("CategoryId", params.get("categoryid")); Page page = userService.getPageData(index, pageSize, filterMap, likeMap, sortMap); List<Map<String, Object>> categories = getCategories(); ViewPager pager = new ViewPager("/user/index", index, pageSize, page.count, params); model.addAttribute("users", page.data); model.addAttribute("pager", pager.render()); model.addAttribute("criteria", filterMap); model.addAttribute("categories", categories); return new ModelAndView("user/index", "model", model); } @RequestMapping(value = "/user/add", method = RequestMethod.GET) public ModelAndView add(Model model) { List<Map<String, Object>> categories = getCategories(); model.addAttribute("categories", categories); model.addAttribute("action", "/user/save"); model.addAttribute("title", "User Add"); return new ModelAndView("user/edit", "model", model); } @RequestMapping(value = "/user/edit/{userId}", method = RequestMethod.GET) public ModelAndView edit(@PathVariable Long userId, Model model) { List<Map<String, Object>> categories = getCategories(); if(!model.containsAttribute("user")){ Map<String, Object> user = userService.getById(userId); model.addAttribute("user", user); } model.addAttribute("categories", categories); model.addAttribute("action", "/user/update"); model.addAttribute("title", "User Edit"); return new ModelAndView("user/edit", "model", model); } @RequestMapping(value = "/user/update", method = RequestMethod.POST) public ModelAndView update(HttpServletRequest request, Model model) { MyEntity result = EntityFactory.getEntityFormRequest(request, MyEntities.User.class); //if do validation is failure. if (!result.validation) { model.addAttribute("messages", result.messages); return add(model); } Entity user = result.entity; //set the entity's category setCategoryName(user); try { userService.update(user); model.addAttribute("success", true); model.addAttribute("message", "保存成功!"); } catch (Exception ex) { model.addAttribute("success", false); model.addAttribute("message", "保存失败!"); } // model.addAttribute("user",EntityFactory.entityToMap(user)); Long userId = Long.parseLong(user.getProperty("Id").toString()); return edit(userId, model); } @RequestMapping(value = "/user/save", method = RequestMethod.POST) public ModelAndView save(HttpServletRequest request, Model model) { MyEntity result = EntityFactory.getEntityFormRequest(request, MyEntities.User.class); Entity user = result.entity; if (!result.validation) { model.addAttribute("messages", result.messages); model.addAttribute("user", EntityFactory.entityToMap(user)); return add(model); } else { setCategoryName(user); try { userService.create(user); model.addAttribute("success", true); model.addAttribute("message", "保存成功!"); Long userId = user.getKey().getId(); model.addAttribute("user", EntityFactory.entityToMap(user)); return edit(userId, model); } catch (Exception ex) { model.addAttribute("success", false); model.addAttribute("message", "保存失败!"); model.addAttribute("user", EntityFactory.entityToMap(user)); return add(model); } } } @RequestMapping(value = "/user/delete", method = RequestMethod.POST) public String delete(HttpServletRequest request) { return "redirect:/user/index/1"; } private List<Map<String, Object>> getCategories() { Map<String, Object> item = dictionaryService.getByTypeAndValue( "Category", "User"); List<Map<String, Object>> categories = this.categoryService .getByType(Long.parseLong(item.get("Id").toString())); return categories; } private void setCategoryName(Entity user) { Long categoryId = Long.parseLong(user.getProperty("CategoryId") .toString()); Object value = categoryService.getById(categoryId).get("Name"); user.setProperty("CategoryName", value); } }
80e3b0093da061f3377869a6ceb84a3c3374b909
bdbb884b92db7939eaae415f99eb83bd6ed72b54
/src/day12_switch_ternary/CalculatorV02.java
c0d4c00cd6d993108ba5ab293fc4c351040ffd20
[]
no_license
XeniyaFesenko/JavaProgramming_Spring2019
b31bd4c509b6a95be4c1ff31b69656b970b1bdbb
ba561aac4c808f0b3988fa1ca6474448378f024b
refs/heads/master
2020-05-29T18:47:31.708932
2019-05-29T22:39:12
2019-05-29T22:39:12
189,308,467
0
0
null
null
null
null
UTF-8
Java
false
false
868
java
package day12_switch_ternary; import java.util.Scanner; public class CalculatorV02 { public static void main(String[] args) { Scanner murodil = new Scanner(System.in); double num1, num2, result; String operator; System.out.println("Enter first number"); num1 = murodil.nextDouble(); System.out.println("Enter second number"); num2 = murodil.nextDouble(); System.out.println("Select operator: \"+\", \"-\", \"*\", \"/\""); operator = murodil.next(); murodil.close(); switch (operator) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": result = num1 / num2; break; case "%": result = num1 % num2; break; default: System.out.println("Invalid operator"); return; } System.out.println("Result " + result); } }
0be1d38ba0003e42419c1112cd0db4c0b546c46e
64afe984458a2cb1a8f0c7939d6aaf41f760adbe
/DesignPattern/src/com/demo/multithreading/ThreadYieldMain.java
e242cde6b918c9ac83af05b7c30ffe00a246af14
[]
no_license
zhangrq1983/ideaProjects
3157a390c476afe891d9ddc6c77774d7c2435062
4c6263a8d8351bf0cfdaf1b8edd4c9443408ee62
refs/heads/master
2023-01-07T13:09:21.953732
2020-07-27T02:48:29
2020-07-27T02:48:29
247,912,000
0
0
null
2022-12-16T03:32:34
2020-03-17T08:03:35
CSS
UTF-8
Java
false
false
266
java
package com.demo.multithreading; public class ThreadYieldMain { public static void main(String[] args) { ThreadYield yt1 = new ThreadYield("张三"); ThreadYield yt2 = new ThreadYield("李四"); yt1.start(); yt2.start(); } }
07809855d06387c11c1b903255ff1ad8b1f5ea2d
693f3c6892f82174799a430842549ccf4236dd01
/src/sortInterface/Mansion.java
51e3961af9bd87cca65bf3a98b4d8c9454a292f0
[]
no_license
yudurrani/java-problems
9ab31fa2494681fcbb9cbd9fd620736d5d6a64b6
ad581ef5eba1da050e793c9b30bc99273649c5e4
refs/heads/master
2020-04-14T15:27:13.127385
2020-01-21T00:47:22
2020-01-21T00:47:22
163,927,258
0
0
null
null
null
null
UTF-8
Java
false
false
1,395
java
package sortInterface; import java.util.HashMap; public class Mansion implements HouseInterface{ Room[] rooms; HashMap<String, Person> persons; String location; public Mansion(String location) { rooms = new Room[15]; for(int i =0 ;i < rooms.length; i++) { rooms[i] = new Room(200, 200, 10, 1, "Marble"); } persons = new HashMap<String, Person>(); this.location = location; } @Override public int totalRooms() { // TODO Auto-generated method stub return rooms.length; } @Override public double getArea() { int totalArea=0; for(int x=0; x<rooms.length; x++) { totalArea += rooms[x].getRoomSize(); } return totalArea; } @Override public int noOfPeople() { // TODO Auto-generated method stub return persons.size(); } @Override public void walkIn(Person value) { // TODO Auto-generated method stub persons.put( value.name, value ); } @Override public void walkOut(String name) { // TODO Auto-generated method stub persons.remove(name); } @Override public boolean hasGarden() { // TODO Auto-generated method stub return true; } @Override public int hasParking() { // TODO Auto-generated method stub return 10; } @Override public String getLocation() { // TODO Auto-generated method stub return location; } }
cbd253df0d775dfc90789a29c9c7f2753d7f325b
805189b7584dbe61cc97cc81e15f59dbc37aa01e
/src/main/java/com/pretius/currencyexchange/demo/cache/NBPCache.java
fd18672977f95e2655a873f907c2bf4f430ff699
[]
no_license
kbogusze/pretius
5e44acc2a648115af06e4e3bb50ce64f0a0eeef0
59ffc53ab6c849be3cfce1fcd25dd2ed98c6bd58
refs/heads/master
2020-04-24T09:40:03.765755
2019-02-21T13:04:03
2019-02-21T13:04:03
171,869,377
0
0
null
null
null
null
UTF-8
Java
false
false
2,681
java
/* * 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 com.pretius.currencyexchange.demo.cache; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.pretius.currencyexchange.demo.models.CurrencyRate; import com.pretius.currencyexchange.demo.models.IncomingRates; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; /** * * @author Krzysztof Boguszewski */ public class NBPCache { private static NBPCache instance; private IncomingRates tableA; public NBPCache() { this.tableA = new IncomingRates(); } private static NBPCache getInstance() { if(instance == null) { instance = new NBPCache(); initCache(instance); } return instance; } private static synchronized void initCache (NBPCache instance){ try { RestTemplate restTemplate = new RestTemplate(); String uri = "http://api.nbp.pl/api/exchangerates/tables/a?format=json"; ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, null,String.class); ObjectMapper mapper = new ObjectMapper(); List<IncomingRates> list = mapper.readValue(response.getBody(), TypeFactory.defaultInstance().constructCollectionLikeType(List.class, IncomingRates.class)); if (list.size() > 0) instance.setTableA(list.get(0)); } catch (IOException ex) { Logger.getLogger(NBPCache.class.getName()).log(Level.SEVERE, null, ex); } } private void setTableA(IncomingRates tableA) { this.tableA = tableA; } public static synchronized Optional<CurrencyRate> findByCurrency(String currency) { return getInstance().tableA.getRates().stream().filter(p ->p.getCurrency()!=null && p.getCurrency().toUpperCase().equals(currency.toUpperCase())).findAny(); } public static synchronized Optional<CurrencyRate> findByCode(String code) { return getInstance().tableA.getRates().stream().filter(p ->p.getCode()!=null && p.getCode().toUpperCase().equals(code.toUpperCase())).findAny(); } }
343b1cb4b60a6db16d12e219ca717c25c793c2cd
37aacd31e867407effa37731efbdb3290b37e883
/nhom1201/src/DAO/kiemTraTungCauHoiDAO.java
e78fa0a7d92479e14cec03fae0c59832fed239fc
[]
no_license
dominhhau/nhom012
09eedde2da4b50bc4d4a841e588e3b10fc34298d
f655880b35a906d5a184d9da353b73a2f1d3953a
refs/heads/master
2021-09-02T07:21:30.952218
2017-12-31T11:49:29
2017-12-31T11:49:29
115,858,447
0
0
null
null
null
null
UTF-8
Java
false
false
2,720
java
package DAO; import java.io.IOException; import java.lang.reflect.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Vector; 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 com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import com.sun.org.apache.xpath.internal.operations.Bool; import connect.DBConnect; import model.Cauhoi; @WebServlet("/kiemTraTungCauHoiDAO") public class kiemTraTungCauHoiDAO extends HttpServlet { private static final long serialVersionUID = 1L; String soCauHoi=""; String Thoigian_Thi=""; public kiemTraTungCauHoiDAO() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int Thoigian = Integer.parseInt(request.getParameter("Thoigian_Thi")); int SoCauHoi = Integer.parseInt(request.getParameter("soCauHoi")); Connection c = DBConnect.getConnection(); ArrayList<Cauhoi> entries = new ArrayList<Cauhoi>(SoCauHoi); ArrayList<Integer> check = new ArrayList<Integer>(SoCauHoi); try { Random rd = new Random(); int iNew = 0; for (int i = 0; i < SoCauHoi; i++) { iNew = rd.nextInt(SoCauHoi); while (check.contains(iNew)) { iNew = rd.nextInt(SoCauHoi); } check.add(iNew); Statement stmt = (Statement) c.createStatement(); ResultSet rs = stmt.executeQuery("select * from cauhoi where cauhoi.index=" + (iNew + 1)); while (rs.next()) { Cauhoi entry = new Cauhoi(rs.getInt("index"), rs.getString("noidung"), rs.getString("QA"), rs.getString("QB"), rs.getString("QC"), rs.getString("QD"), rs.getString("dapan")); entries.add(entry); } } } catch ( SQLException e) { throw new ServletException(e); } finally { try { if (c != null) c.close(); } catch (SQLException e) { throw new ServletException(e); } } request.getServletContext().setAttribute("Thoigian_Thi", Thoigian); request.getServletContext().setAttribute("SoCauHoi", SoCauHoi); request.getServletContext().setAttribute("entries", entries); //request.setAttribute("entries", entries); request.getRequestDispatcher("/kiemTraTungCau.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
[ "Do Hau@MinhHauDo" ]
Do Hau@MinhHauDo
86b89925660c38f967ada6885904762e9994158e
d75b8208c64c48bbfffb829eae2a834a9e6e6f3d
/android/app/src/main/java/com/rummikub/MainApplication.java
a71bae0970625bd6965ae70d3db72501aa65e93c
[]
no_license
ventinus/RN-Rummikub
ced987d43291f3b70f0002277d4edc61652e850b
4ad95843b68b5052d0cfbc6cc656320dde43cbba
refs/heads/master
2021-01-20T14:58:42.981071
2017-05-09T03:10:11
2017-05-09T03:10:11
90,696,854
0
0
null
null
null
null
UTF-8
Java
false
false
1,049
java
package com.rummikub; import android.app.Application; import com.facebook.react.ReactApplication; import com.BV.LinearGradient.LinearGradientPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new LinearGradientPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
54d4b215aa2eb28dc5209f9b893a47fbd615b38e
0b94b0cf65c058d89cf94dc0ef3d085847c5df79
/Diccionario/src/Main.java
bb807673447c7447c16cfc08de36f57c8ef52ef3
[]
no_license
Jibun/deep-mt
23f8d5f18836e7f57e097c2bb7c7cddaac21029d
730c730045286c7f812cf0b3eda33a9b8f7d9e01
refs/heads/master
2016-09-06T11:06:30.581437
2015-05-20T14:57:48
2015-05-20T14:57:48
35,901,795
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
11,411
java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /** * @param args * @throws FileNotFoundException * @throws UnsupportedEncodingException */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub /* * Lista de palabras en ingles y su traduccion al espanol dependiendo de su morfologia */ InputStreamReader dic = new InputStreamReader(new FileInputStream("assets/wiktionary.en-es"), "UTF8"); BufferedReader br = new BufferedReader(dic); String s; int i = 0; HashMap<String, HashMap<String, ArrayList<String>>> hs = new HashMap<String, HashMap<String, ArrayList<String>>>(); while ((s = br.readLine()) != null) { String[] wordDetails = s.split(" \\|\\|\\| "); if(wordDetails != null && wordDetails.length == 2){ if(!hs.containsKey(wordDetails[0].trim())){ HashMap<String, ArrayList<String>> tagLema = new HashMap<String, ArrayList<String>>(); ArrayList<String> lemas = new ArrayList<String>(); lemas.add(wordDetails[1].trim()); tagLema.put("unknown", lemas); hs.put(wordDetails[0].trim(), tagLema); }else{ HashMap<String, ArrayList<String>> tag = hs.get(wordDetails[0].trim()); ArrayList<String> containedIn = new ArrayList<String>(); for (Map.Entry<String, ArrayList<String>> entry : tag.entrySet()) { String key = entry.getKey(); ArrayList<String> spanishLemas = entry.getValue(); if(spanishLemas.contains(wordDetails[1].trim())){ containedIn.add(key); } } if(containedIn.size() == 0){ if(tag.containsKey("unknown")){ ArrayList<String> lemas = tag.get("unknown"); lemas.add(wordDetails[1].trim()); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(wordDetails[1].trim()); tag.put("unknown", lemas); } }else{ if(!containedIn.contains("unknown")){ if(tag.containsKey("unknown")){ ArrayList<String> lemas = tag.get("unknown"); lemas.add(wordDetails[1].trim()); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(wordDetails[1].trim()); tag.put("unknown", lemas); } } } } i++; } } dic.close(); InputStreamReader dic1 = new InputStreamReader(new FileInputStream("assets/dic-raw1.txt"), "UTF8"); BufferedReader br2 = new BufferedReader(dic1); i = 0; while ((s = br2.readLine()) != null) { String[] wordDetails = s.split("\t"); if(wordDetails != null && wordDetails.length >= 2){ String[] wordsPerDefinition = wordDetails[0].toLowerCase().split(" "); if(wordsPerDefinition.length == 1){ String reconstructedCorrespondances = wordDetails[1].replaceAll("\\(.+?\\)", ""); String[] correspondances = reconstructedCorrespondances.split("; "); if(correspondances.length == 1) correspondances = reconstructedCorrespondances.split(", "); if(!hs.containsKey(wordDetails[0].toLowerCase())){ HashMap<String, ArrayList<String>> tagLema = new HashMap<String, ArrayList<String>>(); ArrayList<String> lemas = new ArrayList<String>(); for(String c1 : correspondances){ lemas.add(c1.trim()); } tagLema.put("unknown", lemas); hs.put(wordDetails[0].toLowerCase(), tagLema); i++; }else{ HashMap<String, ArrayList<String>> tag = hs.get(wordDetails[0].toLowerCase()); for(String c1 : correspondances){ ArrayList<String> containedIn = new ArrayList<String>(); for (Map.Entry<String, ArrayList<String>> entry : tag.entrySet()) { String key = entry.getKey(); ArrayList<String> spanishLemas = entry.getValue(); if(spanishLemas.contains(c1.trim())){ containedIn.add(key); } } if(containedIn.size() == 0){ if(tag.containsKey("unknown")){ ArrayList<String> lemas = tag.get("unknown"); lemas.add(c1.trim()); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(c1.trim()); tag.put("unknown", lemas); } }else{ if(!containedIn.contains("unknown")){ if(tag.containsKey("unknown")){ ArrayList<String> lemas = tag.get("unknown"); lemas.add(c1.trim()); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(c1.trim()); tag.put("unknown", lemas); } } } } } } } } dic1.close(); InputStreamReader dic3 = new InputStreamReader(new FileInputStream("assets/en_es_all.txt"), "UTF8"); BufferedReader br4 = new BufferedReader(dic3); i = 0; while ((s = br4.readLine()) != null) { String[] wordDetails = s.split("\t"); if(wordDetails != null && wordDetails.length == 3){ wordDetails[0] = wordDetails[0].toLowerCase().trim(); wordDetails[2] = wordDetails[2].toLowerCase().trim(); if(!hs.containsKey(wordDetails[0])){ HashMap<String, ArrayList<String>> tagLema = new HashMap<String, ArrayList<String>>(); ArrayList<String> lemas = new ArrayList<String>(); lemas.add(wordDetails[2]); tagLema.put(wordDetails[1], lemas); hs.put(wordDetails[0], tagLema); }else{ HashMap<String, ArrayList<String>> tag = hs.get(wordDetails[0]); ArrayList<String> containedIn = new ArrayList<String>(); for (Map.Entry<String, ArrayList<String>> entry : tag.entrySet()) { String key = entry.getKey(); ArrayList<String> spanishLemas = entry.getValue(); if(spanishLemas.contains(wordDetails[2])){ containedIn.add(key); } } if(containedIn.size()==0){ if(tag.containsKey(wordDetails[1])){ ArrayList<String> lemas = tag.get(wordDetails[1]); lemas.add(wordDetails[2]); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(wordDetails[2]); tag.put(wordDetails[1], lemas); } }else{ if(!containedIn.contains(wordDetails[1])){ if(tag.containsKey(wordDetails[1])){ ArrayList<String> lemas = tag.get(wordDetails[1]); lemas.add(wordDetails[2]); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(wordDetails[2]); tag.put(wordDetails[1], lemas); } } } } } } dic3.close(); InputStreamReader dic2 = new InputStreamReader(new FileInputStream("assets/dic-raw2revised.txt"), "UTF8"); BufferedReader br3 = new BufferedReader(dic2); //BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("assets/dic-raw2revised.txt"), "UTF-8")); i = 0; while ((s = br3.readLine()) != null) { // s = s.replaceAll("a/", "á"); // s = s.replaceAll("e/", "é"); // s = s.replaceAll("i/", "í"); // s = s.replaceAll("o/", "ó"); // s = s.replaceAll("u/", "ú"); // s = s.replaceAll("n~", "ñ"); // s = s.replaceAll(",-a", ""); // s = s.replaceAll("adj\\.", "[adjective]"); // s = s.replaceAll("\\(v\\)", "[verb]"); // s = s.replaceAll("\\(n\\)", "[noun]"); // s = s.replaceAll("\\(.+?\\)", ""); // s = s.replaceAll("/", ";"); // s = s.replaceAll("\tel ", "\t"); // s = s.replaceAll("\tla ", "\t"); // s = s.replaceAll("\tlos ", "\t"); // s = s.replaceAll("\tlas ", "\t"); // out.write(s + "\n"); String[] wordDetails = s.split("\t"); if(wordDetails != null && wordDetails.length >= 2){ wordDetails[0] = wordDetails[0].toLowerCase().trim(); String[] wordsPerDefinition = wordDetails[0].split(" "); if(wordsPerDefinition.length == 1){ wordDetails[1] = wordDetails[1].toLowerCase().trim(); String[] correspondances = wordDetails[1].split("; "); if(correspondances.length == 1) correspondances = wordDetails[1].split(", "); String type = "unknown"; for(int j = 0; j < correspondances.length; j++){ Matcher m = Pattern.compile("\\[([^\\[]+)\\]").matcher(correspondances[j]); if(m.find()) { type = m.group(1); if(type.equals("article")){ type = "det"; }else if(type.equals("adverb")){ type = "adv"; }else if(type.equals("noun")){ type = "n"; }else if(type.equals("adjective")){ type = "adj"; }else if(type.equals("verb")){ type = "v"; }else if(type.equals("preposition")){ type = "prep"; }else if(type.equals("conjunction")){ type = "conj"; }else if(type.equals("pronoun")){ type = "pron"; } correspondances[j] = m.replaceAll(""); } } if(!hs.containsKey(wordDetails[0])){ HashMap<String, ArrayList<String>> tagLema = new HashMap<String, ArrayList<String>>(); ArrayList<String> lemas = new ArrayList<String>(); for(String c1 : correspondances){ lemas.add(c1.trim()); } tagLema.put(type, lemas); hs.put(wordDetails[0], tagLema); i++; }else{ HashMap<String, ArrayList<String>> tag = hs.get(wordDetails[0]); for(String c1 : correspondances){ ArrayList<String> containedIn = new ArrayList<String>(); for (Map.Entry<String, ArrayList<String>> entry : tag.entrySet()) { String key = entry.getKey(); ArrayList<String> spanishLemas = entry.getValue(); if(spanishLemas.contains(c1.trim())){ containedIn.add(key); } } if(containedIn.size()==0){ if(tag.containsKey(type)){ ArrayList<String> lemas = tag.get(type); lemas.add(c1.trim()); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(c1.trim()); tag.put(type, lemas); } }else{ if(!containedIn.contains(type)){ if(tag.containsKey(type)){ ArrayList<String> lemas = tag.get(type); lemas.add(c1.trim()); }else{ ArrayList<String> lemas = new ArrayList<String>(); lemas.add(c1.trim()); tag.put(type, lemas); } } } } } } } } dic2.close(); //out.close(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("assets/dic-full-en-es.txt"), "UTF-8")); SortedSet<String> engWords = new TreeSet<String>(hs.keySet()); for (String engWord : engWords) { HashMap<String,ArrayList<String>> TagsPlusEsp = hs.get(engWord); SortedSet<String> tags = new TreeSet<String>(TagsPlusEsp.keySet()); for (String tag : tags) { ArrayList<String> spaWords = TagsPlusEsp.get(tag); Collections.sort(spaWords); for(String spaWord: spaWords){ out.write(engWord + "\t" + tag + "\t" + spaWord + "\n"); } } } out.close(); } }
eae4a07bd98cce5f6f193ada3c0a10b052d9cf1d
56bd998eb4bcc151885e40c0917744aaf5273752
/src/test/java/org/prebid/server/bidder/alkimi/AlkimiBidderTest.java
41c3df7ff632bda96971bf3965193b67e1c5bb12
[ "Apache-2.0" ]
permissive
adpushup/prebid-server-java
b808923864f487f4497b5985aeef15ce8f813465
f1ef567d30f02078f0b252ae313566520162997b
refs/heads/master
2022-12-11T06:48:27.454781
2022-10-05T10:45:22
2022-10-05T10:45:22
251,230,769
0
2
Apache-2.0
2022-10-27T05:11:16
2020-03-30T07:20:50
Java
UTF-8
Java
false
false
11,233
java
package org.prebid.server.bidder.alkimi; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.ObjectNode; import com.iab.openrtb.request.Banner; import com.iab.openrtb.request.BidRequest; import com.iab.openrtb.request.Format; import com.iab.openrtb.request.Imp; import com.iab.openrtb.request.Video; import com.iab.openrtb.response.Bid; import com.iab.openrtb.response.BidResponse; import com.iab.openrtb.response.SeatBid; import org.junit.Before; import org.junit.Test; import org.prebid.server.VertxTest; import org.prebid.server.bidder.model.BidderBid; import org.prebid.server.bidder.model.BidderCall; import org.prebid.server.bidder.model.BidderError; import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; import org.prebid.server.proto.openrtb.ext.ExtPrebid; import org.prebid.server.proto.openrtb.ext.request.alkimi.ExtImpAlkimi; import java.math.BigDecimal; import java.util.Collections; import java.util.List; import java.util.function.Function; import static java.util.Collections.singletonList; import static java.util.function.Function.identity; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.prebid.server.proto.openrtb.ext.response.BidType.banner; import static org.prebid.server.proto.openrtb.ext.response.BidType.video; public class AlkimiBidderTest extends VertxTest { private static final String ENDPOINT_URL = "https://exchange.alkimi-onboarding.com/server/bid"; private static final String DIV_BANNER_ID = "div_banner_1"; private static final String DIV_VIDEO_ID = "div_video_1"; private static final String PUB_TOKEN = "testPubToken"; private static final String TYPE_BANNER = "Banner"; private static final String TYPE_VIDEO = "Video"; private AlkimiBidder alkimiBidder; @Before public void setUp() { alkimiBidder = new AlkimiBidder(ENDPOINT_URL, jacksonMapper); } @Test public void creationShouldFailOnInvalidEndpointUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new AlkimiBidder("invalid_url", jacksonMapper)); } @Test public void makeHttpRequestsShouldUseCorrectURL() { final BidRequest bidRequest = givenBidRequest(impBuilder -> impBuilder.banner(Banner.builder().build())); final Result<List<HttpRequest<BidRequest>>> result = alkimiBidder.makeHttpRequests(bidRequest); assertThat(result.getErrors()).isEmpty(); assertThat(result.getValue()) .extracting(HttpRequest::getUri) .containsExactly(ENDPOINT_URL); } @Test public void makeHttpRequestsShouldUpdateImps() { final BidRequest bidRequest = givenBidRequest(); final Result<List<HttpRequest<BidRequest>>> result = alkimiBidder.makeHttpRequests(bidRequest); final BidRequest expectedBidRequest = BidRequest.builder() .imp(List.of(Imp.builder() .id(DIV_BANNER_ID) .bidfloor(BigDecimal.valueOf(0.2)) .banner(expectedBanner()) .ext(expectedBannerExt()) .build(), Imp.builder() .id(DIV_VIDEO_ID) .bidfloor(BigDecimal.valueOf(0.3)) .video(expectedVideo()) .ext(expectedVideoExt()) .build()) ).build(); assertThat(result.getValue()) .extracting(HttpRequest::getPayload) .containsExactly(expectedBidRequest); } private Banner expectedBanner() { return Banner.builder() .pos(5) .w(300) .h(250) .format(Collections.singletonList(Format.builder() .w(300) .h(250) .build()) ).build(); } private ObjectNode expectedBannerExt() { return mapper.valueToTree(ExtPrebid.of( null, ExtImpAlkimi.builder() .token(PUB_TOKEN) .bidFloor(BigDecimal.valueOf(0.2)) .pos(5) .width(300) .height(250) .impMediaType(TYPE_BANNER) .build())); } private Video expectedVideo() { return Video.builder() .pos(7) .w(1024) .h(768) .mimes(List.of("video/mp4")) .protocols(List.of(1, 2, 3, 4, 5)) .build(); } private ObjectNode expectedVideoExt() { return mapper.valueToTree(ExtPrebid.of( null, ExtImpAlkimi.builder() .token(PUB_TOKEN) .bidFloor(BigDecimal.valueOf(0.3)) .pos(7) .width(1024) .height(768) .impMediaType(TYPE_VIDEO) .build())); } @Test public void makeBidsShouldReturnErrorIfResponseBodyCouldNotBeParsed() { final BidderCall<BidRequest> httpCall = givenHttpCall(null, "invalid"); final Result<List<BidderBid>> result = alkimiBidder.makeBids(httpCall, null); assertThat(result.getErrors()) .hasSize(1) .allMatch(error -> error.getType() == BidderError.Type.bad_server_response && error.getMessage().startsWith("Failed to decode: Unrecognized token")); assertThat(result.getValue()).isEmpty(); } @Test public void makeBidsShouldReturnEmptyListIfBidResponseIsNull() throws JsonProcessingException { final BidderCall<BidRequest> httpCall = givenHttpCall(null, mapper.writeValueAsString(null)); final Result<List<BidderBid>> result = alkimiBidder.makeBids(httpCall, null); assertThat(result.getErrors()).isEmpty(); assertThat(result.getValue()).isEmpty(); } @Test public void makeBidsShouldReturnEmptyListIfBidResponseSeatBidIsNull() throws JsonProcessingException { final BidderCall<BidRequest> httpCall = givenHttpCall( null, mapper.writeValueAsString(BidResponse.builder().build())); final Result<List<BidderBid>> result = alkimiBidder.makeBids(httpCall, null); assertThat(result.getErrors()).isEmpty(); assertThat(result.getValue()).isEmpty(); } @Test public void makeBidsShouldReturnBidsForBannerAndVideoImps() throws JsonProcessingException { final BidderCall<BidRequest> httpCall = givenHttpCall( givenBidRequest(), mapper.writeValueAsString(givenBidResponse())); final Result<List<BidderBid>> result = alkimiBidder.makeBids(httpCall, null); assertThat(result.getErrors()).isEmpty(); assertThat(result.getValue()).contains(BidderBid.of(givenBannerBid(identity()), banner, null)); assertThat(result.getValue()).contains(BidderBid.of(givenVideoBid(identity()), video, null)); } private static BidRequest givenBidRequest() { return givenBidRequest(identity()); } private static BidRequest givenBidRequest(Function<Imp.ImpBuilder, Imp.ImpBuilder> impCustomizer) { return givenBidRequest(identity(), impCustomizer); } private static BidRequest givenBidRequest( Function<BidRequest.BidRequestBuilder, BidRequest.BidRequestBuilder> bidRequestCustomizer, Function<Imp.ImpBuilder, Imp.ImpBuilder> impCustomizer ) { return bidRequestCustomizer.apply(BidRequest.builder() .imp(List.of(givenBannerImp(impCustomizer), givenVideoImp(impCustomizer))) ).build(); } private static Imp givenBannerImp(Function<Imp.ImpBuilder, Imp.ImpBuilder> impCustomizer) { return impCustomizer.apply(Imp.builder() .id(DIV_BANNER_ID) .banner(Banner.builder() .format(Collections.singletonList(Format.builder() .w(300) .h(250) .build()) ).build()) .ext(mapper.valueToTree(ExtPrebid.of( null, ExtImpAlkimi.builder() .token(PUB_TOKEN) .bidFloor(BigDecimal.valueOf(0.2)) .pos(5) .build()))) ).build(); } private static Imp givenVideoImp(Function<Imp.ImpBuilder, Imp.ImpBuilder> impCustomizer) { return impCustomizer.apply(Imp.builder() .id(DIV_VIDEO_ID) .video(Video.builder() .w(1024) .h(768) .mimes(List.of("video/mp4")) .protocols(List.of(1, 2, 3, 4, 5)) .build()) .ext(mapper.valueToTree(ExtPrebid.of( null, ExtImpAlkimi.builder() .token(PUB_TOKEN) .bidFloor(BigDecimal.valueOf(0.3)) .pos(7) .build()))) ).build(); } private static BidResponse givenBidResponse() { return givenBidResponse(identity()); } private static BidResponse givenBidResponse(Function<Bid.BidBuilder, Bid.BidBuilder> bidCustomizer) { return givenBidResponse(identity(), bidCustomizer); } private static BidResponse givenBidResponse( Function<BidResponse.BidResponseBuilder, BidResponse.BidResponseBuilder> bidResponseCustomizer, Function<Bid.BidBuilder, Bid.BidBuilder> bidCustomizer ) { return bidResponseCustomizer.apply(BidResponse.builder() .seatbid(singletonList(SeatBid.builder().bid(List.of( givenBannerBid(bidCustomizer), givenVideoBid(bidCustomizer)) ).build())) ).build(); } private static Bid givenBannerBid(Function<Bid.BidBuilder, Bid.BidBuilder> bidCustomizer) { return bidCustomizer.apply(Bid.builder() .impid(DIV_BANNER_ID) ).build(); } private static Bid givenVideoBid(Function<Bid.BidBuilder, Bid.BidBuilder> bidCustomizer) { return bidCustomizer.apply(Bid.builder() .impid(DIV_VIDEO_ID) ).build(); } private static BidderCall<BidRequest> givenHttpCall(BidRequest bidRequest, String body) { return BidderCall.succeededHttp( HttpRequest.<BidRequest>builder().payload(bidRequest).build(), HttpResponse.of(200, null, body), null); } }
95991b85d800b9cb598ac68e90bbcd650d49dcb3
6ebdb8191d797246b22bec5cf877ce5fa70ad665
/springboot-servicio-zuul-server/src/main/java/com/formacionbdi/springboot/app/zuul/filters/PostTiempoTranscurridoFilter.java
4079e1d6b83459ab7b343333d6ead84af250b69d
[]
no_license
bpilegi98/Microservicios
41b6bc25d57798288b64fed1e84983e70589191a
faf9b780e9f959ae8453c2e2fed901fcb768eeba
refs/heads/main
2023-03-12T12:41:50.753819
2021-03-06T15:24:10
2021-03-06T15:24:10
342,016,318
0
0
null
null
null
null
UTF-8
Java
false
false
1,403
java
package com.formacionbdi.springboot.app.zuul.filters; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; @Component public class PostTiempoTranscurridoFilter extends ZuulFilter{ private static Logger log = LoggerFactory.getLogger(PostTiempoTranscurridoFilter.class); //Metodo que devuelve true o false dependiendo, se utiliza para validar si se ejecuta o no el filtro @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info("Entrando a post filter"); Long tiempoInicio = (Long)request.getAttribute("tiempoInicio"); Long tiempoFinal = System.currentTimeMillis(); Long tiempoTranscurrido = tiempoFinal - tiempoInicio; log.info(String.format("Tiempo transcurrido en segundos %s seg.", tiempoTranscurrido.doubleValue()/1000.0)); log.info(String.format("Tiempo transcurrido en milisegundos %s ms.", tiempoTranscurrido)); return null; } @Override public String filterType() { return "post"; } @Override public int filterOrder() { return 1; } }
d1becc77697022b3f6f4a12a6c114aa6ca50ec52
0b6c332c6d22d2329e89517a2eb99de4b2491677
/sample/src/main/java/com/cysion/videosample/entity/ExpertMapEntity.java
d403cd8bc00d4b7b98ab5fea4bd35924ba7726af
[]
no_license
xiaoweiage/DevBox
9825848cf3961daf5f63f3a1a6c7378a4eb1c3ab
a1be407352cac287f726595a9ad4bb62771dc649
refs/heads/master
2020-04-14T19:54:03.571909
2018-12-02T11:27:41
2018-12-02T11:27:41
164,074,514
1
0
null
2019-01-04T07:36:34
2019-01-04T07:36:34
null
UTF-8
Java
false
false
583
java
package com.cysion.videosample.entity; import java.util.List; import java.util.Map; public class ExpertMapEntity extends BaseEntity { private Map<String,ExpertEntity> data; private List<ExpertEntity> revisedData; public List<ExpertEntity> getRevisedData() { return revisedData; } public void setRevisedData(List<ExpertEntity> aRevisedData) { revisedData = aRevisedData; } public Map<String, ExpertEntity> getData() { return data; } public void setData(Map<String, ExpertEntity> aData) { data = aData; } }
519a6f74186e3cf9d2c601b7bbcadf4e8f384223
828b5327357d0fb4cb8f3b4472f392f3b8b10328
/flink-clients/src/test/java/org/apache/flink/client/cli/CliFrontendStopWithSavepointTest.java
d8a40676cee13bc91c4ba0fda6d3f4ad15091170
[ "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "ISC", "MIT-0", "GPL-2.0-only", "BSD-2-Clause-Views", "OFL-1.1", "Apache-2.0", "LicenseRef-scancode-jdom", "GCC-exception-3.1", "MPL-2.0", "CC-PDDC", "AGPL-3.0-only", "MPL-2.0-no-copyleft-exception", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "BSD-2-Clause", "CDDL-1.1", "CDDL-1.0", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-free-unknown", "CC0-1.0", "Classpath-exception-2.0", "CC-BY-2.5" ]
permissive
Romance-Zhang/flink_tpc_ds_game
7e82d801ebd268d2c41c8e207a994700ed7d28c7
8202f33bed962b35c81c641a05de548cfef6025f
refs/heads/master
2022-11-06T13:24:44.451821
2019-09-27T09:22:29
2019-09-27T09:22:29
211,280,838
0
1
Apache-2.0
2022-10-06T07:11:45
2019-09-27T09:11:11
Java
UTF-8
Java
false
false
7,232
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.client.cli; import org.apache.flink.api.common.JobID; import org.apache.flink.client.cli.util.MockedCliFrontend; import org.apache.flink.client.program.ClusterClient; import org.apache.flink.configuration.Configuration; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.FlinkException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import javax.annotation.Nullable; import java.util.Collections; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.doThrow; /** * Tests for the STOP command. */ public class CliFrontendStopWithSavepointTest extends CliFrontendTestBase { @BeforeClass public static void setup() { CliFrontendTestUtils.pipeSystemOutToNull(); } @AfterClass public static void shutdown() { CliFrontendTestUtils.restoreSystemOut(); } @Test public void testStopWithOnlyJobId() throws Exception { // test stop properly JobID jid = new JobID(); String jidString = jid.toString(); String[] parameters = { jidString }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(false), isNull()); } @Test public void testStopWithDefaultSavepointDir() throws Exception { JobID jid = new JobID(); String[] parameters = {jid.toString() }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(false), isNull()); } @Test public void testStopWithExplicitSavepointDir() throws Exception { JobID jid = new JobID(); String[] parameters = { "-p", "test-target-dir", jid.toString() }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(false), eq("test-target-dir")); } @Test public void testStopOnlyWithMaxWM() throws Exception { JobID jid = new JobID(); String[] parameters = { "-d", jid.toString() }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(true), isNull()); } @Test public void testStopWithMaxWMAndDefaultSavepointDir() throws Exception { JobID jid = new JobID(); String[] parameters = { "-p", "-d", jid.toString() }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(true), isNull()); } @Test public void testStopWithMaxWMAndExplicitSavepointDir() throws Exception { JobID jid = new JobID(); String[] parameters = { "-d", "-p", "test-target-dir", jid.toString() }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(true), eq("test-target-dir")); } @Test(expected = CliArgsException.class) public void testUnrecognizedOption() throws Exception { // test unrecognized option String[] parameters = { "-v", "-l" }; Configuration configuration = getConfiguration(); CliFrontend testFrontend = new CliFrontend( configuration, Collections.singletonList(getCli(configuration))); testFrontend.stop(parameters); } @Test(expected = CliArgsException.class) public void testMissingJobId() throws Exception { // test missing job id String[] parameters = {}; Configuration configuration = getConfiguration(); CliFrontend testFrontend = new CliFrontend( configuration, Collections.singletonList(getCli(configuration))); testFrontend.stop(parameters); } @Test(expected = CliArgsException.class) public void testWrongSavepointDirOrder() throws Exception { JobID jid = new JobID(); String[] parameters = { "-s", "-d", "test-target-dir", jid.toString() }; final ClusterClient<String> clusterClient = createClusterClient(null); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); testFrontend.stop(parameters); Mockito.verify(clusterClient, times(1)) .stopWithSavepoint(eq(jid), eq(false), eq("test-target-dir")); } @Test public void testUnknownJobId() throws Exception { // test unknown job Id JobID jid = new JobID(); String[] parameters = { "-p", "test-target-dir", jid.toString() }; String expectedMessage = "Test exception"; FlinkException testException = new FlinkException(expectedMessage); final ClusterClient<String> clusterClient = createClusterClient(testException); MockedCliFrontend testFrontend = new MockedCliFrontend(clusterClient); try { testFrontend.stop(parameters); fail("Should have failed."); } catch (FlinkException e) { assertTrue(ExceptionUtils.findThrowableWithMessage(e, expectedMessage).isPresent()); } } private static ClusterClient<String> createClusterClient(@Nullable Exception exception) throws Exception { final ClusterClient<String> clusterClient = mock(ClusterClient.class); if (exception != null) { doThrow(exception).when(clusterClient).stopWithSavepoint(any(JobID.class), anyBoolean(), anyString()); } return clusterClient; } }
a1e1279fbe738b046bbcc1b1546e39d0c4800407
c72b2185097a354705b2eb715af39c1f2941003e
/src/test/java/com/todoapp/domain/TaskInstanceTest.java
e3f0aa7fa922505086b27fecfa3db71ad52bbf17
[]
no_license
anurvaibhav1985/todo
b049732367d6968627c85714dc5eaf5a0699e678
2ddb734772d1c9f2016bbbb11b37e69d73a88dc9
refs/heads/master
2023-06-04T07:53:43.910083
2021-06-22T20:01:46
2021-06-22T20:01:46
378,827,310
0
0
null
null
null
null
UTF-8
Java
false
false
757
java
package com.todoapp.domain; import static org.assertj.core.api.Assertions.assertThat; import com.todoapp.web.rest.TestUtil; import org.junit.jupiter.api.Test; class TaskInstanceTest { @Test void equalsVerifier() throws Exception { TestUtil.equalsVerifier(TaskInstance.class); TaskInstance taskInstance1 = new TaskInstance(); taskInstance1.setId(1L); TaskInstance taskInstance2 = new TaskInstance(); taskInstance2.setId(taskInstance1.getId()); assertThat(taskInstance1).isEqualTo(taskInstance2); taskInstance2.setId(2L); assertThat(taskInstance1).isNotEqualTo(taskInstance2); taskInstance1.setId(null); assertThat(taskInstance1).isNotEqualTo(taskInstance2); } }
43f85660ea5d1929073916a8e0fb51f0ae4ec57f
af1e5b8fc25fad38caf98dd739204909d7760adc
/TencentDataServer/weibo/analysis/cc/pp/tencent/analysis/topic/TopicAnalysis.java
e92044a9cbf40e75905ee128bac6b0b7c115c16f
[]
no_license
tomdev2008/svnprojects
12fb11a7fa3a3679ae9d20b5a6a2ad779361a322
4f5f9be34cefcd223ad792120fd8a521faab321e
refs/heads/master
2021-01-25T05:21:57.868789
2014-01-23T06:49:46
2014-01-23T06:49:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
19,302
java
package cc.pp.tencent.analysis.topic; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import net.sf.json.JSONArray; import org.codehaus.jackson.JsonNode; import cc.pp.tencent.algorithms.InsertSort; import cc.pp.tencent.result.TopicResult; import cc.pp.tencent.utils.JsonUtils; import com.tencent.weibo.api.TAPI; import com.tencent.weibo.api.UserAPI; import com.tencent.weibo.oauthv1.OAuthV1; /** * Title: 话题分析 * @author wanggang * @version 1.1 * @since 2013-05-27 */ public class TopicAnalysis implements Serializable { /** * 默认的序列化版本号 */ private static final long serialVersionUID = 1L; private String ip = ""; private int apicount = 0; /** * @构造函数 * @param ip,服务器IP地址 * @param pages,新浪微博中话题页码数 */ public TopicAnalysis(String ip) { this.ip = ip; } /** * 测试函数 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { TopicAnalysis ta = new TopicAnalysis("192.168.1.151"); String keywords = new String("复旦投毒"); String[] result = ta.analysis(keywords, 3); System.out.println(result[0]); System.out.println(result[1]); } /** * @分析函数 * @return * @throws Exception */ @SuppressWarnings("unused") public String[] analysis(String keywords, int pages) throws Exception { JSONArray jsonresult = null; // TopicJDBC weibomysql = new TopicJDBC(this.ip); String[] tworesult = new String[2]; // if (weibomysql.mysqlStatus()) // { TopicResult result = new TopicResult(); /**********提取accesstoken*************/ /**********************用户授权****************************/ TopicUtils tpoicUtils = new TopicUtils(); String[] wids = tpoicUtils.getWids(keywords, pages); result.setOriginalUser(Integer.toString(wids.length)); //原创用户数 String[] tokens = tpoicUtils.getAccessToken(wids.length + 1, this.ip); JsonUtils jsonutils = new JsonUtils(); OAuthV1 oauth = new OAuthV1(); /**********************转发数据****************************/ HashMap<String, Integer> reposttimelinebyDay = new HashMap<String, Integer>(); //3、转发时间线--按天 HashMap<Integer, String> username = new HashMap<Integer, String>(); //存放用户名 int[] reposttimelineby24H = new int[24]; //按24小时内 int[] gender = new int[3]; //性别分布 int[] repostergrade = new int[5]; //9、转发用户等级(按粉丝量) int[] reposterquality = new int[2]; //11、转发用户质量(水军比例) int exposionsum = 0; //12、总曝光量 int[] location = new int[101]; //6、区域分布 int[] viptype = new int[14]; ; //7、VIP类型 int[] isself = new int[2]; //9、是否自己发的微博 int[] addVRatio = new int[3]; //10、加V比例,0-老用户,1-已实名认证,2-未实名认证 int[] weibotype = new int[8]; //12、微博类型,1-原创发表,2-转载,3-私信,4-回复,5-空回,6-提及,7-评论 // int[] etype = new int[2]; //13、心情类型 int[] weibostatus = new int[5]; //14、微博状态,0-正常,1-系统删除,2-审核中,3-用户删除,4-根删除 String[] keyusersbyrep = new String[50]; //15、关键账号,按照转发量 for (int i = 0; i < 50; i++) { keyusersbyrep[i] = "0=0"; } String[] keyusersbycom = new String[50]; //15、关键账号,按评论量 for (int i = 0; i < 50; i++) { keyusersbycom[i] = "0=0"; } int existwb = 0; int wbsum = 0; int comsum = 0; String name; String uid; String head; int rcount; int ccount; String rewid; //转发微博wid int self; //是否自己发的微博 int wbtype; //微博类型,1-原创发表,2-转载,3-私信,4-回复,5-空回,6-提及,7-评论 String citys; int city; //区域信息 int emotiontype; //心情类型 int addv; //加V信息 int isvip; //VIP类型 int wbstatus; //微博状态,0-正常,1-系统删除,2-审核中,3-用户删除,4-根删除 long reposttime; //转发时间 SimpleDateFormat fo1; String hour; SimpleDateFormat fo2; String date; JsonNode weibodata; JsonNode jsoninfo; JsonNode oriuserinfo; String accesstoken; String tokensecret; TAPI weibo; int cursor = 0; String lastreposttime = null; String lastwid = null; int index = 99; /**********************循环计算****************************/ for (int nums = 0; nums < wids.length; nums++) { // System.out.println(nums); accesstoken = tokens[nums].substring(0, tokens[nums].indexOf(",")); tokensecret = tokens[nums].substring(tokens[nums].indexOf(",") + 1); TopicAnalysis.oauthInit(oauth, accesstoken, tokensecret); weibo = new TAPI(oauth.getOauthVersion()); /**********************转发数据****************************/ String weiboinfo = weibo.reList(oauth, "json", "0", wids[nums], "1", "0", "100", "0"); this.apicount++; weibodata = JsonUtils.getJsonNode(weiboinfo); if (!weibodata.get("errcode").toString().equals("0") || (weibodata.get("data").toString().equals("null"))) { //返回错误信息处理 continue; } //1、转发量 wbsum += Integer.parseInt(weibodata.get("data").get("totalnum").toString()); jsoninfo = weibodata.get("data").get("info"); if (jsoninfo == null) { continue; } cursor = 0; lastreposttime = null; lastwid = null; index = 99; while ((cursor * 100 < wbsum) && (this.apicount < 100)) { jsoninfo = weibodata.get("data").get("info"); if (jsoninfo == null) { break; } for (int i = 0; i < 100; i++) { if (jsoninfo.get(i) == null) { index = i - 1; break; } name = jsoninfo.get(i).get("nick").toString(); name = name.substring(1, name.length() - 1).replaceAll("\"", "\\\\\""); uid = jsoninfo.get(i).get("name").toString(); uid = uid.substring(1, uid.length() - 1); head = jsoninfo.get(i).get("head").toString(); head = head.substring(1, head.length() - 1); rcount = Integer.parseInt(jsoninfo.get(i).get("count").toString()); ccount = Integer.parseInt(jsoninfo.get(i).get("mcount").toString()); rewid = jsoninfo.get(i).get("id").toString(); rewid = rewid.substring(1, rewid.length() - 1); self = Integer.parseInt(jsoninfo.get(i).get("self").toString()); wbtype = Integer.parseInt(jsoninfo.get(i).get("type").toString()); citys = jsoninfo.get(i).get("province_code").toString(); if (citys.length() == 2) { city = 0; } else { city = Integer.parseInt(citys.substring(1, citys.length() - 1)); } isvip = Integer.parseInt(jsoninfo.get(i).get("isvip").toString()); wbstatus = Integer.parseInt(jsoninfo.get(i).get("status").toString()); addv = Integer.parseInt(jsoninfo.get(i).get("isrealname").toString()); emotiontype = Integer.parseInt(jsoninfo.get(i).get("emotiontype").toString()); reposttime = Integer.parseInt(jsoninfo.get(i).get("timestamp").toString()); fo1 = new SimpleDateFormat("HH"); hour = fo1.format(new Date(reposttime * 1000l)); if (hour.substring(0, 1).equals("0")) { hour = hour.substring(1); } fo2 = new SimpleDateFormat("yyyy-MM-dd"); date = fo2.format(new Date(reposttime * 1000l)); username.put(existwb, uid); existwb++; /**************************15、关键账号*********************************/ keyusersbyrep = InsertSort.toptable(keyusersbyrep, name + "," + head + "=" + rcount); keyusersbycom = InsertSort.toptable(keyusersbycom, name + "," + head + "=" + ccount); /**************************3、转发时间线--按天*********************************/ reposttimelineby24H[Integer.parseInt(hour)]++; if (reposttimelinebyDay.get(date) == null) { reposttimelinebyDay.put(date, 1); } else { reposttimelinebyDay.put(date, reposttimelinebyDay.get(date) + 1); } /**************************6、区域分布*********************************/ if (city == 400) { location[0]++; } else { location[city]++; } /**************************7、VIP类型*********************************/ viptype[isvip]++; ; /************************9、是否自己发的微博******************************/ isself[self]++; /**************************10、加V比例*********************************/ addVRatio[addv]++; /********************11、转发用户质量(水军比例)****************************/ /**************************12、微博类型*********************************/ weibotype[wbtype]++; //1-原创发表,2-转载,3-私信,4-回复,5-空回,6-提及,7-评论 /**************************13、心情类型*********************************/ /**************************14、微博状态*********************************/ weibostatus[wbstatus]++; //0-正常,1-系统删除,2-审核中,3-用户删除,4-根删除 } lastreposttime = jsoninfo.get(index).get("timestamp").toString(); lastwid = jsoninfo.get(index).get("id").toString(); weiboinfo = weibo.reList(oauth, "json", "0", wids[nums], "1", lastreposttime, "100", lastwid); cursor++; this.apicount++; weibodata = JsonUtils.getJsonNode(weiboinfo); if (weibodata.get("data") == null) { //返回错误信息处理 break; } } /**********************评论数据****************************/ weiboinfo = weibo.reList(oauth, "json", "1", wids[nums], "1", "0", "100", "0"); this.apicount++; weibodata = JsonUtils.getJsonNode(weiboinfo); //1、评论量 if (weibodata.get("data").toString().equals("null")) { continue; } comsum += Integer.parseInt(weibodata.get("data").get("totalnum").toString()); } /**************************用户数据*********************************/ accesstoken = tokens[wids.length].substring(0, tokens[wids.length].indexOf(",")); tokensecret = tokens[wids.length].substring(tokens[wids.length].indexOf(",") + 1); TopicAnalysis.oauthInit(oauth, accesstoken, tokensecret); UserAPI user = new UserAPI(oauth.getOauthVersion()); String userinfo; String uids = null; JsonNode userdata; int usersum = 0; ; int fanssum; int sex; int count = username.size() / 30; count = (count < 100) ? count : 100; for (int i = 0; i < 1; i++) { for (int j = 0; j < 30; j++) { uids += username.get(i * 30 + j) + ","; } uids = uids.substring(0, uids.length() - 1); userinfo = user.infos(oauth, "json", uids, ""); userdata = JsonUtils.getJsonNode(userinfo); if (!userdata.get("errcode").toString().equals("0")) { continue; } jsoninfo = userdata.get("data").get("info"); if (jsoninfo == null) { continue; } for (int j = 0; j < 30; j++) { if (jsoninfo.get(j) == null) { break; } usersum++; fanssum = Integer.parseInt(jsoninfo.get(j).get("fansnum").toString()); sex = Integer.parseInt(jsoninfo.get(j).get("sex").toString()); /*************************4、性别分布****************************/ gender[sex]++; //1-男,2-女,0-未填写 /*********************9、转发用户等级(按粉丝量**********************/ if (fanssum < 100) { repostergrade[0]++; //0-----"X<100" } else if (fanssum < 1000) { repostergrade[1]++; //1-----"100<X<1000" } else if (fanssum < 10000) { repostergrade[2]++; //2-----"1000<X<1w" } else if (fanssum < 100000) { repostergrade[3]++; //3-----"1w<X<10w" } else { repostergrade[4]++; //4-----"X>10w" } /*********************11、转发用户质量(水军比例)**********************/ if (fanssum < 100) { reposterquality[0]++; } else { reposterquality[1]++; } /*************************12、总曝光****************************/ exposionsum += fanssum; } this.apicount++; } /**************************数据整理*********************************/ /**********************转发量****************************/ result.setRepostCount(Integer.toString(wbsum)); /**********************评论量****************************/ result.setCommentCount(Integer.toString(comsum)); /**************************15、关键账号*********************************/ for (int n = 0; n < 50; n++) { if (keyusersbyrep[n].length() > 5) { result.getKeyUsersByRep().put(Integer.toString(n), keyusersbyrep[n]); } else { break; } } for (int n = 0; n < 50; n++) { if (keyusersbycom[n].length() > 5) { result.getKeyUserByCom().put(Integer.toString(n), keyusersbycom[n]); } else { break; } } /**************************3、转发时间线--按天*********************************/ for (int i = 0; i < 24; i++) { result.getReposttimelineBy24H().put(Integer.toString(i), Float.toString((float) Math.round(((float) reposttimelineby24H[i] / existwb) * 10000) / 100) + "%"); } Set<String> keys = reposttimelinebyDay.keySet(); Iterator<String> iterator = keys.iterator(); int sum = 0; while (iterator.hasNext()) { sum += reposttimelinebyDay.get(iterator.next()); } iterator = keys.iterator(); String nextkey = null; while (iterator.hasNext()) { nextkey = iterator.next().toString(); result.getReposttimelineByDay().put( nextkey, Float.toString((float) Math.round(((float) reposttimelinebyDay.get(nextkey) / sum) * 10000) / 100) + "%"); } /*************************4、性别分布****************************/ result.getGender().put("m", Float.toString((float) Math.round(((float) gender[2] / (gender[1] + gender[2])) * 10000) / 100) + "%"); result.getGender().put("f", Float.toString((float) Math.round(((float) gender[1] / (gender[1] + gender[2])) * 10000) / 100) + "%"); /************4、用户等级分析(按粉丝量)*************/ result.getReposterGrade().put("<100", Float.toString((float) Math.round(((float) repostergrade[0] / usersum) * 10000) / 100) + "%"); result.getReposterGrade().put("100~1000", Float.toString((float) Math.round(((float) repostergrade[1] / usersum) * 10000) / 100) + "%"); result.getReposterGrade().put("1000~1w", Float.toString((float) Math.round(((float) repostergrade[2] / usersum) * 10000) / 100) + "%"); result.getReposterGrade().put("1w~10w", Float.toString((float) Math.round(((float) repostergrade[3] / usersum) * 10000) / 100) + "%"); result.getReposterGrade().put(">10w", Float.toString((float) Math.round(((float) repostergrade[4] / usersum) * 10000) / 100) + "%"); /**************************6、区域分布*********************************/ if (location[0] != 0) { result.getLocation().put("400", Float.toString((float) Math.round(((float) location[0] / existwb) * 10000) / 100) + "%"); } for (int j = 1; j < location.length; j++) { if (location[j] != 0) { result.getLocation().put(Integer.toString(j), Float.toString((float) Math.round(((float) location[j] / existwb) * 10000) / 100) + "%"); } } /**************************7、VIP类型*********************************/ result.getVipType().put("no", Float.toString((float) Math.round(((float) viptype[0] / existwb) * 10000) / 100) + "%"); result.getVipType().put("yes", Float.toString((float) Math.round(((float) viptype[1] / existwb) * 10000) / 100) + "%"); /******************8、水军分析******************/ result.getReposterQuality().put("mask", Float.toString((float) Math.round(((float) reposterquality[0] / usersum) * 10000) / 100) + "%"); result.getReposterQuality().put("real", Float.toString((float) Math.round(((float) reposterquality[1] / usersum) * 10000) / 100) + "%"); /************************9、是否自己发的微博******************************/ result.getIsSelf().put("no", Float.toString((float) Math.round(((float) isself[0] / existwb) * 10000) / 100) + "%"); result.getIsSelf().put("yes", Float.toString((float) Math.round(((float) isself[1] / existwb) * 10000) / 100) + "%"); /**************************10、加V比例*********************************/ result.getAddVRatio().put("old", Float.toString((float) Math.round(((float) addVRatio[0] / existwb) * 10000) / 100) + "%"); result.getAddVRatio().put("yes", Float.toString((float) Math.round(((float) addVRatio[1] / existwb) * 10000) / 100) + "%"); result.getAddVRatio().put("no", Float.toString((float) Math.round(((float) addVRatio[2] / existwb) * 10000) / 100) + "%"); /*************************12、总曝光****************************/ result.setExposionSum(Long.toString((long) exposionsum * existwb / usersum)); /**************************12、微博类型*********************************/ //1-原创发表,2-转载,3-私信,4-回复,5-空回,6-提及,7-评论 for (int i = 0; i < weibotype.length; i++) { if (weibotype[i] != 0) { result.getWeiboType().put(Integer.toString(i), Float.toString((float) Math.round(((float) weibotype[i] / existwb) * 10000) / 100) + "%"); } } /**************************13、心情类型*********************************/ /**************************14、微博状态*********************************/ //0-正常,1-系统删除,2-审核中,3-用户删除,4-根删除 result.getWeiboStatus().put("normal", Float.toString((float) Math.round(((float) weibostatus[0] / existwb) * 10000) / 100) + "%"); result.getWeiboStatus().put("sysdel", Float.toString((float) Math.round(((float) weibostatus[1] / existwb) * 10000) / 100) + "%"); result.getWeiboStatus().put("verfy", Float.toString((float) Math.round(((float) weibostatus[2] / existwb) * 10000) / 100) + "%"); result.getWeiboStatus().put("userdel", Float.toString((float) Math.round(((float) weibostatus[3] / existwb) * 10000) / 100) + "%"); result.getWeiboStatus().put("rootdel", Float.toString((float) Math.round(((float) weibostatus[4] / existwb) * 10000) / 100) + "%"); /***************数据转换与存储**************/ jsonresult = JSONArray.fromObject(result); // weibomysql.sqlClose(); // } tworesult[0] = jsonresult.toString(); tworesult[1] = Integer.toString(apicount); return tworesult; } /** * @授权参数初始化 * @param oauth */ public static void oauthInit(OAuthV1 oauth, String accesstoken, String tokensecret) { /***************皮皮时光机appkey和appsecret***********************/ oauth.setOauthConsumerKey("11b5a3c188484c3f8654b83d32e19bab"); oauth.setOauthConsumerSecret("dc5cd31e1ddf556a42a40a1cff7efd5c"); /**************************************************************/ //oauth.setOauthCallback(""); oauth.setOauthToken(accesstoken); oauth.setOauthTokenSecret(tokensecret); } }
eff056e9678070989819ef5f24954c0753254d73
195dd41b065cbfaeececcf4ed3a95d67bd3fb964
/src/com/reflect/JvmAnalysis.java
4e4176d42f556b59575a33f409eba812d8fe9415
[]
no_license
haoze15236/javalearn
eea8ebd84f1138e1e29e81cb150f4dc35e345003
7d7eee62ec136caccceecf42df295e7035022900
refs/heads/master
2021-07-18T12:36:50.969475
2020-05-18T13:33:42
2020-05-18T13:33:42
220,955,345
0
0
null
2020-10-13T17:55:41
2019-11-11T10:23:25
Java
UTF-8
Java
false
false
4,280
java
package com.reflect; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /**JVM核心机制 * 【1】类加载机制 * 加载 * ①获取字节数组(Class文件字节码,网络资源字节码,数据库字节码) * ②类加载器加载到方法区,静态二进制字节码数据转换成运行时数据结构 * ③堆中生成一个对应的Class对象,指向方法区中的运行数据结构 * 链接: * 验证-确保加载的类符合JVM规范,没有安全方面的问题 * 准备-正式为类变量(static)分配内存并设置初始值(static int a=3,此时设置初始值a=0),这些内存都在方法区中进行分配 * 解析-虚拟机常量池内(每一个类都有一个常量池)的符号引用(类名,方法名,字符串常量等等)替换成直接引用 * 初始化: * 执行类构造器<clinit>()方法,类构造器<clinit>()方法是由编译器自动收集类中的所有类变量的赋值动作和静态语句块组合而成 * 当初始化一个类时,若其父类未初始化,则先初始化其父类 * 初始化线程安全 * 主动引用(new 对象,调用静态成员,反射调用)才会初始化 * 被动引用(调用final成员,由于final成员是在常量池里的直接引用)不会初始化 * 使用/卸载 * 【2】类加载器层次 * 引导类加载器bootstrap class loader * 扩展类加载器extensions class loader * 应用程序类加载器application class loader * 双亲委派机制 * 【3】自定义类加载器 * [1]首先检查类是否已经被加载到命名空间中 * [2]调用本类的findClass()方法,获取类对应的字节码 * [3]调用defineClass()导入类型到方法区 * 注意:同一个类被不同类加载器加载,JVM不认为是相同的类 * @author zee * */ public class JvmAnalysis { public static void main(String[] args) { ClassLoadertest.get(); System.out.println(JvmAnalysis.class.getResource("/").getPath().substring(1)); } } //自定义文件系统类加载器 class FileSystemClassLoader extends ClassLoader{ private String rootDir;//类加载路劲 public FileSystemClassLoader() { this.rootDir = FileSystemClassLoader.class.getResource("/").getPath().substring(1); } public FileSystemClassLoader(String rootDir) { this.rootDir = rootDir+'/'; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { //[1]首先检查类是否已经被加载到命名空间中 Class<?> c = findLoadedClass(name); if(c!=null){ return c; }else{ //委派父类加载器加载 c = this.getParent().loadClass(name); if(c!=null){ return c; }else{ //开始自己加载,获取类对用的字节码,调用defineClass()导入类型到方法区 byte[] classdata = getClassData(name); if(classdata==null){ throw new ClassNotFoundException(); }else{ c = defineClass(name,classdata,0,classdata.length); return c; } } } } //class文件内容转换成字节数组 private byte[] getClassData(String name){ String filepath = this.rootDir+name.replace(".", "/")+".class"; try(InputStream is = new FileInputStream(filepath); ByteArrayOutputStream bos = new ByteArrayOutputStream()){ byte[] classdata = new byte[1024*5]; int count =0; while((count = is.read(classdata))!=-1){ bos.write(classdata,0,count); } return bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e1) { e1.printStackTrace(); return null; } } } class ClassLoadertest{ public static void get(){ System.out.println(ClassLoader.getSystemClassLoader());//应用程序类加载器 System.out.println(ClassLoader.getSystemClassLoader().getParent());//扩展类加载器 System.out.println(ClassLoader.getSystemClassLoader().getParent().getParent());//引导类加载器,C写的,java获取不到 System.out.println(System.getProperty("java.class.path"));//当前系统类加载器加载路径 System.out.println(String.class.getClassLoader());//通过class对象可以获取到该类的加载器 } }
8596bfd7ab72f87776e846c411ac5ecace08b61c
d85eea278f53c2d60197a0b479c074b5a52bdf1e
/Common/msk-common-config/src/main/java/com/msk/common/listener/package-info.java
aa9b8823c6e105e00b5734faf0ac945bef52a349
[]
no_license
YuanChenM/xcdv1.5
baeaab6e566236d0f3e170ceae186b6d2999c989
77bf0e90102f5704fe186140e1792396b7ade91d
refs/heads/master
2021-05-26T04:51:12.441499
2017-08-14T03:06:07
2017-08-14T03:06:07
100,221,981
1
2
null
null
null
null
UTF-8
Java
false
false
77
java
/** * Created by jackjiang on 16/8/13. */ package com.msk.common.listener;
44a25fa3645417acc3eeb8b60dbb5da3d75f19df
b425fc7adc3bbbf5d6e773fed23f26e5b1771944
/cloud-service/cloud-service-biz/cloud-service-file-biz/src/main/java/com/dcy/file/biz/mapper/FileInfoMapper.java
f1914c383c190391af5b7838f7c4984228e11fc9
[]
no_license
dcy421/dcy-dubbo-cloud
79e0380c0d6ff7ee15ce424afabc783813fa1986
bc58b71db81de1007b3213dc078b2ce36c1a71f6
refs/heads/master
2022-12-28T20:47:46.086912
2020-09-23T02:11:46
2020-09-23T02:11:46
289,156,560
1
1
null
null
null
null
UTF-8
Java
false
false
330
java
package com.dcy.file.biz.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.dcy.file.biz.model.FileInfo; import org.apache.ibatis.annotations.Mapper; /** * <p> * Mapper 接口 * </p> * * @author dcy * @since 2019-09-18 */ @Mapper public interface FileInfoMapper extends BaseMapper<FileInfo> { }
a9582d348941dc655ef30e19c6cdc5123a6c3c45
5e58f68c80101a4621c16016b7ea414867b13ba8
/Q4.java
29e818c908aee61d2b8cf57fb28a9f0cb8658cb9
[]
no_license
Battulapraveenkumar/prograd-excercise
96be75d2972094b3d0802d77aad0d37d3fd747ce
b75f5d4de7e5180e2685e8a6d86f393a7acfcf35
refs/heads/main
2023-07-20T11:11:55.196758
2021-08-13T04:13:31
2021-08-13T04:13:31
394,616,003
0
0
null
null
null
null
UTF-8
Java
false
false
430
java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n= sc.nextInt(); while (n != 1) { System.out.print(n + "\n"); // If n is odd if ((n & 1) == 1) n = 3 * n + 1; // If even else n = n / 2; } System.out.print(n); } }
1ff24c7d1efbeda97968d5efdaa872784fdc52aa
bf72fa5767b1693f635aa79c52cf3886e46d03a9
/planeGame/GameObject.java
139eae08ac9874e526506d3e440afc4ef5708cc1
[]
no_license
xyptnjxn/planeGame
f949ac9f4d7d2ecc42b123d953b8c969bc3267ad
87d483d20fddaf74513ee5f4cba1db8812cf12f2
refs/heads/master
2020-09-08T20:50:00.945601
2019-11-12T14:39:07
2019-11-12T14:39:07
221,237,960
0
0
null
null
null
null
UTF-8
Java
false
false
733
java
package planeGame; import java.awt.*; public class GameObject { Image img; double x, y; int speed; int width, height; public void drawSelf(Graphics g){ g.drawImage(img, (int)x, (int)y, null); } public Rectangle getRect(){ return new Rectangle((int)x, (int)y, width, height); } public GameObject() { } public GameObject(Image img, double x, double y, int speed, int width, int height) { this.img = img; this.x =x; this.y = y; this.speed = speed; this.width = width; this.height = height; } public GameObject(Image img, double x, double y) { this.img = img; this.x =x; this.y = y; } }
eed8a18f2dcf305c9660e171c2b460e60dd84a17
212d84f94aac5bf4373c5f40563a08148bcac9bd
/amazon-ds/src/com/amazon/ds/strings/LongestCommonPrefix.java
99dbdc3e5bdcc2bbd95a0e3d24c8827789b4ac7c
[]
no_license
shivangi-12/data_structures_and_algorithms
90ea77ce3b6bb6cf1ed6f4ba565bab74a0ca97be
2d453d53b50a54d8324ce7441bdb7c0f9b02abaf
refs/heads/master
2022-08-15T14:50:40.213651
2020-03-14T09:16:41
2020-03-14T09:16:41
244,615,998
0
0
null
null
null
null
UTF-8
Java
false
false
1,600
java
package com.amazon.ds.strings; import java.util.Scanner; //Given an array of Strings , find the common prefix between array of Strings //Input: {"geeksforgeeks","geezer","geek"} //Output: "gee" //Using the divide and conquer approach here public class LongestCommonPrefix { static String commonPrefixUtil(String str1, String str2) { String result=" "; int n=str1.length(); int m=str2.length(); for(int i=0,j=0;i<=n-1&&j<=m-1;i++,j++) { if (str1.charAt(i) != str2.charAt(j)) { break; } result += str1.charAt(i); } return result; } public static String commonPrefix(String arr[],int low,int high) { if(low==high) { return (arr[low]); } if(high>low) { int mid=low+(high-low)/2; String str1=commonPrefix(arr, low, mid); String str2=commonPrefix(arr, mid+1, high); return (commonPrefixUtil(str1, str2)); } return null; } public static void main(String[] args) { int n; String arr[]=new String[20]; @SuppressWarnings("resource") Scanner in=new Scanner(System.in); System.out.println("Enter the number of strings in the array"); n=in.nextInt(); System.out.println("Enter the strings"); for(int i=0;i<n;i++) { arr[i]=in.next(); } String ans=commonPrefix(arr,0,n-1); if (ans.length() != 0) { System.out.println("The longest common prefix is "+ ans); } else { System.out.println("There is no common prefix"); } } }
2ac54a66609078026f33fb59d7a3bb3bede9a16c
2dac6a6d488c53c3a53484bbc6a05aee6f53665d
/src/gameobject.java
206234b2891d125671539ca043e4182347bb094f
[]
no_license
League-level2-student/league-invaders-isabelluu
9350367066df7cb73b1ae7f50dfebc3acdcc5dc6
4fc4983c4948be5c55f3dac5c44d857541d67c3f
refs/heads/master
2020-12-14T16:01:10.201319
2020-02-01T22:21:18
2020-02-01T22:21:18
234,799,001
0
0
null
null
null
null
UTF-8
Java
false
false
383
java
public class gameobject { static int x; static int y; static int width; static int height; int speed = 0; boolean isActive = true; gameobject object = new gameobject(x, y, width, height); gameobject(int x, int y, int width, int height) { gameobject.x = x; gameobject.y = y; gameobject.width = width; gameobject.height = height; } }
2381522ab2e2c7c4fee91ba5374f6ac3822130a8
a68fec2bfeec08f7d14a7a2ad1def42f62d38d68
/springcloud-login/src/main/java/com/springcloud/login/utils/CommonUtil.java
3d06e100ea1d4477b54eeac78fc05c5017d10f46
[]
no_license
dawei1980/Springcloud-Test
dd56e26bd2a358d41bb6bbb37411970450ba2dce
5501af0fe3894d546463a61de1a9684fdde2ff40
refs/heads/master
2022-11-10T22:32:58.194960
2020-06-30T07:11:11
2020-06-30T07:11:11
268,693,485
0
0
null
null
null
null
UTF-8
Java
false
false
248
java
package com.springcloud.login.utils; import java.util.UUID; public class CommonUtil { /** * 获取36位uuid * @return */ public static String getUuid() { return UUID.randomUUID().toString().replace("-",""); } }
fdcaa58b674954f91d0f090387fc9837d3156542
5f2be2df1592121fb4b383b3bfdf30d903a6d074
/app/src/main/java/com/netglue/ngtmobile/model/SharedStorage.java
7d6dec4b57ed9c1119d159ef1c0f6ae92f603f01
[]
no_license
waterflower124/android-event-notice-app
6f037e58ebe87360fae23171282a58f028c2e3ef
0b8c4a9d5d67e33a8964181d57a6ccde4faf47cf
refs/heads/main
2023-05-07T03:44:37.833688
2021-05-27T02:11:02
2021-05-27T02:11:02
371,220,023
0
0
null
null
null
null
UTF-8
Java
false
false
1,187
java
package com.netglue.ngtmobile.model; import java.util.ArrayList; import java.util.List; public class SharedStorage { private static final SharedStorage ourInstance = new SharedStorage(); public static SharedStorage getInstance() { return ourInstance; } private SharedStorage() { assets = new ArrayList<>(); alerts = new ArrayList<>(); asset_push = new ArrayList<>(); notificationList = new ArrayList<>(); alert_search_asset_name = ""; trips_list = new ArrayList<>(); notificationToneItemList = new ArrayList<>(); currentAsset = new AssetItem(); connection_lost = false; } public List<AssetItem> assets; public AssetItem currentAsset; public TripItem currentTrip; public List<AlertItem> alerts; public List<AssetPushItem> asset_push; public boolean connection_lost; public List<NotificationItem> notificationList; public String alert_search_asset_name; // when click bell icon from List page public List<TripItem> trips_list; public List<NotificationToneItem> notificationToneItemList; }
ad87e39f217ae01c72e2c0a703d75aea0a446bfc
d5e336a49c4fa55906d7be2f406a787d759b3ec6
/src/排序专题/Shell排序_shellSort/ShellSort.java
866529c44367e11cca01febb6359c63cfe083984
[]
no_license
chenxy1996/leetcode
68853a77425041b9ec702f72630fac68e9835031
5204bd426a9e42bf8450704c42cd9179348bc676
refs/heads/master
2021-07-02T09:11:33.201710
2020-10-14T09:02:36
2020-10-14T09:02:36
179,980,417
4
0
null
null
null
null
UTF-8
Java
false
false
2,359
java
package 排序专题.Shell排序_shellSort; import 排序专题.SortTest; import 排序专题.View; import java.util.Arrays; import java.util.stream.IntStream; public class ShellSort { public static void sort(int[] nums) { if (nums == null || nums.length == 1) { return; } sort(nums, 0, nums.length - 1); } private static void sort(int[] nums, int left, int right) { int step = nums.length / 2; step = step > 0 ? step : 1; while (step > 0) { for (int i = 0; i < step; i++) { shellSort(nums, i, step); // 可视化 // ------------------------------------------ int start = i; int finalStep = step; IntStream stream = IntStream.iterate(start, num -> num < nums.length, num -> num + finalStep); View.viewArray(nums, stream.toArray()); // ------------------------------------------ } step = step >> 1; } } private static void shellSort(int[] nums, int start, int step) { for (int i = start; i < nums.length; i += step) { int target = nums[i]; int pos = findPos(nums, start, i - step, step, target); pos = pos >= 0 ? pos : i; insert(nums, pos, step, i - step, target); } } private static int findPos(int[] nums, int start, int end, int step, int target) { int l = 0; int r = (end - start) / step; end = r; while (l <= r) { int m = l + (r - l) / 2; int m1 = m * step + start; int valM = nums[m1]; if (valM <= target) { l = m + 1; } else { r = m - 1; } } return l <= end ? l * step + start : -1; } private static void insert(int[] nums, int pos, int step, int end, int target) { for (int i = end; i >= pos; i -= step) { nums[i + step] = nums[i]; } nums[pos] = target; } public static void main(String[] args) { int[] nums = {7, 1, 3, 2, 1, 12, 0, 7, 8, 3, 2, 2, 4, 9, 5, 5, 6, 12}; sort(nums); System.out.println(Arrays.toString(nums)); System.out.println(SortTest.test(ShellSort::sort)); } }
0ef92bbbdedde86c1744b0304828cef4002d79ab
12fa53865000e47bf61c513f307fc91de4da946d
/day07/Method_dg04.java
7d66aa5bd3fed57b9dae78366e0a3955a8931f66
[]
no_license
Lafilosofia/JavaBasic
898934211a7ba6124f6bfee242a6fe77e3fda4c8
9920767f2f14516401416c12f7d5655bcee7fd65
refs/heads/main
2023-03-12T16:13:38.213559
2021-03-03T05:47:39
2021-03-03T05:47:39
338,732,702
0
0
null
null
null
null
GB18030
Java
false
false
1,590
java
package day07; import java.util.Scanner; /** * 作业: * 买汽水: * 加入一块钱买一瓶汽水, * 但是两个瓶盖兑换一瓶汽水, * 三个空瓶子兑换一瓶汽水 * 让用户输入钱数(正整数) * 求一共可以喝多少瓶汽水 * 分析:例如: * 停止条件:瓶盖 < && 2 空瓶子 < 3 * 11块钱 有11个瓶盖 有11个空瓶子 * int a = 11 \ 2 瓶盖兑换的汽水 int a1 = 11 % 2 瓶盖兑换汽水后剩余的瓶盖 * int b = 11 \ 3 空瓶子兑换的汽水 int b1 = 11 % 3 空瓶子兑换汽水后剩余的空瓶子 * * @author 86180 * */ public class Method_dg04 { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("请输入大于0的正整数"); int money = scanner.nextInt(); //钱数 money大于1 才有兑换的情况 if(money == 1){ System.out.println("你可以喝"+money+"瓶汽水"); } else{ //一共喝的汽水=money+空瓶子所兑换的汽水 int all = money + dg(money,money); System.out.println("你一共可以喝"+all); } } public static int dg(int a,int b){ /* * a是瓶盖 * b是空瓶子 */ // if(a < 2 && b <3){ return 0; } //瓶盖兑换的汽水 //瓶盖兑换汽水后剩余的瓶盖 //空瓶子兑换的汽水 //空瓶子兑换汽水后剩余的空瓶子 int empty = a / 2; int empty1 = a % 2; int pool = b / 3; int pool1 = b % 3; return empty + pool + dg(empty + empty1 + pool,empty + pool + pool1); } }
5d1cfaedfc8df91796fcc13b3bf9b3959696e3c4
a12a0f98b7a768c02d8d8329d1c52e2610fc7c51
/app/src/main/java/in/vinkrish/quickwash/ReplaceFragment.java
d14fc70b6c13c62af150a17314772044c1c01c22
[]
no_license
emppas/QuickWash
1bff50439f20f1089c4dd3bafa10616c9d5277c3
24cc2e04b61a06590927aeaeb848e26608f465f8
refs/heads/master
2021-08-30T07:16:57.983949
2017-12-16T17:16:54
2017-12-16T17:16:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
365
java
package in.vinkrish.quickwash; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; /** * Created by vinkrish. */ class ReplaceFragment { static void replace(Fragment f, FragmentManager fm) { fm .beginTransaction() .replace(R.id.content_frame, f) .commit(); } }
f6f30395e9911682672ee0f7f29b92c8d11f693f
7984e49995a31009ab3258fbbaf7f45ece763391
/src/com/erdenbatuhan/mvc/CourseQuerySystemView.java
903774e9bb826da33067bfaf472c7f8eba242ad1
[ "MIT" ]
permissive
erdenbatuhan/Course-Query-System
f76eac7c9b4aa036c8141e645b123db7915f4a24
5f133d93a1b4dbab5fee45a402f9f722b3963a24
refs/heads/master
2021-06-14T06:19:22.239274
2017-06-01T22:56:38
2017-06-01T22:56:38
66,128,300
0
0
null
null
null
null
UTF-8
Java
false
false
4,362
java
package com.erdenbatuhan.mvc; /* * Project : CourseQuerySystem * Class : CourseQuerySystemView.java * Developer : Batuhan Erden */ import com.erdenbatuhan.object.*; import java.text.*; import java.util.*; public class CourseQuerySystemView { public static final String NEW_LINE = System.lineSeparator(); public static final Scanner SCANNER = new Scanner(System.in); private CourseQuerySystemController controller; private int userInputAsInt = -1; public CourseQuerySystemView(final CourseQuerySystemController controller) { this.controller = controller; printUserMenu(); } private void printUserMenu() { System.out.println("-------------------------------------------------------------- " + NEW_LINE + " Course Query System " + NEW_LINE + "-------------------------------------------------------------- " + NEW_LINE + "Operations: " + NEW_LINE + "0. Terminate the program " + NEW_LINE + "1. Add a course " + NEW_LINE + "2. Add a student " + NEW_LINE + "3. Print student's weekly plan by entering his/her student ID " + NEW_LINE + "4. List instructors " + NEW_LINE + "5. List rooms " + NEW_LINE + "6. List subject names " + NEW_LINE + "7. List course numbers " + NEW_LINE + "8. Query courses by specific room " + NEW_LINE + "9. Query courses by specific day " + NEW_LINE + "10. Query courses by specific instructor " + NEW_LINE + "11. Query courses by specific course number " + NEW_LINE + "12. Query courses by specific subject name " + NEW_LINE + "13. Query courses that start in the morning (08:40 - 11:40) " + NEW_LINE + "-------------------------------------------------------------- " ); } public void takeUserInputAsInt() { while (true) { System.out.print("-> Please enter your operation number: "); try { userInputAsInt = Integer.parseInt(SCANNER.nextLine()); controller.processInput(userInputAsInt); } catch (NumberFormatException e) { System.out.println("--> Error: The input must be a number"); userInputAsInt = -1; } printUserMenu(); } } public String getUserInputAsString(String chosenData) { System.out.print("--> Please enter " + chosenData + ": "); String userInputAsString = SCANNER.nextLine(); return userInputAsString; } public void takeUserInputToAddStudent() { System.out.print("--> Please enter student's full name: "); String fullName = SCANNER.nextLine(); System.out.print("--> Please enter student's ID: "); String studentId = SCANNER.nextLine().toUpperCase(); System.out.println("--> Please enter courses taken by the student (e.g. -> CS102): "); Student student = new Student(fullName, studentId); while (true) { System.out.print("---> Enter a course (-1 to stop): "); String courseEntered = SCANNER.nextLine().toUpperCase(); if (courseEntered.equals("-1")) break; controller.addCourseToStudent(student, courseEntered); } } public void printUniqueList(String printMessage, List<String> list) { System.out.println("-----------------"); System.out.println(printMessage); System.out.println("-----------------"); Set<String> uniqueList = new TreeSet<String>(list); list = new ArrayList<String>(uniqueList); /* The "Collator" below is used for UTF-8 sorting */ Collections.sort(list, Collator.getInstance(new Locale("lt_LT"))); for (String listItem : list) if (listItem.length() != 0) System.out.println("~ " + listItem); } public void printCourses(List<Course> courses) { if (courses.size() == 0) System.out.println("---> Error: There is no data found"); else for (Course course : courses) course.printData(); } public CourseQuerySystemController getController() { return controller; } public void setController(CourseQuerySystemController controller) { this.controller = controller; } public int getUserInputAsInt() { return userInputAsInt; } public void setUserInputAsInt(int userInputAsInt) { this.userInputAsInt = userInputAsInt; } }
b1a9dfdcc0a6ed8bc100bd37c8fb6a5efb2a22e9
d9493c1a388fb7d505db859a46ab16f09b9456a4
/java/OpenDental/FormScreenGroups.java
4f12fdaff56bc51b165907d8288c141438b3bc90
[]
no_license
leelingco/opendental
f29c51a76bf455496bbc307ab0a5cd588792e7a0
aaf621b2b5b64e1d8d0f3318050d143abeefe594
refs/heads/master
2021-01-21T00:25:30.774258
2016-02-16T04:23:27
2016-02-16T04:23:27
51,807,222
0
0
null
2016-02-16T04:12:27
2016-02-16T04:12:27
null
UTF-8
Java
false
false
16,283
java
// // Translated by CS2J (http://www.cs2j.com): 2/15/2016 7:59:45 PM // package OpenDental; import CS2JNet.System.StringSupport; import java.util.ArrayList; import java.util.List; import OpenDental.FormScreenGroupEdit; import OpenDental.Lan; import OpenDental.PIn; import OpenDental.Properties.Resources; import OpenDental.ScreenGroup; import OpenDental.ScreenGroups; import OpenDental.Screens; import OpenDental.UI.__MultiODGridClickEventHandler; import OpenDental.UI.ODGridColumn; /** * */ public class FormScreenGroups extends System.Windows.Forms.Form { private System.Windows.Forms.TextBox textDateFrom = new System.Windows.Forms.TextBox(); private System.Windows.Forms.Label label2 = new System.Windows.Forms.Label(); private OpenDental.UI.Button butRefresh; private System.Windows.Forms.TextBox textDateTo = new System.Windows.Forms.TextBox(); private OpenDental.UI.Button butAdd; private IContainer components = new IContainer(); private OpenDental.UI.Button butClose; private OpenDental.UI.ODGrid gridMain; private MainMenu mainMenu = new MainMenu(); private List<ScreenGroup> ScreenGroupList = new List<ScreenGroup>(); private OpenDental.UI.Button butLeft; private OpenDental.UI.Button butRight; private OpenDental.UI.Button butToday; private Label label1 = new Label(); public ScreenGroup ScreenGroupCur = new ScreenGroup(); private DateTime dateCur = new DateTime(); /** * */ public FormScreenGroups() throws Exception { // // Required for Windows Form Designer support // initializeComponent(); Lan.f(this); } /** * Clean up any resources being used. */ protected void dispose(boolean disposing) throws Exception { if (disposing) { if (components != null) { components.Dispose(); } } super.Dispose(disposing); } /** * Required method for Designer support - do not modify * the contents of this method with the code editor. */ private void initializeComponent() throws Exception { this.components = new System.ComponentModel.Container(); this.textDateFrom = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.textDateTo = new System.Windows.Forms.TextBox(); this.butRefresh = new OpenDental.UI.Button(); this.butAdd = new OpenDental.UI.Button(); this.butClose = new OpenDental.UI.Button(); this.mainMenu = new System.Windows.Forms.MainMenu(this.components); this.gridMain = new OpenDental.UI.ODGrid(); this.butLeft = new OpenDental.UI.Button(); this.butRight = new OpenDental.UI.Button(); this.butToday = new OpenDental.UI.Button(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // textDateFrom // this.textDateFrom.Location = new System.Drawing.Point(150, 52); this.textDateFrom.Name = "textDateFrom"; this.textDateFrom.Size = new System.Drawing.Size(69, 20); this.textDateFrom.TabIndex = 74; this.textDateFrom.Validating += new System.ComponentModel.CancelEventHandler(this.textDateFrom_Validating); // // label2 // this.label2.Location = new System.Drawing.Point(218, 56); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(25, 13); this.label2.TabIndex = 77; this.label2.Text = "To"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textDateTo // this.textDateTo.Location = new System.Drawing.Point(243, 52); this.textDateTo.Name = "textDateTo"; this.textDateTo.Size = new System.Drawing.Size(75, 20); this.textDateTo.TabIndex = 76; this.textDateTo.Validating += new System.ComponentModel.CancelEventHandler(this.textDateTo_Validating); // // butRefresh // this.butRefresh.setAdjustImageLocation(new System.Drawing.Point(0, 0)); this.butRefresh.setAutosize(true); this.butRefresh.setBtnShape(OpenDental.UI.enumType.BtnShape.Rectangle); this.butRefresh.setBtnStyle(OpenDental.UI.enumType.XPStyle.Silver); this.butRefresh.setCornerRadius(4F); this.butRefresh.Location = new System.Drawing.Point(326, 51); this.butRefresh.Name = "butRefresh"; this.butRefresh.Size = new System.Drawing.Size(55, 21); this.butRefresh.TabIndex = 78; this.butRefresh.Text = "Refresh"; this.butRefresh.Click += new System.EventHandler(this.butRefresh_Click); // // butAdd // this.butAdd.setAdjustImageLocation(new System.Drawing.Point(0, 0)); this.butAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.butAdd.setAutosize(true); this.butAdd.setBtnShape(OpenDental.UI.enumType.BtnShape.Rectangle); this.butAdd.setBtnStyle(OpenDental.UI.enumType.XPStyle.Silver); this.butAdd.setCornerRadius(4F); this.butAdd.Image = Resources.getAdd(); this.butAdd.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.butAdd.Location = new System.Drawing.Point(13, 502); this.butAdd.Name = "butAdd"; this.butAdd.Size = new System.Drawing.Size(70, 24); this.butAdd.TabIndex = 79; this.butAdd.Text = "Add"; this.butAdd.Click += new System.EventHandler(this.butAdd_Click); // // butClose // this.butClose.setAdjustImageLocation(new System.Drawing.Point(0, 0)); this.butClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.butClose.setAutosize(true); this.butClose.setBtnShape(OpenDental.UI.enumType.BtnShape.Rectangle); this.butClose.setBtnStyle(OpenDental.UI.enumType.XPStyle.Silver); this.butClose.setCornerRadius(4F); this.butClose.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.butClose.Location = new System.Drawing.Point(441, 502); this.butClose.Name = "butClose"; this.butClose.Size = new System.Drawing.Size(70, 24); this.butClose.TabIndex = 79; this.butClose.Text = "Close"; this.butClose.Click += new System.EventHandler(this.butClose_Click); // // gridMain // this.gridMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.gridMain.setHScrollVisible(false); this.gridMain.Location = new System.Drawing.Point(13, 82); this.gridMain.Name = "gridMain"; this.gridMain.setScrollValue(0); this.gridMain.Size = new System.Drawing.Size(499, 402); this.gridMain.TabIndex = 80; this.gridMain.setTitle("Screening Groups"); this.gridMain.setTranslationName(null); this.gridMain.CellDoubleClick = __MultiODGridClickEventHandler.combine(this.gridMain.CellDoubleClick,new OpenDental.UI.ODGridClickEventHandler() { public System.Void invoke(System.Object sender, OpenDental.UI.ODGridClickEventArgs e) throws Exception { this.gridMain_CellDoubleClick(sender, e); } public List<OpenDental.UI.ODGridClickEventHandler> getInvocationList() throws Exception { List<OpenDental.UI.ODGridClickEventHandler> ret = new ArrayList<OpenDental.UI.ODGridClickEventHandler>(); ret.add(this); return ret; } }); // // butLeft // this.butLeft.setAdjustImageLocation(new System.Drawing.Point(0, 0)); this.butLeft.setAutosize(true); this.butLeft.setBtnShape(OpenDental.UI.enumType.BtnShape.Rectangle); this.butLeft.setBtnStyle(OpenDental.UI.enumType.XPStyle.Silver); this.butLeft.setCornerRadius(4F); this.butLeft.Image = Resources.getLeft(); this.butLeft.Location = new System.Drawing.Point(167, 13); this.butLeft.Name = "butLeft"; this.butLeft.Size = new System.Drawing.Size(39, 24); this.butLeft.TabIndex = 78; this.butLeft.Click += new System.EventHandler(this.butLeft_Click); // // butRight // this.butRight.setAdjustImageLocation(new System.Drawing.Point(0, 0)); this.butRight.setAutosize(true); this.butRight.setBtnShape(OpenDental.UI.enumType.BtnShape.Rectangle); this.butRight.setBtnStyle(OpenDental.UI.enumType.XPStyle.Silver); this.butRight.setCornerRadius(4F); this.butRight.Image = Resources.getRight(); this.butRight.Location = new System.Drawing.Point(307, 13); this.butRight.Name = "butRight"; this.butRight.Size = new System.Drawing.Size(39, 24); this.butRight.TabIndex = 78; this.butRight.Click += new System.EventHandler(this.butRight_Click); // // butToday // this.butToday.setAdjustImageLocation(new System.Drawing.Point(0, 0)); this.butToday.setAutosize(true); this.butToday.setBtnShape(OpenDental.UI.enumType.BtnShape.Rectangle); this.butToday.setBtnStyle(OpenDental.UI.enumType.XPStyle.Silver); this.butToday.setCornerRadius(4F); this.butToday.Location = new System.Drawing.Point(215, 13); this.butToday.Name = "butToday"; this.butToday.Size = new System.Drawing.Size(83, 24); this.butToday.TabIndex = 78; this.butToday.Text = "Today"; this.butToday.Click += new System.EventHandler(this.butToday_Click); // // label1 // this.label1.Location = new System.Drawing.Point(92, 56); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(57, 13); this.label1.TabIndex = 77; this.label1.Text = "From"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // FormScreenGroups // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(524, 541); this.Controls.Add(this.gridMain); this.Controls.Add(this.butClose); this.Controls.Add(this.butAdd); this.Controls.Add(this.textDateFrom); this.Controls.Add(this.textDateTo); this.Controls.Add(this.butRight); this.Controls.Add(this.butLeft); this.Controls.Add(this.butToday); this.Controls.Add(this.butRefresh); this.Controls.Add(this.label1); this.Controls.Add(this.label2); this.Menu = this.mainMenu; this.Name = "FormScreenGroups"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Screening Groups"; this.Load += new System.EventHandler(this.FormScreenings_Load); this.ResumeLayout(false); this.PerformLayout(); } private void formScreenings_Load(Object sender, System.EventArgs e) throws Exception { dateCur = DateTime.Today; textDateFrom.Text = DateTime.Today.ToShortDateString(); textDateTo.Text = DateTime.Today.ToShortDateString(); fillGrid(); } private void fillGrid() throws Exception { ScreenGroupList = ScreenGroups.Refresh(PIn.Date(textDateFrom.Text), PIn.Date(textDateTo.Text)); gridMain.beginUpdate(); gridMain.getColumns().Clear(); ODGridColumn col; col = new ODGridColumn(Lan.g(this,"Date"),70); gridMain.getColumns().add(col); col = new ODGridColumn(Lan.g(this,"Description"),140); gridMain.getColumns().add(col); gridMain.getRows().Clear(); OpenDental.UI.ODGridRow row; ListViewItem[] items = new ListViewItem[ScreenGroupList.Count]; for (int i = 0;i < items.Length;i++) { row = new OpenDental.UI.ODGridRow(); row.getCells().Add(ScreenGroupList[i].SGDate.ToShortDateString()); row.getCells().Add(ScreenGroupList[i].Description); gridMain.getRows().add(row); } gridMain.endUpdate(); } private void gridMain_CellDoubleClick(Object sender, OpenDental.UI.ODGridClickEventArgs e) throws Exception { FormScreenGroupEdit FormSG = new FormScreenGroupEdit(); FormSG.ScreenGroupCur = ScreenGroupList[gridMain.getSelectedIndex()]; FormSG.ShowDialog(); fillGrid(); } private void textDateFrom_Validating(Object sender, System.ComponentModel.CancelEventArgs e) throws Exception { if (StringSupport.equals(textDateFrom.Text, "")) return ; try { DateTime.Parse(textDateFrom.Text); } catch (Exception __dummyCatchVar0) { MessageBox.Show("Date invalid"); e.Cancel = true; } } private void textDateTo_Validating(Object sender, System.ComponentModel.CancelEventArgs e) throws Exception { if (StringSupport.equals(textDateTo.Text, "")) return ; try { DateTime.Parse(textDateTo.Text); } catch (Exception __dummyCatchVar1) { MessageBox.Show("Date invalid"); e.Cancel = true; } } private void butRefresh_Click(Object sender, System.EventArgs e) throws Exception { fillGrid(); } /* private void menuItemSetup_Click(object sender,EventArgs e) { FormScreenSetup FormSS=new FormScreenSetup(); FormSS.ShowDialog(); } */ private void butAdd_Click(Object sender, System.EventArgs e) throws Exception { FormScreenGroupEdit FormSG = new FormScreenGroupEdit(); FormSG.IsNew = true; //ScreenGroups.Cur=new ScreenGroup(); if (ScreenGroupList.Count == 0) { FormSG.ScreenGroupCur = new ScreenGroup(); } else { FormSG.ScreenGroupCur = ScreenGroupList[ScreenGroupList.Count - 1]; } //'remembers' the last entry FormSG.ScreenGroupCur.SGDate = DateTime.Today; //except date will be today FormSG.ShowDialog(); //if(FormSG.DialogResult!=DialogResult.OK){ // return; //} fillGrid(); } private void butToday_Click(Object sender, EventArgs e) throws Exception { dateCur = DateTime.Today; textDateFrom.Text = DateTime.Today.ToShortDateString(); textDateTo.Text = DateTime.Today.ToShortDateString(); } private void butLeft_Click(Object sender, EventArgs e) throws Exception { dateCur = dateCur.AddDays(-1); textDateFrom.Text = dateCur.ToShortDateString(); textDateTo.Text = dateCur.ToShortDateString(); } private void butRight_Click(Object sender, EventArgs e) throws Exception { dateCur = dateCur.AddDays(1); textDateFrom.Text = dateCur.ToShortDateString(); textDateTo.Text = dateCur.ToShortDateString(); } private void butDelete_Click(Object sender, System.EventArgs e) throws Exception { if (gridMain.getSelectedIndices().Length != 1) { MessageBox.Show("Please select one item first."); return ; } ScreenGroupCur = ScreenGroupList[gridMain.getSelectedIndex()]; OpenDentBusiness.Screen[] screenList = Screens.Refresh(ScreenGroupCur.ScreenGroupNum); if (screenList.Length > 0) { MessageBox.Show("Not allowed to delete a screening group with items in it."); return ; } ScreenGroups.Delete(ScreenGroupCur); fillGrid(); } private void butClose_Click(Object sender, EventArgs e) throws Exception { DialogResult = DialogResult.Cancel; } }
9e20a7ddc2991b71cf4e721685bb3832916b5f64
8b50d0492f737eac9153393838b8c9e808dbe78c
/src/main/java/com/byd/modules/oss/controller/SysOssController.java
8befe4d8304268d111dc63e14f6c4f8258170f59
[]
no_license
raafostrorn/byd
df2ea0111bf91653595c411652481779909435f2
3d55ebe3446b8fddb3b0e78967ae18472d4706e2
refs/heads/master
2023-06-02T05:13:16.338758
2021-06-15T13:30:18
2021-06-15T13:30:18
363,407,743
0
0
null
null
null
null
UTF-8
Java
false
false
3,870
java
package com.byd.modules.oss.controller; import com.byd.common.exception.RRException; import com.byd.common.utils.*; import com.byd.common.validator.ValidatorUtils; import com.byd.common.validator.group.AliyunGroup; import com.byd.common.validator.group.QcloudGroup; import com.byd.common.validator.group.QiniuGroup; import com.byd.modules.oss.cloud.CloudStorageConfig; import com.byd.modules.oss.cloud.OSSFactory; import com.byd.modules.oss.entity.SysOssEntity; import com.byd.modules.oss.service.SysOssService; import com.byd.modules.sys.service.SysConfigService; import com.google.gson.Gson; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.Date; import java.util.List; import java.util.Map; /** * 文件上传 * * @author chenshun * @email [email protected] * @date 2017-03-25 12:13:26 */ @RestController @RequestMapping("sys/oss") public class SysOssController { @Autowired private SysOssService sysOssService; @Autowired private SysConfigService sysConfigService; private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY; /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("sys:oss:all") public R list(@RequestParam Map<String, Object> params){ //查询列表数据 Query query = new Query(params); List<SysOssEntity> sysOssList = sysOssService.queryList(query); int total = sysOssService.queryTotal(query); PageUtils pageUtil = new PageUtils(sysOssList, total, query.getLimit(), query.getPage()); return R.ok().put("page", pageUtil); } /** * 云存储配置信息 */ @RequestMapping("/config") @RequiresPermissions("sys:oss:all") public R config(){ CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class); return R.ok().put("config", config); } /** * 保存云存储配置信息 */ @RequestMapping("/saveConfig") @RequiresPermissions("sys:oss:all") public R saveConfig(@RequestBody CloudStorageConfig config){ //校验类型 ValidatorUtils.validateEntity(config); if(config.getType() == Constant.CloudService.QINIU.getValue()){ //校验七牛数据 ValidatorUtils.validateEntity(config, QiniuGroup.class); }else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){ //校验阿里云数据 ValidatorUtils.validateEntity(config, AliyunGroup.class); }else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){ //校验腾讯云数据 ValidatorUtils.validateEntity(config, QcloudGroup.class); } sysConfigService.updateValueByKey(KEY, new Gson().toJson(config)); return R.ok(); } /** * 上传文件 */ @RequestMapping("/upload") @RequiresPermissions("sys:oss:all") public R upload(@RequestParam("file") MultipartFile file) throws Exception { if (file.isEmpty()) { throw new RRException("上传文件不能为空"); } //上传文件 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix); //保存文件信息 SysOssEntity ossEntity = new SysOssEntity(); ossEntity.setUrl(url); ossEntity.setCreateDate(new Date()); sysOssService.save(ossEntity); return R.ok().put("url", url); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("sys:oss:all") public R delete(@RequestBody Long[] ids){ sysOssService.deleteBatch(ids); return R.ok(); } }
9d28724b8a0f30e64b784cea5610a7b1a19694e6
6f2df7e148751a0985e35ff1e9cbba4796dbe5c8
/src/main/java/com/msco/mil/client/com/sencha/gxt/desktopapp/client/servicebus/ServiceProvider.java
7600b2befab9d57bc6ebb20e13719d0a2fdadba8
[]
no_license
gadisridhar/gxt-examples
942fd7c71d740b72d7690078f390de7358c4eb34
8d4a5464599d0c81057571a82f3d97916bdc2f72
refs/heads/master
2020-05-29T12:21:54.590033
2014-05-12T18:01:07
2014-05-12T18:01:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * [email protected] * * http://www.sencha.com/products/gxt/license/ */ package com.msco.mil.client.com.sencha.gxt.desktopapp.client.servicebus; public interface ServiceProvider<T extends ServiceRequest> { public void onServiceRequest(T serviceRequest); }
810fd864becc5e0eb7593e9d23e76530a104e711
8103d4ad4939517f4a47c23e7623d8c2ed668664
/src/main/java/actions/TopAction.java
34c6ffb68dd8e069d32cdfdca7f2701eb039d8fc
[]
no_license
MurakamiRyou/daily_report_system
4d5c5e9730b7aee4882f30317fe3935e13ee90d6
6d6102c5f04ba44c1c24e476739b48e11d65cdc5
refs/heads/main
2023-06-29T19:40:16.576000
2021-08-05T05:49:11
2021-08-05T05:49:11
389,856,039
0
0
null
null
null
null
UTF-8
Java
false
false
1,481
java
package actions; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import actions.views.ReportView; import constants.AttributeConst; import constants.ForwardConst; import constants.JpaConst; import services.ReportService; public class TopAction extends ActionBase { private ReportService service; public void process() throws ServletException, IOException { service = new ReportService(); invoke(); service.close(); } public void index() throws ServletException, IOException { //EmployeeView loginEmployee = (EmployeeView) getSessionScope(AttributeConst.LOGIN_EMP); int page = getPage(); // List<ReportView> reports = service.getMinePerPage(loginEmployee, page); // long myReportsCount = service.countAllMine(loginEmployee); List<ReportView> reports = service.getAllPerPage(page); long myReportsCount = service.countAll(); putRequestScope(AttributeConst.REPORTS, reports); //取得した日報データ putRequestScope(AttributeConst.REP_COUNT, myReportsCount); //ログイン中の従業員が作成した日報の数 putRequestScope(AttributeConst.PAGE, page); //ページ数 putRequestScope(AttributeConst.MAX_ROW, JpaConst.ROW_PER_PAGE); String flush = getSessionScope(AttributeConst.FLUSH); if (flush != null) { putRequestScope(AttributeConst.FLUSH, flush); removeSessionScope(AttributeConst.FLUSH); } forward(ForwardConst.FW_TOP_INDEX); } }
a521f9a818cbb220323f134244f50507c0a8b6c7
4b40066d48092bba23b29e2c012c8c4d3105ddfb
/src/main/java/es/tellier/recommander/api/exceptions/PeopleManipulationException.java
3a42b8b045ae60e1e921ee8e4c572e414128c7ab
[]
no_license
chibenwa/java-recommend
6cc316c361d3293fe2b28f535f2251fbc971a50a
34a46d4debaa19c87936f7cabb4fe691bc231b2e
refs/heads/master
2021-01-10T13:40:08.495341
2015-05-25T13:53:13
2015-05-25T20:27:01
36,253,070
1
0
null
null
null
null
UTF-8
Java
false
false
188
java
package es.tellier.recommander.api.exceptions; public class PeopleManipulationException extends Exception { public PeopleManipulationException(String s) { super(s); } }
294c48395875a27c61b1c8eebe07f7a574f657f1
a5bd3196428957f8c6a1598847cc6b3ea688e282
/app/src/main/java/com/example/yard/SplashActivity.java
181285b322986fd4308429038e3df0db9dd0b3ad
[]
no_license
LazyTechwork/youryard-android
61aaf27b39ba75eaa81559dcfe7b7480223e7d7e
c0b90299382f5ea7bc43e628ba284e84b4b9fcdc
refs/heads/master
2023-01-31T00:39:40.431563
2020-12-12T17:53:04
2020-12-12T17:53:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
957
java
package com.example.yard; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import androidx.appcompat.app.AppCompatActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); //JUST SPLASH ACTIVITY, NOTHING SPECIAL int milliseconds_delayed = 1200; new Handler().postDelayed(new Runnable() { @Override public void run() { if (Register.getDefaults("visited", SplashActivity.this) == null) { startActivity(new Intent(SplashActivity.this, Login.class)); } else { startActivity(new Intent(SplashActivity.this, MainActivity.class)); } finish(); } }, milliseconds_delayed); } }
2b7fb84ebe4a442d35f55b7bd06097a7726668dd
d154d3dd32aabc70e1ba8425eaf4cdc33baf2b26
/src/main/java/com/another/Goodsprolist/controller/GoodsprolistController.java
c312b80f7cee79b1a470f490e111f7ce6eef5dcf
[]
no_license
fushanlin/ZJ
d177d1178198b3173f759276333800385b2c592c
2a543b3afb38aceb60ec96b66ee712d9e43121c7
refs/heads/master
2021-07-10T00:45:49.201681
2017-10-09T11:45:10
2017-10-09T11:45:11
106,276,177
0
0
null
null
null
null
UTF-8
Java
false
false
3,182
java
package com.another.Goodsprolist.controller; import com.another.base.common.ResultCode; import com.another.base.entity.Json; import com.another.base.entity.Page; import com.another.Goodsprolist.common.GoodsprolistMessage; import com.another.Goodsprolist.entity.Goodsprolist; import com.another.Goodsprolist.pageModel.PageGoodsprolist; import com.another.Goodsprolist.service.GoodsprolistService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * */ @RestController @RequestMapping("/Goodsprolist") public class GoodsprolistController { @Autowired GoodsprolistService GoodsprolistService; Logger logger = Logger.getLogger(this.getClass()); @RequestMapping(value = "/addGoodsprolist", method = RequestMethod.POST) @ResponseBody public Json addGoodsprolist(@RequestBody PageGoodsprolist pageGoodsprolist){ Json json = new Json(); try { GoodsprolistService.addGoodsprolist(pageGoodsprolist); json.setCode(ResultCode.SUCCESS_CODE); }catch (Exception ex){ logger.error(ex); json.setCode(ResultCode.FAILURE_CODE).setMsg(GoodsprolistMessage.ADD_ERROR_MSG); } return json; } @RequestMapping(value = "/deleteGoodsprolistById", method = RequestMethod.POST) @ResponseBody public Json deleteGoodsprolist(@RequestBody PageGoodsprolist pageGoodsprolist){ Json json = new Json(); try { GoodsprolistService.deleteGoodsprolistById(pageGoodsprolist); json.setCode(ResultCode.SUCCESS_CODE); }catch (Exception ex){ logger.error(ex); json.setCode(ResultCode.FAILURE_CODE).setMsg(GoodsprolistMessage.DELETE_ERROR_MSG); } return json; } @RequestMapping(value = "/getGoodsprolistList", method = RequestMethod.POST) @ResponseBody public Json getGoodsprolist(@RequestBody PageGoodsprolist pageGoodsprolist){ Json json = new Json(); Page<Goodsprolist> page = GoodsprolistService.getGoodsprolistList(pageGoodsprolist); json.setCode(ResultCode.SUCCESS_CODE).setData(page); return json; } @RequestMapping(value = "/getGoodsprolistById", method = RequestMethod.POST) @ResponseBody public Json getGoodsprolistById(@RequestBody PageGoodsprolist pageGoodsprolist){ Json json = new Json(); Goodsprolist rGoodsprolist= GoodsprolistService.getGoodsprolistById(pageGoodsprolist); json.setCode(ResultCode.SUCCESS_CODE).setData(rGoodsprolist); return json; } @RequestMapping(value = "/updateGoodsprolist", method = RequestMethod.POST) @ResponseBody public Json updateGoodsprolist(@RequestBody PageGoodsprolist pageGoodsprolist){ Json json = new Json(); try { GoodsprolistService.updateGoodsprolist(pageGoodsprolist); json.setCode(ResultCode.SUCCESS_CODE); }catch (Exception ex){ logger.error(ex); json.setCode(ResultCode.FAILURE_CODE).setMsg(GoodsprolistMessage.UPDATE_ERROR_MSG); } return json; } }
e4136d8c66e80eb91355d26fe8ebd1a7a149b541
8740b13932b1f19d213ad6a99be5d907e1f12bc5
/src/com/mraof/minestuck/inventory/captchalouge/SetModus.java
039a24eab116116434d36b4d711f3558e97f24c9
[]
no_license
Padamariuse/Minestuck
eb89e55a94989b7cb50f9f03d8f24525d8f2c314
bc74f85bd766881e8151fc7f196599de0a0afeb7
refs/heads/1.12
2021-06-26T12:59:41.390650
2019-06-22T21:13:25
2019-06-22T21:13:25
151,946,739
3
0
null
2019-04-18T07:25:18
2018-10-07T13:54:02
Java
UTF-8
Java
false
false
4,137
java
package com.mraof.minestuck.inventory.captchalouge; import com.mraof.minestuck.MinestuckConfig; import com.mraof.minestuck.client.gui.captchalouge.SetGuiHandler; import com.mraof.minestuck.client.gui.captchalouge.SylladexGuiHandler; import com.mraof.minestuck.item.MinestuckItems; import com.mraof.minestuck.alchemy.AlchemyRecipes; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Iterator; public class SetModus extends Modus { protected int size; protected NonNullList<ItemStack> list; @SideOnly(Side.CLIENT) protected boolean changed; @SideOnly(Side.CLIENT) protected NonNullList<ItemStack> items; @SideOnly(Side.CLIENT) protected SylladexGuiHandler gui; @Override public void initModus(NonNullList<ItemStack> prev, int size) { this.size = size; list = NonNullList.<ItemStack>create(); /*if(prev != null) { for(ItemStack stack : prev) if(stack != null) list.add(stack); }*/ if(player.world.isRemote) { items = NonNullList.<ItemStack>create(); changed = true; } } @Override public void readFromNBT(NBTTagCompound nbt) { size = nbt.getInteger("size"); list = NonNullList.<ItemStack>create(); for(int i = 0; i < size; i++) if(nbt.hasKey("item"+i)) list.add(new ItemStack(nbt.getCompoundTag("item"+i))); else break; if(side.isClient()) { if(items == null) items = NonNullList.create(); changed = true; } } @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt.setInteger("size", size); Iterator<ItemStack> iter = list.iterator(); for(int i = 0; i < list.size(); i++) { ItemStack stack = iter.next(); nbt.setTag("item"+i, stack.writeToNBT(new NBTTagCompound())); } return nbt; } @Override public boolean putItemStack(ItemStack item) { if(size <= list.size() || item.isEmpty()) return false; for(ItemStack stack : list) if(stack.getItem() == item.getItem() && (!stack.getHasSubtypes() || stack.getMetadata() == item.getMetadata())) { CaptchaDeckHandler.launchItem(player, item); return true; } if(item.getCount() > 1) { ItemStack stack = item.copy(); stack.shrink(1); item.setCount(1); CaptchaDeckHandler.launchItem(player, stack); } list.add(item); return true; } @Override public NonNullList<ItemStack> getItems() { if(side.isServer()) //Used only when replacing the modus { NonNullList<ItemStack> items = NonNullList.<ItemStack>create(); fillList(items); return items; } if(changed) { fillList(items); } return items; } protected void fillList(NonNullList<ItemStack> items) { items.clear(); Iterator<ItemStack> iter = list.iterator(); for(int i = 0; i < size; i++) if(iter.hasNext()) items.add(iter.next()); else items.add(ItemStack.EMPTY); } @Override public boolean increaseSize() { if(MinestuckConfig.modusMaxSize > 0 && size >= MinestuckConfig.modusMaxSize) return false; size++; return true; } @Override public ItemStack getItem(int id, boolean asCard) { if(id == CaptchaDeckHandler.EMPTY_CARD) { if(list.size() < size) { size--; return new ItemStack(MinestuckItems.captchaCard); } else return ItemStack.EMPTY; } if(list.isEmpty()) return ItemStack.EMPTY; if(id == CaptchaDeckHandler.EMPTY_SYLLADEX) { for(ItemStack item : list) CaptchaDeckHandler.launchAnyItem(player, item); list.clear(); return ItemStack.EMPTY; } if(id < 0 || id >= list.size()) return ItemStack.EMPTY; ItemStack item = list.remove(id); if(asCard) { size--; item = AlchemyRecipes.createCard(item, false); } return item; } @Override public boolean canSwitchFrom(Modus modus) { return false; } @Override public int getSize() { return size; } @Override @SideOnly(Side.CLIENT) public SylladexGuiHandler getGuiHandler() { if(gui == null) gui = new SetGuiHandler(this); return gui; } }
a844ad0c8613764212f33efceb8c8c38b27e466b
b0c84538bc16e3e28c2ac4fd2ba2056286227a2e
/JProbe/src/chiptools/jprobe/function/SequencesArg.java
6edcc13e75c4008202c8a48ad2ed0e4e947462d9
[]
no_license
tiffanydho/JProbe
a3247ac4dd692a6236834ff39484b3026cf19724
c375d440522951d8bc47b0472c1d7d91dcce85a3
refs/heads/master
2020-03-23T14:07:45.426730
2018-12-05T18:10:40
2018-12-05T18:10:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,496
java
package chiptools.jprobe.function; import java.awt.GridBagConstraints; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import chiptools.Constants; import chiptools.jprobe.ChiptoolsActivator; import jprobe.services.ErrorHandler; import jprobe.services.function.Function; public abstract class SequencesArg<P> extends ChiptoolsFileArg<P>{ private final JPanel m_Panel = new JPanel(); @SuppressWarnings("rawtypes") protected SequencesArg(Class<? extends Function> funcClass, Class<? extends SequencesArg> clazz, boolean optional) { super(funcClass, clazz, optional); m_Panel.setLayout(new BoxLayout(m_Panel, BoxLayout.Y_AXIS)); } abstract protected void process(P params, List<String> seqs, String fileName); @Override protected void setFile(File f){ m_Panel.removeAll(); int count = 0; for(String s : readFile(f)){ if(count >= Constants.SEQS_ARG_MAX_DISPLAY){ m_Panel.add(new JLabel("...")); break; } m_Panel.add(new JLabel(s)); ++count; } super.setFile(f); SwingUtilities.getWindowAncestor(m_Panel).pack(); } protected List<String> readFile(File f){ List<String> seqs = new ArrayList<String>(); try { BufferedReader reader = new BufferedReader(new FileReader(f)); try{ String line; while((line = reader.readLine()) != null){ if(!line.startsWith(">")){ seqs.add(line); } } }catch(Exception e){ ErrorHandler.getInstance().handleException(e, ChiptoolsActivator.getBundle()); } reader.close(); } catch (Exception e1) { ErrorHandler.getInstance().handleException(e1, ChiptoolsActivator.getBundle()); } return seqs; } @Override public JComponent getComponent(){ JComponent comp = super.getComponent(); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.HORIZONTAL; comp.add(m_Panel, gbc); return comp; } @Override protected boolean isValid(File f) { return f != null && f.exists() && f.canRead(); } @Override protected void process(P params, File f) { List<String> seqs = this.readFile(f); String fileName = f.getName(); String name = fileName.substring(0, fileName.lastIndexOf('.')); this.process(params, seqs, name); } }
405c7ee279f65e2fda68c850346628015cd9dc20
ce8c6b6c9dd9db0ebdb82cb40f6b954ea9649971
/bootstrap/src/main/java/boot/service/DeptManagerService.java
8e5693cfc5fee1ab4e5e51bbef0c21f8fc6456d2
[]
no_license
roza-sara-hurta/unidad-4-ordinario-spring
31defccf9904b34c9ee90cd5d728e0a04ad7dcf4
d13895e7622a1a75a8a736114ba9c1684b8c1890
refs/heads/master
2020-06-21T10:23:45.724419
2016-11-25T22:24:48
2016-11-25T22:24:48
74,791,079
0
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package boot.service; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import boot.dao.DeptManagerRepository; import boot.model.DeptManager; @Service @Transactional public class DeptManagerService { private final DeptManagerRepository deptManagerRepository; public DeptManagerService(DeptManagerRepository deptManagerRepository){ super(); this.deptManagerRepository= deptManagerRepository; } public List <DeptManager> findAll(){ List<DeptManager> deptManagers = new ArrayList<DeptManager>(); for(DeptManager deptManager : deptManagerRepository.findAll()){ deptManagers.add(deptManager); } return deptManagers; } public void save(DeptManager deptManager){ deptManagerRepository.save(deptManager); } public void delete(int id){ deptManagerRepository.delete(id); } public DeptManager finOne(int id){ return deptManagerRepository.findOne(id); } }
ab8a11def825ffcbb1eaab1c84cb7d74dc7fb75d
4783239122c9958696655f7e446f2e74b9846f71
/src/main/java/ru/betterend/util/BonemealUtil.java
c604aaa40b410613e3b740c057c23a20375eff4e
[ "MIT" ]
permissive
burned-salmon/BetterEnd
4ea80d53e987a9bb99426181bad719407b48bfa8
f7421bc055858af74a9693f20b0bf8e6b8f75b61
refs/heads/master
2023-07-06T11:09:28.541256
2021-01-18T17:09:13
2021-01-18T17:09:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,759
java
package ru.betterend.util; import java.util.List; import java.util.Map; import java.util.Random; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.block.Block; import ru.betterend.registry.EndBlocks; public class BonemealUtil { private static final Map<Block, GrassList> GRASS_TYPES = Maps.newHashMap(); public static void init() { addBonemealGrass(EndBlocks.END_MOSS, EndBlocks.CREEPING_MOSS); addBonemealGrass(EndBlocks.END_MOSS, EndBlocks.UMBRELLA_MOSS); addBonemealGrass(EndBlocks.END_MYCELIUM, EndBlocks.CREEPING_MOSS); addBonemealGrass(EndBlocks.END_MYCELIUM, EndBlocks.UMBRELLA_MOSS); addBonemealGrass(EndBlocks.CAVE_MOSS, EndBlocks.CAVE_GRASS); addBonemealGrass(EndBlocks.CHORUS_NYLIUM, EndBlocks.CHORUS_GRASS); addBonemealGrass(EndBlocks.CRYSTAL_MOSS, EndBlocks.CRYSTAL_GRASS); addBonemealGrass(EndBlocks.SHADOW_GRASS, EndBlocks.SHADOW_PLANT); addBonemealGrass(EndBlocks.PINK_MOSS, EndBlocks.BUSHY_GRASS); addBonemealGrass(EndBlocks.AMBER_MOSS, EndBlocks.AMBER_GRASS); addBonemealGrass(EndBlocks.JUNGLE_MOSS, EndBlocks.JUNGLE_GRASS); addBonemealGrass(EndBlocks.JUNGLE_MOSS, EndBlocks.TWISTED_UMBRELLA_MOSS); addBonemealGrass(EndBlocks.JUNGLE_MOSS, EndBlocks.SMALL_JELLYSHROOM, 0.1F); } public static void addBonemealGrass(Block terrain, Block plant) { addBonemealGrass(terrain, plant, 1F); } public static void addBonemealGrass(Block terrain, Block plant, float chance) { GrassList list = GRASS_TYPES.get(terrain); if (list == null) { list = new GrassList(); GRASS_TYPES.put(terrain, list); } list.addGrass(plant, chance); } public static Block getGrass(Block terrain, Random random) { GrassList list = GRASS_TYPES.get(terrain); return list == null ? null : list.getGrass(random); } private static final class GrassInfo { final Block grass; float chance; public GrassInfo(Block grass, float chance) { this.grass = grass; this.chance = chance; } public float addChance(float chance) { this.chance += chance; return this.chance; } } private static final class GrassList { final List<GrassInfo> list = Lists.newArrayList(); float maxChance = 0; public void addGrass(Block grass, float chance) { GrassInfo info = new GrassInfo(grass, chance); maxChance = info.addChance(maxChance); list.add(info); } public Block getGrass(Random random) { if (maxChance == 0 || list.isEmpty()) { return null; } float chance = random.nextFloat() * maxChance; for (GrassInfo info: list) { if (chance <= info.chance) { return info.grass; } } return null; } } }
fe33f62d09a6dd34ad41edc09ebe0fd0fb56073b
236553b7cd6ad1a79a41d53cd41bd3f470ced6c6
/src/main/java/org/apache/ibatis/executor/resultset/ResultSetWrapper.java
92dbd5f04eb499250334d73396f2c65eb50698c5
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
kongq1983/mybatis352
0d75815c551f1755b728a4c742313f5108d938d9
16ee87ad86963b2d8f5ac92b5b00bf089c11de20
refs/heads/master
2023-04-21T02:11:27.532051
2020-12-14T02:50:24
2020-12-14T02:50:24
297,322,471
0
0
null
null
null
null
UTF-8
Java
false
false
7,472
java
/** * Copyright 2009-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.ibatis.executor.resultset; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.ResultMap; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.ObjectTypeHandler; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; import org.apache.ibatis.type.UnknownTypeHandler; /** * @author Iwao AVE! */ public class ResultSetWrapper { private final ResultSet resultSet; private final TypeHandlerRegistry typeHandlerRegistry; private final List<String> columnNames = new ArrayList<>(); private final List<String> classNames = new ArrayList<>(); private final List<JdbcType> jdbcTypes = new ArrayList<>(); private final Map<String, Map<Class<?>, TypeHandler<?>>> typeHandlerMap = new HashMap<>(); private final Map<String, List<String>> mappedColumnNamesMap = new HashMap<>(); private final Map<String, List<String>> unMappedColumnNamesMap = new HashMap<>(); public ResultSetWrapper(ResultSet rs, Configuration configuration) throws SQLException { super(); this.typeHandlerRegistry = configuration.getTypeHandlerRegistry(); this.resultSet = rs; final ResultSetMetaData metaData = rs.getMetaData(); final int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { columnNames.add(configuration.isUseColumnLabel() ? metaData.getColumnLabel(i) : metaData.getColumnName(i)); //获得sql语句的列名 jdbcTypes.add(JdbcType.forCode(metaData.getColumnType(i))); // 获得jdbc类型 classNames.add(metaData.getColumnClassName(i)); // 获得该字段的java类型 } } public ResultSet getResultSet() { return resultSet; } public List<String> getColumnNames() { return this.columnNames; } public List<String> getClassNames() { return Collections.unmodifiableList(classNames); } public List<JdbcType> getJdbcTypes() { return jdbcTypes; } public JdbcType getJdbcType(String columnName) { for (int i = 0 ; i < columnNames.size(); i++) { if (columnNames.get(i).equalsIgnoreCase(columnName)) { return jdbcTypes.get(i); } } return null; } /** * Gets the type handler to use when reading the result set. * Tries to get from the TypeHandlerRegistry by searching for the property type. * If not found it gets the column JDBC type and tries to get a handler for it. * * @param propertyType * @param columnName * @return */ public TypeHandler<?> getTypeHandler(Class<?> propertyType, String columnName) { TypeHandler<?> handler = null; Map<Class<?>, TypeHandler<?>> columnHandlers = typeHandlerMap.get(columnName); if (columnHandlers == null) { columnHandlers = new HashMap<>(); typeHandlerMap.put(columnName, columnHandlers); } else { handler = columnHandlers.get(propertyType); } if (handler == null) { JdbcType jdbcType = getJdbcType(columnName); handler = typeHandlerRegistry.getTypeHandler(propertyType, jdbcType); // Replicate logic of UnknownTypeHandler#resolveTypeHandler // See issue #59 comment 10 if (handler == null || handler instanceof UnknownTypeHandler) { final int index = columnNames.indexOf(columnName); final Class<?> javaType = resolveClass(classNames.get(index)); if (javaType != null && jdbcType != null) { handler = typeHandlerRegistry.getTypeHandler(javaType, jdbcType); } else if (javaType != null) { handler = typeHandlerRegistry.getTypeHandler(javaType); } else if (jdbcType != null) { handler = typeHandlerRegistry.getTypeHandler(jdbcType); } } if (handler == null || handler instanceof UnknownTypeHandler) { handler = new ObjectTypeHandler(); } columnHandlers.put(propertyType, handler); } return handler; } private Class<?> resolveClass(String className) { try { // #699 className could be null if (className != null) { return Resources.classForName(className); } } catch (ClassNotFoundException e) { // ignore } return null; } private void loadMappedAndUnmappedColumnNames(ResultMap resultMap, String columnPrefix) throws SQLException { List<String> mappedColumnNames = new ArrayList<>(); List<String> unmappedColumnNames = new ArrayList<>(); final String upperColumnPrefix = columnPrefix == null ? null : columnPrefix.toUpperCase(Locale.ENGLISH); final Set<String> mappedColumns = prependPrefixes(resultMap.getMappedColumns(), upperColumnPrefix); for (String columnName : columnNames) { final String upperColumnName = columnName.toUpperCase(Locale.ENGLISH); if (mappedColumns.contains(upperColumnName)) { mappedColumnNames.add(upperColumnName); } else { unmappedColumnNames.add(columnName); } } mappedColumnNamesMap.put(getMapKey(resultMap, columnPrefix), mappedColumnNames); unMappedColumnNamesMap.put(getMapKey(resultMap, columnPrefix), unmappedColumnNames); } public List<String> getMappedColumnNames(ResultMap resultMap, String columnPrefix) throws SQLException { List<String> mappedColumnNames = mappedColumnNamesMap.get(getMapKey(resultMap, columnPrefix)); if (mappedColumnNames == null) { loadMappedAndUnmappedColumnNames(resultMap, columnPrefix); mappedColumnNames = mappedColumnNamesMap.get(getMapKey(resultMap, columnPrefix)); } return mappedColumnNames; } public List<String> getUnmappedColumnNames(ResultMap resultMap, String columnPrefix) throws SQLException { List<String> unMappedColumnNames = unMappedColumnNamesMap.get(getMapKey(resultMap, columnPrefix)); if (unMappedColumnNames == null) { loadMappedAndUnmappedColumnNames(resultMap, columnPrefix); unMappedColumnNames = unMappedColumnNamesMap.get(getMapKey(resultMap, columnPrefix)); } return unMappedColumnNames; } private String getMapKey(ResultMap resultMap, String columnPrefix) { return resultMap.getId() + ":" + columnPrefix; } private Set<String> prependPrefixes(Set<String> columnNames, String prefix) { if (columnNames == null || columnNames.isEmpty() || prefix == null || prefix.length() == 0) { return columnNames; } final Set<String> prefixed = new HashSet<>(); for (String columnName : columnNames) { prefixed.add(prefix + columnName); } return prefixed; } }
bcb89fa7103addf083f6f1244eabeea0812a6fcb
a47333cea615e44b8f1254bde905bb10de160cca
/T/t-dal/src/main/java/com/zillionfortune/t/dal/dao/ScoreDao.java
1c1d585b5fb0023a54f78e92af8c1d858ea62300
[]
no_license
zb-ty-system/qiyelicai
ce942faa27a84b7b12ed3e206da8fcaf14bf743d
765be984c988d17c03d59fba2a7702ba8b80e2da
refs/heads/master
2020-05-02T02:13:23.129269
2019-03-26T02:28:08
2019-03-26T02:28:08
177,699,797
0
2
null
null
null
null
UTF-8
Java
false
false
549
java
package com.zillionfortune.t.dal.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.zillionfortune.t.dal.entity.Score; @Repository public interface ScoreDao { int deleteByPrimaryKey(Long id); int insert(Score record); int insertSelective(Score record); Score selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Score record); int updateByPrimaryKey(Score record); List<Score> selectByCriteria(Score record); int updateByMemberIdSelective(Score record); }
fbb99b605c8061f3493e706aa931558a3ba5ae7d
62fbdb2171719b12f8b08ac8716a43d1ed914623
/src/by/it/voronko/jd01_01/Hello.java
58adbcc9e6f31fa3506b231bdedb7a4bde5bd543
[]
no_license
DmitryMarus/JD2021-04-21
2eea39f1658ff639326c35b4acdda2f079aa74e4
7b83a62133dd978a7751517843f096fae43aedf2
refs/heads/master
2023-06-10T21:22:51.794722
2021-07-06T21:00:47
2021-07-06T21:00:47
365,497,418
0
0
null
null
null
null
UTF-8
Java
false
false
253
java
package by.it.voronko.jd01_01; public class Hello { private String slogan = "Hello world"; public void setSlogan(String slogan) { this.slogan = slogan; } public void printSlogan(){ System.out.println(slogan); } }
e17ee5e7f47d6d6e3934216fc0fc5f1e31b76bec
a46809ebc645c82c2651724a6db45179c3fed1e0
/src/main/java/com/sda/serwisaukcyjnybackend/application/auction/exception/CannotRatePurchaseException.java
630b2cc834ac236c862a099d19b1bee9f7939977
[]
no_license
Dregosh/Serwis-Aukcyjny-Backend
d5efd62c691bc79075b22826e3924151bf16233e
6299e8d1425ccbe58181f97033f0d67c8db62334
refs/heads/main
2023-03-19T18:53:11.049471
2021-03-09T11:29:54
2021-03-09T11:29:54
330,576,022
0
0
null
null
null
null
UTF-8
Java
false
false
299
java
package com.sda.serwisaukcyjnybackend.application.auction.exception; public class CannotRatePurchaseException extends RuntimeException { public CannotRatePurchaseException(Long purchaseId, String cause) { super(String.format("Cannot rate purchase %d - %s", purchaseId, cause)); } }
981dc399f5523c076952b9cef1e5152d6cf06d72
7a0d50cccff77200b2dbcd7a720ece25d4c45d3e
/OnlineBanking/src/main/java/com/valuelabs/service/LoginServiceImpl.java
c84afb5a2aa8cf75d51b84311a158e6c3eb4eb63
[]
no_license
SrujanaMedagam/Test
022a50e66ffa447aeb4bb56625d04bb5d44291d0
32266968da8b31d5bbd434631e806525c3757bd3
refs/heads/master
2021-09-11T17:46:25.487317
2018-04-10T13:17:10
2018-04-10T13:17:10
116,675,164
0
0
null
2018-04-10T12:03:27
2018-01-08T12:42:08
Roff
UTF-8
Java
false
false
4,399
java
package com.valuelabs.service; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.valuelabs.bean.AccountDetailsBean; import com.valuelabs.bean.LoginDetailsBean; import com.valuelabs.dao.LoginDao; @Service("loginService") public class LoginServiceImpl implements LoginService { @Autowired(required = true) LoginDao loginDao; @Autowired(required = true) LoginDetailsBean loginDetailsBean; @Autowired(required = true) AccountDetailsBean accountDetailsBean; @Override public boolean checkUserLoginCredentials(String username, String password) { List list = loginDao.checkLoginCredentials(username, password); Iterator<String> iterator = list.iterator(); if (!list.isEmpty()) { return true; } return false; } @Override public boolean checkIsAccountNumber(String accountNumber) { List list = loginDao.checkIsAccountNumber(accountNumber); Iterator<String> iterator = list.iterator(); if (list.isEmpty()) { return true; } return false; } @Override public List checkIsValidAccountNumber(String accountNumber) { List list = loginDao.checkIsAccountNumber(accountNumber); return list; } @Override public boolean checkUserId(String username) { List list = loginDao.checkIsUsername(username); Iterator<String> iterator = list.iterator(); if (list.isEmpty()) { return true; } return false; } @Override public String checkUserAccountNumber(String username, String password) { String accountNumber = null; List list = loginDao.checkLoginCredentials(username, password); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { accountNumber = iterator.next(); } return accountNumber; } public boolean newUserPermission(String accountNumber, String accountName, String username, String password, String address, String emailId, int phoneNumber, String panNumber, int aadharNumber, String accountType, String date) { loginDetailsBean.setAccountNumber(accountNumber); loginDetailsBean.setAccountName(accountName); loginDetailsBean.setUsername(username); loginDetailsBean.setPassword(password); loginDetailsBean.setAddress(address); loginDetailsBean.setEmailId(emailId); loginDetailsBean.setPhoneNumber(phoneNumber); loginDetailsBean.setPanNumber(panNumber); loginDetailsBean.setAadharNumber(aadharNumber); loginDetailsBean.setAccountType(accountType); loginDetailsBean.setAccountOpenDate(date); accountDetailsBean.setAccNumber(accountNumber); accountDetailsBean.setAccName(accountName); accountDetailsBean.setStatusOfAccount("Active"); accountDetailsBean.setAccountOpenDate(date); accountDetailsBean.setAccountType(accountType); if (loginDao.newUserPermissionInfo(loginDetailsBean, accountDetailsBean)) { return true; } return false; } @Override public String getAccountNumber(String username, String password) { String accountNumber = ""; List list = loginDao.getAccountNumber(username, password); Iterator iterator = list.iterator(); while (iterator.hasNext()) { accountNumber = (String) iterator.next(); } return accountNumber; } @Override public boolean isAccountNumber(String username, String password) { int accountNumber = 0; List list = loginDao.getAccountNumber(username, password); Iterator iterator = list.iterator(); if (list.isEmpty()) { return false; } return true; } @Override public List getProfileData(String accountNumber) { List list = loginDao.getProfile(accountNumber); return list; } @Override public boolean getProfileUpdate(String accountNumber, String address, String emailId, int phoneNumber, String panNumber, int aadharNumber) { // loginDao.profileUpdate(con.getConnection(),accountNumber,address,emailId,phoneNumber,panNumber,aadharNumber); return loginDao.profileUpdate(address, emailId, phoneNumber, panNumber, aadharNumber, accountNumber); } /* * @Override public boolean getEmail(String username, String password) { * List list = loginDao.checkLoginCredentials(username, password); * Iterator<String> iterator = list.iterator(); if (!list.isEmpty()) { * return true; } return false; * * } * */ }
48e85695985a8b4348efb6a4879c1d71a00814ae
b9f800da20b0da6a91f3368a0e87ee3967ee7165
/OOP Advanced/Annotations/src/com/annotations/Human.java
c0320b1b72ada80695f8d2a975e10157e78fa70c
[]
no_license
marinaskevin/CodingDojo-JavaAcademy
e8ea83c233a39908990cf28d7711995b5921a696
74cc14e94540297d449543a4b74b8558641c5694
refs/heads/master
2020-06-17T08:26:07.127595
2019-10-22T06:50:54
2019-10-22T06:50:54
195,860,723
0
0
null
null
null
null
UTF-8
Java
false
false
189
java
package com.annotations; public class Human { private String name; public String getName(){ return name; } public void setName(String n){ name = n; } }
85246b9a9b4dd3ca7a66eec44c41c3ac52c8177b
20bb49c60f5c9c1290f08f9199c3ecca6146e9c3
/src/main/java/top/minecode/exception/NameExistedException.java
6cdde7f2b68bf2c9c7d2fb17910a79f33cce8f11
[]
no_license
NJULighting/NaiveTag_Phase_II
9f805dda2b847942623b70ae28480f0c93e56818
44cd966690d89c9e7a509326f62d3fd29fde41cd
refs/heads/master
2020-03-20T21:55:57.767456
2018-05-07T09:36:12
2018-05-07T09:36:12
137,769,082
0
0
null
null
null
null
UTF-8
Java
false
false
158
java
package top.minecode.exception; /** * Created on 2018/4/2. * Description: * * @author iznauy */ public class NameExistedException extends Exception { }
56d0fc2c2e8d4f5d4cc9ff556a63a10beb53c91b
b7208e9cbfa987e4f5280bbdcb4eb68139a33a1c
/imagepicker/src/main/java/com/lzy/imagepicker/loader/UILImageLoader.java
9ba256af6adc06f39a20ade4047b5b0082d8d796
[]
no_license
gyadministrator/ImageRecyclerView
e4808c4c6b56cf1a2c45412e628dcb58e10ef7f1
68d60ea969acd4e995ffa16bbb8853ce95ad8c5d
refs/heads/master
2023-01-07T01:52:37.930126
2020-11-11T08:26:17
2020-11-11T08:26:17
311,840,426
0
0
null
null
null
null
UTF-8
Java
false
false
1,277
java
package com.lzy.imagepicker.loader; /** * ================================================ * 作 者:jeasonlzy(廖子尧) * 版 本:1.0 * 创建日期:2016/3/28 * 描 述:我的Github地址 https://github.com/jeasonlzy0216 * 修订历史: * ================================================ */ import android.app.Activity; import android.net.Uri; import android.widget.ImageView; import com.nostra13.universalimageloader.core.assist.ImageSize; import java.io.File; public class UILImageLoader implements ImageLoader { @Override public void displayImage(Activity activity, String path, ImageView imageView, int width, int height) { ImageSize size = new ImageSize(width, height); com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(Uri.fromFile(new File(path)).toString(), imageView, size); } @Override public void displayImagePreview(Activity activity, String path, ImageView imageView, int width, int height) { ImageSize size = new ImageSize(width, height); com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(Uri.fromFile(new File(path)).toString(), imageView, size); } @Override public void clearMemoryCache() { } }
86da4c23e56ca532befc256a5b6fe170ba72c5c1
2e76ee7edbb7fd762bc28bfb3874c799139e3ae1
/app/src/main/java/com/yunyou/icloudinn/bookhouse/JavaBean/BookCollectData.java
9d35e04cc6512028ea1d494e811537e633b5ba6e
[]
no_license
ypl1306961052/bt
c47f1f2460bc381c424cc70f1869c8e33804e24e
7a4e3ba26146daae07edf06f686dbdd950112147
refs/heads/master
2020-03-27T15:54:34.817777
2018-08-30T12:32:54
2018-08-30T12:32:54
146,746,805
0
0
null
null
null
null
UTF-8
Java
false
false
11,613
java
package com.yunyou.icloudinn.bookhouse.JavaBean; import java.util.List; public class BookCollectData { /** * code : 100 * msg : success */ private int code; private String msg; private DataBeanX data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public DataBeanX getData() { return data; } public void setData(DataBeanX data) { this.data = data; } public static class DataBeanX { /** * total : 2 * per_page : 20 * current_page : 1 * last_page : 1 */ private int total; private int per_page; private int current_page; private int last_page; private List<DataBean> data; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getPer_page() { return per_page; } public void setPer_page(int per_page) { this.per_page = per_page; } public int getCurrent_page() { return current_page; } public void setCurrent_page(int current_page) { this.current_page = current_page; } public int getLast_page() { return last_page; } public void setLast_page(int last_page) { this.last_page = last_page; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { /** * id : 213 * source_id : 58 * user_id : 12142941 * type : 2 * create_time : 0 * update_time : 0 */ private int id; private int source_id; private int user_id; private int type; private int create_time; private int update_time; private BookBean book; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getSource_id() { return source_id; } public void setSource_id(int source_id) { this.source_id = source_id; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getCreate_time() { return create_time; } public void setCreate_time(int create_time) { this.create_time = create_time; } public int getUpdate_time() { return update_time; } public void setUpdate_time(int update_time) { this.update_time = update_time; } public BookBean getBook() { return book; } public void setBook(BookBean book) { this.book = book; } public static class BookBean { /** * id : 58 * model_id : 18 * book_house_id : 1 * price : 25 * status : 1 * read_num : 762 * rent_num : 0 * renting_user : * create_time : 1496200858 */ private int id; private int model_id; private int book_house_id; private int price; private int status; private int read_num; private int rent_num; private String renting_user; private String create_time; private ModelBean model; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getModel_id() { return model_id; } public void setModel_id(int model_id) { this.model_id = model_id; } public int getBook_house_id() { return book_house_id; } public void setBook_house_id(int book_house_id) { this.book_house_id = book_house_id; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getRead_num() { return read_num; } public void setRead_num(int read_num) { this.read_num = read_num; } public int getRent_num() { return rent_num; } public void setRent_num(int rent_num) { this.rent_num = rent_num; } public String getRenting_user() { return renting_user; } public void setRenting_user(String renting_user) { this.renting_user = renting_user; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public ModelBean getModel() { return model; } public void setModel(ModelBean model) { this.model = model; } public static class ModelBean { /** * id : 18 * name : 人性的弱点 * auther : 戴尔·卡耐基 * edition : 无 * nationality : [美] * cover_img : /uploads/20170531/0e0b27e5938cbf59fb2367ee37cfd8c9.jpg * publisher : 中国发展出版社 * publish_time : null * category_id : 5 * intro : <p>适当放松的方式的 &nbsp; &nbsp; &nbsp;</p> * status : 1 * create_time : 1496200858 * update_time : 1499161541 */ private int id; private String name; private String auther; private String edition; private String nationality; private String cover_img; private String publisher; private Object publish_time; private int category_id; private String intro; private int status; private int create_time; private int update_time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuther() { return auther; } public void setAuther(String auther) { this.auther = auther; } public String getEdition() { return edition; } public void setEdition(String edition) { this.edition = edition; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getCover_img() { return cover_img; } public void setCover_img(String cover_img) { this.cover_img = cover_img; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public Object getPublish_time() { return publish_time; } public void setPublish_time(Object publish_time) { this.publish_time = publish_time; } public int getCategory_id() { return category_id; } public void setCategory_id(int category_id) { this.category_id = category_id; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getCreate_time() { return create_time; } public void setCreate_time(int create_time) { this.create_time = create_time; } public int getUpdate_time() { return update_time; } public void setUpdate_time(int update_time) { this.update_time = update_time; } } } } } }
2e906d7d4d352ad39ee5180b1d2fd7a23d538da2
bf1635ba45dcf483f0a63dc219ce4e87728a6349
/OopMasterChallenge/src/com/company/DeluxeHamburger.java
802dd20a3cdee8a12c532dfcaaa7e2bb81e5ea18
[]
no_license
pankaj-pant/java-udemy
1ff0609b8b99ac32e3f9034861328295bab007d7
06ddb853285ff8854fd411c2c9240801d9acc216
refs/heads/master
2020-08-01T02:14:49.059925
2019-09-25T11:07:01
2019-09-25T11:07:01
210,824,343
0
0
null
null
null
null
UTF-8
Java
false
false
2,297
java
package com.company; // The purpose of the application is to help a fictitious company called Bills Burgers to manage // their process of selling hamburgers. // Our application will help Bill to select types of burgers, some of the additional items (additions) to // be added to the burgers and pricing. // We want to create a base hamburger, but also two other types of hamburgers that are popular ones in Bills store. // The basic hamburger should have the following items. // Bread roll type, meat and up to 4 additional additions (things like lettuce, tomato, carrot, etc) that // the customer can select to be added to the burger. // Each one of these items gets charged an additional price so you need some way to track how many items got added // and to calculate the final price (base burger with all the additions). // This burger has a base price and the additions are all separately priced (up to 4 additions, see above). // Create a Hamburger class to deal with all the above. // The constructor should only include the roll type, meat and price, can also include name of burger or you // can use a setter. // Also create two extra varieties of Hamburgers (subclasses) to cater for // a) Healthy burger (on a brown rye bread roll), plus two addition items that can be added. // The healthy burger can have 6 items (Additions) in total. // hint: you probably want to process the two additional items in this new class (subclass of Hamburger), // not the base class (Hamburger), since the two additions are only appropriate for this new class // (in other words new burger type). // b) Deluxe hamburger - comes with chips and drinks as additions, but no extra additions are allowed. // hint: You have to find a way to automatically add these new additions at the time the deluxe burger // object is created, and then prevent other additions being made. // All 3 classes should have a method that can be called anytime to show the base price of the hamburger // plus all additionals, each showing the addition name, and addition price, and a grand/final total for the // burger (base price + all additions) // For the two additional classes this may require you to be looking at the base class for pricing and then // adding totals to final price. public class DeluxeHamburger { }
92cdcdd13fcd5ec16b6054f654547809385c7936
b0c613bc03b8fca1b29d258a92de07e55866bb74
/src/main/java/ch.randelshofer.cubetwister/ch/randelshofer/rubik/cube3d/RubiksCubeIdx3D.java
86685567a4189dc161280f205c1b28118c083b0e
[ "MIT" ]
permissive
RakhithJK/CubeTwister
20663aae2521c01f5859e02c493588b47b3c7c80
b392b191cc83de52d1ab3e5638802156558f1aeb
refs/heads/master
2023-01-09T23:41:06.241085
2020-10-31T07:24:20
2020-10-31T07:24:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
54,015
java
/* * @(#)RubiksCubeIdx3D.java * CubeTwister. Copyright © 2020 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.rubik.cube3d; import ch.randelshofer.rubik.CubeAttributes; import ch.randelshofer.rubik.CubeKind; import ch.randelshofer.rubik.DefaultCubeAttributes; import idx3d.idx3d_Group; import idx3d.idx3d_InternalMaterial; import idx3d.idx3d_Node; import idx3d.idx3d_Object; import idx3d.idx3d_ObjectFactory; import idx3d.idx3d_Scene; import idx3d.idx3d_Triangle; import org.jhotdraw.annotation.Nonnull; import java.awt.Color; import java.util.Arrays; /** * A 3D model of a Rubik's Cube for the Idx3D rendering engine. * * @author Werner Randelshofer */ public class RubiksCubeIdx3D extends AbstractRubiksCubeIdx3D { /** * Image width is 504 pixels out of 512 pixels. */ private final static float imageWidth = 504f / 512f; /** * Sticker size is one ninth of the imag width. */ private final static float ss = imageWidth / 9f; /** * Bevelling is cut of from each sticker. */ private float bevel; @Override protected void init() { bevel = 3f / 512f; super.init(); } /** * Specifies how many pixels are cut off from the stickers image * for each sticker. */ @Override public void setStickerBeveling(float newValue) { new Throwable().printStackTrace(); bevel = newValue; initEdgeUVMap(); initCornerUVMap(); initSideUVMap(); } private final static float[] CORNER_VERTS = { // Vertices of the main cubicle // ---------------------------- //0: Front Face: luff, ruff, rdff, ldff -8, 8, 9, 8, 8, 9, 8, -8, 9, -8, -8, 9, //4: Right Face: top-front, top-back, centerPart-back, bottom-centerPart, bottom-front 9, 8, 8, 9, 8, -8, 9, -5, -8, 9, -8, -5, 9, -8, 8, //9: Bottom Face: front-left, front-right, centerPart-right, back-centerPart, back-left -8, -9, 8, 8, -9, 8, 8, -9, -5, 5, -9, -8, -8, -9, -8, //14: Back Face: up-right, up-left, down-left, down-centerPart, centerPart-right 8, 8, -9, -8, 8, -9, -8, -8, -9, 5, -8, -9, 8, -5, -9, //19: Left Face: top-back, top-front, bottom-front, bottom-back -9, 8, -8, -9, 8, 8, -9, -8, 8, -9, -8, -8, //23: Top Face: back-left, back-right, front-right, front-left -8, 9, -8, 8, 9, -8, 8, 9, 8, -8, 9, 8, // Vertices of the additional cubicle at the bottom right //27 9, -4, -14, 14, -4, -14, 9, -4, -9, 14, -4, -9, //31 4, -9, -14, 4, -9, -9, 4, -14, -14, 4, -14, -9, //35 9, -14, -4, 14, -14, -4, 9, -9, -4, 14, -9, -4, 14, -14, -14, // Copy 1 of vertices of the additional cubicle at the bottom right //40 9, -4, -14, 14, -4, -14, 9, -4, -9, 14, -4, -9, //44 4, -9, -14, 4, -9, -9, 4, -14, -14, 4, -14, -9, //48 9, -14, -4, 14, -14, -4, 9, -9, -4, 14, -9, -4, 14, -14, -14, // Copy 2 of vertices of the additional cubicle at the bottom right //53 9, -4, -14, 14, -4, -14, 9, -4, -9, 14, -4, -9, //57 4, -9, -14, 4, -9, -9, 4, -14, -14, 4, -14, -9, //61 9, -14, -4, 14, -14, -4, 9, -9, -4, 14, -9, -4, 14, -14, -14, // Copy 3 of vertices of the additional cubicle at the bottom right //66 9, -4, -14, 14, -4, -14, 9, -4, -9, 14, -4, -9, //70 4, -9, -14, 4, -9, -9, 4, -14, -14, 4, -14, -9, //74 9, -14, -4, 14, -14, -4, 9, -9, -4, 14, -9, -4, 14, -14, -14 }; private final static int[][] CORNER_FACES = { // Faces with stickers and with outlines //-------------------------------------- {0, 1, 2, 3}, //Up face The sequence of these faces {23, 24, 25, 26}, //Front face is relevant, for method {22, 19, 20, 21}, //Left face updateStickersFillColor() // Inner edges of the main cubicle. We assign swipe actions to these. {3, 2, 10, 9}, //Up Back {1, 4, 8, 2}, //Up Right {24, 5, 4, 25}, //Front Right {15, 14, 24, 23}, //Front Bottom {13, 22, 21, 9}, //Left Back {16, 15, 19, 22}, //Left Bottom // Outer edges of the main cubicle. We assign no actions to these. {26, 25, 1, 0}, //Up Front {23, 26, 20, 19}, //Up Left {11, 10, 8, 7}, //Down Right {13, 12, 17, 16}, //Down Back {0, 3, 21, 20}, //Front Left {14, 18, 6, 5}, //Back Right // Faces of the main cubicle {4, 5, 6, 7, 8}, //Right Face {9, 10, 11, 12, 13}, //Down Face {14, 15, 16, 17, 18},//Back Face // Triangles at the cornerParts of the main cubicle {9, 21, 3}, //Bottom Left Front {10, 2, 8}, //Bottom Front Right {13, 16, 22},//Bottom Back Left {26, 0, 20}, //Top Front Left {25, 4, 1}, //Top Right Front ruuf rruf ruff {23, 19, 15},//Top Left Back luub llub lubb {24, 14, 5}, //Top Back Right ruub rubb rrub // Faces of the additional cubicle at the bottom right {27 + 10, 27 + 11, 27 + 9, 27 + 8}, // small up ⃞ //{27 + 11, 27 + 3, 27 + 1, 27 + 12, 27 + 9},// left wall |_\ //{27 + 1, 27 + 0, 27 + 4, 27 + 6, 27 + 12},// bottom wall |_\ {27 + 5, 27 + 7, 27 + 6, 27 + 4},// small front ⃞ {27 + 5, 27 + 10, 27 + 8, 27 + 7},// rect front up {27 + 2, 27 + 3, 27 + 11, 27 + 10},//rect right up {27 + 0, 27 + 2, 27 + 5, 27 + 4},//rect right front {27 + 2, 27 + 10, 27 + 5},// diagonal triangle {27 + 0, 27 + 1, 27 + 3, 27 + 2},//small right //{27 + 12, 27 + 6, 27 + 7, 27 + 8, 27 + 9},// down wall |_\ // Copy of faces of the additional cubicle at the bottom right {40 + 11, 40 + 3, 40 + 1, 40 + 12, 40 + 9},// left wall |_\ {53 + 1, 53 + 0, 53 + 4, 53 + 6, 53 + 12},// bottom wall |_\ {66 + 12, 66 + 6, 66 + 7, 66 + 8, 66 + 9},// down wall |_\ }; @Override protected void initCorners() { int i, j, part; float[] verts = CORNER_VERTS; int[][] faces = CORNER_FACES; for (part = 0; part < 8; part++) { idx3d_Object object3D = new idx3d_Object(); idx3d_Object stickerR = new idx3d_Object(); idx3d_Object stickerU = new idx3d_Object(); idx3d_Object stickerF = new idx3d_Object(); object3D.name = "corner" + part; stickerR.name = "cornerR" + part; stickerU.name = "cornerU" + part; stickerF.name = "cornerF" + part; for (i = 0; i < verts.length / 3; i++) { object3D.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); stickerR.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); stickerU.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); stickerF.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); } for (i = 0; i < faces.length; i++) { idx3d_Object obj; switch (i) { case 0: obj = stickerR; break; case 1: obj = stickerU; break; case 2: obj = stickerF; break; default: obj = object3D; break; } for (j = 2; j < faces[i].length; j++) { idx3d_Triangle triangle = new idx3d_Triangle( obj.vertex(faces[i][0]), obj.vertex(faces[i][j - 1]), obj.vertex(faces[i][j])); obj.addTriangle(triangle); } } object3D.material = stickerR.material = stickerU.material = stickerF.material = new idx3d_InternalMaterial(); idx3d_InternalMaterial sticker = new idx3d_InternalMaterial(); stickerR.triangle(0).setTriangleMaterial(sticker); stickerR.triangle(1).setTriangleMaterial(sticker); sticker = new idx3d_InternalMaterial(); stickerU.triangle(0).setTriangleMaterial(sticker); stickerU.triangle(1).setTriangleMaterial(sticker); sticker = new idx3d_InternalMaterial(); stickerF.triangle(0).setTriangleMaterial(sticker); stickerF.triangle(1).setTriangleMaterial(sticker); idx3d_Group group3D = new idx3d_Group(); group3D.addChild(stickerR); group3D.addChild(stickerU); group3D.addChild(stickerF); group3D.addChild(object3D); parts[cornerOffset + part] = group3D; } initCornerUVMap(); } /** * Initializes the UV Map for the corner parts. * <pre> * 0 1 2 3 4 5 6 7 8 9 * 0 +---+---+---+ * |4.0| |2.0| * 1 +---+ +---+ * | u | * 2 +---+ +---+ * |6.0| |0.0| * 3 +---+---+---+---+---+---+---+---+---+...........+ * |4.1| |6.2|6.1| |0.2|0.1| |2.2| ' * 4 +---+ +---+---+ +---+---+ +---+ ' * | l | f | r | b ' * 5 +---+ +---+---+ +---+---+ +---+ ' * |5.2| |7.1|7.2| |1.1|1.2| |3.1| ' * 6 +---+---+---+---+---+---+---+---+---+...........+ * |7.0| |1.0|2.1| |4.2| | * 7 +---+ +---+---+ +---+ | * | d | b | &lt;--+ * 8 +---+ +---+---+ +---+ * |5.0| |3.0|3.2| |5.1| * 9 +---+---+---+---+---+---+ * </pre> */ protected void initCornerUVMap() { for (int part = 0; part < 8; part++) { idx3d_Group group = parts[cornerOffset + part]; idx3d_Object stickerR = (idx3d_Object) group.getChild(0); idx3d_Object stickerU = (idx3d_Object) group.getChild(1); idx3d_Object stickerF = (idx3d_Object) group.getChild(2); switch (part) { case 0: // up right front stickerR.triangle(0).setUV(ss * 6 - bevel, ss * 3 - bevel, ss * 6 - bevel, ss * 2 + bevel, ss * 5 + bevel, ss * 2 + bevel); stickerR.triangle(1).setUV(ss * 6 - bevel, ss * 3 - bevel, ss * 5 + bevel, ss * 2 + bevel, ss * 5 + bevel, ss * 3 - bevel); stickerU.triangle(0).setUV(ss * 6 + bevel, ss * 4 - bevel, ss * 7 - bevel, ss * 4 - bevel, ss * 7 - bevel, ss * 3 + bevel); stickerU.triangle(1).setUV(ss * 6 + bevel, ss * 4 - bevel, ss * 7 - bevel, ss * 3 + bevel, ss * 6 + bevel, ss * 3 + bevel); stickerF.triangle(0).setUV(ss * 5 + bevel, ss * 4 - bevel, ss * 6 - bevel, ss * 4 - bevel, ss * 6 - bevel, ss * 3 + bevel); stickerF.triangle(1).setUV(ss * 5 + bevel, ss * 4 - bevel, ss * 6 - bevel, ss * 3 + bevel, ss * 5 + bevel, ss * 3 + bevel); break; case 1: // down front right stickerR.triangle(0).setUV(ss * 6 - bevel, ss * 6 + bevel, ss * 5 + bevel, ss * 6 + bevel, ss * 5 + bevel, ss * 7 - bevel); stickerR.triangle(1).setUV(ss * 6 - bevel, ss * 6 + bevel, ss * 5 + bevel, ss * 7 - bevel, ss * 6 - bevel, ss * 7 - bevel); stickerU.triangle(0).setUV(ss * 6 - bevel, ss * 5 + bevel, ss * 5 + bevel, ss * 5 + bevel, ss * 5 + bevel, ss * 6 - bevel); stickerU.triangle(1).setUV(ss * 6 - bevel, ss * 5 + bevel, ss * 5 + bevel, ss * 6 - bevel, ss * 6 - bevel, ss * 6 - bevel); stickerF.triangle(0).setUV(ss * 7 - bevel, ss * 5 + bevel, ss * 6 + bevel, ss * 5 + bevel, ss * 6 + bevel, ss * 6 - bevel); stickerF.triangle(1).setUV(ss * 7 - bevel, ss * 5 + bevel, ss * 6 + bevel, ss * 6 - bevel, ss * 7 - bevel, ss * 6 - bevel); break; case 2: // up back right stickerR.triangle(0).setUV(ss * 6 - bevel, ss * 0 + bevel, ss * 5 + bevel, ss * 0 + bevel, ss * 5 + bevel, ss * 1 - bevel); stickerR.triangle(1).setUV(ss * 6 - bevel, ss * 0 + bevel, ss * 5 + bevel, ss * 1 - bevel, ss * 6 - bevel, ss * 1 - bevel); stickerU.triangle(0).setUV(ss * 6 + bevel, ss * 7 - bevel, ss * 7 - bevel, ss * 7 - bevel, ss * 7 - bevel, ss * 6 + bevel); stickerU.triangle(1).setUV(ss * 6 + bevel, ss * 7 - bevel, ss * 7 - bevel, ss * 6 + bevel, ss * 6 + bevel, ss * 6 + bevel); stickerF.triangle(0).setUV(ss * 8 + bevel, ss * 4 - bevel, ss * 9 - bevel, ss * 4 - bevel, ss * 9 - bevel, ss * 3 + bevel); stickerF.triangle(1).setUV(ss * 8 + bevel, ss * 4 - bevel, ss * 9 - bevel, ss * 3 + bevel, ss * 8 + bevel, ss * 3 + bevel); break; case 3: // down right back stickerR.triangle(0).setUV(ss * 6 - bevel, ss * 9 - bevel, ss * 6 - bevel, ss * 8 + bevel, ss * 5 + bevel, ss * 8 + bevel); stickerR.triangle(1).setUV(ss * 6 - bevel, ss * 9 - bevel, ss * 5 + bevel, ss * 8 + bevel, ss * 5 + bevel, ss * 9 - bevel); stickerU.triangle(0).setUV(ss * 9 - bevel, ss * 5 + bevel, ss * 8 + bevel, ss * 5 + bevel, ss * 8 + bevel, ss * 6 - bevel); stickerU.triangle(1).setUV(ss * 9 - bevel, ss * 5 + bevel, ss * 8 + bevel, ss * 6 - bevel, ss * 9 - bevel, ss * 6 - bevel); stickerF.triangle(0).setUV(ss * 7 - bevel, ss * 8 + bevel, ss * 6 + bevel, ss * 8 + bevel, ss * 6 + bevel, ss * 9 - bevel); stickerF.triangle(1).setUV(ss * 7 - bevel, ss * 8 + bevel, ss * 6 + bevel, ss * 9 - bevel, ss * 7 - bevel, ss * 9 - bevel); break; case 4: // up left back stickerR.triangle(0).setUV(ss * 3 + bevel, ss * 0 + bevel, ss * 3 + bevel, ss * 1 - bevel, ss * 4 - bevel, ss * 1 - bevel); stickerR.triangle(1).setUV(ss * 3 + bevel, ss * 0 + bevel, ss * 4 - bevel, ss * 1 - bevel, ss * 4 - bevel, ss * 0 + bevel); stickerU.triangle(0).setUV(ss * 0 + bevel, ss * 4 - bevel, ss * 1 - bevel, ss * 4 - bevel, ss * 1 - bevel, ss * 3 + bevel); stickerU.triangle(1).setUV(ss * 0 + bevel, ss * 4 - bevel, ss * 1 - bevel, ss * 3 + bevel, ss * 0 + bevel, ss * 3 + bevel); stickerF.triangle(0).setUV(ss * 8 + bevel, ss * 7 - bevel, ss * 9 - bevel, ss * 7 - bevel, ss * 9 - bevel, ss * 6 + bevel); stickerF.triangle(1).setUV(ss * 8 + bevel, ss * 7 - bevel, ss * 9 - bevel, ss * 6 + bevel, ss * 8 + bevel, ss * 6 + bevel); break; case 5: // down back left stickerR.triangle(0).setUV(ss * 3 + bevel, ss * 9 - bevel, ss * 4 - bevel, ss * 9 - bevel, ss * 4 - bevel, ss * 8 + bevel); stickerR.triangle(1).setUV(ss * 3 + bevel, ss * 9 - bevel, ss * 4 - bevel, ss * 8 + bevel, ss * 3 + bevel, ss * 8 + bevel); stickerU.triangle(0).setUV(ss * 9 - bevel, ss * 8 + bevel, ss * 8 + bevel, ss * 8 + bevel, ss * 8 + bevel, ss * 9 - bevel); stickerU.triangle(1).setUV(ss * 9 - bevel, ss * 8 + bevel, ss * 8 + bevel, ss * 9 - bevel, ss * 9 - bevel, ss * 9 - bevel); stickerF.triangle(0).setUV(ss * 1 - bevel, ss * 5 + bevel, ss * 0 + bevel, ss * 5 + bevel, ss * 0 + bevel, ss * 6 - bevel); stickerF.triangle(1).setUV(ss * 1 - bevel, ss * 5 + bevel, ss * 0 + bevel, ss * 6 - bevel, ss * 1 - bevel, ss * 6 - bevel); break; case 6: // up front left stickerR.triangle(0).setUV(ss * 3 + bevel, ss * 3 - bevel, ss * 4 - bevel, ss * 3 - bevel, ss * 4 - bevel, ss * 2 + bevel); stickerR.triangle(1).setUV(ss * 3 + bevel, ss * 3 - bevel, ss * 4 - bevel, ss * 2 + bevel, ss * 3 + bevel, ss * 2 + bevel); stickerU.triangle(0).setUV(ss * 3 + bevel, ss * 4 - bevel, ss * 4 - bevel, ss * 4 - bevel, ss * 4 - bevel, ss * 3 + bevel); stickerU.triangle(1).setUV(ss * 3 + bevel, ss * 4 - bevel, ss * 4 - bevel, ss * 3 + bevel, ss * 3 + bevel, ss * 3 + bevel); stickerF.triangle(0).setUV(ss * 2 + bevel, ss * 4 - bevel, ss * 3 - bevel, ss * 4 - bevel, ss * 3 - bevel, ss * 3 + bevel); stickerF.triangle(1).setUV(ss * 2 + bevel, ss * 4 - bevel, ss * 3 - bevel, ss * 3 + bevel, ss * 2 + bevel, ss * 3 + bevel); break; case 7: // down left front stickerR.triangle(0).setUV(ss * 3 + bevel, ss * 6 + bevel, ss * 3 + bevel, ss * 7 - bevel, ss * 4 - bevel, ss * 7 - bevel); stickerR.triangle(1).setUV(ss * 3 + bevel, ss * 6 + bevel, ss * 4 - bevel, ss * 7 - bevel, ss * 4 - bevel, ss * 6 + bevel); stickerU.triangle(0).setUV(ss * 3 - bevel, ss * 5 + bevel, ss * 2 + bevel, ss * 5 + bevel, ss * 2 + bevel, ss * 6 - bevel); stickerU.triangle(1).setUV(ss * 3 - bevel, ss * 5 + bevel, ss * 2 + bevel, ss * 6 - bevel, ss * 3 - bevel, ss * 6 - bevel); stickerF.triangle(0).setUV(ss * 4 - bevel, ss * 5 + bevel, ss * 3 + bevel, ss * 5 + bevel, ss * 3 + bevel, ss * 6 - bevel); stickerF.triangle(1).setUV(ss * 4 - bevel, ss * 5 + bevel, ss * 3 + bevel, ss * 6 - bevel, ss * 4 - bevel, ss * 6 - bevel); break; } } } private final static float[] EDGE_VERTS = { // Vertices of the main cubicle //----------------------------- //0: Front Face: top-left, top-right, bottom-right, bottom-left -8, 8, 9, 8, 8, 9, 8, -8, 9, -8, -8, 9, //4: Right Face: top-front, top-back, centerPart-back, bottom-centerPart, bottom-front 9, 8, 8, 9, 8, -8, 9, -4, -8, 9, -8, -4, 9, -8, 8, //9: Bottom Face: front-left, front-right, back-right, back-left -8, -9, 8, 8, -9, 8, 8, -9, -3, -8, -9, -3, //13: Back Face: up-right, up-left, down-left, down-right 8, 8, -9, -8, 8, -9, -8, -3, -9, 8, -3, -9, //17: Left Face: top-back, top-front, bottom-front, bottom-centerPart, centerPart-back -9, 8, -8, -9, 8, 8, -9, -8, 8, -9, -8, -4, -9, -4, -8, //22: Top Face: back-left, back-right, front-right, front-left -8, 9, -8, 8, 9, -8, 8, 9, 8, -8, 9, 8, // Vertices of the additional cubicle at the back bottom. //------------------------------------------------------- //26 4, -3, -9, 4, -1, -9, 4, -1, -14, 4, -14, -14, 4, -14, -1, 4, -9, -1, 4, -9, -3, //33 -4, -3, -9, -4, -1, -9, -4, -1, -14, -4, -14, -14, -4, -14, -1, -4, -9, -1, -4, -9, -3 }; private final static int[][] EDGE_FACES = { // Faces with stickers and with outlines //-------------------------------------- {0, 1, 2, 3}, //Front The order of these faces is relevant {22, 23, 24, 25}, //Top for method updateStickersFillColor // Inner edges of the main cubicle. We assign swipe actions to these. {1, 4, 8, 2}, //Front Right {18, 0, 3, 19}, //Front Left 6+7 {3, 2, 10, 9}, //Bottom Front 8+9 {23, 5, 4, 24}, //Top Right 10+11 {14, 13, 23, 22}, //Top Back 12+13 {17, 22, 25, 18}, //Top Left // Outer edges of the main cubicle. We assign no actions to these. {25, 24, 1, 0}, //Top Front {8, 7, 11, 10}, //Bottom Right {20, 19, 9, 12}, //Bottom Left {5, 13, 16, 6}, //Back Right {14, 17, 21, 15}, //Back Left // Faces of the main cubicle {4, 5, 6, 7, 8}, //Right {9, 10, 11, 12}, //Bottom {13, 14, 15, 16}, //Back {17, 18, 19, 20, 21}, //Left {16, 15, 21, 20, 12, 11, 7, 6}, // Back Down // Faces of the additional cubicle at the back and bottom {26 + 0, 26 + 1, 26 + 2}, {26 + 0, 26 + 2, 26 + 3, 26 + 4, 26 + 6}, {26 + 4, 26 + 5, 26 + 6}, {26 + 9, 26 + 8, 26 + 7}, {26 + 13, 26 + 11, 26 + 10, 26 + 9, 26 + 7}, {26 + 13, 26 + 12, 26 + 11}, {26 + 1, 26 + 8, 26 + 9, 26 + 2}, {26 + 2, 26 + 9, 26 + 10, 26 + 3}, {26 + 3, 26 + 10, 26 + 11, 26 + 4}, {26 + 5, 26 + 4, 26 + 11, 26 + 12}, // Triangular faces at the cornerParts of the main cubicle {25, 0, 18}, //Top Front Left {24, 4, 1}, //Top Right Front {22, 17, 14}, //Top Left Back {23, 13, 5}, //Top Back Right {9, 19, 3}, //Bottom Left Front {10, 2, 8}, //Bottom Front Right }; @Override protected void initEdges() { int i, j, part; float[] verts = EDGE_VERTS; int[][] faces = EDGE_FACES; for (part = 0; part < 12; part++) { idx3d_Object object3D = new idx3d_Object(); object3D.name = "edge" + part; idx3d_Object stickerR = new idx3d_Object(); stickerR.name = "edgeR" + part; idx3d_Object stickerU = new idx3d_Object(); stickerU.name = "edgeU" + part; for (i = 0; i < verts.length / 3; i++) { object3D.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); stickerR.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); stickerU.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); } for (i = 0; i < faces.length; i++) { idx3d_Object obj; switch (i) { case 0: obj = stickerR; break; case 1: obj = stickerU; break; default: obj = object3D; break; } for (j = 2; j < faces[i].length; j++) { idx3d_Triangle triangle = new idx3d_Triangle( obj.vertex(faces[i][0]), obj.vertex(faces[i][j - 1]), obj.vertex(faces[i][j])); obj.addTriangle(triangle); } } object3D.material = stickerR.material = stickerU.material = new idx3d_InternalMaterial(); idx3d_InternalMaterial sticker = new idx3d_InternalMaterial(); stickerR.triangle(0).setTriangleMaterial(sticker); stickerR.triangle(1).setTriangleMaterial(sticker); sticker = new idx3d_InternalMaterial(); stickerU.triangle(0).setTriangleMaterial(sticker); stickerU.triangle(1).setTriangleMaterial(sticker); idx3d_Group group3D = new idx3d_Group(); group3D.addChild(stickerR); group3D.addChild(stickerU); group3D.addChild(object3D); parts[edgeOffset + part] = group3D; } initEdgeUVMap(); } /** * Initializes the UV Map for the edge parts. * <pre> * 0 1 2 3 4 5 6 7 8 9 * 0 +---+---+---+ * | |3.1| | * 1 +--- --- ---+ * |6.0| u |0.0| * 2 +--- --- ---+ * | |9.1| | * 3 +---+---+---+---+---+---+---+---+---+...........+ * | |6.1| | |9.0| | |0.1| | ' * 4 +--- --- ---+--- --- ---+--- --- ---+ ' * |7.0| l 10.0|10.1 f |1.1|1.0| r |4.0| b ' * 5 +--- --- ---+--- --- ---+--- --- ---+ ' * | |8.1| | |11.0 | |2.1| | ' * 6 +---+---+---+---+---+---+---+---+---+...........+ * | |11.1 | |3.0| | | * 7 +--- --- ---+--- --- ---+ | * |8.0| d |2.0|4.1| b |7.1| &lt;--+ * 8 +--- --- ---+--- --- ---+ * | |5.1| | |5.0| | * 9 +---+---+---+---+---+---+ * </pre> */ protected void initEdgeUVMap() { for (int part = 0; part < 12; part++) { idx3d_Group group = parts[edgeOffset + part]; idx3d_Object stickerR = (idx3d_Object) group.getChild(0); idx3d_Object stickerU = (idx3d_Object) group.getChild(1); switch (part) { case 0: // up right stickerR.triangle(0).setUV(ss * 6 - bevel, ss * 2 - bevel, ss * 6 - bevel, ss * 1 + bevel, ss * 5 + bevel, ss * 1 + bevel); stickerR.triangle(1).setUV(ss * 6 - bevel, ss * 2 - bevel, ss * 5 + bevel, ss * 1 + bevel, ss * 5 + bevel, ss * 2 - bevel); stickerU.triangle(0).setUV(ss * 7 + bevel, ss * 4 - bevel, ss * 8 - bevel, ss * 4 - bevel, ss * 8 - bevel, ss * 3 + bevel); stickerU.triangle(1).setUV(ss * 7 + bevel, ss * 4 - bevel, ss * 8 - bevel, ss * 3 + bevel, ss * 7 + bevel, ss * 3 + bevel); break; case 1: // right front stickerR.triangle(0).setUV(ss * 6 + bevel, ss * 4 + bevel, ss * 6 + bevel, ss * 5 - bevel, ss * 7 - bevel, ss * 5 - bevel); stickerR.triangle(1).setUV(ss * 6 + bevel, ss * 4 + bevel, ss * 7 - bevel, ss * 5 - bevel, ss * 7 - bevel, ss * 4 + bevel); stickerU.triangle(0).setUV(ss * 5 + bevel, ss * 4 + bevel, ss * 5 + bevel, ss * 5 - bevel, ss * 6 - bevel, ss * 5 - bevel); stickerU.triangle(1).setUV(ss * 5 + bevel, ss * 4 + bevel, ss * 6 - bevel, ss * 5 - bevel, ss * 6 - bevel, ss * 4 + bevel); break; case 2: // down right stickerR.triangle(0).setUV(ss * 6 - bevel, ss * 8 - bevel, ss * 6 - bevel, ss * 7 + bevel, ss * 5 + bevel, ss * 7 + bevel); stickerR.triangle(1).setUV(ss * 6 - bevel, ss * 8 - bevel, ss * 5 + bevel, ss * 7 + bevel, ss * 5 + bevel, ss * 8 - bevel); stickerU.triangle(0).setUV(ss * 8 - bevel, ss * 5 + bevel, ss * 7 + bevel, ss * 5 + bevel, ss * 7 + bevel, ss * 6 - bevel); stickerU.triangle(1).setUV(ss * 8 - bevel, ss * 5 + bevel, ss * 7 + bevel, ss * 6 - bevel, ss * 8 - bevel, ss * 6 - bevel); break; case 3: // back up stickerR.triangle(0).setUV(ss * 8 - bevel, ss * 6 + bevel, ss * 7 + bevel, ss * 6 + bevel, ss * 7 + bevel, ss * 7 - bevel); stickerR.triangle(1).setUV(ss * 8 - bevel, ss * 6 + bevel, ss * 7 + bevel, ss * 7 - bevel, ss * 8 - bevel, ss * 7 - bevel); stickerU.triangle(0).setUV(ss * 4 + bevel, ss * 1 - bevel, ss * 5 - bevel, ss * 1 - bevel, ss * 5 - bevel, ss * 0 + bevel); stickerU.triangle(1).setUV(ss * 4 + bevel, ss * 1 - bevel, ss * 5 - bevel, ss * 0 + bevel, ss * 4 + bevel, ss * 0 + bevel); break; case 4: // right back stickerR.triangle(0).setUV(ss * 9 - bevel, ss * 5 - bevel, ss * 9 - bevel, ss * 4 + bevel, ss * 8 + bevel, ss * 4 + bevel); stickerR.triangle(1).setUV(ss * 9 - bevel, ss * 5 - bevel, ss * 8 + bevel, ss * 4 + bevel, ss * 8 + bevel, ss * 5 - bevel); stickerU.triangle(0).setUV(ss * 7 - bevel, ss * 8 - bevel, ss * 7 - bevel, ss * 7 + bevel, ss * 6 + bevel, ss * 7 + bevel); stickerU.triangle(1).setUV(ss * 7 - bevel, ss * 8 - bevel, ss * 6 + bevel, ss * 7 + bevel, ss * 6 + bevel, ss * 8 - bevel); break; case 5: // back down stickerR.triangle(0).setUV(ss * 7 + bevel, ss * 9 - bevel, ss * 8 - bevel, ss * 9 - bevel, ss * 8 - bevel, ss * 8 + bevel); stickerR.triangle(1).setUV(ss * 7 + bevel, ss * 9 - bevel, ss * 8 - bevel, ss * 8 + bevel, ss * 7 + bevel, ss * 8 + bevel); stickerU.triangle(0).setUV(ss * 5 - bevel, ss * 8 + bevel, ss * 4 + bevel, ss * 8 + bevel, ss * 4 + bevel, ss * 9 - bevel); stickerU.triangle(1).setUV(ss * 5 - bevel, ss * 8 + bevel, ss * 4 + bevel, ss * 9 - bevel, ss * 5 - bevel, ss * 9 - bevel); break; case 6: // up left stickerR.triangle(0).setUV(ss * 3 + bevel, ss * 1 + bevel, ss * 3 + bevel, ss * 2 - bevel, ss * 4 - bevel, ss * 2 - bevel); stickerR.triangle(1).setUV(ss * 3 + bevel, ss * 1 + bevel, ss * 4 - bevel, ss * 2 - bevel, ss * 4 - bevel, ss * 1 + bevel); stickerU.triangle(0).setUV(ss * 1 + bevel, ss * 4 - bevel, ss * 2 - bevel, ss * 4 - bevel, ss * 2 - bevel, ss * 3 + bevel); stickerU.triangle(1).setUV(ss * 1 + bevel, ss * 4 - bevel, ss * 2 - bevel, ss * 3 + bevel, ss * 1 + bevel, ss * 3 + bevel); break; case 7: // left back stickerR.triangle(0).setUV(ss * 0 + bevel, ss * 4 + bevel, ss * 0 + bevel, ss * 5 - bevel, ss * 1 - bevel, ss * 5 - bevel); stickerR.triangle(1).setUV(ss * 0 + bevel, ss * 4 + bevel, ss * 1 - bevel, ss * 5 - bevel, ss * 1 - bevel, ss * 4 + bevel); stickerU.triangle(0).setUV(ss * 8 + bevel, ss * 7 + bevel, ss * 8 + bevel, ss * 8 - bevel, ss * 9 - bevel, ss * 8 - bevel); stickerU.triangle(1).setUV(ss * 8 + bevel, ss * 7 + bevel, ss * 9 - bevel, ss * 8 - bevel, ss * 9 - bevel, ss * 7 + bevel); break; case 8: // down left stickerR.triangle(0).setUV(ss * 3 + bevel, ss * 7 + bevel, ss * 3 + bevel, ss * 8 - bevel, ss * 4 - bevel, ss * 8 - bevel); stickerR.triangle(1).setUV(ss * 3 + bevel, ss * 7 + bevel, ss * 4 - bevel, ss * 8 - bevel, ss * 4 - bevel, ss * 7 + bevel); stickerU.triangle(0).setUV(ss * 2 - bevel, ss * 5 + bevel, ss * 1 + bevel, ss * 5 + bevel, ss * 1 + bevel, ss * 6 - bevel); stickerU.triangle(1).setUV(ss * 2 - bevel, ss * 5 + bevel, ss * 1 + bevel, ss * 6 - bevel, ss * 2 - bevel, ss * 6 - bevel); break; case 9: // front up stickerR.triangle(0).setUV(ss * 5 - bevel, ss * 3 + bevel, ss * 4 + bevel, ss * 3 + bevel, ss * 4 + bevel, ss * 4 - bevel); stickerR.triangle(1).setUV(ss * 5 - bevel, ss * 3 + bevel, ss * 4 + bevel, ss * 4 - bevel, ss * 5 - bevel, ss * 4 - bevel); stickerU.triangle(0).setUV(ss * 5 - bevel, ss * 2 + bevel, ss * 4 + bevel, ss * 2 + bevel, ss * 4 + bevel, ss * 3 - bevel); stickerU.triangle(1).setUV(ss * 5 - bevel, ss * 2 + bevel, ss * 4 + bevel, ss * 3 - bevel, ss * 5 - bevel, ss * 3 - bevel); break; case 10: // left front stickerR.triangle(0).setUV(ss * 3 - bevel, ss * 5 - bevel, ss * 3 - bevel, ss * 4 + bevel, ss * 2 + bevel, ss * 4 + bevel); stickerR.triangle(1).setUV(ss * 3 - bevel, ss * 5 - bevel, ss * 2 + bevel, ss * 4 + bevel, ss * 2 + bevel, ss * 5 - bevel); stickerU.triangle(0).setUV(ss * 4 - bevel, ss * 5 - bevel, ss * 4 - bevel, ss * 4 + bevel, ss * 3 + bevel, ss * 4 + bevel); stickerU.triangle(1).setUV(ss * 4 - bevel, ss * 5 - bevel, ss * 3 + bevel, ss * 4 + bevel, ss * 3 + bevel, ss * 5 - bevel); break; case 11: // front down stickerR.triangle(0).setUV(ss * 4 + bevel, ss * 6 - bevel, ss * 5 - bevel, ss * 6 - bevel, ss * 5 - bevel, ss * 5 + bevel); stickerR.triangle(1).setUV(ss * 4 + bevel, ss * 6 - bevel, ss * 5 - bevel, ss * 5 + bevel, ss * 4 + bevel, ss * 5 + bevel); stickerU.triangle(0).setUV(ss * 4 + bevel, ss * 7 - bevel, ss * 5 - bevel, ss * 7 - bevel, ss * 5 - bevel, ss * 6 + bevel); stickerU.triangle(1).setUV(ss * 4 + bevel, ss * 7 - bevel, ss * 5 - bevel, ss * 6 + bevel, ss * 4 + bevel, ss * 6 + bevel); break; } } } private final static float[] SIDE_VERTS = { //0:luff ldff ruff rdff -8, 8, 9, -8, -8, 9, 8, 8, 9, 8, -8, 9, //4:rubb, rdbb, lubb, ldbb 8, 8, -1, 8, -8, -1, -8, 8, -1, -8, -8, -1, //8:lluf lldf - rruf - rrdf -9, 8, 8, -9, -8, 8, 9, 8, 8, 9, -8, 8, //12:rrub, - rrdb, llub, lldb 9, 8, 0, 9, -8, 0, -9, 8, 0, -9, -8, 0, //16:luuf lddf ruuf rddf -8, 9, 8, -8, -9, 8, 8, 9, 8, 8, -9, 8, //20:ruub, rddb, luub, lddb 8, 9, 0, 8, -9, 0, -8, 9, 0, -8, -9, 0, /* //24 2,4.5f,-1, 4.5f,2,-1, 4.5f,-2,-1, 2,-4.5f,-1, -2,-4.5f,-1, -4.5f,-2,-1, -4.5f,2,-1, -2,4.5f,-1, //32 2,4.5f,-9, 4.5f,2,-9, 4.5f,-2,-9, 2,-4.5f,-9, -2,-4.5f,-9, -4.5f,-2,-9, -4.5f,2,-9, -2,4.5f,-9, */}; private final static int[][] SIDE_FACES = { // Faces with stickers and with outlines //-------------------------------------- {0, 2, 3, 1}, //Front // Inner edges of the main cubicle. We assign swipe actions to these. {16, 18, 2, 0}, //Top Front {1, 3, 19, 17}, //Bottom Front {2, 10, 11, 3}, //Front Right rdff ruff rruf rrdf {8, 0, 1, 9}, //Front Left // Outer edges of the main cubicle. We assign no actions to these. {18, 20, 12, 10}, //Top Right {20, 22, 6, 4}, //Top Back {22, 16, 8, 14}, //Top Left {4, 5, 13, 12}, //Back Right {7, 6, 14, 15}, //Back Left {21, 19, 11, 13}, //Bottom Right rddb rddf rrdf rrdb {23, 21, 5, 7}, //Bottom Back lddb rddb rdbb ldbb {17, 23, 15, 9}, //Bottom Left lddf lddb lldb lldf // Side faces {16, 22, 20, 18}, //Top {14, 8, 9, 15}, //Left {12, 13, 11, 10}, //Right {17, 19, 21, 23}, //Bottom {4, 6, 7, 5}, //Back // Triangular faces at the cornerParts of the main cubicle {17, 9, 1}, //Bottom Left Front lddf lldf ldff {19, 3, 11}, //Bottom Front Right rddf rdff rrdf {23, 7, 15}, //Bottom Back Left lddb ldbb lldb {21, 13, 5}, //Bottom Right Back rddb rrdb rdbb {16, 0, 8}, //Top Front Left luuf luff lluf {18, 10, 2}, //Top Right Front ruuf rruf ruff {22, 14, 6}, //Top Left Back luub llub lubb {20, 4, 12}, //Top Back Right ruub rubb rrub /* // Back face of the axis {39, 38, 37, 36, 35, 34, 33, 32}, // Faces of the axis {24, 32, 33, 25}, {25, 33, 34, 26}, {26, 34, 35, 27}, {27, 35, 36, 28}, {28, 36, 37, 29}, {29, 37, 38, 30}, {30, 38, 39, 31}, {31, 39, 32, 24}, */}; @Override protected void initSides() { int i, j, part; idx3d_Object cylinder; float[] verts = SIDE_VERTS; int[][] faces = SIDE_FACES; for (part = 0; part < 6; part++) { idx3d_Group group3D = new idx3d_Group(); idx3d_Object object3D = new idx3d_Object(); object3D.name = "side" + part; idx3d_Object stickerR = new idx3d_Object(); stickerR.name = "sideR" + part; object3D.children(); for (i = 0; i < verts.length / 3; i++) { object3D.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); stickerR.addVertex( verts[i * 3], verts[i * 3 + 1], verts[i * 3 + 2]); } for (i = 0; i < faces.length; i++) { idx3d_Object obj = i == 0 ? stickerR : object3D; for (j = 2; j < faces[i].length; j++) { idx3d_Triangle triangle = new idx3d_Triangle( obj.vertex(faces[i][0]), obj.vertex(faces[i][j - 1]), obj.vertex(faces[i][j])); obj.addTriangle(triangle); } } cylinder = idx3d_ObjectFactory.CYLINDER(8f, 4.5f, 12, true, false); cylinder.rotate((float) (Math.PI / 2), 0f, 0f); cylinder.shift(0f, 0f, -5f); cylinder.matrixMeltdown(); object3D.incorporateGeometry(cylinder); object3D.material = stickerR.material = new idx3d_InternalMaterial(); idx3d_InternalMaterial sticker = new idx3d_InternalMaterial(); stickerR.triangle(0).setTriangleMaterial(sticker); stickerR.triangle(1).setTriangleMaterial(sticker); group3D.addChild(stickerR); group3D.addChild(object3D); parts[sideOffset + part] = group3D; } initSideUVMap(); } /** * Initializes the UV coordinates for the side parts. * <pre> * 0 1 2 3 4 5 6 7 8 9 * 0 +-----------+ * | | * 1 | +---+ u | * | | 1 | | * 2 | +---+ | * | | * 3 +-----------+-----------+-----------+...........+ * | | | | ' * 4 | +---+ l | +---+ f | +---+ r | ' * | | 3 | | | 2 | | | 0 | | b ' * 5 | +---+ | +---+ | +---+ | ' * | | | | ' * 6 +-----------+-----------+-----------+...........+ * | | | | * 7 | +---+ d | +---+ b | | * | | 4 | | | 5 | | &lt;--+ * 8 | +---+ | +---+ | * | | | * 9 +-----------+-----------+ * </pre> */ protected void initSideUVMap() { /* UV coordinates for stickers on side parts. * First dimension = parts, * Second dimension = sticker coordinates * Third dimension = x and y coordinate values */ for (int part = 0; part < 6; part++) { idx3d_Group group3D = parts[sideOffset + part]; idx3d_Object object3D = (idx3d_Object) group3D.getChild(0); switch (part) { case 0: // right object3D.triangle(0).setUV(ss * 7 + bevel, ss * 4 + bevel, ss * 7 + bevel, ss * 5 - bevel, ss * 8 - bevel, ss * 5 - bevel); object3D.triangle(1).setUV(ss * 7 + bevel, ss * 4 + bevel, ss * 8 - bevel, ss * 5 - bevel, ss * 8 - bevel, ss * 4 + bevel); break; case 1: // up object3D.triangle(0).setUV(ss * 5 - bevel, ss * 2 - bevel, ss * 5 - bevel, ss * 1 + bevel, ss * 4 + bevel, ss * 1 + bevel); object3D.triangle(1).setUV(ss * 5 - bevel, ss * 2 - bevel, ss * 4 + bevel, ss * 1 + bevel, ss * 4 + bevel, ss * 2 - bevel); break; case 2: // front object3D.triangle(0).setUV(ss * 5 - bevel, ss * 4 + bevel, ss * 4 + bevel, ss * 4 + bevel, ss * 4 + bevel, ss * 5 - bevel); object3D.triangle(1).setUV(ss * 5 - bevel, ss * 4 + bevel, ss * 4 + bevel, ss * 5 - bevel, ss * 5 - bevel, ss * 5 - bevel); break; case 4: // down object3D.triangle(0).setUV(ss * 4 + bevel, ss * 8 - bevel, ss * 5 - bevel, ss * 8 - bevel, ss * 5 - bevel, ss * 7 + bevel); object3D.triangle(1).setUV(ss * 4 + bevel, ss * 8 - bevel, ss * 5 - bevel, ss * 7 + bevel, ss * 4 + bevel, ss * 7 + bevel); break; case 3: // left object3D.triangle(0).setUV(ss * 1 + bevel, ss * 5 - bevel, ss * 2 - bevel, ss * 5 - bevel, ss * 2 - bevel, ss * 4 + bevel); object3D.triangle(1).setUV(ss * 1 + bevel, ss * 5 - bevel, ss * 2 - bevel, ss * 4 + bevel, ss * 1 + bevel, ss * 4 + bevel); break; case 5: // back object3D.triangle(0).setUV(ss * 8 - bevel, ss * 8 - bevel, ss * 8 - bevel, ss * 7 + bevel, ss * 7 + bevel, ss * 7 + bevel); object3D.triangle(1).setUV(ss * 8 - bevel, ss * 8 - bevel, ss * 7 + bevel, ss * 7 + bevel, ss * 7 + bevel, ss * 8 - bevel); break; } } } /* Maps stickers to cube parts. * +----+----+----+ * | 4.0|11 | 2.0| * +---- ----+ * |14.0 21 8.0| * +---- ----+ * | 6.0|17 | 0.0| * +----+----+----+----+----+----+----+----+----+----+----+----+ * | 4.1|14 | 6.2| 6.1|17.0| 0.2| 0.1| 8 | 2.2| 2.1|11.0| 4.2| * +---- ----+---- ----+---- ----+---- ----+ * |15.0 23 18.0|18 22 9 | 9.0 20 12.0|12 25 15 | * +---- ----+---- ----+---- ----+---- ----+ * | 5.2|16 | 7.1| 7.2|19.0| 1.1| 1.2|10 | 3.1| 3.2|13.0| 5.1| * +----+----+----+----+----+----+----+----+----+----+----+----+ * | 7.0|19 | 1.0| * +---- ----+ * |16.0 24 10.0| * +---- ----+ * |5.0 |13 | 3.0| * +----+----+----+ */ private final static int[] stickerToPartMap = { 0, 8, 2, 9, 20, 12, 1, 10, 3, // right 4, 11, 2, 14, 21, 8, 6, 17, 0, // up 6, 17, 0, 18, 22, 9, 7, 19, 1, // front 4, 14, 6, 15, 23, 18, 5, 16, 7, // left 7, 19, 1, 16, 24, 10, 5, 13, 3, // down 2, 11, 4, 12, 25, 15, 3, 13, 5 // back }; /** * Gets the part which holds the indicated sticker. * The sticker index is interpreted according to this * scheme: * <pre> * +---+---+---+ * | 9 | 10| 11| * +---+---+---+ * | 12| 13| 14| * +---+---+---+ * | 15| 16| 17| * +---+---+---+---+---+---+---+---+---+---+---+---+ * | 27| 28| 29| 18| 19| 20| 0 | 1 | 2 | 45| 46| 47| * +---+---+---+---+---+---+---+---+---+---+---+---+ * | 30| 31| 32| 21| 22| 23| 3 | 4 | 5 | 48| 49| 50| * +---+---+---+---+---+---+---+---+---+---+---+---+ * | 33| 34| 35| 24| 25| 26| 6 | 7 | 8 | 51| 52| 53| * +---+---+---+---+---+---+---+---+---+---+---+---+ * | 36| 37| 38| * +---+---+---+ * | 39| 40| 41| * +---+---+---+ * | 42| 43| 44| * +---+---+---+ * </pre> */ @Override public int getPartIndexForStickerIndex(int stickerIndex) { return stickerToPartMap[stickerIndex]; } private final static int[] stickerToFaceMap = { 1, 1, 2, 0, 0, 0, 2, 1, 1, // right 0, 1, 0, 0, 0, 0, 0, 1, 0, // up 1, 0, 2, 1, 0, 1, 2, 0, 1, // front 1, 1, 2, 0, 0, 0, 2, 1, 1, // left 0, 1, 0, 0, 0, 0, 0, 1, 0, // down 1, 0, 2, 1, 0, 1, 2, 0, 1 // back }; @Override protected int getPartFaceIndexForStickerIndex(int stickerIndex) { return stickerToFaceMap[stickerIndex] * 2; } @Override protected int getStickerIndexForPart(int part, int orientation) { int sticker; for (sticker = stickerToPartMap.length - 1; sticker >= 0; sticker--) { if (stickerToPartMap[sticker] == part && stickerToFaceMap[sticker] == orientation) { break; } } return sticker; } @Override public int getStickerCount() { return 54; } @Nonnull @Override public CubeAttributes createAttributes() { DefaultCubeAttributes a = new DefaultCubeAttributes(partCount, getStickerCount(), new int[]{9, 9, 9, 9, 9, 9}); Color[] partsFillColor = new Color[partCount]; Color[] partsOutlineColor = new Color[partCount]; Color[] stickersFillColor = new Color[getStickerCount()]; Arrays.fill(partsFillColor, 0, partCount - 1, new Color(24, 24, 24)); Arrays.fill(partsOutlineColor, 0, partCount - 1, new Color(16, 16, 16)); Arrays.fill(partsFillColor, centerOffset, partCount, new Color(240, 240, 240)); Arrays.fill(partsOutlineColor, centerOffset, partCount, new Color(240, 240, 240)); Arrays.fill(stickersFillColor, 0 * 3 * 3, 1 * 3 * 3, new Color(255, 210, 0)); // Right: Yellow Arrays.fill(stickersFillColor, 1 * 3 * 3, 2 * 3 * 3, new Color(0, 51, 115)); // Up: Blue Arrays.fill(stickersFillColor, 2 * 3 * 3, 3 * 3 * 3, new Color(140, 0, 15)); // Front: Red Arrays.fill(stickersFillColor, 3 * 3 * 3, 4 * 3 * 3, new Color(248, 248, 248)); // Left: White Arrays.fill(stickersFillColor, 4 * 3 * 3, 5 * 3 * 3, new Color(0, 115, 47)); // Down: Green Arrays.fill(stickersFillColor, 5 * 3 * 3, 6 * 3 * 3, new Color(255, 70, 0)); // Back: Orange a.setPartFillColor(partsFillColor); a.setPartOutlineColor(partsOutlineColor); a.setStickerFillColor(stickersFillColor); return a; } @Override protected void initActions(@Nonnull idx3d_Scene scene) { int i, j; PartAction action; // Corners for (i = 0; i < 8; i++) { int index = cornerOffset + i; for (j = 0; j < 3; j++) { action = new PartAction( index, j, getStickerIndexForPart(index, j)); idx3d_Object stickerR = (idx3d_Object) parts[index].getChild(0); idx3d_Object stickerU = (idx3d_Object) parts[index].getChild(1); idx3d_Object stickerF = (idx3d_Object) parts[index].getChild(2); idx3d_Object obj = (idx3d_Object) parts[index].getChild(3); switch (j) { case 0: { SwipeAction a0 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI + Math.PI / 2f + Math.PI / 4f)); SwipeAction a1 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI + Math.PI / 2f)); scene.addMouseListener(stickerR.triangle(0), action); scene.addMouseListener(stickerR.triangle(1), action); scene.addSwipeListener(stickerR.triangle(0), a0); scene.addSwipeListener(stickerR.triangle(1), a1); scene.addSwipeListener(obj.triangle(8 - 6), a0); scene.addSwipeListener(obj.triangle(7 - 6), a1); scene.addSwipeListener(obj.triangle(8 - 6), a0); scene.addSwipeListener(obj.triangle(9 - 6), a1); break; } case 1: { SwipeAction a0 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI / 2 + Math.PI / 2f + Math.PI / 4f)); SwipeAction a1 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI / 2 + Math.PI / 2f)); scene.addMouseListener(stickerU.triangle(0), action); scene.addMouseListener(stickerU.triangle(1), action); scene.addSwipeListener(stickerU.triangle(0), a0); scene.addSwipeListener(stickerU.triangle(1), a1); scene.addSwipeListener(obj.triangle(10 - 6), a0); scene.addSwipeListener(obj.triangle(11 - 6), a1); scene.addSwipeListener(obj.triangle(12 - 6), a0); scene.addSwipeListener(obj.triangle(13 - 6), a1); break; } case 2: { SwipeAction a0 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI + Math.PI / 2f + Math.PI / 4f)); SwipeAction a1 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI + Math.PI / 2f)); scene.addMouseListener(stickerF.triangle(0), action); scene.addMouseListener(stickerF.triangle(1), action); scene.addSwipeListener(stickerF.triangle(0), a0); scene.addSwipeListener(stickerF.triangle(1), a1); scene.addSwipeListener(obj.triangle(14 - 6), a0); scene.addSwipeListener(obj.triangle(15 - 6), a1); scene.addSwipeListener(obj.triangle(16 - 6), a0); scene.addSwipeListener(obj.triangle(17 - 6), a1); } break; } } } // Edges for (i = 0; i < 12; i++) { int index = edgeOffset + i; for (j = 0; j < 2; j++) { action = new PartAction( i + 8, j, getStickerIndexForPart(index, j)); idx3d_Object stickerR = (idx3d_Object) parts[index].getChild(0); idx3d_Object stickerU = (idx3d_Object) parts[index].getChild(1); idx3d_Object obj = (idx3d_Object) parts[index].getChild(2); switch (j) { case 0: { SwipeAction a0 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI + Math.PI / 2f + Math.PI / 4f)); SwipeAction a1 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI + Math.PI / 2f)); scene.addMouseListener(stickerR.triangle(0), action); scene.addMouseListener(stickerR.triangle(1), action); scene.addSwipeListener(stickerR.triangle(0), a0); scene.addSwipeListener(stickerR.triangle(1), a1); scene.addSwipeListener(obj.triangle(4 - 4), a0); scene.addSwipeListener(obj.triangle(5 - 4), a1); scene.addSwipeListener(obj.triangle(6 - 4), a0); scene.addSwipeListener(obj.triangle(7 - 4), a1); scene.addSwipeListener(obj.triangle(8 - 4), a0); scene.addSwipeListener(obj.triangle(9 - 4), a1); break; } case 1: { SwipeAction a0 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI / 2f + Math.PI / 4f)); SwipeAction a1 = new SwipeAction(index, j, getStickerIndexForPart(index, j), (float) (Math.PI / 2f)); scene.addMouseListener(stickerU.triangle(0), action); scene.addMouseListener(stickerU.triangle(1), action); scene.addSwipeListener(stickerU.triangle(0), a0); scene.addSwipeListener(stickerU.triangle(1), a1); scene.addSwipeListener(obj.triangle(10 - 4), a0); scene.addSwipeListener(obj.triangle(11 - 4), a1); scene.addSwipeListener(obj.triangle(12 - 4), a0); scene.addSwipeListener(obj.triangle(13 - 4), a1); scene.addSwipeListener(obj.triangle(14 - 4), a0); scene.addSwipeListener(obj.triangle(15 - 4), a1); break; } } } } // Sides for (i = 0; i < 6; i++) { int index = sideOffset + i; action = new PartAction( index, 0, getStickerIndexForPart(index, 0)); idx3d_Object stickerR = (idx3d_Object) parts[index].getChild(0); idx3d_Object obj = (idx3d_Object) parts[index].getChild(1); scene.addMouseListener(stickerR.triangle(0), action); scene.addMouseListener(stickerR.triangle(1), action); SwipeAction a0 = new SwipeAction(index, 0, getStickerIndexForPart(index, 0), (float) (Math.PI / 2f + Math.PI / 4f)); SwipeAction a1 = new SwipeAction(index, 0, getStickerIndexForPart(index, 0), (float) Math.PI / 2f); scene.addSwipeListener(stickerR.triangle(0), a0); scene.addSwipeListener(stickerR.triangle(1), a1); scene.addSwipeListener(obj.triangle(2 - 2), a0); scene.addSwipeListener(obj.triangle(3 - 2), a1); scene.addSwipeListener(obj.triangle(4 - 2), a0); scene.addSwipeListener(obj.triangle(5 - 2), a1); scene.addSwipeListener(obj.triangle(6 - 2), a0); scene.addSwipeListener(obj.triangle(7 - 2), a1); scene.addSwipeListener(obj.triangle(8 - 2), a0); scene.addSwipeListener(obj.triangle(9 - 2), a1); } for (i = 0; i < 27; i++) { action = new PartAction( i, -1, -1); for (idx3d_Node child : parts[i].children()) { scene.addMouseListener((idx3d_Object) child, action); } } } @Nonnull @Override public CubeKind getKind() { return CubeKind.RUBIK; } }
562be6af2423a0bfb16c677ffe7b3a898f231273
303160d76cf663e648e7d324a023795c0b40d41d
/app/src/main/java/inc/frontlooksoftwares/app_test/splash.java
887ae708881f650a25f52c371111549f1b36e90b
[]
no_license
emeraldsoff/app_test
a559b641e664eb48092ea31ae3d64cde613feeeb
4dd3c3d61ab647d2e19631b359bb77211bbc28dc
refs/heads/master
2020-03-28T19:40:16.123740
2018-09-16T13:27:47
2018-09-16T13:27:47
148,998,315
0
0
null
null
null
null
UTF-8
Java
false
false
1,050
java
package inc.frontlooksoftwares.app_test; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; public class splash extends Activity { TextView brand; protected void onStart() { super.onStart(); // mAuth = FirebaseAuth.getInstance(); int SPLASH_DISPLAY_LENGTH = 5000; new Handler().postDelayed(new Runnable() { @Override public void run() { // splash.this.onDestroy(); startActivity(new Intent(splash.this, MainActivity.class)); } }, SPLASH_DISPLAY_LENGTH); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); brand = findViewById(R.id.textView); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Harlow.ttf"); brand.setTypeface(typeface); } }
afec715e39de39ce01fbf4e982f50eef49de394a
cdd72ee2a2eb40b17f0aac6497872f6c9b7ca0f9
/src/FenetreAffichageScores.java
96a2665b6c2aed3974d43050e060ef6e58ec0a75
[]
no_license
mariusbordier/Master-Mind
c0f737d02476287e14c8c5341e4f1be1d232029f
8cb47b22cf428c04558bba62099213be072be95e
refs/heads/master
2021-01-10T20:06:45.148175
2013-02-28T10:18:05
2013-02-28T10:18:05
null
0
0
null
null
null
null
MacCentralEurope
Java
false
false
2,833
java
import java.awt.Color; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class FenetreAffichageScores extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Integer i=0; private JLabel titre = new JLabel("Tableau des meilleures scores: "); private JLabel positionJoueur,labelPositionJoueur; private JLabel nomJoueur,labelNomJoueur; private JLabel scoreJoueur,labelScoreJoueur; private JMenuBar menuBar = new JMenuBar(); private JMenu menuprincipal = new JMenu("Fichier"); private JMenuItem quitter = new JMenuItem("Quitter"); public FenetreAffichageScores(){ super("Master Mind") ; this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setResizable(false); this.menuprincipal.add(quitter); this.menuBar.add(menuprincipal); this.setJMenuBar(menuBar); this.menuBar.add(menuprincipal); this.setJMenuBar(menuBar); this.setVisible(true); MeilleuresScores.lire(); titre.setBounds(50,20,220,50); titre.setForeground(Color.WHITE); this.add(titre); labelPositionJoueur = new JLabel("Position"); labelNomJoueur = new JLabel("Prénom"); labelScoreJoueur= new JLabel("Nombre de tours"); labelPositionJoueur.setForeground(Color.white); labelNomJoueur.setForeground(Color.white); labelScoreJoueur.setForeground(Color.white); labelPositionJoueur.setBounds(50, 50, 100, 50); labelNomJoueur.setBounds(150, 50, 100, 50); labelScoreJoueur.setBounds(250, 50, 150, 50); this.add(labelPositionJoueur); this.add(labelNomJoueur); this.add(labelScoreJoueur); for(i=0;i<MeilleuresScores.getscore().size();i++){ String[] s = (String[]) MeilleuresScores.getscore().get(i); Integer pos=i+1; positionJoueur = new JLabel(pos.toString()); nomJoueur = new JLabel(s[0]); scoreJoueur = new JLabel(s[1]); positionJoueur.setForeground(Color.white); nomJoueur.setForeground(Color.white); scoreJoueur.setForeground(Color.white); positionJoueur.setBounds(50,70+i*20, 100, 50); nomJoueur.setBounds(150,70+i*20, 100, 50); scoreJoueur.setBounds(250,70+i*20, 100, 50); this.add(positionJoueur); this.add(nomJoueur); this.add(scoreJoueur); } quitter.addActionListener(new MenuQuitter()); } class MenuQuitter implements ActionListener{ public void actionPerformed(ActionEvent arg) { hide(); Frame fenJoueur = new FenetreChoixJoueur(); ImagePanel panel = new ImagePanel(new ImageIcon(fenJoueur.getClass().getResource("/Images/fd.png")).getImage()); ((JFrame) fenJoueur).getContentPane().add(panel); } } }
d5e2fa7659e830b964d2eb6f9fa8c82e1816ee52
8ec3dbbcd910ec0b2fa7c1be26bdc160630f59aa
/NetherBits/machine/ItemBlockMachine.java
d3d1aa7173c027a8eb81ebc4de60e0747c334f37
[ "MIT" ]
permissive
magico13/OldMCMods
3c765a3eecb5bdd08d3876a09c0c4c950928188e
101277575db2d5b7aca6952347d8a1e02a0dc8dc
refs/heads/master
2022-04-14T05:22:54.260608
2020-04-15T22:21:11
2020-04-15T22:21:11
256,048,693
0
0
null
null
null
null
UTF-8
Java
false
false
682
java
package magico13.mods.NetherBits.machine; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; public class ItemBlockMachine extends ItemBlock { public static final String[] BlockNames = new String[] {"CobbleGen", "LavaGen"}; public ItemBlockMachine(int par1, Block block) { super(par1); setHasSubtypes(true); } public String getItemNameIS(ItemStack itemstack) { int var2 = MathHelper.clamp_int(itemstack.getItemDamage(), 0, BlockNames.length-1); return super.getItemName() + "." + BlockNames[var2]; } public int getMetadata(int metadata) { return metadata; } }
19d5d8d61d78cc664f9ccb654022b3bb35b22f4e
26e181fe6e1c97117bb6da2e6643cbf3176212fc
/src/main/java/com/fjw/po/Comment.java
2e38e22c61cccebbb25c0032179fdcf700766e86
[]
no_license
yedeng01/privateBlog
f6e47bd9b37d2bc412c4e7d2c16342895549ef24
d187af1d4db6ecefed0e47ebbd06867bab3eb8a5
refs/heads/master
2022-11-26T08:29:04.520183
2020-08-07T17:33:27
2020-08-07T17:33:30
285,874,649
0
0
null
null
null
null
UTF-8
Java
false
false
2,844
java
package com.fjw.po; import com.fjw.po.Blog; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by limi on 2017/10/14. */ @Entity @Table(name = "t_comment") public class Comment { @Id @GeneratedValue private Long id; private String nickname; private String email; private String content; private String avatar; @Temporal(TemporalType.TIMESTAMP) private Date createTime; @ManyToOne private Blog blog; @OneToMany(mappedBy = "parentComment") private List<Comment> replyComments = new ArrayList<>(); @ManyToOne private Comment parentComment; private boolean adminComment; public Comment() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Blog getBlog() { return blog; } public void setBlog(Blog blog) { this.blog = blog; } public List<Comment> getReplyComments() { return replyComments; } public void setReplyComments(List<Comment> replyComments) { this.replyComments = replyComments; } public Comment getParentComment() { return parentComment; } public void setParentComment(Comment parentComment) { this.parentComment = parentComment; } public boolean isAdminComment() { return adminComment; } public void setAdminComment(boolean adminComment) { this.adminComment = adminComment; } @Override public String toString() { return "Comment{" + "id=" + id + ", nickname='" + nickname + '\'' + ", email='" + email + '\'' + ", content='" + content + '\'' + ", avatar='" + avatar + '\'' + ", createTime=" + createTime + ", blog=" + blog + ", replyComments=" + replyComments + ", parentComment=" + parentComment + ", adminComment=" + adminComment + '}'; } }
842d8de483f9d01f656185fddd021e7debcb343f
f12ac48a1f34c0c7d12d4c12ffe7092323ad2c76
/jdk8-boot2-yidao620c-2018-xkcoding-2020@nice/ch3-biz/springboot-img-compress-thumbnailator@nice@todo/src/main/java/com/xncoding/pos/controller/UploadController.java
7f60a6cdd8b0f1788a555974f9df6953b3a54105
[ "MIT" ]
permissive
mphz/summer-demo-springboot
8a3df406baa69eb8e5dabe76de3196618561dd3a
821075a97454f52b7f88532c7853fbab38be21ba
refs/heads/master
2023-01-25T00:54:41.754275
2020-11-22T05:30:54
2020-11-22T05:30:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,113
java
package com.xncoding.pos.controller; import cn.hutool.core.date.DateUtil; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; @Controller @RequestMapping("/") public class UploadController { private static final Logger logger = LoggerFactory.getLogger(UploadController.class); /** * java 上传图片 并压缩图片大小 * https://www.cnblogs.com/miskis/p/5500822.html */ @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("imgFile") MultipartFile imageFile) { // 校验判断 if (imageFile == null) { // return new BaseResult(false, "imageFile不能为空"); } if (imageFile.getSize() >= 10 * 1024 * 1024) { // return new BaseResult(false, "文件不能大于10M"); } //拼接后台文件名称 String uuid = UUID.randomUUID().toString(); String fileDirectory = DateUtil.format(new Date(), "YYYY-MM-DD"); String pathName = fileDirectory + File.separator + uuid + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); // 构建保存文件 String realPath = "d:/upload"; //获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置 String filePathName = realPath + File.separator + pathName; logger.info("图片上传路径:" + filePathName); // 判断文件保存是否存在 File file = new File(filePathName); if (file.getParentFile() != null || !file.getParentFile().isDirectory()) { file.getParentFile().mkdirs(); } InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { inputStream = imageFile.getInputStream(); fileOutputStream = new FileOutputStream(file); //写出文件 //2016-05-12 yangkang 改为增加缓存 // IOUtils.copy(inputStream, fileOutputStream); byte[] buffer = new byte[2048]; IOUtils.copyLarge(inputStream, fileOutputStream, buffer); buffer = null; } catch (IOException e) { filePathName = null; // return new BaseResult(false, "操作失败", e.getMessage()); } finally { try { if (inputStream != null) { inputStream.close(); } if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } catch (IOException e) { filePathName = null; // return new BaseResult(false, "操作失败", e.getMessage()); } } // 生成缩略图 String thumbnailPathName = fileDirectory + File.separator + uuid + "small." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); if (thumbnailPathName.contains(".png")) { thumbnailPathName = thumbnailPathName.replace(".png", ".jpg"); } long size = imageFile.getSize(); double scale = 1.0d; if (size >= 200 * 1024) { if (size > 0) { scale = (200 * 1024f) / size; } } // 缩略图路径 String thumbnailFilePathName = realPath + File.separator + thumbnailPathName; try { //added by chenshun 2016-3-22 注释掉之前长宽的方式,改用大小 // Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName); if (size < 200 * 1024) { Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName); } else { Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName); } } catch (Exception e) { // return new BaseResult(false, "操作失败", e1.getMessage()); } /** * 缩略图end */ Map<String, Object> map = new HashMap<String, Object>(); // 原图地址 map.put("originalUrl", pathName); // 缩略图地址 map.put("thumbnailUrl", thumbnailPathName); return map.toString(); } @RequestMapping("/") public String demo() { return "index"; } }
874c525962892924c408197b093b3d3757afb6f7
72d93b110b4395ee907cb0874af27642e8c69695
/Gutierrr_CSC165_A2/myGame/moveRightAction.java
1d4e6765c894525d4301201a3891280e6dba4d24
[]
no_license
Krohnis/Million-Years-Computer-Game-Architecture
2003bb22d1b3c79979cb98a6753675ad651ecbe2
18df655a309b419bc8889a0d67ea9bb3458ada0f
refs/heads/master
2020-04-02T09:13:31.063384
2018-10-23T07:43:02
2018-10-23T07:43:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,374
java
package myGame; import ray.input.action.AbstractInputAction; import ray.rage.scene.*; import ray.rml.*; import net.java.games.input.Event; public class moveRightAction extends AbstractInputAction { private Camera myCamera; private SceneNode dolphinNode; private modifiedRightAction modRightAction; private float movementSpeed; private float previousTime = 0.0f; private float currentTime; public moveRightAction(modifiedRightAction modRight, Camera camera, SceneNode dolphin, float movement) { myCamera = camera; dolphinNode = dolphin; modRightAction = modRight; movementSpeed = movement; } @Override public void performAction(float time, Event event) { currentTime = time / 1000; float timeScale = ((currentTime - previousTime) % 0.1f) * event.getValue(); float rightSpeed = movementSpeed * timeScale; if (myCamera.getMode() == 'n' && (event.getValue() > 0.1 || event.getValue() < -0.1)) { modRightAction.performAction(timeScale, event); } else { Vector3f Y = myCamera.getRt(); Vector3f P = myCamera.getPo(); Vector3f P1 = (Vector3f) Vector3f.createFrom(rightSpeed * Y.x(), rightSpeed * Y.y(), rightSpeed * Y.z()); Vector3f P2 = (Vector3f) P.add((Vector3)P1); myCamera.setPo((Vector3f)Vector3f.createFrom(P2.x(),P2.y(),P2.z())); } previousTime = currentTime; } }
5450c5acd07777722540eaeeb828a0dc4d813bfd
f07d88c8c39327b68429da398460088ece22bba8
/src/com/zahdoo/android/extension/tts/TTSSpeakFunction.java
59cd63d050c5c0c70eff53c6f205a4f87d142f27
[]
no_license
ma-hussain/CadieNative
1efba4906ed358bc6730ca06513125e3cf7ec0a5
c00f50b846e51bc0b92074d165357bf88e0fc558
refs/heads/master
2020-03-26T01:10:32.903308
2015-09-10T12:58:43
2015-09-10T12:58:43
42,244,790
0
0
null
null
null
null
UTF-8
Java
false
false
1,199
java
package com.zahdoo.android.extension.tts; import android.speech.tts.TextToSpeech; import android.widget.Toast; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; public class TTSSpeakFunction implements FREFunction { public FREObject call(FREContext context, FREObject[] passedArgs) { try { FREObject fro = passedArgs[0]; String text = fro.getAsString(); TextToSpeech tts = TTSController.getInstance().getTTS(); try { if (text.contains("AppName") || text.contains("AboutApp") || text.contains("AboutTime")) { String[] vStrings = fro.getAsString().split("\\^"); if (vStrings[1].equalsIgnoreCase("AppName") || vStrings[1].equalsIgnoreCase("AboutTime") || vStrings[1].equalsIgnoreCase("AboutApp")) { TTSController.getInstance().speak(vStrings[1], vStrings[0]); } } else { TTSController.getInstance().speak(text,""); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { Toast.makeText(context.getActivity(), "error : " + e.toString(), Toast.LENGTH_SHORT).show(); } return null; } }
824d8ad872c64022a579e8e632dee8897d4d3e2b
77e817c6d10a8f3f8b6162d1f4be3bc568668a45
/platforms/android/gen/is/route/www/R.java
076613d8c90743eeca91b201eafeb7623c20d43f
[]
no_license
Kresendo/routeIsApp
5fd003e24482ab4fa978371e50dcd357a61dcf91
d94cb111943f7a7992bf0937e7e0624ebe7e9b61
refs/heads/master
2020-04-06T04:05:46.859858
2013-10-30T11:52:24
2013-10-30T11:52:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
710
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package is.route.www; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; public static final int icon=0x7f020001; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f050000; } public static final class xml { public static final int config=0x7f040000; } }
b56563c1bd01ea02cedc0fdecb0334efadfa2d09
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipseswt_cluster/29058/src_0.java
ae09ff2f679a77aca1620c821003c45ee9fc9a72
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
159,616
java
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.widgets; import org.eclipse.swt.*; import org.eclipse.swt.accessibility.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.internal.*; import org.eclipse.swt.internal.cairo.*; import org.eclipse.swt.internal.gtk.*; /** * Control is the abstract superclass of all windowed user interface classes. * <p> * <dl> * <dt><b>Styles:</b> * <dd>BORDER</dd> * <dd>LEFT_TO_RIGHT, RIGHT_TO_LEFT</dd> * <dt><b>Events:</b> * <dd>DragDetect, FocusIn, FocusOut, Help, KeyDown, KeyUp, MenuDetect, MouseDoubleClick, MouseDown, MouseEnter, * MouseExit, MouseHover, MouseUp, MouseMove, MouseWheel, MouseHorizontalWheel, MouseVerticalWheel, Move, * Paint, Resize, Traverse</dd> * </dl> * </p><p> * Only one of LEFT_TO_RIGHT or RIGHT_TO_LEFT may be specified. * </p><p> * IMPORTANT: This class is intended to be subclassed <em>only</em> * within the SWT implementation. * </p> * * @see <a href="http://www.eclipse.org/swt/snippets/#control">Control snippets</a> * @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: ControlExample</a> * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> * @noextend This class is not intended to be subclassed by clients. */ public abstract class Control extends Widget implements Drawable { int /*long*/ fixedHandle; int /*long*/ redrawWindow, enableWindow; int drawCount; Composite parent; Cursor cursor; Menu menu; Image backgroundImage; Font font; Region region; String toolTipText; Object layoutData; Accessible accessible; Control labelRelation; Control () { } /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * <p> * The style value is either one of the style constants defined in * class <code>SWT</code> which is applicable to instances of this * class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>SWT</code> style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see SWT#BORDER * @see SWT#LEFT_TO_RIGHT * @see SWT#RIGHT_TO_LEFT * @see Widget#checkSubclass * @see Widget#getStyle */ public Control (Composite parent, int style) { super (parent, style); this.parent = parent; createWidget (0); } Font defaultFont () { return display.getSystemFont (); } void deregister () { super.deregister (); if (fixedHandle != 0) display.removeWidget (fixedHandle); int /*long*/ imHandle = imHandle (); if (imHandle != 0) display.removeWidget (imHandle); } void drawBackground (Control control, int /*long*/ window, int /*long*/ region, int x, int y, int width, int height) { int /*long*/ gdkGC = OS.gdk_gc_new (window); if (region != 0) OS.gdk_gc_set_clip_region (gdkGC, region); if (control.backgroundImage != null) { Point pt = display.map (this, control, 0, 0); OS.gdk_gc_set_fill (gdkGC, OS.GDK_TILED); OS.gdk_gc_set_ts_origin (gdkGC, -pt.x, -pt.y); OS.gdk_gc_set_tile (gdkGC, control.backgroundImage.pixmap); OS.gdk_draw_rectangle (window, gdkGC, 1, x, y, width, height); } else { GdkColor color = control.getBackgroundColor (); OS.gdk_gc_set_foreground (gdkGC, color); OS.gdk_draw_rectangle (window, gdkGC, 1, x, y, width, height); } OS.g_object_unref (gdkGC); } boolean drawGripper (int x, int y, int width, int height, boolean vertical) { int /*long*/ paintHandle = paintHandle (); int /*long*/ window = OS.GTK_WIDGET_WINDOW (paintHandle); if (window == 0) return false; int orientation = vertical ? OS.GTK_ORIENTATION_HORIZONTAL : OS.GTK_ORIENTATION_VERTICAL; if ((style & SWT.MIRRORED) != 0) x = getClientWidth () - width - x; OS.gtk_paint_handle (OS.gtk_widget_get_style (paintHandle), window, OS.GTK_STATE_NORMAL, OS.GTK_SHADOW_OUT, null, paintHandle, new byte [1], x, y, width, height, orientation); return true; } void enableWidget (boolean enabled) { OS.gtk_widget_set_sensitive (handle, enabled); } int /*long*/ enterExitHandle () { return eventHandle (); } int /*long*/ eventHandle () { return handle; } int /*long*/ eventWindow () { int /*long*/ eventHandle = eventHandle (); OS.gtk_widget_realize (eventHandle); return OS.GTK_WIDGET_WINDOW (eventHandle); } void fixFocus (Control focusControl) { Shell shell = getShell (); Control control = this; while (control != shell && (control = control.parent) != null) { if (control.setFocus ()) return; } shell.setSavedFocus (focusControl); int /*long*/ focusHandle = shell.vboxHandle; OS.GTK_WIDGET_SET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); OS.gtk_widget_grab_focus (focusHandle); OS.GTK_WIDGET_UNSET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); } void fixStyle () { if (fixedHandle != 0) fixStyle (fixedHandle); } void fixStyle (int /*long*/ handle) { /* * Feature in GTK. Some GTK themes apply a different background to * the contents of a GtkNotebook. However, in an SWT TabFolder, the * children are not parented below the GtkNotebook widget, and usually * have their own GtkFixed. The fix is to look up the correct style * for a child of a GtkNotebook and apply its background to any GtkFixed * widgets that are direct children of an SWT TabFolder. * * Note that this has to be when the theme settings changes and that it * should not override the application background. */ if ((state & BACKGROUND) != 0) return; if ((state & THEME_BACKGROUND) == 0) return; int /*long*/ childStyle = parent.childStyle (); if (childStyle != 0) { GdkColor color = new GdkColor(); OS.gtk_style_get_bg (childStyle, 0, color); setBackgroundColor (color); } } int /*long*/ focusHandle () { return handle; } int /*long*/ fontHandle () { return handle; } boolean hasFocus () { return this == display.getFocusControl(); } void hookEvents () { /* Connect the keyboard signals */ int /*long*/ focusHandle = focusHandle (); int focusMask = OS.GDK_KEY_PRESS_MASK | OS.GDK_KEY_RELEASE_MASK | OS.GDK_FOCUS_CHANGE_MASK; OS.gtk_widget_add_events (focusHandle, focusMask); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [POPUP_MENU], 0, display.closures [POPUP_MENU], false); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [SHOW_HELP], 0, display.closures [SHOW_HELP], false); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [KEY_PRESS_EVENT], 0, display.closures [KEY_PRESS_EVENT], false); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [KEY_RELEASE_EVENT], 0, display.closures [KEY_RELEASE_EVENT], false); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS], 0, display.closures [FOCUS], false); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS_IN_EVENT], 0, display.closures [FOCUS_IN_EVENT], false); OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS_OUT_EVENT], 0, display.closures [FOCUS_OUT_EVENT], false); /* Connect the mouse signals */ int /*long*/ eventHandle = eventHandle (); int eventMask = OS.GDK_POINTER_MOTION_MASK | OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK; OS.gtk_widget_add_events (eventHandle, eventMask); OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [BUTTON_PRESS_EVENT], 0, display.closures [BUTTON_PRESS_EVENT], false); OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [BUTTON_RELEASE_EVENT], 0, display.closures [BUTTON_RELEASE_EVENT], false); OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [MOTION_NOTIFY_EVENT], 0, display.closures [MOTION_NOTIFY_EVENT], false); OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [SCROLL_EVENT], 0, display.closures [SCROLL_EVENT], false); /* Connect enter/exit signals */ int /*long*/ enterExitHandle = enterExitHandle (); int enterExitMask = OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK; OS.gtk_widget_add_events (enterExitHandle, enterExitMask); OS.g_signal_connect_closure_by_id (enterExitHandle, display.signalIds [ENTER_NOTIFY_EVENT], 0, display.closures [ENTER_NOTIFY_EVENT], false); OS.g_signal_connect_closure_by_id (enterExitHandle, display.signalIds [LEAVE_NOTIFY_EVENT], 0, display.closures [LEAVE_NOTIFY_EVENT], false); /* * Feature in GTK. Events such as mouse move are propagate up * the widget hierarchy and are seen by the parent. This is the * correct GTK behavior but not correct for SWT. The fix is to * hook a signal after and stop the propagation using a negative * event number to distinguish this case. * * The signal is hooked to the fixedHandle to catch events sent to * lightweight widgets. */ int /*long*/ blockHandle = fixedHandle != 0 ? fixedHandle : eventHandle; OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [BUTTON_PRESS_EVENT], 0, display.closures [BUTTON_PRESS_EVENT_INVERSE], true); OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [BUTTON_RELEASE_EVENT], 0, display.closures [BUTTON_RELEASE_EVENT_INVERSE], true); OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [MOTION_NOTIFY_EVENT], 0, display.closures [MOTION_NOTIFY_EVENT_INVERSE], true); /* Connect the event_after signal for both key and mouse */ OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [EVENT_AFTER], 0, display.closures [EVENT_AFTER], false); if (focusHandle != eventHandle) { OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [EVENT_AFTER], 0, display.closures [EVENT_AFTER], false); } /* Connect the paint signal */ int /*long*/ paintHandle = paintHandle (); int paintMask = OS.GDK_EXPOSURE_MASK | OS.GDK_VISIBILITY_NOTIFY_MASK; OS.gtk_widget_add_events (paintHandle, paintMask); OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [EXPOSE_EVENT], 0, display.closures [EXPOSE_EVENT_INVERSE], false); OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [VISIBILITY_NOTIFY_EVENT], 0, display.closures [VISIBILITY_NOTIFY_EVENT], false); OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [EXPOSE_EVENT], 0, display.closures [EXPOSE_EVENT], true); /* Connect the Input Method signals */ OS.g_signal_connect_closure_by_id (handle, display.signalIds [REALIZE], 0, display.closures [REALIZE], true); OS.g_signal_connect_closure_by_id (handle, display.signalIds [UNREALIZE], 0, display.closures [UNREALIZE], false); int /*long*/ imHandle = imHandle (); if (imHandle != 0) { OS.g_signal_connect_closure (imHandle, OS.commit, display.closures [COMMIT], false); OS.g_signal_connect_closure (imHandle, OS.preedit_changed, display.closures [PREEDIT_CHANGED], false); } OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [STYLE_SET], 0, display.closures [STYLE_SET], false); int /*long*/ topHandle = topHandle (); OS.g_signal_connect_closure_by_id (topHandle, display.signalIds [MAP], 0, display.closures [MAP], true); } int /*long*/ hoverProc (int /*long*/ widget) { int [] x = new int [1], y = new int [1], mask = new int [1]; OS.gdk_window_get_pointer (0, x, y, mask); sendMouseEvent (SWT.MouseHover, 0, /*time*/0, x [0], y [0], false, mask [0]); /* Always return zero in order to cancel the hover timer */ return 0; } int /*long*/ topHandle() { if (fixedHandle != 0) return fixedHandle; return super.topHandle (); } int /*long*/ paintHandle () { int /*long*/ topHandle = topHandle (); int /*long*/ paintHandle = handle; while (paintHandle != topHandle) { if ((OS.GTK_WIDGET_FLAGS (paintHandle) & OS.GTK_NO_WINDOW) == 0) break; paintHandle = OS.gtk_widget_get_parent (paintHandle); } return paintHandle; } int /*long*/ paintWindow () { int /*long*/ paintHandle = paintHandle (); OS.gtk_widget_realize (paintHandle); return OS.GTK_WIDGET_WINDOW (paintHandle); } /** * Prints the receiver and all children. * * @param gc the gc where the drawing occurs * @return <code>true</code> if the operation was successful and <code>false</code> otherwise * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the gc is null</li> * <li>ERROR_INVALID_ARGUMENT - if the gc has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.4 */ public boolean print (GC gc) { checkWidget (); if (gc == null) error (SWT.ERROR_NULL_ARGUMENT); if (gc.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); int /*long*/ topHandle = topHandle (); OS.gtk_widget_realize (topHandle); int /*long*/ window = OS.GTK_WIDGET_WINDOW (topHandle); GCData data = gc.getGCData (); OS.gdk_window_process_updates (window, true); printWidget (gc, data.drawable, OS.gdk_drawable_get_depth (data.drawable), 0, 0); return true; } void printWidget (GC gc, int /*long*/ drawable, int depth, int x, int y) { boolean obscured = (state & OBSCURED) != 0; state &= ~OBSCURED; int /*long*/ topHandle = topHandle (); int /*long*/ window = OS.GTK_WIDGET_WINDOW (topHandle); printWindow (true, this, gc, drawable, depth, window, x, y); if (obscured) state |= OBSCURED; } void printWindow (boolean first, Control control, GC gc, int /*long*/ drawable, int depth, int /*long*/ window, int x, int y) { if (OS.gdk_drawable_get_depth (window) != depth) return; GdkRectangle rect = new GdkRectangle (); int [] width = new int [1], height = new int [1]; OS.gdk_drawable_get_size (window, width, height); rect.width = width [0]; rect.height = height [0]; OS.gdk_window_begin_paint_rect (window, rect); int /*long*/ [] real_drawable = new int /*long*/ [1]; int [] x_offset = new int [1], y_offset = new int [1]; OS.gdk_window_get_internal_paint_info (window, real_drawable, x_offset, y_offset); int /*long*/ [] userData = new int /*long*/ [1]; OS.gdk_window_get_user_data (window, userData); if (userData [0] != 0) { int /*long*/ eventPtr = OS.gdk_event_new (OS.GDK_EXPOSE); GdkEventExpose event = new GdkEventExpose (); event.type = OS.GDK_EXPOSE; event.window = OS.g_object_ref (window); event.area_width = rect.width; event.area_height = rect.height; event.region = OS.gdk_region_rectangle (rect); OS.memmove (eventPtr, event, GdkEventExpose.sizeof); OS.gtk_widget_send_expose (userData [0], eventPtr); OS.gdk_event_free (eventPtr); } int srcX = x_offset [0], srcY = y_offset [0]; int destX = x, destY = y, destWidth = width [0], destHeight = height [0]; if (!first) { int [] cX = new int [1], cY = new int [1]; OS.gdk_window_get_position (window, cX, cY); int /*long*/ parentWindow = OS.gdk_window_get_parent (window); int [] pW = new int [1], pH = new int [1]; OS.gdk_drawable_get_size (parentWindow, pW, pH); srcX = x_offset [0] - cX [0]; srcY = y_offset [0] - cY [0]; destX = x - cX [0]; destY = y - cY [0]; destWidth = Math.min (cX [0] + width [0], pW [0]); destHeight = Math.min (cY [0] + height [0], pH [0]); } GCData gcData = gc.getGCData(); int /*long*/ cairo = gcData.cairo; if (cairo != 0) { int /*long*/ xDisplay = OS.GDK_DISPLAY(); int /*long*/ xVisual = OS.gdk_x11_visual_get_xvisual(OS.gdk_visual_get_system()); int /*long*/ xDrawable = OS.GDK_PIXMAP_XID(real_drawable [0]); int /*long*/ surface = Cairo.cairo_xlib_surface_create(xDisplay, xDrawable, xVisual, width [0], height [0]); if (surface == 0) SWT.error(SWT.ERROR_NO_HANDLES); Cairo.cairo_save(cairo); Cairo.cairo_rectangle(cairo, destX , destY, destWidth, destHeight); Cairo.cairo_clip(cairo); Cairo.cairo_translate(cairo, destX, destY); int /*long*/ pattern = Cairo.cairo_pattern_create_for_surface(surface); if (pattern == 0) SWT.error(SWT.ERROR_NO_HANDLES); Cairo.cairo_pattern_set_filter(pattern, Cairo.CAIRO_FILTER_BEST); Cairo.cairo_set_source(cairo, pattern); if (gcData.alpha != 0xFF) { Cairo.cairo_paint_with_alpha(cairo, gcData.alpha / (float)0xFF); } else { Cairo.cairo_paint(cairo); } Cairo.cairo_restore(cairo); Cairo.cairo_pattern_destroy(pattern); Cairo.cairo_surface_destroy(surface); } else { OS.gdk_draw_drawable (drawable, gc.handle, real_drawable [0], srcX, srcY, destX, destY, destWidth, destHeight); } OS.gdk_window_end_paint (window); int /*long*/ children = OS.gdk_window_get_children (window); if (children != 0) { int /*long*/ windows = children; while (windows != 0) { int /*long*/ child = OS.g_list_data (windows); if (OS.gdk_window_is_visible (child)) { int /*long*/ [] data = new int /*long*/ [1]; OS.gdk_window_get_user_data (child, data); if (data [0] != 0) { Widget widget = display.findWidget (data [0]); if (widget == null || widget == control) { int [] x_pos = new int [1], y_pos = new int [1]; OS.gdk_window_get_position (child, x_pos, y_pos); printWindow (false, control, gc, drawable, depth, child, x + x_pos [0], y + y_pos [0]); } } } windows = OS.g_list_next (windows); } OS.g_list_free (children); } } /** * Returns the preferred size of the receiver. * <p> * The <em>preferred size</em> of a control is the size that it would * best be displayed at. The width hint and height hint arguments * allow the caller to ask a control questions such as "Given a particular * width, how high does the control need to be to show all of the contents?" * To indicate that the caller does not wish to constrain a particular * dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. * </p> * * @param wHint the width hint (can be <code>SWT.DEFAULT</code>) * @param hHint the height hint (can be <code>SWT.DEFAULT</code>) * @return the preferred size of the control * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Layout * @see #getBorderWidth * @see #getBounds * @see #getSize * @see #pack(boolean) * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint) { return computeSize (wHint, hHint, true); } Widget computeTabGroup () { if (isTabGroup()) return this; return parent.computeTabGroup (); } Widget[] computeTabList() { if (isTabGroup()) { if (getVisible() && getEnabled()) { return new Widget[] {this}; } } return new Widget[0]; } Control computeTabRoot () { Control[] tabList = parent._getTabList(); if (tabList != null) { int index = 0; while (index < tabList.length) { if (tabList [index] == this) break; index++; } if (index == tabList.length) { if (isTabGroup ()) return this; } } return parent.computeTabRoot (); } void checkBuffered () { style |= SWT.DOUBLE_BUFFERED; } void checkBackground () { Shell shell = getShell (); if (this == shell) return; state &= ~PARENT_BACKGROUND; Composite composite = parent; do { int mode = composite.backgroundMode; if (mode != SWT.INHERIT_NONE) { if (mode == SWT.INHERIT_DEFAULT) { Control control = this; do { if ((control.state & THEME_BACKGROUND) == 0) { return; } control = control.parent; } while (control != composite); } state |= PARENT_BACKGROUND; return; } if (composite == shell) break; composite = composite.parent; } while (true); } void checkBorder () { if (getBorderWidth () == 0) style &= ~SWT.BORDER; } void checkMirrored () { if ((style & SWT.RIGHT_TO_LEFT) != 0) style |= SWT.MIRRORED; } int /*long*/ childStyle () { return parent.childStyle (); } void createWidget (int index) { state |= DRAG_DETECT; checkOrientation (parent); super.createWidget (index); checkBackground (); if ((state & PARENT_BACKGROUND) != 0) setParentBackground (); checkBuffered (); showWidget (); setInitialBounds (); setZOrder (null, false, false); setRelations (); checkMirrored (); checkBorder (); } /** * Returns the preferred size of the receiver. * <p> * The <em>preferred size</em> of a control is the size that it would * best be displayed at. The width hint and height hint arguments * allow the caller to ask a control questions such as "Given a particular * width, how high does the control need to be to show all of the contents?" * To indicate that the caller does not wish to constrain a particular * dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. * </p><p> * If the changed flag is <code>true</code>, it indicates that the receiver's * <em>contents</em> have changed, therefore any caches that a layout manager * containing the control may have been keeping need to be flushed. When the * control is resized, the changed flag will be <code>false</code>, so layout * manager caches can be retained. * </p> * * @param wHint the width hint (can be <code>SWT.DEFAULT</code>) * @param hHint the height hint (can be <code>SWT.DEFAULT</code>) * @param changed <code>true</code> if the control's contents have changed, and <code>false</code> otherwise * @return the preferred size of the control. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Layout * @see #getBorderWidth * @see #getBounds * @see #getSize * @see #pack(boolean) * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint, boolean changed) { checkWidget(); if (wHint != SWT.DEFAULT && wHint < 0) wHint = 0; if (hHint != SWT.DEFAULT && hHint < 0) hHint = 0; return computeNativeSize (handle, wHint, hHint, changed); } Point computeNativeSize (int /*long*/ h, int wHint, int hHint, boolean changed) { int width = wHint, height = hHint; if (wHint == SWT.DEFAULT && hHint == SWT.DEFAULT) { GtkRequisition requisition = new GtkRequisition (); gtk_widget_size_request (h, requisition); width = OS.GTK_WIDGET_REQUISITION_WIDTH (h); height = OS.GTK_WIDGET_REQUISITION_HEIGHT (h); } else if (wHint == SWT.DEFAULT || hHint == SWT.DEFAULT) { int [] reqWidth = new int [1], reqHeight = new int [1]; OS.gtk_widget_get_size_request (h, reqWidth, reqHeight); OS.gtk_widget_set_size_request (h, wHint, hHint); GtkRequisition requisition = new GtkRequisition (); gtk_widget_size_request (h, requisition); OS.gtk_widget_set_size_request (h, reqWidth [0], reqHeight [0]); width = wHint == SWT.DEFAULT ? requisition.width : wHint; height = hHint == SWT.DEFAULT ? requisition.height : hHint; } return new Point (width, height); } void forceResize () { /* * Force size allocation on all children of this widget's * topHandle. Note that all calls to gtk_widget_size_allocate() * must be preceded by a call to gtk_widget_size_request(). */ int /*long*/ topHandle = topHandle (); GtkRequisition requisition = new GtkRequisition (); gtk_widget_size_request (topHandle, requisition); GtkAllocation allocation = new GtkAllocation (); allocation.x = OS.GTK_WIDGET_X (topHandle); allocation.y = OS.GTK_WIDGET_Y (topHandle); allocation.width = OS.GTK_WIDGET_WIDTH (topHandle); allocation.height = OS.GTK_WIDGET_HEIGHT (topHandle); OS.gtk_widget_size_allocate (topHandle, allocation); } /** * Returns the accessible object for the receiver. * If this is the first time this object is requested, * then the object is created and returned. * * @return the accessible object * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Accessible#addAccessibleListener * @see Accessible#addAccessibleControlListener * * @since 2.0 */ public Accessible getAccessible () { checkWidget (); return _getAccessible (); } Accessible _getAccessible () { if (accessible == null) { accessible = Accessible.internal_new_Accessible (this); } return accessible; } /** * Returns a rectangle describing the receiver's size and location * relative to its parent (or its display if its parent is null), * unless the receiver is a shell. In this case, the location is * relative to the display. * * @return the receiver's bounding rectangle * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Rectangle getBounds () { checkWidget(); int /*long*/ topHandle = topHandle (); int x = OS.GTK_WIDGET_X (topHandle); int y = OS.GTK_WIDGET_Y (topHandle); int width = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); int height = (state & ZERO_HEIGHT) != 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); if ((parent.style & SWT.MIRRORED) != 0) x = parent.getClientWidth () - width - x; return new Rectangle (x, y, width, height); } /** * Sets the receiver's size and location to the rectangular * area specified by the argument. The <code>x</code> and * <code>y</code> fields of the rectangle are relative to * the receiver's parent (or its display if its parent is null). * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param rect the new bounds for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds (Rectangle rect) { checkWidget (); if (rect == null) error (SWT.ERROR_NULL_ARGUMENT); setBounds (rect.x, rect.y, Math.max (0, rect.width), Math.max (0, rect.height), true, true); } /** * Sets the receiver's size and location to the rectangular * area specified by the arguments. The <code>x</code> and * <code>y</code> arguments are relative to the receiver's * parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the <code>x</code> * and <code>y</code> arguments are relative to the display. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param x the new x coordinate for the receiver * @param y the new y coordinate for the receiver * @param width the new width for the receiver * @param height the new height for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds (int x, int y, int width, int height) { checkWidget(); setBounds (x, y, Math.max (0, width), Math.max (0, height), true, true); } void markLayout (boolean changed, boolean all) { /* Do nothing */ } void modifyStyle (int /*long*/ handle, int /*long*/ style) { super.modifyStyle(handle, style); /* * Bug in GTK. When changing the style of a control that * has had a region set on it, the region is lost. The * fix is to set the region again. */ if (region != null) OS.gdk_window_shape_combine_region (OS.GTK_WIDGET_WINDOW (topHandle ()), region.handle, 0, 0); } void moveHandle (int x, int y) { int /*long*/ topHandle = topHandle (); int /*long*/ parentHandle = parent.parentingHandle (); /* * Feature in GTK. Calling gtk_fixed_move() to move a child causes * the whole parent to redraw. This is a performance problem. The * fix is temporarily make the parent not visible during the move. * * NOTE: Because every widget in SWT has an X window, the new and * old bounds of the child are correctly redrawn. */ int flags = OS.GTK_WIDGET_FLAGS (parentHandle); OS.GTK_WIDGET_UNSET_FLAGS (parentHandle, OS.GTK_VISIBLE); OS.gtk_fixed_move (parentHandle, topHandle, x, y); if ((flags & OS.GTK_VISIBLE) != 0) { OS.GTK_WIDGET_SET_FLAGS (parentHandle, OS.GTK_VISIBLE); } } void resizeHandle (int width, int height) { int /*long*/ topHandle = topHandle (); OS.gtk_widget_set_size_request (topHandle, width, height); if (topHandle != handle) OS.gtk_widget_set_size_request (handle, width, height); } int setBounds (int x, int y, int width, int height, boolean move, boolean resize) { int /*long*/ topHandle = topHandle (); boolean sendMove = move; if ((parent.style & SWT.MIRRORED) != 0) { int clientWidth = parent.getClientWidth (); int oldWidth = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); int oldX = clientWidth - oldWidth - OS.GTK_WIDGET_X (topHandle); if (move) { sendMove &= x != oldX; x = clientWidth - (resize ? width : oldWidth) - x; } else { move = true; x = clientWidth - (resize ? width : oldWidth) - oldX; y = OS.GTK_WIDGET_Y (topHandle); } } boolean sameOrigin = true, sameExtent = true; if (move) { int oldX = OS.GTK_WIDGET_X (topHandle); int oldY = OS.GTK_WIDGET_Y (topHandle); sameOrigin = x == oldX && y == oldY; if (!sameOrigin) { if (enableWindow != 0) { OS.gdk_window_move (enableWindow, x, y); } moveHandle (x, y); } } int clientWidth = 0; if (resize) { int oldWidth = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); int oldHeight = (state & ZERO_HEIGHT) != 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); sameExtent = width == oldWidth && height == oldHeight; if (!sameExtent && (style & SWT.MIRRORED) != 0) clientWidth = getClientWidth (); if (!sameExtent && !(width == 0 && height == 0)) { int newWidth = Math.max (1, width); int newHeight = Math.max (1, height); if (redrawWindow != 0) { OS.gdk_window_resize (redrawWindow, newWidth, newHeight); } if (enableWindow != 0) { OS.gdk_window_resize (enableWindow, newWidth, newHeight); } resizeHandle (newWidth, newHeight); } } if (!sameOrigin || !sameExtent) { /* * Cause a size allocation this widget's topHandle. Note that * all calls to gtk_widget_size_allocate() must be preceded by * a call to gtk_widget_size_request(). */ GtkRequisition requisition = new GtkRequisition (); gtk_widget_size_request (topHandle, requisition); GtkAllocation allocation = new GtkAllocation (); if (move) { allocation.x = x; allocation.y = y; } else { allocation.x = OS.GTK_WIDGET_X (topHandle); allocation.y = OS.GTK_WIDGET_Y (topHandle); } if (resize) { allocation.width = width; allocation.height = height; } else { allocation.width = OS.GTK_WIDGET_WIDTH (topHandle); allocation.height = OS.GTK_WIDGET_HEIGHT (topHandle); } OS.gtk_widget_size_allocate (topHandle, allocation); } /* * Bug in GTK. Widgets cannot be sized smaller than 1x1. * The fix is to hide zero-sized widgets and show them again * when they are resized larger. */ if (!sameExtent) { state = (width == 0) ? state | ZERO_WIDTH : state & ~ZERO_WIDTH; state = (height == 0) ? state | ZERO_HEIGHT : state & ~ZERO_HEIGHT; if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) != 0) { if (enableWindow != 0) { OS.gdk_window_hide (enableWindow); } OS.gtk_widget_hide (topHandle); } else { if ((state & HIDDEN) == 0) { if (enableWindow != 0) { OS.gdk_window_show_unraised (enableWindow); } OS.gtk_widget_show (topHandle); } } if ((style & SWT.MIRRORED) != 0) moveChildren (clientWidth); } int result = 0; if (move && !sameOrigin) { Control control = findBackgroundControl (); if (control != null && control.backgroundImage != null) { if (isVisible ()) redrawWidget (0, 0, 0, 0, true, true, true); } if (sendMove) sendEvent (SWT.Move); result |= MOVED; } if (resize && !sameExtent) { sendEvent (SWT.Resize); result |= RESIZED; } return result; } /** * Returns a point describing the receiver's location relative * to its parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the point is * relative to the display. * * @return the receiver's location * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getLocation () { checkWidget(); int /*long*/ topHandle = topHandle (); int x = OS.GTK_WIDGET_X (topHandle); int y = OS.GTK_WIDGET_Y (topHandle); if ((parent.style & SWT.MIRRORED) != 0) { int width = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); x = parent.getClientWidth () - width - x; } return new Point (x, y); } /** * Sets the receiver's location to the point specified by * the arguments which are relative to the receiver's * parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the point is * relative to the display. * * @param location the new location for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLocation (Point location) { checkWidget (); if (location == null) error (SWT.ERROR_NULL_ARGUMENT); setBounds (location.x, location.y, 0, 0, true, false); } /** * Sets the receiver's location to the point specified by * the arguments which are relative to the receiver's * parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the point is * relative to the display. * * @param x the new x coordinate for the receiver * @param y the new y coordinate for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLocation(int x, int y) { checkWidget(); setBounds (x, y, 0, 0, true, false); } /** * Returns a point describing the receiver's size. The * x coordinate of the result is the width of the receiver. * The y coordinate of the result is the height of the * receiver. * * @return the receiver's size * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getSize () { checkWidget(); int /*long*/ topHandle = topHandle (); int width = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); int height = (state & ZERO_HEIGHT) != 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); return new Point (width, height); } /** * Sets the receiver's size to the point specified by the argument. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause them to be * set to zero instead. * </p> * * @param size the new size for the receiver * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSize (Point size) { checkWidget (); if (size == null) error (SWT.ERROR_NULL_ARGUMENT); setBounds (0, 0, Math.max (0, size.x), Math.max (0, size.y), false, true); } /** * Sets the shape of the control to the region specified * by the argument. When the argument is null, the * default shape of the control is restored. * * @param region the region that defines the shape of the control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the region has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.4 */ public void setRegion (Region region) { checkWidget (); if (region != null && region.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT); int /*long*/ window = OS.GTK_WIDGET_WINDOW (topHandle ()); int /*long*/ shape_region = (region == null) ? 0 : region.handle; OS.gdk_window_shape_combine_region (window, shape_region, 0, 0); this.region = region; } void setRelations () { int /*long*/ parentHandle = parent.parentingHandle (); int /*long*/ list = OS.gtk_container_get_children (parentHandle); if (list == 0) return; int count = OS.g_list_length (list); if (count > 1) { /* * the receiver is the last item in the list, so its predecessor will * be the second-last item in the list */ int /*long*/ handle = OS.g_list_nth_data (list, count - 2); if (handle != 0) { Widget widget = display.getWidget (handle); if (widget != null && widget != this) { if (widget instanceof Control) { Control sibling = (Control)widget; sibling.addRelation (this); } } } } OS.g_list_free (list); } /** * Sets the receiver's size to the point specified by the arguments. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param width the new width for the receiver * @param height the new height for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSize (int width, int height) { checkWidget(); setBounds (0, 0, Math.max (0, width), Math.max (0, height), false, true); } boolean isActive () { return getShell ().getModalShell () == null && display.getModalDialog () == null; } /* * Answers a boolean indicating whether a Label that precedes the receiver in * a layout should be read by screen readers as the recevier's label. */ boolean isDescribedByLabel () { return true; } boolean isFocusHandle (int /*long*/ widget) { return widget == focusHandle (); } /** * Moves the receiver above the specified control in the * drawing order. If the argument is null, then the receiver * is moved to the top of the drawing order. The control at * the top of the drawing order will not be covered by other * controls even if they occupy intersecting areas. * * @param control the sibling control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the control has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Control#moveBelow * @see Composite#getChildren */ public void moveAbove (Control control) { checkWidget(); if (control != null) { if (control.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); if (parent != control.parent) return; } setZOrder (control, true, true); } /** * Moves the receiver below the specified control in the * drawing order. If the argument is null, then the receiver * is moved to the bottom of the drawing order. The control at * the bottom of the drawing order will be covered by all other * controls which occupy intersecting areas. * * @param control the sibling control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the control has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Control#moveAbove * @see Composite#getChildren */ public void moveBelow (Control control) { checkWidget(); if (control != null) { if (control.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (parent != control.parent) return; } setZOrder (control, false, true); } void moveChildren (int oldWidth) { } /** * Causes the receiver to be resized to its preferred size. * For a composite, this involves computing the preferred size * from its layout, if there is one. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #computeSize(int, int, boolean) */ public void pack () { pack (true); } /** * Causes the receiver to be resized to its preferred size. * For a composite, this involves computing the preferred size * from its layout, if there is one. * <p> * If the changed flag is <code>true</code>, it indicates that the receiver's * <em>contents</em> have changed, therefore any caches that a layout manager * containing the control may have been keeping need to be flushed. When the * control is resized, the changed flag will be <code>false</code>, so layout * manager caches can be retained. * </p> * * @param changed whether or not the receiver's contents have changed * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #computeSize(int, int, boolean) */ public void pack (boolean changed) { setSize (computeSize (SWT.DEFAULT, SWT.DEFAULT, changed)); } /** * Sets the layout data associated with the receiver to the argument. * * @param layoutData the new layout data for the receiver. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLayoutData (Object layoutData) { checkWidget(); this.layoutData = layoutData; } /** * Returns a point which is the result of converting the * argument, which is specified in display relative coordinates, * to coordinates relative to the receiver. * <p> * @param x the x coordinate to be translated * @param y the y coordinate to be translated * @return the translated coordinates * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public Point toControl (int x, int y) { checkWidget (); int /*long*/ window = eventWindow (); int [] origin_x = new int [1], origin_y = new int [1]; OS.gdk_window_get_origin (window, origin_x, origin_y); x -= origin_x [0]; y -= origin_y [0]; if ((style & SWT.MIRRORED) != 0) x = getClientWidth () - x; return new Point (x, y); } /** * Returns a point which is the result of converting the * argument, which is specified in display relative coordinates, * to coordinates relative to the receiver. * <p> * @param point the point to be translated (must not be null) * @return the translated coordinates * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point toControl (Point point) { checkWidget (); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); return toControl (point.x, point.y); } /** * Returns a point which is the result of converting the * argument, which is specified in coordinates relative to * the receiver, to display relative coordinates. * <p> * @param x the x coordinate to be translated * @param y the y coordinate to be translated * @return the translated coordinates * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public Point toDisplay (int x, int y) { checkWidget(); int /*long*/ window = eventWindow (); int [] origin_x = new int [1], origin_y = new int [1]; OS.gdk_window_get_origin (window, origin_x, origin_y); if ((style & SWT.MIRRORED) != 0) x = getClientWidth () - x; x += origin_x [0]; y += origin_y [0]; return new Point (x, y); } /** * Returns a point which is the result of converting the * argument, which is specified in coordinates relative to * the receiver, to display relative coordinates. * <p> * @param point the point to be translated (must not be null) * @return the translated coordinates * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point toDisplay (Point point) { checkWidget(); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); return toDisplay (point.x, point.y); } /** * Adds the listener to the collection of listeners who will * be notified when the control is moved or resized, by sending * it one of the messages defined in the <code>ControlListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ControlListener * @see #removeControlListener */ public void addControlListener(ControlListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Resize,typedListener); addListener (SWT.Move,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when a drag gesture occurs, by sending it * one of the messages defined in the <code>DragDetectListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see DragDetectListener * @see #removeDragDetectListener * * @since 3.3 */ public void addDragDetectListener (DragDetectListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.DragDetect,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the control gains or loses focus, by sending * it one of the messages defined in the <code>FocusListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see FocusListener * @see #removeFocusListener */ public void addFocusListener(FocusListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.FocusIn,typedListener); addListener(SWT.FocusOut,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when help events are generated for the control, * by sending it one of the messages defined in the * <code>HelpListener</code> interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see HelpListener * @see #removeHelpListener */ public void addHelpListener (HelpListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Help, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when keys are pressed and released on the system keyboard, by sending * it one of the messages defined in the <code>KeyListener</code> * interface. * <p> * When a key listener is added to a control, the control * will take part in widget traversal. By default, all * traversal keys (such as the tab key and so on) are * delivered to the control. In order for a control to take * part in traversal, it should listen for traversal events. * Otherwise, the user can traverse into a control but not * out. Note that native controls such as table and tree * implement key traversal in the operating system. It is * not necessary to add traversal listeners for these controls, * unless you want to override the default traversal. * </p> * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see KeyListener * @see #removeKeyListener */ public void addKeyListener(KeyListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.KeyUp,typedListener); addListener(SWT.KeyDown,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the platform-specific context menu trigger * has occurred, by sending it one of the messages defined in * the <code>MenuDetectListener</code> interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MenuDetectListener * @see #removeMenuDetectListener * * @since 3.3 */ public void addMenuDetectListener (MenuDetectListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MenuDetect, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when mouse buttons are pressed and released, by sending * it one of the messages defined in the <code>MouseListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseListener * @see #removeMouseListener */ public void addMouseListener(MouseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.MouseDown,typedListener); addListener(SWT.MouseUp,typedListener); addListener(SWT.MouseDoubleClick,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse moves, by sending it one of the * messages defined in the <code>MouseMoveListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseMoveListener * @see #removeMouseMoveListener */ public void addMouseMoveListener(MouseMoveListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.MouseMove,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse passes or hovers over controls, by sending * it one of the messages defined in the <code>MouseTrackListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseTrackListener * @see #removeMouseTrackListener */ public void addMouseTrackListener (MouseTrackListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MouseEnter,typedListener); addListener (SWT.MouseExit,typedListener); addListener (SWT.MouseHover,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse wheel is scrolled, by sending * it one of the messages defined in the * <code>MouseWheelListener</code> interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseWheelListener * @see #removeMouseWheelListener * * @since 3.3 */ public void addMouseWheelListener (MouseWheelListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MouseWheel, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the receiver needs to be painted, by sending it * one of the messages defined in the <code>PaintListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see PaintListener * @see #removePaintListener */ public void addPaintListener(PaintListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.Paint,typedListener); } void addRelation (Control control) { } /** * Adds the listener to the collection of listeners who will * be notified when traversal events occur, by sending it * one of the messages defined in the <code>TraverseListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TraverseListener * @see #removeTraverseListener */ public void addTraverseListener (TraverseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Traverse,typedListener); } /** * Removes the listener from the collection of listeners who will * be notified when the control is moved or resized. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ControlListener * @see #addControlListener */ public void removeControlListener (ControlListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Move, listener); eventTable.unhook (SWT.Resize, listener); } /** * Removes the listener from the collection of listeners who will * be notified when a drag gesture occurs. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see DragDetectListener * @see #addDragDetectListener * * @since 3.3 */ public void removeDragDetectListener(DragDetectListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.DragDetect, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the control gains or loses focus. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see FocusListener * @see #addFocusListener */ public void removeFocusListener(FocusListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.FocusIn, listener); eventTable.unhook (SWT.FocusOut, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the help events are generated for the control. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see HelpListener * @see #addHelpListener */ public void removeHelpListener (HelpListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Help, listener); } /** * Removes the listener from the collection of listeners who will * be notified when keys are pressed and released on the system keyboard. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see KeyListener * @see #addKeyListener */ public void removeKeyListener(KeyListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.KeyUp, listener); eventTable.unhook (SWT.KeyDown, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the platform-specific context menu trigger has * occurred. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MenuDetectListener * @see #addMenuDetectListener * * @since 3.3 */ public void removeMenuDetectListener (MenuDetectListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MenuDetect, listener); } /** * Removes the listener from the collection of listeners who will * be notified when mouse buttons are pressed and released. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseListener * @see #addMouseListener */ public void removeMouseListener (MouseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseDown, listener); eventTable.unhook (SWT.MouseUp, listener); eventTable.unhook (SWT.MouseDoubleClick, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse moves. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseMoveListener * @see #addMouseMoveListener */ public void removeMouseMoveListener(MouseMoveListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseMove, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse passes or hovers over controls. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseTrackListener * @see #addMouseTrackListener */ public void removeMouseTrackListener(MouseTrackListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseEnter, listener); eventTable.unhook (SWT.MouseExit, listener); eventTable.unhook (SWT.MouseHover, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse wheel is scrolled. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseWheelListener * @see #addMouseWheelListener * * @since 3.3 */ public void removeMouseWheelListener (MouseWheelListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseWheel, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the receiver needs to be painted. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see PaintListener * @see #addPaintListener */ public void removePaintListener(PaintListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.Paint, listener); } /* * Remove "Labelled by" relation from the receiver. */ void removeRelation () { if (!isDescribedByLabel ()) return; /* there will not be any */ if (labelRelation != null) { _getAccessible().removeRelation (ACC.RELATION_LABELLED_BY, labelRelation._getAccessible()); labelRelation = null; } } /** * Removes the listener from the collection of listeners who will * be notified when traversal events occur. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TraverseListener * @see #addTraverseListener */ public void removeTraverseListener(TraverseListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Traverse, listener); } /** * Detects a drag and drop gesture. This method is used * to detect a drag gesture when called from within a mouse * down listener. * * <p>By default, a drag is detected when the gesture * occurs anywhere within the client area of a control. * Some controls, such as tables and trees, override this * behavior. In addition to the operating system specific * drag gesture, they require the mouse to be inside an * item. Custom widget writers can use <code>setDragDetect</code> * to disable the default detection, listen for mouse down, * and then call <code>dragDetect()</code> from within the * listener to conditionally detect a drag. * </p> * * @param event the mouse down event * * @return <code>true</code> if the gesture occurred, and <code>false</code> otherwise. * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT if the event is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see DragDetectListener * @see #addDragDetectListener * * @see #getDragDetect * @see #setDragDetect * * @since 3.3 */ public boolean dragDetect (Event event) { checkWidget (); if (event == null) error (SWT.ERROR_NULL_ARGUMENT); return dragDetect (event.button, event.count, event.stateMask, event.x, event.y); } /** * Detects a drag and drop gesture. This method is used * to detect a drag gesture when called from within a mouse * down listener. * * <p>By default, a drag is detected when the gesture * occurs anywhere within the client area of a control. * Some controls, such as tables and trees, override this * behavior. In addition to the operating system specific * drag gesture, they require the mouse to be inside an * item. Custom widget writers can use <code>setDragDetect</code> * to disable the default detection, listen for mouse down, * and then call <code>dragDetect()</code> from within the * listener to conditionally detect a drag. * </p> * * @param event the mouse down event * * @return <code>true</code> if the gesture occurred, and <code>false</code> otherwise. * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT if the event is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see DragDetectListener * @see #addDragDetectListener * * @see #getDragDetect * @see #setDragDetect * * @since 3.3 */ public boolean dragDetect (MouseEvent event) { checkWidget (); if (event == null) error (SWT.ERROR_NULL_ARGUMENT); return dragDetect (event.button, event.count, event.stateMask, event.x, event.y); } boolean dragDetect (int button, int count, int stateMask, int x, int y) { if (button != 1 || count != 1) return false; if (!dragDetect (x, y, false, null)) return false; return sendDragEvent (button, stateMask, x, y, true); } boolean dragDetect (int x, int y, boolean filter, boolean [] consume) { boolean quit = false, dragging = false; while (!quit) { int /*long*/ eventPtr = 0; /* * There should be an event on the queue already, but * in cases where there isn't one, stop trying after * half a second. */ long timeout = System.currentTimeMillis() + 500; while (System.currentTimeMillis() < timeout) { eventPtr = OS.gdk_event_get (); if (eventPtr != 0) { break; } else { try {Thread.sleep(50);} catch (Exception ex) {} } } if (eventPtr == 0) return false; switch (OS.GDK_EVENT_TYPE (eventPtr)) { case OS.GDK_MOTION_NOTIFY: { GdkEventMotion gdkMotionEvent = new GdkEventMotion (); OS.memmove (gdkMotionEvent, eventPtr, GdkEventMotion.sizeof); if ((gdkMotionEvent.state & OS.GDK_BUTTON1_MASK) != 0) { if (OS.gtk_drag_check_threshold (handle, x, y, (int) gdkMotionEvent.x, (int) gdkMotionEvent.y)) { dragging = true; quit = true; } } else { quit = true; } int [] newX = new int [1], newY = new int [1]; OS.gdk_window_get_pointer (gdkMotionEvent.window, newX, newY, null); break; } case OS.GDK_KEY_PRESS: case OS.GDK_KEY_RELEASE: { GdkEventKey gdkEvent = new GdkEventKey (); OS.memmove (gdkEvent, eventPtr, GdkEventKey.sizeof); if (gdkEvent.keyval == OS.GDK_Escape) quit = true; break; } case OS.GDK_BUTTON_RELEASE: case OS.GDK_BUTTON_PRESS: case OS.GDK_2BUTTON_PRESS: case OS.GDK_3BUTTON_PRESS: { OS.gdk_event_put (eventPtr); quit = true; break; } default: OS.gtk_main_do_event (eventPtr); } OS.gdk_event_free (eventPtr); } return dragging; } boolean filterKey (int keyval, int /*long*/ event) { int /*long*/ imHandle = imHandle (); if (imHandle != 0) { return OS.gtk_im_context_filter_keypress (imHandle, event); } return false; } Control findBackgroundControl () { if ((state & BACKGROUND) != 0 || backgroundImage != null) return this; return (state & PARENT_BACKGROUND) != 0 ? parent.findBackgroundControl () : null; } Menu [] findMenus (Control control) { if (menu != null && this != control) return new Menu [] {menu}; return new Menu [0]; } void fixChildren (Shell newShell, Shell oldShell, Decorations newDecorations, Decorations oldDecorations, Menu [] menus) { oldShell.fixShell (newShell, this); oldDecorations.fixDecorations (newDecorations, this, menus); } int /*long*/ fixedMapProc (int /*long*/ widget) { OS.GTK_WIDGET_SET_FLAGS (widget, OS.GTK_MAPPED); int /*long*/ widgetList = OS.gtk_container_get_children (widget); if (widgetList != 0) { int /*long*/ widgets = widgetList; while (widgets != 0) { int /*long*/ child = OS.g_list_data (widgets); if (OS.GTK_WIDGET_VISIBLE (child) && OS.gtk_widget_get_child_visible (child) && !OS.GTK_WIDGET_MAPPED (child)) { OS.gtk_widget_map (child); } widgets = OS.g_list_next (widgets); } OS.g_list_free (widgetList); } if ((OS.GTK_WIDGET_FLAGS (widget) & OS.GTK_NO_WINDOW) == 0) { OS.gdk_window_show_unraised (OS.GTK_WIDGET_WINDOW (widget)); } return 0; } void fixModal(int /*long*/ group, int /*long*/ modalGroup) { } /** * Forces the receiver to have the <em>keyboard focus</em>, causing * all keyboard events to be delivered to it. * * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setFocus */ public boolean forceFocus () { checkWidget(); if (display.focusEvent == SWT.FocusOut) return false; Shell shell = getShell (); shell.setSavedFocus (this); if (!isEnabled () || !isVisible ()) return false; shell.bringToTop (false); return forceFocus (focusHandle ()); } boolean forceFocus (int /*long*/ focusHandle) { if (OS.GTK_WIDGET_HAS_FOCUS (focusHandle)) return true; /* When the control is zero sized it must be realized */ OS.gtk_widget_realize (focusHandle); OS.gtk_widget_grab_focus (focusHandle); Shell shell = getShell (); int /*long*/ shellHandle = shell.shellHandle; int /*long*/ handle = OS.gtk_window_get_focus (shellHandle); while (handle != 0) { if (handle == focusHandle) { /* Cancel any previous ignoreFocus requests */ display.ignoreFocus = false; return true; } Widget widget = display.getWidget (handle); if (widget != null && widget instanceof Control) { return widget == this; } handle = OS.gtk_widget_get_parent (handle); } return false; } /** * Returns the receiver's background color. * <p> * Note: This operation is a hint and may be overridden by the platform. * For example, on some versions of Windows the background of a TabFolder, * is a gradient rather than a solid color. * </p> * @return the background color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getBackground () { checkWidget(); Control control = findBackgroundControl (); if (control == null) control = this; return Color.gtk_new (display, control.getBackgroundColor ()); } GdkColor getBackgroundColor () { return getBgColor (); } /** * Returns the receiver's background image. * * @return the background image * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ public Image getBackgroundImage () { checkWidget (); Control control = findBackgroundControl (); if (control == null) control = this; return control.backgroundImage; } GdkColor getBgColor () { int /*long*/ fontHandle = fontHandle (); OS.gtk_widget_realize (fontHandle); GdkColor color = new GdkColor (); OS.gtk_style_get_bg (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); return color; } GdkColor getBaseColor () { int /*long*/ fontHandle = fontHandle (); OS.gtk_widget_realize (fontHandle); GdkColor color = new GdkColor (); OS.gtk_style_get_base (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); return color; } /** * Returns the receiver's border width. * * @return the border width * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getBorderWidth () { checkWidget(); return 0; } int getClientWidth () { return 0; } /** * Returns the receiver's cursor, or null if it has not been set. * <p> * When the mouse pointer passes over a control its appearance * is changed to match the control's cursor. * </p> * * @return the receiver's cursor or <code>null</code> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.3 */ public Cursor getCursor () { checkWidget (); return cursor; } /** * Returns <code>true</code> if the receiver is detecting * drag gestures, and <code>false</code> otherwise. * * @return the receiver's drag detect state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.3 */ public boolean getDragDetect () { checkWidget (); return (state & DRAG_DETECT) != 0; } /** * Returns <code>true</code> if the receiver is enabled, and * <code>false</code> otherwise. A disabled control is typically * not selectable from the user interface and draws with an * inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #isEnabled */ public boolean getEnabled () { checkWidget (); return (state & DISABLED) == 0; } /** * Returns the font that the receiver will use to paint textual information. * * @return the receiver's font * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Font getFont () { checkWidget(); return font != null ? font : defaultFont (); } int /*long*/ getFontDescription () { int /*long*/ fontHandle = fontHandle (); OS.gtk_widget_realize (fontHandle); return OS.gtk_style_get_font_desc (OS.gtk_widget_get_style (fontHandle)); } /** * Returns the foreground color that the receiver will use to draw. * * @return the receiver's foreground color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getForeground () { checkWidget(); return Color.gtk_new (display, getForegroundColor ()); } GdkColor getForegroundColor () { return getFgColor (); } GdkColor getFgColor () { int /*long*/ fontHandle = fontHandle (); OS.gtk_widget_realize (fontHandle); GdkColor color = new GdkColor (); OS.gtk_style_get_fg (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); return color; } Point getIMCaretPos () { return new Point (0, 0); } GdkColor getTextColor () { int /*long*/ fontHandle = fontHandle (); OS.gtk_widget_realize (fontHandle); GdkColor color = new GdkColor (); OS.gtk_style_get_text (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); return color; } /** * Returns layout data which is associated with the receiver. * * @return the receiver's layout data * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Object getLayoutData () { checkWidget(); return layoutData; } /** * Returns the receiver's pop up menu if it has one, or null * if it does not. All controls may optionally have a pop up * menu that is displayed when the user requests one for * the control. The sequence of key strokes, button presses * and/or button releases that are used to request a pop up * menu is platform specific. * * @return the receiver's menu * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Menu getMenu () { checkWidget(); return menu; } /** * Returns the receiver's monitor. * * @return the receiver's monitor * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.0 */ public Monitor getMonitor () { checkWidget(); Monitor monitor = null; int /*long*/ screen = OS.gdk_screen_get_default (); if (screen != 0) { int monitorNumber = OS.gdk_screen_get_monitor_at_window (screen, paintWindow ()); GdkRectangle dest = new GdkRectangle (); OS.gdk_screen_get_monitor_geometry (screen, monitorNumber, dest); monitor = new Monitor (); monitor.handle = monitorNumber; monitor.x = dest.x; monitor.y = dest.y; monitor.width = dest.width; monitor.height = dest.height; Rectangle workArea = null; if (monitorNumber == 0) workArea = display.getWorkArea (); if (workArea != null) { monitor.clientX = workArea.x; monitor.clientY = workArea.y; monitor.clientWidth = workArea.width; monitor.clientHeight = workArea.height; } else { monitor.clientX = monitor.x; monitor.clientY = monitor.y; monitor.clientWidth = monitor.width; monitor.clientHeight = monitor.height; } } else { monitor = display.getPrimaryMonitor (); } return monitor; } /** * Returns the receiver's parent, which must be a <code>Composite</code> * or null when the receiver is a shell that was created with null or * a display for a parent. * * @return the receiver's parent * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Composite getParent () { checkWidget(); return parent; } Control [] getPath () { int count = 0; Shell shell = getShell (); Control control = this; while (control != shell) { count++; control = control.parent; } control = this; Control [] result = new Control [count]; while (control != shell) { result [--count] = control; control = control.parent; } return result; } /** * Returns the region that defines the shape of the control, * or null if the control has the default shape. * * @return the region that defines the shape of the shell (or null) * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.4 */ public Region getRegion () { checkWidget (); return region; } /** * Returns the receiver's shell. For all controls other than * shells, this simply returns the control's nearest ancestor * shell. Shells return themselves, even if they are children * of other shells. * * @return the receiver's shell * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getParent */ public Shell getShell() { checkWidget(); return _getShell(); } Shell _getShell() { return parent._getShell(); } /** * Returns the receiver's tool tip text, or null if it has * not been set. * * @return the receiver's tool tip text * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getToolTipText () { checkWidget(); return toolTipText; } /** * Returns <code>true</code> if the receiver is visible, and * <code>false</code> otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, this method * may still indicate that it is considered visible even though * it may not actually be showing. * </p> * * @return the receiver's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean getVisible () { checkWidget(); return (state & HIDDEN) == 0; } int /*long*/ gtk_button_press_event (int /*long*/ widget, int /*long*/ event) { return gtk_button_press_event (widget, event, true); } int /*long*/ gtk_button_press_event (int /*long*/ widget, int /*long*/ event, boolean sendMouseDown) { GdkEventButton gdkEvent = new GdkEventButton (); OS.memmove (gdkEvent, event, GdkEventButton.sizeof); if (gdkEvent.type == OS.GDK_3BUTTON_PRESS) return 0; /* * When a shell is created with SWT.ON_TOP and SWT.NO_FOCUS, * do not activate the shell when the user clicks on the * the client area or on the border or a control within the * shell that does not take focus. */ Shell shell = _getShell (); if (((shell.style & SWT.ON_TOP) != 0) && (((shell.style & SWT.NO_FOCUS) == 0) || ((style & SWT.NO_FOCUS) == 0))) { shell.forceActive(); } int /*long*/ result = 0; if (gdkEvent.type == OS.GDK_BUTTON_PRESS) { display.clickCount = 1; int /*long*/ nextEvent = OS.gdk_event_peek (); if (nextEvent != 0) { int eventType = OS.GDK_EVENT_TYPE (nextEvent); if (eventType == OS.GDK_2BUTTON_PRESS) display.clickCount = 2; if (eventType == OS.GDK_3BUTTON_PRESS) display.clickCount = 3; OS.gdk_event_free (nextEvent); } boolean dragging = false; if ((state & DRAG_DETECT) != 0 && hooks (SWT.DragDetect)) { if (gdkEvent.button == 1) { boolean [] consume = new boolean [1]; if (dragDetect ((int) gdkEvent.x, (int) gdkEvent.y, true, consume)) { dragging = true; if (consume [0]) result = 1; } if (isDisposed ()) return 1; } } if (sendMouseDown && !sendMouseEvent (SWT.MouseDown, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state)) { result = 1; } if (isDisposed ()) return 1; if (dragging) { sendDragEvent (gdkEvent.button, gdkEvent.state, (int) gdkEvent.x, (int) gdkEvent.y, false); if (isDisposed ()) return 1; } /* * Pop up the context menu in the button press event for widgets * that have default operating system menus in order to stop the * operating system from displaying the menu if necessary. */ if ((state & MENU) != 0) { if (gdkEvent.button == 3) { if (showMenu ((int)gdkEvent.x_root, (int)gdkEvent.y_root)) { result = 1; } } } } else { display.clickCount = 2; result = sendMouseEvent (SWT.MouseDoubleClick, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; if (isDisposed ()) return 1; } if (!shell.isDisposed ()) shell.setActiveControl (this); return result; } int /*long*/ gtk_button_release_event (int /*long*/ widget, int /*long*/ event) { GdkEventButton gdkEvent = new GdkEventButton (); OS.memmove (gdkEvent, event, GdkEventButton.sizeof); return sendMouseEvent (SWT.MouseUp, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; } int /*long*/ gtk_commit (int /*long*/ imcontext, int /*long*/ text) { if (text == 0) return 0; int length = OS.strlen (text); if (length == 0) return 0; byte [] buffer = new byte [length]; OS.memmove (buffer, text, length); char [] chars = Converter.mbcsToWcs (null, buffer); sendIMKeyEvent (SWT.KeyDown, null, chars); return 0; } int /*long*/ gtk_enter_notify_event (int /*long*/ widget, int /*long*/ event) { if (OS.GTK_VERSION >= OS.VERSION (2, 12, 0)) { /* * Feature in GTK. Children of a shell will inherit and display the shell's * tooltip if they do not have a tooltip of their own. The fix is to use the * new tooltip API in GTK 2.12 to null the shell's tooltip when the control * being entered does not have any tooltip text set. */ byte [] buffer = null; if (toolTipText != null && toolTipText.length() != 0) { char [] chars = fixMnemonic (toolTipText, false); buffer = Converter.wcsToMbcs (null, chars, true); } int /*long*/ toolHandle = getShell().handle; OS.gtk_widget_set_tooltip_text (toolHandle, buffer); } if (display.currentControl == this) return 0; GdkEventCrossing gdkEvent = new GdkEventCrossing (); OS.memmove (gdkEvent, event, GdkEventCrossing.sizeof); /* * It is possible to send out too many enter/exit events if entering a * control through a subwindow. The fix is to return without sending any * events if the GdkEventCrossing subwindow field is set and the control * requests to check the field. */ if (gdkEvent.subwindow != 0 && checkSubwindow ()) return 0; if (gdkEvent.mode != OS.GDK_CROSSING_NORMAL && gdkEvent.mode != OS.GDK_CROSSING_UNGRAB) return 0; if ((gdkEvent.state & (OS.GDK_BUTTON1_MASK | OS.GDK_BUTTON2_MASK | OS.GDK_BUTTON3_MASK)) != 0) return 0; if (display.currentControl != null && !display.currentControl.isDisposed ()) { display.removeMouseHoverTimeout (display.currentControl.handle); display.currentControl.sendMouseEvent (SWT.MouseExit, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state); } if (!isDisposed ()) { display.currentControl = this; return sendMouseEvent (SWT.MouseEnter, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; } return 0; } boolean checkSubwindow () { return false; } int /*long*/ gtk_event_after (int /*long*/ widget, int /*long*/ gdkEvent) { GdkEvent event = new GdkEvent (); OS.memmove (event, gdkEvent, GdkEvent.sizeof); switch (event.type) { case OS.GDK_BUTTON_PRESS: { if (widget != eventHandle ()) break; /* * Pop up the context menu in the event_after signal to allow * the widget to process the button press. This allows widgets * such as GtkTreeView to select items before a menu is shown. */ if ((state & MENU) == 0) { GdkEventButton gdkEventButton = new GdkEventButton (); OS.memmove (gdkEventButton, gdkEvent, GdkEventButton.sizeof); if (gdkEventButton.button == 3) { showMenu ((int) gdkEventButton.x_root, (int) gdkEventButton.y_root); } } break; } case OS.GDK_FOCUS_CHANGE: { if (!isFocusHandle (widget)) break; GdkEventFocus gdkEventFocus = new GdkEventFocus (); OS.memmove (gdkEventFocus, gdkEvent, GdkEventFocus.sizeof); /* * Feature in GTK. The GTK combo box popup under some window managers * is implemented as a GTK_MENU. When it pops up, it causes the combo * box to lose focus when focus is received for the menu. The * fix is to check the current grab handle and see if it is a GTK_MENU * and ignore the focus event when the menu is both shown and hidden. * * NOTE: This code runs for all menus. */ Display display = this.display; if (gdkEventFocus.in != 0) { if (display.ignoreFocus) { display.ignoreFocus = false; break; } } else { display.ignoreFocus = false; int /*long*/ grabHandle = OS.gtk_grab_get_current (); if (grabHandle != 0) { if (OS.G_OBJECT_TYPE (grabHandle) == OS.GTK_TYPE_MENU ()) { display.ignoreFocus = true; break; } } } sendFocusEvent (gdkEventFocus.in != 0 ? SWT.FocusIn : SWT.FocusOut); break; } } return 0; } int /*long*/ gtk_expose_event (int /*long*/ widget, int /*long*/ eventPtr) { if ((state & OBSCURED) != 0) return 0; if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return 0; GdkEventExpose gdkEvent = new GdkEventExpose (); OS.memmove(gdkEvent, eventPtr, GdkEventExpose.sizeof); Event event = new Event (); event.count = gdkEvent.count; event.x = gdkEvent.area_x; event.y = gdkEvent.area_y; event.width = gdkEvent.area_width; event.height = gdkEvent.area_height; if ((style & SWT.MIRRORED) != 0) event.x = getClientWidth () - event.width - event.x; GCData data = new GCData (); data.damageRgn = gdkEvent.region; GC gc = event.gc = GC.gtk_new (this, data); OS.gdk_gc_set_clip_region (gc.handle, gdkEvent.region); sendEvent (SWT.Paint, event); gc.dispose (); event.gc = null; return 0; } int /*long*/ gtk_focus (int /*long*/ widget, int /*long*/ directionType) { /* Stop GTK traversal for every widget */ return 1; } int /*long*/ gtk_focus_in_event (int /*long*/ widget, int /*long*/ event) { // widget could be disposed at this point if (handle != 0) { Control oldControl = display.imControl; if (oldControl != this) { if (oldControl != null && !oldControl.isDisposed ()) { int /*long*/ oldIMHandle = oldControl.imHandle (); if (oldIMHandle != 0) OS.gtk_im_context_reset (oldIMHandle); } } if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { int /*long*/ imHandle = imHandle (); if (imHandle != 0) OS.gtk_im_context_focus_in (imHandle); } } return 0; } int /*long*/ gtk_focus_out_event (int /*long*/ widget, int /*long*/ event) { // widget could be disposed at this point if (handle != 0) { if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { int /*long*/ imHandle = imHandle (); if (imHandle != 0) { OS.gtk_im_context_focus_out (imHandle); } } } return 0; } int /*long*/ gtk_key_press_event (int /*long*/ widget, int /*long*/ event) { if (!hasFocus ()) return 0; GdkEventKey gdkEvent = new GdkEventKey (); OS.memmove (gdkEvent, event, GdkEventKey.sizeof); if (translateMnemonic (gdkEvent.keyval, gdkEvent)) return 1; // widget could be disposed at this point if (isDisposed ()) return 0; if (filterKey (gdkEvent.keyval, event)) return 1; // widget could be disposed at this point if (isDisposed ()) return 0; if (translateTraversal (gdkEvent)) return 1; // widget could be disposed at this point if (isDisposed ()) return 0; return super.gtk_key_press_event (widget, event); } int /*long*/ gtk_key_release_event (int /*long*/ widget, int /*long*/ event) { if (!hasFocus ()) return 0; int /*long*/ imHandle = imHandle (); if (imHandle != 0) { if (OS.gtk_im_context_filter_keypress (imHandle, event)) return 1; } return super.gtk_key_release_event (widget, event); } int /*long*/ gtk_leave_notify_event (int /*long*/ widget, int /*long*/ event) { if (display.currentControl != this) return 0; display.removeMouseHoverTimeout (handle); int result = 0; if (sendLeaveNotify () || display.getCursorControl () == null) { GdkEventCrossing gdkEvent = new GdkEventCrossing (); OS.memmove (gdkEvent, event, GdkEventCrossing.sizeof); if (gdkEvent.mode != OS.GDK_CROSSING_NORMAL && gdkEvent.mode != OS.GDK_CROSSING_UNGRAB) return 0; if ((gdkEvent.state & (OS.GDK_BUTTON1_MASK | OS.GDK_BUTTON2_MASK | OS.GDK_BUTTON3_MASK)) != 0) return 0; result = sendMouseEvent (SWT.MouseExit, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; display.currentControl = null; } return result; } int /*long*/ gtk_mnemonic_activate (int /*long*/ widget, int /*long*/ arg1) { int result = 0; int /*long*/ eventPtr = OS.gtk_get_current_event (); if (eventPtr != 0) { GdkEventKey keyEvent = new GdkEventKey (); OS.memmove (keyEvent, eventPtr, GdkEventKey.sizeof); if (keyEvent.type == OS.GDK_KEY_PRESS) { Control focusControl = display.getFocusControl (); int /*long*/ focusHandle = focusControl != null ? focusControl.focusHandle () : 0; if (focusHandle != 0) { display.mnemonicControl = this; OS.gtk_widget_event (focusHandle, eventPtr); display.mnemonicControl = null; } result = 1; } OS.gdk_event_free (eventPtr); } return result; } int /*long*/ gtk_motion_notify_event (int /*long*/ widget, int /*long*/ event) { GdkEventMotion gdkEvent = new GdkEventMotion (); OS.memmove (gdkEvent, event, GdkEventMotion.sizeof); if (this == display.currentControl && (hooks (SWT.MouseHover) || filters (SWT.MouseHover))) { display.addMouseHoverTimeout (handle); } double x = gdkEvent.x_root, y = gdkEvent.y_root; int state = gdkEvent.state; if (gdkEvent.is_hint != 0) { int [] pointer_x = new int [1], pointer_y = new int [1], mask = new int [1]; int /*long*/ window = eventWindow (); OS.gdk_window_get_pointer (window, pointer_x, pointer_y, mask); x = pointer_x [0]; y = pointer_y [0]; state = mask [0]; } int result = sendMouseEvent (SWT.MouseMove, 0, gdkEvent.time, x, y, gdkEvent.is_hint != 0, state) ? 0 : 1; return result; } int /*long*/ gtk_popup_menu (int /*long*/ widget) { if (!hasFocus()) return 0; int [] x = new int [1], y = new int [1]; OS.gdk_window_get_pointer (0, x, y, null); return showMenu (x [0], y [0]) ? 1 : 0; } int /*long*/ gtk_preedit_changed (int /*long*/ imcontext) { display.showIMWindow (this); return 0; } int /*long*/ gtk_realize (int /*long*/ widget) { int /*long*/ imHandle = imHandle (); if (imHandle != 0) { int /*long*/ window = OS.GTK_WIDGET_WINDOW (paintHandle ()); OS.gtk_im_context_set_client_window (imHandle, window); } if (backgroundImage != null) { setBackgroundPixmap (backgroundImage.pixmap); } return 0; } int /*long*/ gtk_scroll_event (int /*long*/ widget, int /*long*/ eventPtr) { GdkEventScroll gdkEvent = new GdkEventScroll (); OS.memmove (gdkEvent, eventPtr, GdkEventScroll.sizeof); switch (gdkEvent.direction) { case OS.GDK_SCROLL_UP: return sendMouseEvent (SWT.MouseWheel, 0, 3, SWT.SCROLL_LINE, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; case OS.GDK_SCROLL_DOWN: return sendMouseEvent (SWT.MouseWheel, 0, -3, SWT.SCROLL_LINE, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; case OS.GDK_SCROLL_LEFT: return sendMouseEvent (SWT.MouseHorizontalWheel, 0, 3, 0, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; case OS.GDK_SCROLL_RIGHT: return sendMouseEvent (SWT.MouseHorizontalWheel, 0, -3, 0, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; } return 0; } int /*long*/ gtk_show_help (int /*long*/ widget, int /*long*/ helpType) { if (!hasFocus ()) return 0; return sendHelpEvent (helpType) ? 1 : 0; } int /*long*/ gtk_style_set (int /*long*/ widget, int /*long*/ previousStyle) { if (backgroundImage != null) { setBackgroundPixmap (backgroundImage.pixmap); } return 0; } int /*long*/ gtk_unrealize (int /*long*/ widget) { int /*long*/ imHandle = imHandle (); if (imHandle != 0) OS.gtk_im_context_set_client_window (imHandle, 0); return 0; } int /*long*/ gtk_visibility_notify_event (int /*long*/ widget, int /*long*/ event) { GdkEventVisibility gdkEvent = new GdkEventVisibility (); OS.memmove (gdkEvent, event, GdkEventVisibility.sizeof); int /*long*/ paintWindow = paintWindow(); int /*long*/ window = gdkEvent.window; if (window == paintWindow) { if (gdkEvent.state == OS.GDK_VISIBILITY_FULLY_OBSCURED) { state |= OBSCURED; } else { if ((state & OBSCURED) != 0) { int [] width = new int [1], height = new int [1]; OS.gdk_drawable_get_size (window, width, height); GdkRectangle rect = new GdkRectangle (); rect.width = width [0]; rect.height = height [0]; OS.gdk_window_invalidate_rect (window, rect, false); } state &= ~OBSCURED; } } return 0; } void gtk_widget_size_request (int /*long*/ widget, GtkRequisition requisition) { OS.gtk_widget_size_request (widget, requisition); } /** * Invokes platform specific functionality to allocate a new GC handle. * <p> * <b>IMPORTANT:</b> This method is <em>not</em> part of the public * API for <code>Control</code>. It is marked public only so that it * can be shared within the packages provided by SWT. It is not * available on all platforms, and should never be called from * application code. * </p> * * @param data the platform specific GC data * @return the platform specific GC handle * * @noreference This method is not intended to be referenced by clients. */ public int /*long*/ internal_new_GC (GCData data) { checkWidget (); int /*long*/ window = paintWindow (); if (window == 0) SWT.error (SWT.ERROR_NO_HANDLES); int /*long*/ gdkGC = OS.gdk_gc_new (window); if (gdkGC == 0) error (SWT.ERROR_NO_HANDLES); if (data != null) { int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; if ((data.style & mask) == 0) { data.style |= style & (mask | SWT.MIRRORED); } else { if ((data.style & SWT.RIGHT_TO_LEFT) != 0) { data.style |= SWT.MIRRORED; } } data.drawable = window; data.device = display; data.foreground = getForegroundColor (); Control control = findBackgroundControl (); if (control == null) control = this; data.background = control.getBackgroundColor (); data.font = font != null ? font : defaultFont (); } return gdkGC; } int /*long*/ imHandle () { return 0; } /** * Invokes platform specific functionality to dispose a GC handle. * <p> * <b>IMPORTANT:</b> This method is <em>not</em> part of the public * API for <code>Control</code>. It is marked public only so that it * can be shared within the packages provided by SWT. It is not * available on all platforms, and should never be called from * application code. * </p> * * @param hDC the platform specific GC handle * @param data the platform specific GC data * * @noreference This method is not intended to be referenced by clients. */ public void internal_dispose_GC (int /*long*/ gdkGC, GCData data) { checkWidget (); OS.g_object_unref (gdkGC); } /** * Returns <code>true</code> if the underlying operating * system supports this reparenting, otherwise <code>false</code> * * @return <code>true</code> if the widget can be reparented, otherwise <code>false</code> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean isReparentable () { checkWidget(); return true; } boolean isShowing () { /* * This is not complete. Need to check if the * widget is obscurred by a parent or sibling. */ if (!isVisible ()) return false; Control control = this; while (control != null) { Point size = control.getSize (); if (size.x == 0 || size.y == 0) { return false; } control = control.parent; } return true; } boolean isTabGroup () { Control [] tabList = parent._getTabList (); if (tabList != null) { for (int i=0; i<tabList.length; i++) { if (tabList [i] == this) return true; } } int code = traversalCode (0, null); if ((code & (SWT.TRAVERSE_ARROW_PREVIOUS | SWT.TRAVERSE_ARROW_NEXT)) != 0) return false; return (code & (SWT.TRAVERSE_TAB_PREVIOUS | SWT.TRAVERSE_TAB_NEXT)) != 0; } boolean isTabItem () { Control [] tabList = parent._getTabList (); if (tabList != null) { for (int i=0; i<tabList.length; i++) { if (tabList [i] == this) return false; } } int code = traversalCode (0, null); return (code & (SWT.TRAVERSE_ARROW_PREVIOUS | SWT.TRAVERSE_ARROW_NEXT)) != 0; } /** * Returns <code>true</code> if the receiver is enabled and all * ancestors up to and including the receiver's nearest ancestor * shell are enabled. Otherwise, <code>false</code> is returned. * A disabled control is typically not selectable from the user * interface and draws with an inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getEnabled */ public boolean isEnabled () { checkWidget (); return getEnabled () && parent.isEnabled (); } boolean isFocusAncestor (Control control) { while (control != null && control != this && !(control instanceof Shell)) { control = control.parent; } return control == this; } /** * Returns <code>true</code> if the receiver has the user-interface * focus, and <code>false</code> otherwise. * * @return the receiver's focus state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean isFocusControl () { checkWidget(); Control focusControl = display.focusControl; if (focusControl != null && !focusControl.isDisposed ()) { return this == focusControl; } return hasFocus (); } /** * Returns <code>true</code> if the receiver is visible and all * ancestors up to and including the receiver's nearest ancestor * shell are visible. Otherwise, <code>false</code> is returned. * * @return the receiver's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getVisible */ public boolean isVisible () { checkWidget(); return getVisible () && parent.isVisible (); } Decorations menuShell () { return parent.menuShell (); } boolean mnemonicHit (char key) { return false; } boolean mnemonicMatch (char key) { return false; } void register () { super.register (); if (fixedHandle != 0) display.addWidget (fixedHandle, this); int /*long*/ imHandle = imHandle (); if (imHandle != 0) display.addWidget (imHandle, this); } /** * Causes the entire bounds of the receiver to be marked * as needing to be redrawn. The next time a paint request * is processed, the control will be completely painted, * including the background. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #update() * @see PaintListener * @see SWT#Paint * @see SWT#NO_BACKGROUND * @see SWT#NO_REDRAW_RESIZE * @see SWT#NO_MERGE_PAINTS * @see SWT#DOUBLE_BUFFERED */ public void redraw () { checkWidget(); redraw (false); } void redraw (boolean all) { // checkWidget(); if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; redrawWidget (0, 0, 0, 0, true, all, false); } /** * Causes the rectangular area of the receiver specified by * the arguments to be marked as needing to be redrawn. * The next time a paint request is processed, that area of * the receiver will be painted, including the background. * If the <code>all</code> flag is <code>true</code>, any * children of the receiver which intersect with the specified * area will also paint their intersecting areas. If the * <code>all</code> flag is <code>false</code>, the children * will not be painted. * * @param x the x coordinate of the area to draw * @param y the y coordinate of the area to draw * @param width the width of the area to draw * @param height the height of the area to draw * @param all <code>true</code> if children should redraw, and <code>false</code> otherwise * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #update() * @see PaintListener * @see SWT#Paint * @see SWT#NO_BACKGROUND * @see SWT#NO_REDRAW_RESIZE * @see SWT#NO_MERGE_PAINTS * @see SWT#DOUBLE_BUFFERED */ public void redraw (int x, int y, int width, int height, boolean all) { checkWidget(); if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; if ((style & SWT.MIRRORED) != 0) x = getClientWidth () - width - x; redrawWidget (x, y, width, height, false, all, false); } void redrawChildren () { } void redrawWidget (int x, int y, int width, int height, boolean redrawAll, boolean all, boolean trim) { if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) == 0) return; int /*long*/ window = paintWindow (); GdkRectangle rect = new GdkRectangle (); if (redrawAll) { int [] w = new int [1], h = new int [1]; OS.gdk_drawable_get_size (window, w, h); rect.width = w [0]; rect.height = h [0]; } else { rect.x = x; rect.y = y; rect.width = width; rect.height = height; } OS.gdk_window_invalidate_rect (window, rect, all); } void release (boolean destroy) { Control next = null, previous = null; if (destroy && parent != null) { Control[] children = parent._getChildren (); int index = 0; while (index < children.length) { if (children [index] == this) break; index++; } if (0 < index && (index + 1) < children.length) { next = children [index + 1]; previous = children [index - 1]; } } super.release (destroy); if (destroy) { if (previous != null) previous.addRelation (next); } } void releaseHandle () { super.releaseHandle (); fixedHandle = 0; parent = null; } void releaseParent () { parent.removeControl (this); } void releaseWidget () { super.releaseWidget (); if (display.currentControl == this) display.currentControl = null; display.removeMouseHoverTimeout (handle); int /*long*/ imHandle = imHandle (); if (imHandle != 0) { OS.gtk_im_context_reset (imHandle); OS.gtk_im_context_set_client_window (imHandle, 0); } if (enableWindow != 0) { OS.gdk_window_set_user_data (enableWindow, 0); OS.gdk_window_destroy (enableWindow); enableWindow = 0; } redrawWindow = 0; if (menu != null && !menu.isDisposed ()) { menu.dispose (); } menu = null; cursor = null; toolTipText = null; layoutData = null; accessible = null; region = null; } void restackWindow (int /*long*/ window, int /*long*/ sibling, boolean above) { if (OS.GTK_VERSION >= OS.VERSION (2, 17, 11)) { OS.gdk_window_restack (window, sibling, above); } else { /* * Feature in X. If the receiver is a top level, XConfigureWindow () * will fail (with a BadMatch error) for top level shells because top * level shells are reparented by the window manager and do not share * the same X window parent. This is the correct behavior but it is * unexpected. The fix is to use XReconfigureWMWindow () instead. * When the receiver is not a top level shell, XReconfigureWMWindow () * behaves the same as XConfigureWindow (). */ int /*long*/ xDisplay = OS.gdk_x11_drawable_get_xdisplay (window); int /*long*/ xWindow = OS.gdk_x11_drawable_get_xid (window); int xScreen = OS.XDefaultScreen (xDisplay); int flags = OS.CWStackMode | OS.CWSibling; XWindowChanges changes = new XWindowChanges (); changes.sibling = OS.gdk_x11_drawable_get_xid (sibling); changes.stack_mode = above ? OS.Above : OS.Below; OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, changes); } } boolean sendDragEvent (int button, int stateMask, int x, int y, boolean isStateMask) { Event event = new Event (); event.button = button; event.x = x; event.y = y; if ((style & SWT.MIRRORED) != 0) event.x = getClientWidth () - event.x; if (isStateMask) { event.stateMask = stateMask; } else { setInputState (event, stateMask); } postEvent (SWT.DragDetect, event); if (isDisposed ()) return false; return event.doit; } void sendFocusEvent (int type) { Shell shell = _getShell (); Display display = this.display; display.focusControl = this; display.focusEvent = type; sendEvent (type); display.focusControl = null; display.focusEvent = SWT.None; /* * It is possible that the shell may be * disposed at this point. If this happens * don't send the activate and deactivate * events. */ if (!shell.isDisposed ()) { switch (type) { case SWT.FocusIn: shell.setActiveControl (this); break; case SWT.FocusOut: if (shell != display.activeShell) { shell.setActiveControl (null); } break; } } } boolean sendHelpEvent (int /*long*/ helpType) { Control control = this; while (control != null) { if (control.hooks (SWT.Help)) { control.postEvent (SWT.Help); return true; } control = control.parent; } return false; } boolean sendLeaveNotify() { return false; } boolean sendMouseEvent (int type, int button, int time, double x, double y, boolean is_hint, int state) { return sendMouseEvent (type, button, 0, 0, false, time, x, y, is_hint, state); } boolean sendMouseEvent (int type, int button, int count, int detail, boolean send, int time, double x, double y, boolean is_hint, int state) { if (!hooks (type) && !filters (type)) return true; Event event = new Event (); event.time = time; event.button = button; event.detail = detail; event.count = count; if (is_hint) { event.x = (int)x; event.y = (int)y; } else { int /*long*/ window = eventWindow (); int [] origin_x = new int [1], origin_y = new int [1]; OS.gdk_window_get_origin (window, origin_x, origin_y); event.x = (int)x - origin_x [0]; event.y = (int)y - origin_y [0]; } if ((style & SWT.MIRRORED) != 0) event.x = getClientWidth () - event.x; setInputState (event, state); if (send) { sendEvent (type, event); if (isDisposed ()) return false; } else { postEvent (type, event); } return event.doit; } void setBackground () { if ((state & BACKGROUND) == 0 && backgroundImage == null) { if ((state & PARENT_BACKGROUND) != 0) { setParentBackground (); } else { setWidgetBackground (); } redrawWidget (0, 0, 0, 0, true, false, false); } } /** * Sets the receiver's background color to the color specified * by the argument, or to the default system color for the control * if the argument is null. * <p> * Note: This operation is a hint and may be overridden by the platform. * For example, on Windows the background of a Button cannot be changed. * </p> * @param color the new color (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBackground (Color color) { checkWidget(); if (((state & BACKGROUND) == 0) && color == null) return; GdkColor gdkColor = null; if (color != null) { if (color.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); gdkColor = color.handle; } boolean set = false; if (gdkColor == null) { int /*long*/ style = OS.gtk_widget_get_modifier_style (handle); set = (OS.gtk_rc_style_get_color_flags (style, OS.GTK_STATE_NORMAL) & OS.GTK_RC_BG) != 0; } else { GdkColor oldColor = getBackgroundColor (); set = oldColor.pixel != gdkColor.pixel; } if (set) { if (color == null) { state &= ~BACKGROUND; } else { state |= BACKGROUND; } setBackgroundColor (gdkColor); redrawChildren (); } } void setBackgroundColor (int /*long*/ handle, GdkColor color) { int index = OS.GTK_STATE_NORMAL; int /*long*/ style = OS.gtk_widget_get_modifier_style (handle); int /*long*/ ptr = OS.gtk_rc_style_get_bg_pixmap_name (style, index); if (ptr != 0) OS.g_free (ptr); ptr = 0; String pixmapName = null; int flags = OS.gtk_rc_style_get_color_flags (style, index); if (color != null) { flags |= OS.GTK_RC_BG; pixmapName = "<none>"; } else { flags &= ~OS.GTK_RC_BG; if (backgroundImage == null && (state & PARENT_BACKGROUND) != 0) { pixmapName = "<parent>"; } } if (pixmapName != null) { byte[] buffer = Converter.wcsToMbcs (null, pixmapName, true); ptr = OS.g_malloc (buffer.length); OS.memmove (ptr, buffer, buffer.length); } OS.gtk_rc_style_set_bg_pixmap_name (style, index, ptr); OS.gtk_rc_style_set_bg (style, index, color); OS.gtk_rc_style_set_color_flags (style, index, flags); modifyStyle (handle, style); } void setBackgroundColor (GdkColor color) { setBackgroundColor (handle, color); } /** * Sets the receiver's background image to the image specified * by the argument, or to the default system color for the control * if the argument is null. The background image is tiled to fill * the available space. * <p> * Note: This operation is a hint and may be overridden by the platform. * For example, on Windows the background of a Button cannot be changed. * </p> * @param image the new image (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * <li>ERROR_INVALID_ARGUMENT - if the argument is not a bitmap</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ public void setBackgroundImage (Image image) { checkWidget (); if (image != null && image.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if (image == backgroundImage) return; this.backgroundImage = image; if (backgroundImage != null) { setBackgroundPixmap (backgroundImage.pixmap); redrawWidget (0, 0, 0, 0, true, false, false); } else { setWidgetBackground (); } redrawChildren (); } void setBackgroundPixmap (int /*long*/ pixmap) { int /*long*/ window = OS.GTK_WIDGET_WINDOW (paintHandle ()); if (window != 0) OS.gdk_window_set_back_pixmap (window, pixmap, false); } /** * If the argument is <code>true</code>, causes the receiver to have * all mouse events delivered to it until the method is called with * <code>false</code> as the argument. Note that on some platforms, * a mouse button must currently be down for capture to be assigned. * * @param capture <code>true</code> to capture the mouse, and <code>false</code> to release it * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setCapture (boolean capture) { checkWidget(); /* FIXME !!!!! */ /* if (capture) { OS.gtk_widget_grab_focus (handle); } else { OS.gtk_widget_grab_default (handle); } */ } /** * Sets the receiver's cursor to the cursor specified by the * argument, or to the default cursor for that kind of control * if the argument is null. * <p> * When the mouse pointer passes over a control its appearance * is changed to match the control's cursor. * </p> * * @param cursor the new cursor (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setCursor (Cursor cursor) { checkWidget(); if (cursor != null && cursor.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); this.cursor = cursor; setCursor (cursor != null ? cursor.handle : 0); } void setCursor (int /*long*/ cursor) { int /*long*/ window = eventWindow (); if (window != 0) { OS.gdk_window_set_cursor (window, cursor); if (!OS.GDK_WINDOWING_X11 ()) { OS.gdk_flush (); } else { int /*long*/ xDisplay = OS.GDK_DISPLAY (); OS.XFlush (xDisplay); } } } /** * Sets the receiver's drag detect state. If the argument is * <code>true</code>, the receiver will detect drag gestures, * otherwise these gestures will be ignored. * * @param dragDetect the new drag detect state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.3 */ public void setDragDetect (boolean dragDetect) { checkWidget (); if (dragDetect) { state |= DRAG_DETECT; } else { state &= ~DRAG_DETECT; } } /** * Enables the receiver if the argument is <code>true</code>, * and disables it otherwise. A disabled control is typically * not selectable from the user interface and draws with an * inactive or "grayed" look. * * @param enabled the new enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setEnabled (boolean enabled) { checkWidget(); if (((state & DISABLED) == 0) == enabled) return; Control control = null; boolean fixFocus = false; if (!enabled) { if (display.focusEvent != SWT.FocusOut) { control = display.getFocusControl (); fixFocus = isFocusAncestor (control); } } if (enabled) { state &= ~DISABLED; } else { state |= DISABLED; } enableWidget (enabled); if (isDisposed ()) return; if (enabled) { if (enableWindow != 0) { OS.gdk_window_set_user_data (enableWindow, 0); OS.gdk_window_destroy (enableWindow); enableWindow = 0; } } else { OS.gtk_widget_realize (handle); int /*long*/ parentHandle = parent.eventHandle (); int /*long*/ window = parent.eventWindow (); int /*long*/ topHandle = topHandle (); GdkWindowAttr attributes = new GdkWindowAttr (); attributes.x = OS.GTK_WIDGET_X (topHandle); attributes.y = OS.GTK_WIDGET_Y (topHandle); attributes.width = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); attributes.height = (state & ZERO_HEIGHT) != 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); attributes.event_mask = (0xFFFFFFFF & ~OS.ExposureMask); attributes.wclass = OS.GDK_INPUT_ONLY; attributes.window_type = OS.GDK_WINDOW_CHILD; enableWindow = OS.gdk_window_new (window, attributes, OS.GDK_WA_X | OS.GDK_WA_Y); if (enableWindow != 0) { OS.gdk_window_set_user_data (enableWindow, parentHandle); if (!OS.GDK_WINDOWING_X11 ()) { OS.gdk_window_raise (enableWindow); } else { restackWindow (enableWindow, OS.GTK_WIDGET_WINDOW (topHandle), true); } if (OS.GTK_WIDGET_VISIBLE (topHandle)) OS.gdk_window_show_unraised (enableWindow); } } if (fixFocus) fixFocus (control); } /** * Causes the receiver to have the <em>keyboard focus</em>, * such that all keyboard events will be delivered to it. Focus * reassignment will respect applicable platform constraints. * * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #forceFocus */ public boolean setFocus () { checkWidget(); if ((style & SWT.NO_FOCUS) != 0) return false; return forceFocus (); } /** * Sets the font that the receiver will use to paint textual information * to the font specified by the argument, or to the default font for that * kind of control if the argument is null. * * @param font the new font (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setFont (Font font) { checkWidget(); if (((state & FONT) == 0) && font == null) return; this.font = font; int /*long*/ fontDesc; if (font == null) { fontDesc = defaultFont ().handle; } else { if (font.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); fontDesc = font.handle; } if (font == null) { state &= ~FONT; } else { state |= FONT; } setFontDescription (fontDesc); } void setFontDescription (int /*long*/ font) { OS.gtk_widget_modify_font (handle, font); } /** * Sets the receiver's foreground color to the color specified * by the argument, or to the default system color for the control * if the argument is null. * <p> * Note: This operation is a hint and may be overridden by the platform. * </p> * @param color the new color (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setForeground (Color color) { checkWidget(); if (((state & FOREGROUND) == 0) && color == null) return; GdkColor gdkColor = null; if (color != null) { if (color.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); gdkColor = color.handle; } boolean set = false; if (gdkColor == null) { int /*long*/ style = OS.gtk_widget_get_modifier_style (handle); set = (OS.gtk_rc_style_get_color_flags (style, OS.GTK_STATE_NORMAL) & OS.GTK_RC_FG) != 0; } else { GdkColor oldColor = getForegroundColor (); set = oldColor.pixel != gdkColor.pixel; } if (set) { if (color == null) { state &= ~FOREGROUND; } else { state |= FOREGROUND; } setForegroundColor (gdkColor); } } void setForegroundColor (GdkColor color) { setForegroundColor (handle, color); } void setInitialBounds () { if ((state & ZERO_WIDTH) != 0 && (state & ZERO_HEIGHT) != 0) { /* * Feature in GTK. On creation, each widget's allocation is * initialized to a position of (-1, -1) until the widget is * first sized. The fix is to set the value to (0, 0) as * expected by SWT. */ int /*long*/ topHandle = topHandle (); if ((parent.style & SWT.MIRRORED) != 0) { OS.GTK_WIDGET_SET_X (topHandle, parent.getClientWidth ()); } else { OS.GTK_WIDGET_SET_X (topHandle, 0); } OS.GTK_WIDGET_SET_Y (topHandle, 0); } else { resizeHandle (1, 1); forceResize (); } } /** * Sets the receiver's pop up menu to the argument. * All controls may optionally have a pop up * menu that is displayed when the user requests one for * the control. The sequence of key strokes, button presses * and/or button releases that are used to request a pop up * menu is platform specific. * <p> * Note: Disposing of a control that has a pop up menu will * dispose of the menu. To avoid this behavior, set the * menu to null before the control is disposed. * </p> * * @param menu the new pop up menu * * @exception IllegalArgumentException <ul> * <li>ERROR_MENU_NOT_POP_UP - the menu is not a pop up menu</li> * <li>ERROR_INVALID_PARENT - if the menu is not in the same widget tree</li> * <li>ERROR_INVALID_ARGUMENT - if the menu has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setMenu (Menu menu) { checkWidget(); if (menu != null) { if ((menu.style & SWT.POP_UP) == 0) { error (SWT.ERROR_MENU_NOT_POP_UP); } if (menu.parent != menuShell ()) { error (SWT.ERROR_INVALID_PARENT); } } this.menu = menu; } void setOrientation () { if ((style & SWT.RIGHT_TO_LEFT) != 0) { if (handle != 0) OS.gtk_widget_set_direction (handle, OS.GTK_TEXT_DIR_RTL); if (fixedHandle != 0) OS.gtk_widget_set_direction (fixedHandle, OS.GTK_TEXT_DIR_RTL); } } /** * Changes the parent of the widget to be the one provided if * the underlying operating system supports this feature. * Returns <code>true</code> if the parent is successfully changed. * * @param parent the new parent for the control. * @return <code>true</code> if the parent is changed and <code>false</code> otherwise. * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * <li>ERROR_NULL_ARGUMENT - if the parent is <code>null</code></li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean setParent (Composite parent) { checkWidget (); if (parent == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); if (parent.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); if (this.parent == parent) return true; if (!isReparentable ()) return false; OS.gtk_widget_realize (parent.handle); int /*long*/ topHandle = topHandle (); int x = OS.GTK_WIDGET_X (topHandle); int width = (state & ZERO_WIDTH) != 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); if ((this.parent.style & SWT.MIRRORED) != 0) { x = this.parent.getClientWidth () - width - x; } if ((parent.style & SWT.MIRRORED) != 0) { x = parent.getClientWidth () - width - x; } int y = OS.GTK_WIDGET_Y (topHandle); releaseParent (); Shell newShell = parent.getShell (), oldShell = getShell (); Decorations newDecorations = parent.menuShell (), oldDecorations = menuShell (); Menu [] menus = oldShell.findMenus (this); if (oldShell != newShell || oldDecorations != newDecorations) { fixChildren (newShell, oldShell, newDecorations, oldDecorations, menus); newDecorations.fixAccelGroup (); oldDecorations.fixAccelGroup (); } int /*long*/ newParent = parent.parentingHandle(); OS.gtk_widget_reparent (topHandle, newParent); OS.gtk_fixed_move (newParent, topHandle, x, y); this.parent = parent; setZOrder (null, false, true); reskin (SWT.ALL); return true; } void setParentBackground () { setBackgroundColor (handle, null); if (fixedHandle != 0) setBackgroundColor (fixedHandle, null); } void setParentWindow (int /*long*/ widget) { } boolean setRadioSelection (boolean value) { return false; } /** * If the argument is <code>false</code>, causes subsequent drawing * operations in the receiver to be ignored. No drawing of any kind * can occur in the receiver until the flag is set to true. * Graphics operations that occurred while the flag was * <code>false</code> are lost. When the flag is set to <code>true</code>, * the entire widget is marked as needing to be redrawn. Nested calls * to this method are stacked. * <p> * Note: This operation is a hint and may not be supported on some * platforms or for some widgets. * </p> * * @param redraw the new redraw state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #redraw(int, int, int, int, boolean) * @see #update() */ public void setRedraw (boolean redraw) { checkWidget(); if (redraw) { if (--drawCount == 0) { if (redrawWindow != 0) { int /*long*/ window = paintWindow (); /* * Bug in GTK. For some reason, the window does not * redraw in versions of GTK greater than 2.18. The fix * is to hide and show it (without changing the z order). */ boolean fixRedraw = OS.GTK_VERSION >= OS.VERSION (2, 17, 0) && OS.gdk_window_is_visible(window); if (fixRedraw) OS.gdk_window_hide(window); /* Explicitly hiding the window avoids flicker on GTK+ >= 2.6 */ OS.gdk_window_hide (redrawWindow); OS.gdk_window_destroy (redrawWindow); OS.gdk_window_set_events (window, OS.gtk_widget_get_events (paintHandle ())); if (fixRedraw) OS.gdk_window_show_unraised(window); redrawWindow = 0; } } } else { if (drawCount++ == 0) { if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) != 0) { int /*long*/ window = paintWindow (); Rectangle rect = getBounds (); GdkWindowAttr attributes = new GdkWindowAttr (); attributes.width = rect.width; attributes.height = rect.height; attributes.event_mask = OS.GDK_EXPOSURE_MASK; attributes.window_type = OS.GDK_WINDOW_CHILD; redrawWindow = OS.gdk_window_new (window, attributes, 0); if (redrawWindow != 0) { int mouseMask = OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK | OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK | OS.GDK_POINTER_MOTION_MASK | OS.GDK_POINTER_MOTION_HINT_MASK | OS.GDK_BUTTON_MOTION_MASK | OS.GDK_BUTTON1_MOTION_MASK | OS.GDK_BUTTON2_MOTION_MASK | OS.GDK_BUTTON3_MOTION_MASK; OS.gdk_window_set_events (window, OS.gdk_window_get_events (window) & ~mouseMask); OS.gdk_window_set_back_pixmap (redrawWindow, 0, false); //System.out.println("Redraw " + redrawWindow + " WIndow " + window); // OS.gdk_x11_drawable_get_xid(redrawWindow); // OS.gdk_x11_drawable_get_xid(window); OS.gdk_window_show (redrawWindow); } } } } } boolean setTabItemFocus (boolean next) { if (!isShowing ()) return false; return forceFocus (); } /** * Sets the receiver's tool tip text to the argument, which * may be null indicating that the default tool tip for the * control will be shown. For a control that has a default * tool tip, such as the Tree control on Windows, setting * the tool tip text to an empty string replaces the default, * causing no tool tip text to be shown. * <p> * The mnemonic indicator (character '&amp;') is not displayed in a tool tip. * To display a single '&amp;' in the tool tip, the character '&amp;' can be * escaped by doubling it in the string. * </p> * * @param string the new tool tip text (or null) * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setToolTipText (String string) { checkWidget(); setToolTipText (_getShell (), string); toolTipText = string; } void setToolTipText (Shell shell, String newString) { if (OS.GTK_VERSION >= OS.VERSION (2, 12, 0)) { /* * Feature in GTK. In order to prevent children widgets * from inheriting their parent's tooltip, the tooltip is * a set on a shell only. In order to force the shell tooltip * to update when a new tip string is set, the existing string * in the tooltip is set to null, followed by running a query. * The real tip text can then be set. * * Note that this will only run if the control for which the * tooltip is being set is the current control (i.e. the control * under the pointer). */ if (display.currentControl == this) { shell.setToolTipText (shell.handle, eventHandle (), newString); } } else { shell.setToolTipText (eventHandle (), newString); } } /** * Marks the receiver as visible if the argument is <code>true</code>, * and marks it invisible otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, marking * it visible may not actually cause it to be displayed. * </p> * * @param visible the new visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setVisible (boolean visible) { checkWidget(); if (((state & HIDDEN) == 0) == visible) return; int /*long*/ topHandle = topHandle(); if (visible) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the show * event. If this happens, just return. */ sendEvent (SWT.Show); if (isDisposed ()) return; state &= ~HIDDEN; if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) == 0) { if (enableWindow != 0) OS.gdk_window_show_unraised (enableWindow); OS.gtk_widget_show (topHandle); } } else { /* * Bug in GTK. Invoking gtk_widget_hide() on a widget that has * focus causes a focus_out_event to be sent. If the client disposes * the widget inside the event, GTK GP's. The fix is to reassign focus * before hiding the widget. * * NOTE: In order to stop the same widget from taking focus, * temporarily clear and set the GTK_VISIBLE flag. */ Control control = null; boolean fixFocus = false; if (display.focusEvent != SWT.FocusOut) { control = display.getFocusControl (); fixFocus = isFocusAncestor (control); } state |= HIDDEN; if (fixFocus) { OS.GTK_WIDGET_UNSET_FLAGS (topHandle, OS.GTK_VISIBLE); fixFocus (control); if (isDisposed ()) return; OS.GTK_WIDGET_SET_FLAGS (topHandle, OS.GTK_VISIBLE); } OS.gtk_widget_hide (topHandle); if (isDisposed ()) return; if (enableWindow != 0) OS.gdk_window_hide (enableWindow); sendEvent (SWT.Hide); } } void setZOrder (Control sibling, boolean above, boolean fixRelations) { setZOrder (sibling, above, fixRelations, true); } void setZOrder (Control sibling, boolean above, boolean fixRelations, boolean fixChildren) { int index = 0, siblingIndex = 0, oldNextIndex = -1; Control[] children = null; if (fixRelations) { /* determine the receiver's and sibling's indexes in the parent */ children = parent._getChildren (); while (index < children.length) { if (children [index] == this) break; index++; } if (sibling != null) { while (siblingIndex < children.length) { if (children [siblingIndex] == sibling) break; siblingIndex++; } } /* remove "Labelled by" relationships that will no longer be valid */ removeRelation (); if (index + 1 < children.length) { oldNextIndex = index + 1; children [oldNextIndex].removeRelation (); } if (sibling != null) { if (above) { sibling.removeRelation (); } else { if (siblingIndex + 1 < children.length) { children [siblingIndex + 1].removeRelation (); } } } } int /*long*/ topHandle = topHandle (); int /*long*/ siblingHandle = sibling != null ? sibling.topHandle () : 0; int /*long*/ window = OS.GTK_WIDGET_WINDOW (topHandle); if (window != 0) { int /*long*/ siblingWindow = 0; if (sibling != null) { if (above && sibling.enableWindow != 0) { siblingWindow = enableWindow; } else { siblingWindow = OS.GTK_WIDGET_WINDOW (siblingHandle); } } int /*long*/ redrawWindow = fixChildren ? parent.redrawWindow : 0; if (!OS.GDK_WINDOWING_X11 () || (siblingWindow == 0 && (!above || redrawWindow == 0))) { if (above) { OS.gdk_window_raise (window); if (redrawWindow != 0) OS.gdk_window_raise (redrawWindow); if (enableWindow != 0) OS.gdk_window_raise (enableWindow); } else { if (enableWindow != 0) OS.gdk_window_lower (enableWindow); OS.gdk_window_lower (window); } } else { int /*long*/ siblingW = siblingWindow != 0 ? siblingWindow : redrawWindow; boolean stack_mode = above; if (redrawWindow != 0 && siblingWindow == 0) stack_mode = false; restackWindow (window, siblingW, stack_mode); if (enableWindow != 0) { restackWindow (enableWindow, window, true); } } } if (fixChildren) { if (above) { parent.moveAbove (topHandle, siblingHandle); } else { parent.moveBelow (topHandle, siblingHandle); } } /* Make sure that the parent internal windows are on the bottom of the stack */ if (!above && fixChildren) parent.fixZOrder (); if (fixRelations) { /* determine the receiver's new index in the parent */ if (sibling != null) { if (above) { index = siblingIndex - (index < siblingIndex ? 1 : 0); } else { index = siblingIndex + (siblingIndex < index ? 1 : 0); } } else { if (above) { index = 0; } else { index = children.length - 1; } } /* add new "Labelled by" relations as needed */ children = parent._getChildren (); if (0 < index) { children [index - 1].addRelation (this); } if (index + 1 < children.length) { addRelation (children [index + 1]); } if (oldNextIndex != -1) { if (oldNextIndex <= index) oldNextIndex--; /* the last two conditions below ensure that duplicate relations are not hooked */ if (0 < oldNextIndex && oldNextIndex != index && oldNextIndex != index + 1) { children [oldNextIndex - 1].addRelation (children [oldNextIndex]); } } } } void setWidgetBackground () { GdkColor color = (state & BACKGROUND) != 0 ? getBackgroundColor () : null; if (fixedHandle != 0) setBackgroundColor (fixedHandle, color); setBackgroundColor (handle, color); } boolean showMenu (int x, int y) { Event event = new Event (); event.x = x; event.y = y; sendEvent (SWT.MenuDetect, event); //widget could be disposed at this point if (isDisposed ()) return false; if (event.doit) { if (menu != null && !menu.isDisposed ()) { boolean hooksKeys = hooks (SWT.KeyDown) || hooks (SWT.KeyUp); menu.createIMMenu (hooksKeys ? imHandle() : 0); if (event.x != x || event.y != y) { menu.setLocation (event.x, event.y); } menu.setVisible (true); return true; } } return false; } void showWidget () { // Comment this line to disable zero-sized widgets state |= ZERO_WIDTH | ZERO_HEIGHT; int /*long*/ topHandle = topHandle (); int /*long*/ parentHandle = parent.parentingHandle (); parent.setParentWindow (topHandle); OS.gtk_container_add (parentHandle, topHandle); if (handle != 0 && handle != topHandle) OS.gtk_widget_show (handle); if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) == 0) { if (fixedHandle != 0) OS.gtk_widget_show (fixedHandle); } if (fixedHandle != 0) fixStyle (fixedHandle); } void sort (int [] items) { /* Shell Sort from K&R, pg 108 */ int length = items.length; for (int gap=length/2; gap>0; gap/=2) { for (int i=gap; i<length; i++) { for (int j=i-gap; j>=0; j-=gap) { if (items [j] <= items [j + gap]) { int swap = items [j]; items [j] = items [j + gap]; items [j + gap] = swap; } } } } } /** * Based on the argument, perform one of the expected platform * traversal action. The argument should be one of the constants: * <code>SWT.TRAVERSE_ESCAPE</code>, <code>SWT.TRAVERSE_RETURN</code>, * <code>SWT.TRAVERSE_TAB_NEXT</code>, <code>SWT.TRAVERSE_TAB_PREVIOUS</code>, * <code>SWT.TRAVERSE_ARROW_NEXT</code>, <code>SWT.TRAVERSE_ARROW_PREVIOUS</code>, * <code>SWT.TRAVERSE_PAGE_NEXT</code> and <code>SWT.TRAVERSE_PAGE_PREVIOUS</code>. * * @param traversal the type of traversal * @return true if the traversal succeeded * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean traverse (int traversal) { checkWidget (); Event event = new Event (); event.doit = true; event.detail = traversal; return traverse (event); } /** * Performs a platform traversal action corresponding to a <code>KeyDown</code> event. * * <p>Valid traversal values are * <code>SWT.TRAVERSE_NONE</code>, <code>SWT.TRAVERSE_MNEMONIC</code>, * <code>SWT.TRAVERSE_ESCAPE</code>, <code>SWT.TRAVERSE_RETURN</code>, * <code>SWT.TRAVERSE_TAB_NEXT</code>, <code>SWT.TRAVERSE_TAB_PREVIOUS</code>, * <code>SWT.TRAVERSE_ARROW_NEXT</code>, <code>SWT.TRAVERSE_ARROW_PREVIOUS</code>, * <code>SWT.TRAVERSE_PAGE_NEXT</code> and <code>SWT.TRAVERSE_PAGE_PREVIOUS</code>. * If <code>traversal</code> is <code>SWT.TRAVERSE_NONE</code> then the Traverse * event is created with standard values based on the KeyDown event. If * <code>traversal</code> is one of the other traversal constants then the Traverse * event is created with this detail, and its <code>doit</code> is taken from the * KeyDown event. * </p> * * @param traversal the type of traversal, or <code>SWT.TRAVERSE_NONE</code> to compute * this from <code>event</code> * @param event the KeyDown event * * @return <code>true</code> if the traversal succeeded * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT if the event is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.6 */ public boolean traverse (int traversal, Event event) { checkWidget (); if (event == null) error (SWT.ERROR_NULL_ARGUMENT); return traverse (traversal, event.character, event.keyCode, event.keyLocation, event.stateMask, event.doit); } /** * Performs a platform traversal action corresponding to a <code>KeyDown</code> event. * * <p>Valid traversal values are * <code>SWT.TRAVERSE_NONE</code>, <code>SWT.TRAVERSE_MNEMONIC</code>, * <code>SWT.TRAVERSE_ESCAPE</code>, <code>SWT.TRAVERSE_RETURN</code>, * <code>SWT.TRAVERSE_TAB_NEXT</code>, <code>SWT.TRAVERSE_TAB_PREVIOUS</code>, * <code>SWT.TRAVERSE_ARROW_NEXT</code>, <code>SWT.TRAVERSE_ARROW_PREVIOUS</code>, * <code>SWT.TRAVERSE_PAGE_NEXT</code> and <code>SWT.TRAVERSE_PAGE_PREVIOUS</code>. * If <code>traversal</code> is <code>SWT.TRAVERSE_NONE</code> then the Traverse * event is created with standard values based on the KeyDown event. If * <code>traversal</code> is one of the other traversal constants then the Traverse * event is created with this detail, and its <code>doit</code> is taken from the * KeyDown event. * </p> * * @param traversal the type of traversal, or <code>SWT.TRAVERSE_NONE</code> to compute * this from <code>event</code> * @param event the KeyDown event * * @return <code>true</code> if the traversal succeeded * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT if the event is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.6 */ public boolean traverse (int traversal, KeyEvent event) { checkWidget (); if (event == null) error (SWT.ERROR_NULL_ARGUMENT); return traverse (traversal, event.character, event.keyCode, event.keyLocation, event.stateMask, event.doit); } boolean traverse (int traversal, char character, int keyCode, int keyLocation, int stateMask, boolean doit) { if (traversal == SWT.TRAVERSE_NONE) { switch (keyCode) { case SWT.ESC: { traversal = SWT.TRAVERSE_ESCAPE; doit = true; break; } case SWT.CR: { traversal = SWT.TRAVERSE_RETURN; doit = true; break; } case SWT.ARROW_DOWN: case SWT.ARROW_RIGHT: { traversal = SWT.TRAVERSE_ARROW_NEXT; doit = false; break; } case SWT.ARROW_UP: case SWT.ARROW_LEFT: { traversal = SWT.TRAVERSE_ARROW_PREVIOUS; doit = false; break; } case SWT.TAB: { traversal = (stateMask & SWT.SHIFT) != 0 ? SWT.TRAVERSE_TAB_PREVIOUS : SWT.TRAVERSE_TAB_NEXT; doit = true; break; } case SWT.PAGE_DOWN: { if ((stateMask & SWT.CTRL) != 0) { traversal = SWT.TRAVERSE_PAGE_NEXT; doit = true; } break; } case SWT.PAGE_UP: { if ((stateMask & SWT.CTRL) != 0) { traversal = SWT.TRAVERSE_PAGE_PREVIOUS; doit = true; } break; } default: { if (character != 0 && (stateMask & (SWT.ALT | SWT.CTRL)) == SWT.ALT) { traversal = SWT.TRAVERSE_MNEMONIC; doit = true; } break; } } } Event event = new Event (); event.character = character; event.detail = traversal; event.doit = doit; event.keyCode = keyCode; event.keyLocation = keyLocation; event.stateMask = stateMask; Shell shell = getShell (); boolean all = false; switch (traversal) { case SWT.TRAVERSE_ESCAPE: case SWT.TRAVERSE_RETURN: case SWT.TRAVERSE_PAGE_NEXT: case SWT.TRAVERSE_PAGE_PREVIOUS: { all = true; // FALL THROUGH } case SWT.TRAVERSE_ARROW_NEXT: case SWT.TRAVERSE_ARROW_PREVIOUS: case SWT.TRAVERSE_TAB_NEXT: case SWT.TRAVERSE_TAB_PREVIOUS: { /* traversal is a valid traversal action */ break; } case SWT.TRAVERSE_MNEMONIC: { return translateMnemonic (event, null) || shell.translateMnemonic (event, this); } default: { /* traversal is not a valid traversal action */ return false; } } Control control = this; do { if (control.traverse (event)) return true; if (!event.doit && control.hooks (SWT.Traverse)) return false; if (control == shell) return false; control = control.parent; } while (all && control != null); return false; } boolean translateMnemonic (Event event, Control control) { if (control == this) return false; if (!isVisible () || !isEnabled ()) return false; event.doit = this == display.mnemonicControl || mnemonicMatch (event.character); return traverse (event); } boolean translateMnemonic (int keyval, GdkEventKey gdkEvent) { int key = OS.gdk_keyval_to_unicode (keyval); if (key < 0x20) return false; if (gdkEvent.state == 0) { int code = traversalCode (keyval, gdkEvent); if ((code & SWT.TRAVERSE_MNEMONIC) == 0) return false; } else { Shell shell = _getShell (); int mask = OS.GDK_CONTROL_MASK | OS.GDK_SHIFT_MASK | OS.GDK_MOD1_MASK; if ((gdkEvent.state & mask) != OS.gtk_window_get_mnemonic_modifier (shell.shellHandle)) return false; } Decorations shell = menuShell (); if (shell.isVisible () && shell.isEnabled ()) { Event event = new Event (); event.detail = SWT.TRAVERSE_MNEMONIC; if (setKeyState (event, gdkEvent)) { return translateMnemonic (event, null) || shell.translateMnemonic (event, this); } } return false; } boolean translateTraversal (GdkEventKey keyEvent) { int detail = SWT.TRAVERSE_NONE; int key = keyEvent.keyval; int code = traversalCode (key, keyEvent); boolean all = false; switch (key) { case OS.GDK_Escape: { all = true; detail = SWT.TRAVERSE_ESCAPE; break; } case OS.GDK_KP_Enter: case OS.GDK_Return: { all = true; detail = SWT.TRAVERSE_RETURN; break; } case OS.GDK_ISO_Left_Tab: case OS.GDK_Tab: { boolean next = (keyEvent.state & OS.GDK_SHIFT_MASK) == 0; detail = next ? SWT.TRAVERSE_TAB_NEXT : SWT.TRAVERSE_TAB_PREVIOUS; break; } case OS.GDK_Up: case OS.GDK_Left: case OS.GDK_Down: case OS.GDK_Right: { boolean next = key == OS.GDK_Down || key == OS.GDK_Right; if (parent != null && (parent.style & SWT.MIRRORED) != 0) { if (key == OS.GDK_Left || key == OS.GDK_Right) next = !next; } detail = next ? SWT.TRAVERSE_ARROW_NEXT : SWT.TRAVERSE_ARROW_PREVIOUS; break; } case OS.GDK_Page_Up: case OS.GDK_Page_Down: { all = true; if ((keyEvent.state & OS.GDK_CONTROL_MASK) == 0) return false; detail = key == OS.GDK_Page_Down ? SWT.TRAVERSE_PAGE_NEXT : SWT.TRAVERSE_PAGE_PREVIOUS; break; } default: return false; } Event event = new Event (); event.doit = (code & detail) != 0; event.detail = detail; event.time = keyEvent.time; if (!setKeyState (event, keyEvent)) return false; Shell shell = getShell (); Control control = this; do { if (control.traverse (event)) return true; if (!event.doit && control.hooks (SWT.Traverse)) return false; if (control == shell) return false; control = control.parent; } while (all && control != null); return false; } int traversalCode (int key, GdkEventKey event) { int code = SWT.TRAVERSE_RETURN | SWT.TRAVERSE_TAB_NEXT | SWT.TRAVERSE_TAB_PREVIOUS | SWT.TRAVERSE_PAGE_NEXT | SWT.TRAVERSE_PAGE_PREVIOUS; Shell shell = getShell (); if (shell.parent != null) code |= SWT.TRAVERSE_ESCAPE; return code; } boolean traverse (Event event) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the traverse * event. If this happens, return true to stop further * event processing. */ sendEvent (SWT.Traverse, event); if (isDisposed ()) return true; if (!event.doit) return false; switch (event.detail) { case SWT.TRAVERSE_NONE: return true; case SWT.TRAVERSE_ESCAPE: return traverseEscape (); case SWT.TRAVERSE_RETURN: return traverseReturn (); case SWT.TRAVERSE_TAB_NEXT: return traverseGroup (true); case SWT.TRAVERSE_TAB_PREVIOUS: return traverseGroup (false); case SWT.TRAVERSE_ARROW_NEXT: return traverseItem (true); case SWT.TRAVERSE_ARROW_PREVIOUS: return traverseItem (false); case SWT.TRAVERSE_MNEMONIC: return traverseMnemonic (event.character); case SWT.TRAVERSE_PAGE_NEXT: return traversePage (true); case SWT.TRAVERSE_PAGE_PREVIOUS: return traversePage (false); } return false; } boolean traverseEscape () { return false; } boolean traverseGroup (boolean next) { Control root = computeTabRoot (); Widget group = computeTabGroup (); Widget [] list = root.computeTabList (); int length = list.length; int index = 0; while (index < length) { if (list [index] == group) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ if (index == length) return false; int start = index, offset = (next) ? 1 : -1; while ((index = ((index + offset + length) % length)) != start) { Widget widget = list [index]; if (!widget.isDisposed () && widget.setTabGroupFocus (next)) { return true; } } if (group.isDisposed ()) return false; return group.setTabGroupFocus (next); } boolean traverseItem (boolean next) { Control [] children = parent._getChildren (); int length = children.length; int index = 0; while (index < length) { if (children [index] == this) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ if (index == length) return false; int start = index, offset = (next) ? 1 : -1; while ((index = (index + offset + length) % length) != start) { Control child = children [index]; if (!child.isDisposed () && child.isTabItem ()) { if (child.setTabItemFocus (next)) return true; } } return false; } boolean traverseReturn () { return false; } boolean traversePage (boolean next) { return false; } boolean traverseMnemonic (char key) { return mnemonicHit (key); } /** * Forces all outstanding paint requests for the widget * to be processed before this method returns. If there * are no outstanding paint request, this method does * nothing. * <p> * Note: This method does not cause a redraw. * </p> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #redraw() * @see #redraw(int, int, int, int, boolean) * @see PaintListener * @see SWT#Paint */ public void update () { checkWidget (); update (false, true); } void update (boolean all, boolean flush) { // checkWidget(); if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) == 0) return; int /*long*/ window = paintWindow (); if (flush) display.flushExposes (window, all); OS.gdk_window_process_updates (window, all); OS.gdk_flush (); } void updateBackgroundMode () { int oldState = state & PARENT_BACKGROUND; checkBackground (); if (oldState != (state & PARENT_BACKGROUND)) { setBackground (); } } void updateLayout (boolean all) { /* Do nothing */ } int /*long*/ windowProc (int /*long*/ handle, int /*long*/ arg0, int /*long*/ user_data) { switch ((int)/*64*/user_data) { case EXPOSE_EVENT_INVERSE: { if ((OS.GTK_VERSION < OS.VERSION (2, 8, 0)) && ((state & OBSCURED) == 0)) { Control control = findBackgroundControl (); if (control != null && control.backgroundImage != null) { GdkEventExpose gdkEvent = new GdkEventExpose (); OS.memmove (gdkEvent, arg0, GdkEventExpose.sizeof); int /*long*/ paintWindow = paintWindow(); int /*long*/ window = gdkEvent.window; if (window != paintWindow) break; int /*long*/ gdkGC = OS.gdk_gc_new (window); OS.gdk_gc_set_clip_region (gdkGC, gdkEvent.region); int[] dest_x = new int[1], dest_y = new int[1]; OS.gtk_widget_translate_coordinates (paintHandle (), control.paintHandle (), 0, 0, dest_x, dest_y); OS.gdk_gc_set_fill (gdkGC, OS.GDK_TILED); OS.gdk_gc_set_ts_origin (gdkGC, -dest_x [0], -dest_y [0]); OS.gdk_gc_set_tile (gdkGC, control.backgroundImage.pixmap); OS.gdk_draw_rectangle (window, gdkGC, 1, gdkEvent.area_x, gdkEvent.area_y, gdkEvent.area_width, gdkEvent.area_height); OS.g_object_unref (gdkGC); } } break; } } return super.windowProc (handle, arg0, user_data); } }
567ce921ca7eb4e1a3cc69ae307e05b17a12330a
49ea87e7e275b9458e2f7a63c32bcbf4f9739db9
/app/src/main/java/com/example/duan_1/interface_/Meat_OnClickItemListener.java
29c67677ed1e82f1194dd954352c72dbc84f40db
[]
no_license
lvmai1804/DuAn_1
0c48c17815f17e170279628cf428eba0c7095a74
4b3e7fd75a44ee4d59ccb3c42303102efa2f4ede
refs/heads/master
2023-04-04T09:00:07.824027
2021-03-28T18:17:02
2021-03-28T18:17:02
351,681,815
0
1
null
2021-03-28T18:17:03
2021-03-26T06:16:15
Java
UTF-8
Java
false
false
163
java
package com.example.duan_1.interface_; import com.example.duan_1.model.Product; public interface Meat_OnClickItemListener { void onClick(Product product); }
e134714727135afc3aa818d68cb65b58420dc4cd
13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3
/crash-reproduction-new-fitness/results/MATH-70b-3-19-Single_Objective_GGA-WeightedSum-BasicBlockCoverage-opt/org/apache/commons/math/analysis/solvers/BisectionSolver_ESTest.java
9c5ea898afa8f3c614766bfe377e0f88cbe4baab
[ "MIT", "CC-BY-4.0" ]
permissive
STAMP-project/Botsing-basic-block-coverage-application
6c1095c6be945adc0be2b63bbec44f0014972793
80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da
refs/heads/master
2022-07-28T23:05:55.253779
2022-04-20T13:54:11
2022-04-20T13:54:11
285,771,370
0
0
null
null
null
null
UTF-8
Java
false
false
1,159
java
/* * This file was automatically generated by EvoSuite * Tue Oct 26 10:19:10 UTC 2021 */ package org.apache.commons.math.analysis.solvers; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.shaded.org.mockito.Mockito.*; import static org.evosuite.runtime.EvoAssertions.*; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.solvers.BisectionSolver; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.ViolatedAssumptionAnswer; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class BisectionSolver_ESTest extends BisectionSolver_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { BisectionSolver bisectionSolver0 = new BisectionSolver(); UnivariateRealFunction univariateRealFunction0 = mock(UnivariateRealFunction.class, new ViolatedAssumptionAnswer()); // Undeclared exception! bisectionSolver0.solve(univariateRealFunction0, (-1009.0), 1.0, (-827.9565151036117)); } }
f8798b1cdb298b7bc47a77192df98bad95ee06bf
52f1c9f9e82ae977fd27dc90c2be5fc34b39ad8f
/e3-manager/e3-manager-pojo/src/main/java/com/fuyi/e3/pojo/TbItemDescExample.java
e399d0d0240a755410d04e7f20609b40305e89ae
[]
no_license
unknow16/e3-parent
9ad9d894361d11d441f277f6caf9857acd3ec6d1
2abb12f0867505413bc4796bf2aaf05f1a1c11fd
refs/heads/master
2021-07-24T11:25:27.012643
2017-11-03T08:56:56
2017-11-03T08:56:56
108,110,474
0
1
null
null
null
null
UTF-8
Java
false
false
11,079
java
package com.fuyi.e3.pojo; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TbItemDescExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TbItemDescExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andItemIdIsNull() { addCriterion("item_id is null"); return (Criteria) this; } public Criteria andItemIdIsNotNull() { addCriterion("item_id is not null"); return (Criteria) this; } public Criteria andItemIdEqualTo(Long value) { addCriterion("item_id =", value, "itemId"); return (Criteria) this; } public Criteria andItemIdNotEqualTo(Long value) { addCriterion("item_id <>", value, "itemId"); return (Criteria) this; } public Criteria andItemIdGreaterThan(Long value) { addCriterion("item_id >", value, "itemId"); return (Criteria) this; } public Criteria andItemIdGreaterThanOrEqualTo(Long value) { addCriterion("item_id >=", value, "itemId"); return (Criteria) this; } public Criteria andItemIdLessThan(Long value) { addCriterion("item_id <", value, "itemId"); return (Criteria) this; } public Criteria andItemIdLessThanOrEqualTo(Long value) { addCriterion("item_id <=", value, "itemId"); return (Criteria) this; } public Criteria andItemIdIn(List<Long> values) { addCriterion("item_id in", values, "itemId"); return (Criteria) this; } public Criteria andItemIdNotIn(List<Long> values) { addCriterion("item_id not in", values, "itemId"); return (Criteria) this; } public Criteria andItemIdBetween(Long value1, Long value2) { addCriterion("item_id between", value1, value2, "itemId"); return (Criteria) this; } public Criteria andItemIdNotBetween(Long value1, Long value2) { addCriterion("item_id not between", value1, value2, "itemId"); return (Criteria) this; } public Criteria andCreatedIsNull() { addCriterion("created is null"); return (Criteria) this; } public Criteria andCreatedIsNotNull() { addCriterion("created is not null"); return (Criteria) this; } public Criteria andCreatedEqualTo(Date value) { addCriterion("created =", value, "created"); return (Criteria) this; } public Criteria andCreatedNotEqualTo(Date value) { addCriterion("created <>", value, "created"); return (Criteria) this; } public Criteria andCreatedGreaterThan(Date value) { addCriterion("created >", value, "created"); return (Criteria) this; } public Criteria andCreatedGreaterThanOrEqualTo(Date value) { addCriterion("created >=", value, "created"); return (Criteria) this; } public Criteria andCreatedLessThan(Date value) { addCriterion("created <", value, "created"); return (Criteria) this; } public Criteria andCreatedLessThanOrEqualTo(Date value) { addCriterion("created <=", value, "created"); return (Criteria) this; } public Criteria andCreatedIn(List<Date> values) { addCriterion("created in", values, "created"); return (Criteria) this; } public Criteria andCreatedNotIn(List<Date> values) { addCriterion("created not in", values, "created"); return (Criteria) this; } public Criteria andCreatedBetween(Date value1, Date value2) { addCriterion("created between", value1, value2, "created"); return (Criteria) this; } public Criteria andCreatedNotBetween(Date value1, Date value2) { addCriterion("created not between", value1, value2, "created"); return (Criteria) this; } public Criteria andUpdatedIsNull() { addCriterion("updated is null"); return (Criteria) this; } public Criteria andUpdatedIsNotNull() { addCriterion("updated is not null"); return (Criteria) this; } public Criteria andUpdatedEqualTo(Date value) { addCriterion("updated =", value, "updated"); return (Criteria) this; } public Criteria andUpdatedNotEqualTo(Date value) { addCriterion("updated <>", value, "updated"); return (Criteria) this; } public Criteria andUpdatedGreaterThan(Date value) { addCriterion("updated >", value, "updated"); return (Criteria) this; } public Criteria andUpdatedGreaterThanOrEqualTo(Date value) { addCriterion("updated >=", value, "updated"); return (Criteria) this; } public Criteria andUpdatedLessThan(Date value) { addCriterion("updated <", value, "updated"); return (Criteria) this; } public Criteria andUpdatedLessThanOrEqualTo(Date value) { addCriterion("updated <=", value, "updated"); return (Criteria) this; } public Criteria andUpdatedIn(List<Date> values) { addCriterion("updated in", values, "updated"); return (Criteria) this; } public Criteria andUpdatedNotIn(List<Date> values) { addCriterion("updated not in", values, "updated"); return (Criteria) this; } public Criteria andUpdatedBetween(Date value1, Date value2) { addCriterion("updated between", value1, value2, "updated"); return (Criteria) this; } public Criteria andUpdatedNotBetween(Date value1, Date value2) { addCriterion("updated not between", value1, value2, "updated"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
894ae8df5f57119958fb0c82ca4c9fa874617ac2
9cefedc84987b4c32d2f8141aff05bae415bd2d9
/EventEngine-ProcessEvolution/src/ChangeController/FragmentChangeListener.java
baa0f7b983cb2c78ef63ba762a2a78f9107324a0
[]
no_license
lionelinfo2/debo
be3d7576a812b77248ebc238e4acb8c4eb25e32c
05d876e981cddf7572104d60636f14de043d0222
refs/heads/master
2020-05-01T08:24:24.441484
2012-08-22T10:18:50
2012-08-22T10:18:50
34,418,304
0
0
null
null
null
null
UTF-8
Java
false
false
4,873
java
package ChangeController; import java.util.HashSet; import java.util.SortedSet; import javax.xml.stream.util.EventReaderDelegate; import org.eclipse.bpmn2.Bpmn2Factory; import org.eclipse.bpmn2.Documentation; import org.eclipse.bpmn2.Expression; import eventengine.ConjunctionRule; import eventengine.DNFEventRule; import eventengine.Debug; import eventengine.Event; import eventengine.EventEngine; import eventengine.ProcessInstance; import siena.AttributeConstraint; import siena.Filter; import siena.HierarchicalDispatcher; import siena.Notification; import siena.NotificationBuffer; import siena.Op; import siena.SienaException; /** * Fragment specific change controller * Regulates any specific changes from a specific fragment engine * e.g. suspend, resume, getRunningProcessIDs, redeploy */ public class FragmentChangeListener implements Runnable{ NotificationBuffer _controlBuffer = new NotificationBuffer(); EventEngine _engine; public FragmentChangeListener(EventEngine en) { _engine = en; // Subscribe to CTRL notifications this.subscribe(_engine.getName(), _engine.getHierarchicalDispatcher()); } @Override public void run() { Notification e; while(true) { try { e = _controlBuffer.getNotification(-1); String action = e.getAttribute("action").stringValue(); if (action.equals("suspend")) { // Suspend _engine.setSuspended(true); _engine.getGuiController().setEngineTitle(_engine.getName() + " SUSPENDED"); } else if (action.equals("resume")) { // Resume synchronized (_engine) { _engine.setSuspended(false); _engine.notify(); _engine.getGuiController().setEngineTitle(_engine.getName()); } } else if (action.equals("getRunningProcessIDs")) { System.out.println("getRunningProcessIDS: " + _engine.getName()); // Retrieve all process instance events in the buffer HashSet<Integer> PIIDS = new HashSet<Integer>(); for (Notification n: _engine.getNotificationBuffer().getAllNotifications()) { PIIDS.add(n.getAttribute("processInstanceId").intValue()); } // add all instances in already existing (i.e. instances in progress) synchronized (_engine.getProcessInstances()) { for (ProcessInstance pi: _engine.getProcessInstances()) { if (!pi.done()) { PIIDS.add(Integer.valueOf(pi.getInstanceId())); } } } // Publish the results Notification result = new Notification(); result.putAttribute("id", "CTRL"); result.putAttribute("fragment", "ChangeManager"); result.putAttribute("action", "PIIDS"); result.putAttribute("PIIDS", PIIDS.toString()); result.putAttribute("source", _engine.getName()); this.publish(result); } else if (action.equals("redeploy")) { // Redeploy the new event rule // PIIDS which have to run with the old event rule HashSet<Integer> PIIDS = NotificationParser.parsePIIDs(e.getAttribute("PIIDS").stringValue()); DNFEventRule er = NotificationParser.parseER(e.getAttribute("eventRule").stringValue()); _engine.redeploy(er, PIIDS); // TODO if deleted fragment, also unsubscribe for CTRL messages! // if (er.getAllEvents().isEmpty()) { // this.unsubscribe(); // } } } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } private void subscribe(String fragmentName, HierarchicalDispatcher siena) { // Subscribe to two filters, one specifying the CTRL for ALL // and other filter specifying the CTRL for this specific fragment try { Filter f1 = new Filter(); f1.addConstraint("id", "CTRL"); f1.addConstraint("fragment", "ALL"); siena.subscribe(f1, _controlBuffer); Filter f2 = new Filter(); f2.addConstraint("id", "CTRL"); f2.addConstraint("fragment", fragmentName); siena.subscribe(f2, _controlBuffer); } catch (SienaException e) { e.printStackTrace(); } } private void unsubscribe() { Filter f1 = new Filter(); f1.addConstraint("id", "CTRL"); f1.addConstraint("fragment", "ALL"); _engine.getHierarchicalDispatcher().unsubscribe(f1,_controlBuffer); Filter f2 = new Filter(); f2.addConstraint("id", "CTRL"); f2.addConstraint("fragment", _engine.getName()); _engine.getHierarchicalDispatcher().unsubscribe(f2, _controlBuffer); } private void publish(Notification n) { System.out.println("Publishing: " + n); try { _engine.getHierarchicalDispatcher().publish(n); } catch (SienaException e) { e.printStackTrace(); } } }
[ "[email protected]@5e0a034c-d270-59ea-a42c-8aa4efe60014" ]
[email protected]@5e0a034c-d270-59ea-a42c-8aa4efe60014
12c953aeabc2bc44b9a6d8ffb36c4fdeb464916d
b2efdd314204d7905197b5e65a900d63ed588068
/src/main/java/pl/lublin/wsei/klasy/Posilek.java
bce4f31c8cc6bc59348f44fa0058050e9a69faac
[]
no_license
Andrzejasty/kalkulator_dietetyczny
de2d0ac0264755128da7dcb2d67dca662f7060d0
4860042a677bde439477fb4b766881ae47922789
refs/heads/master
2022-11-12T02:22:30.055054
2020-06-23T07:31:12
2020-06-23T07:31:12
269,289,061
0
0
null
2020-06-04T07:23:48
2020-06-04T07:23:47
null
UTF-8
Java
false
false
3,610
java
package pl.lublin.wsei.klasy; import java.util.HashMap; import java.util.Map; public class Posilek { private HashMap<Produkt, Integer> skladnikiPosilku; //Key to Produkt, Value to ilość produktu w posiku. //poniżej są wartośći na bieżąco kalkulowane przez klasę private double iloscTluszczow = 0; private double iloscTluszczowNasyconych = 0; private double iloscBialek = 0; private double iloscWeglowodanow = 0; private double iloscCukrow = 0; private double iloscKCal = 0; public double getIloscTluszczow() { return iloscTluszczow; } public HashMap<Produkt, Integer> getSkladnikiPosilku() { return skladnikiPosilku; } public double getIloscTluszczowNasyconych() { return iloscTluszczowNasyconych; } public double getIloscBialek() { return iloscBialek; } public double getIloscWeglowodanow() { return iloscWeglowodanow; } public double getIloscCukrow() { return iloscCukrow; } public double getIloscKCal() { return iloscKCal; } public Posilek() { this.skladnikiPosilku = new HashMap<>(); } public Posilek(HashMap<Produkt, Integer> skladniki) { this.skladnikiPosilku = skladniki; usunPusteProdukty(); kalkuluj(); } public void dodajProdukty(Produkt produkt, int ilosc) { if (ilosc <= 0) { System.out.println("Nieprawidłowa wartość"); return; } zmienProdukty(produkt, ilosc); } public void usunProdukty(Produkt produkt, int ilosc) { if (ilosc >= 0) { System.out.println("Nieprawidłowa wartość"); return; } zmienProdukty(produkt, -ilosc); } private void zmienProdukty(Produkt produkt, int ilosc) { if (skladnikiPosilku.containsKey(produkt)) { skladnikiPosilku.replace(produkt, skladnikiPosilku.get(produkt) + ilosc); } else { skladnikiPosilku.put(produkt, ilosc); } //Produkt po zmianie może mieć wartość 0. Usuńmy ją. usunPustyProdukt(produkt); kalkuluj(); } private void usunPusteProdukty() { //Automatyczny cleanup for (Map.Entry<Produkt, Integer> wpis : skladnikiPosilku.entrySet()) { Produkt produkt = wpis.getKey(); usunPustyProdukt(produkt); } } private void usunPustyProdukt(Produkt produkt) { if (skladnikiPosilku.get(produkt) == 0) { skladnikiPosilku.remove(produkt); } } private void kalkuluj() { //reset wartosci this.iloscBialek = 0; this.iloscCukrow = 0; this.iloscTluszczow = 0; this.iloscTluszczowNasyconych = 0; this.iloscWeglowodanow = 0; this.iloscKCal = 0; for (Map.Entry<Produkt, Integer> wpis : skladnikiPosilku.entrySet()) { Produkt produkt = wpis.getKey(); int ilosc = wpis.getValue(); this.iloscBialek += produkt.getIloscBialek() * ilosc; this.iloscKCal += produkt.getIloscKCal() * ilosc; this.iloscWeglowodanow += produkt.getIloscWeglowodanow() * ilosc; this.iloscTluszczow += produkt.getIloscTluszczow() * ilosc; this.iloscTluszczowNasyconych += produkt.getIloscTluszczowNasyconych() * ilosc; this.iloscCukrow += produkt.getIloscCukrow() * ilosc; } } }
fa776976ebe6d9b6f8c492163297ca38ad544245
bfa5a8a655fe87bf5da6f984d3ac365b5af3ff97
/safe/src/cn/changl/safe360/android/view/WheelView.java
e7fa157e7897f39c3fe3ed0f423896514685b5d7
[]
no_license
agenliuhuan/myproject-first
e5fcd56bb43736e39a5854928e7a857089b76ccd
cc6b3cd46ec0cba9bd07fc905cb33bf061ed414c
refs/heads/master
2021-01-25T03:19:45.823172
2015-03-13T03:51:47
2015-03-13T03:51:47
32,126,274
0
0
null
null
null
null
UTF-8
Java
false
false
25,635
java
/* * Android Wheel Control. * https://code.google.com/p/android-wheel/ * * Copyright 2011 Yuri Kanivets * * 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 cn.changl.safe360.android.view; import java.util.LinkedList; import java.util.List; import cn.changl.safe360.android.R; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.animation.Interpolator; import android.widget.LinearLayout; /** * Numeric wheel view. * * @author Yuri Kanivets */ public class WheelView extends View { /** Top and bottom shadows colors */ private static final int[] SHADOWS_COLORS = new int[] { 0x00ffffff, 0x00ffffff, 0x00ffffff }; /** Top and bottom items offset (to hide that) */ private static final int ITEM_OFFSET_PERCENT = 10; /** Left and right padding value */ private static final int PADDING = 10; /** Default count of visible items */ private static final int DEF_VISIBLE_ITEMS = 5; // Wheel Values private int currentItem = 0; // Count of visible items private int visibleItems = DEF_VISIBLE_ITEMS; // Item height private int itemHeight = 0; // Center Line private Drawable centerDrawable; // Shadows drawables private GradientDrawable topShadow; private GradientDrawable bottomShadow; // Scrolling private WheelScroller scroller; private boolean isScrollingPerformed; private int scrollingOffset; // Cyclic boolean isCyclic = false; // Items layout private LinearLayout itemsLayout; // The number of first item in layout private int firstItem; // View adapter private WheelViewAdapter viewAdapter; // Recycle private WheelRecycle recycle = new WheelRecycle(this); // Listeners private List<OnWheelChangedListener> changingListeners = new LinkedList<OnWheelChangedListener>(); private List<OnWheelScrollListener> scrollingListeners = new LinkedList<OnWheelScrollListener>(); private List<OnWheelClickedListener> clickingListeners = new LinkedList<OnWheelClickedListener>(); /** * Constructor */ public WheelView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initData(context); } /** * Constructor */ public WheelView(Context context, AttributeSet attrs) { super(context, attrs); initData(context); } /** * Constructor */ public WheelView(Context context) { super(context); initData(context); } /** * Initializes class data * @param context the context */ private void initData(Context context) { scroller = new WheelScroller(getContext(), scrollingListener); } // Scrolling listener WheelScroller.ScrollingListener scrollingListener = new WheelScroller.ScrollingListener() { public void onStarted() { isScrollingPerformed = true; notifyScrollingListenersAboutStart(); } public void onScroll(int distance) { doScroll(distance); int height = getHeight(); if (scrollingOffset > height) { scrollingOffset = height; scroller.stopScrolling(); } else if (scrollingOffset < -height) { scrollingOffset = -height; scroller.stopScrolling(); } } public void onFinished() { if (isScrollingPerformed) { notifyScrollingListenersAboutEnd(); isScrollingPerformed = false; } scrollingOffset = 0; invalidate(); } public void onJustify() { if (Math.abs(scrollingOffset) > WheelScroller.MIN_DELTA_FOR_SCROLLING) { scroller.scroll(scrollingOffset, 0); } } }; /** * Set the the specified scrolling interpolator * @param interpolator the interpolator */ public void setInterpolator(Interpolator interpolator) { scroller.setInterpolator(interpolator); } /** * Gets count of visible items * * @return the count of visible items */ public int getVisibleItems() { return visibleItems; } /** * Sets the desired count of visible items. * Actual amount of visible items depends on wheel layout parameters. * To apply changes and rebuild view call measure(). * * @param count the desired count for visible items */ public void setVisibleItems(int count) { visibleItems = count; } /** * Gets view adapter * @return the view adapter */ public WheelViewAdapter getViewAdapter() { return viewAdapter; } // Adapter listener private DataSetObserver dataObserver = new DataSetObserver() { @Override public void onChanged() { invalidateWheel(false); } @Override public void onInvalidated() { invalidateWheel(true); } }; /** * Sets view adapter. Usually new adapters contain different views, so * it needs to rebuild view by calling measure(). * * @param viewAdapter the view adapter */ public void setViewAdapter(WheelViewAdapter viewAdapter) { if (this.viewAdapter != null) { this.viewAdapter.unregisterDataSetObserver(dataObserver); } this.viewAdapter = viewAdapter; if (this.viewAdapter != null) { this.viewAdapter.registerDataSetObserver(dataObserver); } invalidateWheel(true); } /** * Adds wheel changing listener * @param listener the listener */ public void addChangingListener(OnWheelChangedListener listener) { changingListeners.add(listener); } /** * Removes wheel changing listener * @param listener the listener */ public void removeChangingListener(OnWheelChangedListener listener) { changingListeners.remove(listener); } /** * Notifies changing listeners * @param oldValue the old wheel value * @param newValue the new wheel value */ protected void notifyChangingListeners(int oldValue, int newValue) { for (OnWheelChangedListener listener : changingListeners) { listener.onChanged(this, oldValue, newValue); } } /** * Adds wheel scrolling listener * @param listener the listener */ public void addScrollingListener(OnWheelScrollListener listener) { scrollingListeners.add(listener); } /** * Removes wheel scrolling listener * @param listener the listener */ public void removeScrollingListener(OnWheelScrollListener listener) { scrollingListeners.remove(listener); } /** * Notifies listeners about starting scrolling */ protected void notifyScrollingListenersAboutStart() { for (OnWheelScrollListener listener : scrollingListeners) { listener.onScrollingStarted(this); } } /** * Notifies listeners about ending scrolling */ protected void notifyScrollingListenersAboutEnd() { for (OnWheelScrollListener listener : scrollingListeners) { listener.onScrollingFinished(this); } } /** * Adds wheel clicking listener * @param listener the listener */ public void addClickingListener(OnWheelClickedListener listener) { clickingListeners.add(listener); } /** * Removes wheel clicking listener * @param listener the listener */ public void removeClickingListener(OnWheelClickedListener listener) { clickingListeners.remove(listener); } /** * Notifies listeners about clicking */ protected void notifyClickListenersAboutClick(int item) { for (OnWheelClickedListener listener : clickingListeners) { listener.onItemClicked(this, item); } } /** * Gets current value * * @return the current value */ public int getCurrentItem() { return currentItem; } /** * Sets the current item. Does nothing when index is wrong. * * @param index the item index * @param animated the animation flag */ public void setCurrentItem(int index, boolean animated) { if (viewAdapter == null || viewAdapter.getItemsCount() == 0) { return; // throw? } int itemCount = viewAdapter.getItemsCount(); if (index < 0 || index >= itemCount) { if (isCyclic) { while (index < 0) { index += itemCount; } index %= itemCount; } else{ return; // throw? } } if (index != currentItem) { if (animated) { int itemsToScroll = index - currentItem; if (isCyclic) { int scroll = itemCount + Math.min(index, currentItem) - Math.max(index, currentItem); if (scroll < Math.abs(itemsToScroll)) { itemsToScroll = itemsToScroll < 0 ? scroll : -scroll; } } scroll(itemsToScroll, 0); } else { scrollingOffset = 0; int old = currentItem; currentItem = index; notifyChangingListeners(old, currentItem); invalidate(); } } } /** * Sets the current item w/o animation. Does nothing when index is wrong. * * @param index the item index */ public void setCurrentItem(int index) { setCurrentItem(index, false); } /** * Tests if wheel is cyclic. That means before the 1st item there is shown the last one * @return true if wheel is cyclic */ public boolean isCyclic() { return isCyclic; } /** * Set wheel cyclic flag * @param isCyclic the flag to set */ public void setCyclic(boolean isCyclic) { this.isCyclic = isCyclic; invalidateWheel(false); } /** * Invalidates wheel * @param clearCaches if true then cached views will be clear */ public void invalidateWheel(boolean clearCaches) { if (clearCaches) { recycle.clearAll(); if (itemsLayout != null) { itemsLayout.removeAllViews(); } scrollingOffset = 0; } else if (itemsLayout != null) { // cache all items recycle.recycleItems(itemsLayout, firstItem, new ItemsRange()); } invalidate(); } /** * Initializes resources */ private void initResourcesIfNecessary() { if (centerDrawable == null) { centerDrawable = getContext().getResources().getDrawable(R.drawable.wheel_val); } if (topShadow == null) { topShadow = new GradientDrawable(Orientation.TOP_BOTTOM, SHADOWS_COLORS); } if (bottomShadow == null) { bottomShadow = new GradientDrawable(Orientation.BOTTOM_TOP, SHADOWS_COLORS); } setBackgroundResource(R.drawable.wheel_bg); } /** * Calculates desired height for layout * * @param layout * the source layout * @return the desired layout height */ private int getDesiredHeight(LinearLayout layout) { if (layout != null && layout.getChildAt(0) != null) { itemHeight = layout.getChildAt(0).getMeasuredHeight(); } int desired = itemHeight * visibleItems - itemHeight * ITEM_OFFSET_PERCENT / 50; return Math.max(desired, getSuggestedMinimumHeight()); } /** * Returns height of wheel item * @return the item height */ private int getItemHeight() { if (itemHeight != 0) { return itemHeight; } if (itemsLayout != null && itemsLayout.getChildAt(0) != null) { itemHeight = itemsLayout.getChildAt(0).getHeight(); return itemHeight; } return getHeight() / visibleItems; } /** * Calculates control width and creates text layouts * @param widthSize the input layout width * @param mode the layout mode * @return the calculated control width */ private int calculateLayoutWidth(int widthSize, int mode) { initResourcesIfNecessary(); // TODO: make it static itemsLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); itemsLayout.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int width = itemsLayout.getMeasuredWidth(); if (mode == MeasureSpec.EXACTLY) { width = widthSize; } else { width += 2 * PADDING; // Check against our minimum width width = Math.max(width, getSuggestedMinimumWidth()); if (mode == MeasureSpec.AT_MOST && widthSize < width) { width = widthSize; } } itemsLayout.measure(MeasureSpec.makeMeasureSpec(width - 2 * PADDING, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); return width; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); buildViewForMeasuring(); int width = calculateLayoutWidth(widthSize, widthMode); int height; if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else { height = getDesiredHeight(itemsLayout); if (heightMode == MeasureSpec.AT_MOST) { height = Math.min(height, heightSize); } } setMeasuredDimension(width, height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { layout(r - l, b - t); } /** * Sets layouts width and height * @param width the layout width * @param height the layout height */ private void layout(int width, int height) { int itemsWidth = width - 2 * PADDING; itemsLayout.layout(0, 0, itemsWidth, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (viewAdapter != null && viewAdapter.getItemsCount() > 0) { updateView(); drawItems(canvas); drawCenterRect(canvas); } drawShadows(canvas); } /** * Draws shadows on top and bottom of control * @param canvas the canvas for drawing */ private void drawShadows(Canvas canvas) { int height = (int)(1.5 * getItemHeight()); topShadow.setBounds(0, 0, getWidth(), height); topShadow.draw(canvas); bottomShadow.setBounds(0, getHeight() - height, getWidth(), getHeight()); bottomShadow.draw(canvas); } /** * Draws items * @param canvas the canvas for drawing */ private void drawItems(Canvas canvas) { canvas.save(); int top = (currentItem - firstItem) * getItemHeight() + (getItemHeight() - getHeight()) / 2; canvas.translate(PADDING, - top + scrollingOffset); itemsLayout.draw(canvas); canvas.restore(); } /** * Draws rect for current value * @param canvas the canvas for drawing */ private void drawCenterRect(Canvas canvas) { int center = getHeight() / 2; int offset = (int) (getItemHeight() / 2 * 1.2); centerDrawable.setBounds(0, center - offset, getWidth(), center + offset); centerDrawable.draw(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isEnabled() || getViewAdapter() == null) { return true; } switch (event.getAction()) { case MotionEvent.ACTION_MOVE: if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(true); } break; case MotionEvent.ACTION_UP: if (!isScrollingPerformed) { int distance = (int) event.getY() - getHeight() / 2; if (distance > 0) { distance += getItemHeight() / 2; } else { distance -= getItemHeight() / 2; } int items = distance / getItemHeight(); if (items != 0 && isValidItemIndex(currentItem + items)) { notifyClickListenersAboutClick(currentItem + items); } } break; } return scroller.onTouchEvent(event); } /** * Scrolls the wheel * @param delta the scrolling value */ private void doScroll(int delta) { scrollingOffset += delta; int itemHeight = getItemHeight(); int count = scrollingOffset / itemHeight; int pos = currentItem - count; int itemCount = viewAdapter.getItemsCount(); int fixPos = scrollingOffset % itemHeight; if (Math.abs(fixPos) <= itemHeight / 2) { fixPos = 0; } if (isCyclic && itemCount > 0) { if (fixPos > 0) { pos--; count++; } else if (fixPos < 0) { pos++; count--; } // fix position by rotating while (pos < 0) { pos += itemCount; } pos %= itemCount; } else { // if (pos < 0) { count = currentItem; pos = 0; } else if (pos >= itemCount) { count = currentItem - itemCount + 1; pos = itemCount - 1; } else if (pos > 0 && fixPos > 0) { pos--; count++; } else if (pos < itemCount - 1 && fixPos < 0) { pos++; count--; } } int offset = scrollingOffset; if (pos != currentItem) { setCurrentItem(pos, false); } else { invalidate(); } // update offset scrollingOffset = offset - count * itemHeight; if (scrollingOffset > getHeight()) { scrollingOffset = scrollingOffset % getHeight() + getHeight(); } } /** * Scroll the wheel * @param itemsToSkip items to scroll * @param time scrolling duration */ public void scroll(int itemsToScroll, int time) { int distance = itemsToScroll * getItemHeight() - scrollingOffset; scroller.scroll(distance, time); } /** * Calculates range for wheel items * @return the items range */ private ItemsRange getItemsRange() { if (getItemHeight() == 0) { return null; } int first = currentItem; int count = 1; while (count * getItemHeight() < getHeight()) { first--; count += 2; // top + bottom items } if (scrollingOffset != 0) { if (scrollingOffset > 0) { first--; } count++; // process empty items above the first or below the second int emptyItems = scrollingOffset / getItemHeight(); first -= emptyItems; count += Math.asin(emptyItems); } return new ItemsRange(first, count); } /** * Rebuilds wheel items if necessary. Caches all unused items. * * @return true if items are rebuilt */ private boolean rebuildItems() { boolean updated = false; ItemsRange range = getItemsRange(); if (itemsLayout != null) { int first = recycle.recycleItems(itemsLayout, firstItem, range); updated = firstItem != first; firstItem = first; } else { createItemsLayout(); updated = true; } if (!updated) { updated = firstItem != range.getFirst() || itemsLayout.getChildCount() != range.getCount(); } if (firstItem > range.getFirst() && firstItem <= range.getLast()) { for (int i = firstItem - 1; i >= range.getFirst(); i--) { if (!addViewItem(i, true)) { break; } firstItem = i; } } else { firstItem = range.getFirst(); } int first = firstItem; for (int i = itemsLayout.getChildCount(); i < range.getCount(); i++) { if (!addViewItem(firstItem + i, false) && itemsLayout.getChildCount() == 0) { first++; } } firstItem = first; return updated; } /** * Updates view. Rebuilds items and label if necessary, recalculate items sizes. */ private void updateView() { if (rebuildItems()) { calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY); layout(getWidth(), getHeight()); } } /** * Creates item layouts if necessary */ private void createItemsLayout() { if (itemsLayout == null) { itemsLayout = new LinearLayout(getContext()); itemsLayout.setOrientation(LinearLayout.VERTICAL); } } /** * Builds view for measuring */ private void buildViewForMeasuring() { // clear all items if (itemsLayout != null) { recycle.recycleItems(itemsLayout, firstItem, new ItemsRange()); } else { createItemsLayout(); } // add views int addItems = visibleItems / 2; for (int i = currentItem + addItems; i >= currentItem - addItems; i--) { if (addViewItem(i, true)) { firstItem = i; } } } /** * Adds view for item to items layout * @param index the item index * @param first the flag indicates if view should be first * @return true if corresponding item exists and is added */ private boolean addViewItem(int index, boolean first) { View view = getItemView(index); if (view != null) { if (first) { itemsLayout.addView(view, 0); } else { itemsLayout.addView(view); } return true; } return false; } /** * Checks whether intem index is valid * @param index the item index * @return true if item index is not out of bounds or the wheel is cyclic */ private boolean isValidItemIndex(int index) { return viewAdapter != null && viewAdapter.getItemsCount() > 0 && (isCyclic || index >= 0 && index < viewAdapter.getItemsCount()); } /** * Returns view for specified item * @param index the item index * @return item view or empty view if index is out of bounds */ private View getItemView(int index) { if (viewAdapter == null || viewAdapter.getItemsCount() == 0) { return null; } int count = viewAdapter.getItemsCount(); if (!isValidItemIndex(index)) { return viewAdapter.getEmptyItem(recycle.getEmptyItem(), itemsLayout); } else { while (index < 0) { index = count + index; } } index %= count; return viewAdapter.getItem(index, recycle.getItem(), itemsLayout); } /** * Stops scrolling */ public void stopScrolling() { scroller.stopScrolling(); } }
fa358509e3010f0048203cd764c88bcd33f51175
e63263a23e926e6a5f21084962caeddf811db5e2
/app/src/main/java/com/cs/zhishu/ui/activity/ThemesDailyDetailsActivity.java
a0c0da61d85c817023ea75df3afb9edcde7c10af
[]
no_license
Othell0/ZhiShu
5d8ba8dd0cb505e9cc6b5ab946ad7609ca3b6921
1ebc33af78a480803baa2df75ebf4fd834f2eaee
refs/heads/master
2020-05-21T19:17:50.801937
2016-09-22T02:34:30
2016-09-22T02:39:00
65,199,408
1
0
null
null
null
null
UTF-8
Java
false
false
7,590
java
package com.cs.zhishu.ui.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.cs.zhishu.R; import com.cs.zhishu.adapter.AbsRecyclerViewAdapter; import com.cs.zhishu.adapter.ThemesDetailsHeadAdapter; import com.cs.zhishu.adapter.ThemesDetailsStoriesAdapter; import com.cs.zhishu.base.AbsBaseActivity; import com.cs.zhishu.model.Editors; import com.cs.zhishu.model.Stories; import com.cs.zhishu.model.ThemesDetails; import com.cs.zhishu.network.RetrofitHelper; import com.cs.zhishu.util.refresh.HeaderViewRecyclerAdapter; import com.github.rahatarmanahmed.cpv.CircularProgressView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Othell0 on 2016/7/21. */ public class ThemesDailyDetailsActivity extends AbsBaseActivity { //主题日报故事列表 private List<Stories> stories = new ArrayList<>(); //主题日报主编列表 private List<Editors> editors = new ArrayList<>(); private static final String EXTRA_TYPE = "extra_type"; private int id; private HeaderViewRecyclerAdapter mHeaderViewRecyclerAdapter; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.recycle) RecyclerView mRecyclerView; @BindView(R.id.swipe_refresh) SwipeRefreshLayout mSwipeRefreshLayout; @BindView(R.id.circle_progress) CircularProgressView mCircleProgressView; @Override public int getLayoutId() { return R.layout.activity_type_daily; } @Override public void initViews(Bundle savedInstanceState) { Intent intent = getIntent(); if (intent != null) { id = intent.getIntExtra(EXTRA_TYPE, -1); } startGetThemesDetails(); } private void startGetThemesDetails() { mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(false); } }); mCircleProgressView.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); getThemesDetails(); } private void getThemesDetails() { RetrofitHelper.builder().getThemesDetailsById(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<ThemesDetails>() { @Override public void onCompleted() { Log.e("getThemesDetails", "onCompleted"); } @Override public void onError(Throwable e) { Log.e("getThemesDetails", "onError"); } @Override public void onNext(ThemesDetails themesDetails) { finishGetThemesDetails(themesDetails); } }); } private void finishGetThemesDetails(ThemesDetails themesDetails) { stories.addAll(themesDetails.getStories()); editors.addAll(themesDetails.getEditors()); mToolbar.setTitle(themesDetails.getName()); mRecyclerView.setHasFixedSize(true); LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLinearLayoutManager); ThemesDetailsStoriesAdapter mAdapter = new ThemesDetailsStoriesAdapter(mRecyclerView, stories); mHeaderViewRecyclerAdapter = new HeaderViewRecyclerAdapter(mAdapter); addHeadView(themesDetails); mRecyclerView.setAdapter(mHeaderViewRecyclerAdapter); mAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder holder) { Stories stories = ThemesDailyDetailsActivity.this.stories.get(position); DailyDetailActivity.launch(ThemesDailyDetailsActivity.this, stories.getId()); } }); mCircleProgressView.setVisibility(View.GONE); mRecyclerView.setVisibility(View.VISIBLE); } private void addHeadView(ThemesDetails themesDetails) { View headView = LayoutInflater.from(this) .inflate(R.layout.layout_themes_details_head, mRecyclerView, false); ImageView mThemesBg = (ImageView) headView.findViewById(R.id.type_image); TextView mThemesTitle = (TextView) headView.findViewById(R.id.type_title); Glide.with(this) .load(themesDetails.getBackground()) .placeholder(R.drawable.account_avatar) .into(mThemesBg); mThemesTitle.setText(themesDetails.getDescription()); View editorsHeadView = LayoutInflater.from(this) .inflate(R.layout.layout_themes_details_head1, mRecyclerView, false); RecyclerView mHeadRecycle = (RecyclerView) editorsHeadView.findViewById(R.id.head_recycle); mHeadRecycle.setHasFixedSize(true); LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); mHeadRecycle.setLayoutManager(mLinearLayoutManager); ThemesDetailsHeadAdapter mHeadAdapter = new ThemesDetailsHeadAdapter(mHeadRecycle, editors); mHeadRecycle.setAdapter(mHeadAdapter); mHeadAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder holder) { Editors editor = ThemesDailyDetailsActivity.this.editors.get(position); int id = editor.getId(); String name = editor.getName(); EditorInfoActivity.launcher(ThemesDailyDetailsActivity.this, id, name); } }); mHeaderViewRecyclerAdapter.addHeaderView(headView); mHeaderViewRecyclerAdapter.addHeaderView(editorsHeadView); mHeaderViewRecyclerAdapter.notifyDataSetChanged(); mHeadAdapter.notifyDataSetChanged(); } @Override public void initToolBar() { setSupportActionBar(mToolbar); ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) supportActionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } public static void launch(Activity activity, int id) { Intent mIntent = new Intent(activity, ThemesDailyDetailsActivity.class); mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mIntent.putExtra(EXTRA_TYPE, id); activity.startActivity(mIntent); } }