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
9c196a7af21e0947b946bb7f72585b4420243e62
c48b3d12820f2537297ab9c3b3f2e28c20114cbc
/src/main/java/com/uay/elasticsearch/clients/springdata/BlogpostSpringDataRepository.java
316fdfc673b42c81bd15acdfc490d769d870a5ba
[]
no_license
terrafant/es-feeder
a88f0dcbc563366b9d0384c6d9a5731dd4223d38
99f29d4663c77aae23404db3df30922be3be506e
refs/heads/master
2021-01-21T13:08:27.289582
2016-04-17T09:23:03
2016-04-17T09:23:03
54,430,175
0
1
null
null
null
null
UTF-8
Java
false
false
279
java
package com.uay.elasticsearch.clients.springdata; import com.uay.elasticsearch.model.Blogpost; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface BlogpostSpringDataRepository extends ElasticsearchRepository<Blogpost, String> { }
e5f9a094ff5be4872e10260e1fdeb1e7216bed40
29f62b409b7b5cd260d4526dd228aefff8ab2def
/src/test/java/TeamCityTest2.java
42bdda0dcb369f406c54e139f3921ed5b41b3313
[]
no_license
DavidMcMahon1983/TeamCity
6aed54b74f221b233e2696ce9489679b4a237adf
121ef19a1e1025595cfd1b60a1eedbb937b634ea
refs/heads/master
2021-01-20T13:07:51.166574
2017-04-25T08:45:41
2017-04-25T08:45:41
82,676,642
0
0
null
2017-04-24T23:20:11
2017-02-21T12:21:58
Java
UTF-8
Java
false
false
888
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. */ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author David */ public class TeamCityTest2 { public TeamCityTest2() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // // @Test // public void hello() {} }
ed3203a66b7d1eba94d83057d95dc94a4f630618
7f8f3aeb45c0f1aacaa2741cd535fb3431a68b36
/src/main/java/com/anytec/sdproperty/util/Distance.java
687473efad3212525f3cceb03100019e5fab396c
[]
no_license
coderzhao/sdpboot
9144ee2c2851a3d79959a9d8294634def20f6b03
a91badda306e78a0c3ec79176aa88ede4e14a371
refs/heads/master
2020-03-23T10:08:19.745451
2018-09-09T10:48:47
2018-09-09T10:48:47
141,427,409
2
0
null
null
null
null
UTF-8
Java
false
false
884
java
package com.anytec.sdproperty.util; public class Distance { private static final double EARTH_RADIUS = 6378137; private static double rad(double d) { return d * Math.PI / 180.0; } /** * 根据两点间经纬度坐标(double值),计算两点间距离,单位为米 * @param lng1 * @param lat1 * @param lng2 * @param lat2 * @return */ public static double GetDistance(double lng1, double lat1, double lng2, double lat2) { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10000; return s; } }
9e05aa3af38ff9afa205bde66eae16541bf92de6
1829f8e11b6e21459a7701cf7cd15782a105e50d
/src/main/java/com/sy/service/IBatchService.java
7ceafbf6f77e213a61ab782795f6fc0993a69574
[]
no_license
1394852162/manager
6143464afb6315d4164332b784ed1826d664d5bd
47b79d4b67f95b45d02b963a7ae45a8758bf7b56
refs/heads/master
2021-05-08T17:52:51.288742
2018-03-29T08:26:46
2018-03-29T08:26:46
119,491,941
0
1
null
2018-01-31T02:37:41
2018-01-30T06:20:34
JavaScript
UTF-8
Java
false
false
505
java
package com.sy.service; import com.sy.pojo.Batch; import java.util.HashMap; import java.util.List; /** * Created by haswell on 2018/2/6. */ public interface IBatchService { public List<Batch> getBatList(); public List<Batch> queryNameBatList(String BatName); public int insertBatch(HashMap<String,Object> map); public int updateBatchByKey(HashMap<String,Object> map); public int deleteBatch(int BatId); public List<Batch> getBatListbyDept(HashMap<String,Object> map); }
f89fd29ecff2fba5811a9bbc6590a9837afc9e53
d085062c033f3a89416e7d666c86ac8533056ac9
/src/main/java/com/shop/dao/ProductDao.java
94a8da75660eb19445e5e0b1215b51b4bf650676
[]
no_license
heibaifu/mall-admin-java
fccb888f39a605fecbe36562bbc25b4e8091dec1
9dbdf78de1e2007f5822d47243c9f19e6336eb5f
refs/heads/master
2021-09-28T04:18:27.090583
2018-11-14T10:31:32
2018-11-14T10:31:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,029
java
package com.shop.dao; import com.shop.entity.Goods; import com.shop.entity.GoodsDetailWithBLOBs; import com.shop.entity.Product; import com.shop.mapper.ProductMapper; import com.shop.mapper.ProductSqlProvider; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; import java.util.List; @Mapper public interface ProductDao extends ProductMapper { public static final String UPDATE_PRODUCT_SET_STATUS_1_STATUS_WHERE_PRODUCT_ID_PRODUCT_ID = " UPDATE product SET status = 1 - status WHERE product_id = #{productId}"; public static final String SELECT_FROM_PRODUCT_LIMIT_PAGE_NUM_PAGE_SIZE = " SELECT * FROM product limit #{pageNum},#{pageSize}"; public static final String SELECT_COUNT_PRODUCT_ID_FROM_PRODUCT = " SELECT count(product_id) FROM product "; @InsertProvider(type = ProductSqlProvider.class, method = "insertSelective") @SelectKey(resultType = Long.class, before = false, keyProperty = "product_id", statement = "SELECT LAST_INSERT_ID()") int insertSelectiveCallBack(Product record); @Select(SELECT_COUNT_PRODUCT_ID_FROM_PRODUCT) int findCount(); @Select(SELECT_FROM_PRODUCT_LIMIT_PAGE_NUM_PAGE_SIZE) List<Product> findGoodsList(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize); @Update(UPDATE_PRODUCT_SET_STATUS_1_STATUS_WHERE_PRODUCT_ID_PRODUCT_ID) int updateUpAndDown(Long productId); @Update({ "update goods_detail", "update_time = #{now(),jdbcType=TIMESTAMP},", "goods_banners = #{goods_banners,jdbcType=LONGVARCHAR},", "goods_detail = #{goods_detail,jdbcType=LONGVARCHAR},", "goods_desc = #{goods_desc,jdbcType=LONGVARCHAR}", "where goods_id = #{goods_id,jdbcType=BIGINT}" }) int updateByProductId(GoodsDetailWithBLOBs record); }
6f99d9f071d769e6c85443aa4ae0b7eeff39ea0c
fa777a0bccc4a45f6fdac889a9767fa289f32963
/src/main/java/blackjack/model/domain/Denomination.java
149d73537690bdbc078a1e61c2690e154c8cc9c1
[]
no_license
gyumin-kim/java-blackjack
04e31b3751a99e6b11a2587f050a35228d3d29c1
a5a630f67d05612726abd74fe66238671b03e2c8
refs/heads/main
2023-03-18T08:05:28.126751
2021-03-03T16:42:26
2021-03-03T16:42:26
335,875,324
1
1
null
2021-02-04T07:34:50
2021-02-04T07:34:49
null
UTF-8
Java
false
false
617
java
package blackjack.model.domain; public enum Denomination { ACE(1, "A"), TWO(2, "2"), THREE(3, "3"), FOUR(4, "4"), FIVE(5, "5"), SIX(6, "6"), SEVEN(7, "7"), EIGHT(8, "8"), NINE(9, "9"), TEN(10, "10"), JACK(10, "J"), QUEEN(10, "Q"), KING(10, "K"), ; private final int number; private final String symbol; Denomination(final int number, final String symbol) { this.number = number; this.symbol = symbol; } public int getNumber() { return number; } public String getSymbol() { return symbol; } }
3e4781222c8c374ce0fe7f8cf26bce39d1fb2750
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project85/src/test/java/org/gradle/test/performance85_1/Test85_82.java
5fa44f46819696c4927ace17165a8f2f281718da
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
289
java
package org.gradle.test.performance85_1; import static org.junit.Assert.*; public class Test85_82 { private final Production85_82 production = new Production85_82("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
2bbf8e90d38b36f135171ea28da309172ea21e2f
2c12d4abf2ef35f9974b5a40b5863017ed391a94
/sample/VC_SDK_Demo/Demo/app/src/main/java/com/huawei/opensdk/ec_sdk_demo/ui/conference/ConfListActivity.java
9eb6d4e1e68feb13f45fbd22d7e7bd6a36891487
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
WindowxDeveloper/CloudVC_Client_API_Demo_Android
c8d259a335ad02123d2f793d173023d660910369
849aa24a0c25eb1c7e356000562b806985ad4a51
refs/heads/master
2020-06-17T21:32:58.972830
2019-07-09T01:40:46
2019-07-09T01:40:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,059
java
package com.huawei.opensdk.ec_sdk_demo.ui.conference; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import com.huawei.opensdk.demoservice.ConfBaseInfo; import com.huawei.opensdk.ec_sdk_demo.R; import com.huawei.opensdk.ec_sdk_demo.adapter.ConfListAdapter; import com.huawei.opensdk.ec_sdk_demo.common.UIConstants; import com.huawei.opensdk.ec_sdk_demo.logic.conference.mvp.ConfListPresenter; import com.huawei.opensdk.ec_sdk_demo.logic.conference.mvp.IConfListContract; import com.huawei.opensdk.ec_sdk_demo.ui.IntentConstant; import com.huawei.opensdk.ec_sdk_demo.ui.base.MVPBaseActivity; import com.huawei.opensdk.ec_sdk_demo.util.ActivityUtil; import com.huawei.opensdk.ec_sdk_demo.widget.ThreeInputDialog; import java.util.List; public class ConfListActivity extends MVPBaseActivity<IConfListContract.ConfListView, ConfListPresenter> implements IConfListContract.ConfListView, View.OnClickListener { private ConfListPresenter mPresenter; private ConfListAdapter adapter; private ListView listView; private ImageView rightIV; private ImageView directJoinConfIV; @Override protected IConfListContract.ConfListView createView() { return this; } @Override protected ConfListPresenter createPresenter() { mPresenter = new ConfListPresenter(); return mPresenter; } @Override public void initializeComposition() { setContentView(R.layout.conference_list_layout); listView = (ListView) findViewById(R.id.conference_list); rightIV = (ImageView) findViewById(R.id.right_img); directJoinConfIV = (ImageView) findViewById(R.id.join_conf_iv); //TODO directJoinConfIV.setVisibility(View.VISIBLE); directJoinConfIV.setImageResource(R.drawable.join_conf_by_number_icon); directJoinConfIV.setOnClickListener(this); initRightIV(); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mPresenter.onItemClick(position); } }); } private void initRightIV() { rightIV.setImageResource(R.drawable.icon_create); rightIV.setOnClickListener(this); rightIV.setVisibility(View.VISIBLE); } @Override public void initializeData() { adapter = new ConfListAdapter(this); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void showLoading() { } @Override public void dismissLoading() { } @Override public void showCustomToast(final int resID) { runOnUiThread(new Runnable() { @Override public void run() { showToast(resID); } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.right_img: Intent intent = new Intent(IntentConstant.CREATE_CONF_ACTIVITY_ACTION); ActivityUtil.startActivity(this, intent); break; case R.id.join_conf_iv: showJoinConfDialog(); break; default: break; } } private void showJoinConfDialog() { final ThreeInputDialog editDialog = new ThreeInputDialog(this); editDialog.setTitle(R.string.join_conf); editDialog.setRightButtonListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.joinReserveConf(editDialog.getInput1(), editDialog.getInput2(), editDialog.getInput3()); } }); editDialog.setHint1(R.string.conf_id_input); editDialog.setHint2(R.string.access_code_input); editDialog.setHint3(R.string.password_code_input); editDialog.show(); } @Override public void refreshConfList(final List<ConfBaseInfo> confBaseInfoList) { runOnUiThread(new Runnable() { @Override public void run() { adapter.setData(confBaseInfoList); adapter.notifyDataSetChanged(); } }); } @Override public void gotoConfDetailActivity(String confID) { Intent intent = new Intent(IntentConstant.CONF_DETAIL_ACTIVITY_ACTION); intent.putExtra(UIConstants.CONF_ID, confID); ActivityUtil.startActivity(this, intent); } }
f766db69e8584e3b9db80b8251a8d425c7961ccc
eaf352d52326994ff3761843b753d5fefd20db7d
/src/gameClient/Ex2_Client.java
07852c1b327ce9631486e7da76888d234af0fddf
[]
no_license
Nadav-Paz/Ex2
0c2945261e81b124b1ec3253151c93e0ffded469
eaaa783980a55e450237e51bf809522594426889
refs/heads/main
2023-02-03T02:34:25.774017
2020-12-20T19:27:40
2020-12-20T19:27:40
320,886,564
0
0
null
null
null
null
UTF-8
Java
false
false
3,672
java
package gameClient; import Server.Game_Server_Ex2; import api.directed_weighted_graph; import api.edge_data; import api.game_service; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class Ex2_Client implements Runnable{ private static MyFrame _win; private static Arena _ar; public static void main(String[] a) { Thread client = new Thread(new Ex2_Client()); client.start(); } @Override public void run() { int scenario_num = 11; game_service game = Game_Server_Ex2.getServer(scenario_num); // you have [0,23] games // int id = 999; // game.login(id); String g = game.getGraph(); String pks = game.getPokemons(); directed_weighted_graph gg = game.getJava_Graph_Not_to_be_used(); init(game); game.startGame(); _win.setTitle("Ex2 - OOP: (NONE trivial Solution) "+game.toString()); int ind=0; long dt=1; while(game.isRunning()) { moveAgants(game, gg); try { if(ind%1==0) {_win.repaint();} Thread.sleep(dt); ind++; } catch(Exception e) { e.printStackTrace(); } } String res = game.toString(); System.out.println(res); System.exit(0); } /** * Moves each of the agents along the edge, * in case the agent is on a node the next destination (next edge) is chosen (randomly). * @param game * @param gg * @param */ private static void moveAgants(game_service game, directed_weighted_graph gg) { String lg = game.move(); List<CL_Agent> log = Arena.getAgents(lg, gg); _ar.setAgents(log); //ArrayList<OOP_Point3D> rs = new ArrayList<OOP_Point3D>(); String fs = game.getPokemons(); List<CL_Pokemon> ffs = Arena.json2Pokemons(fs); _ar.setPokemons(ffs); for(int i=0;i<log.size();i++) { CL_Agent ag = log.get(i); int id = ag.getID(); int dest = ag.getNextNode(); int src = ag.getSrcNode(); double v = ag.getValue(); if(dest==-1) { dest = nextNode(gg, src); game.chooseNextEdge(ag.getID(), dest); System.out.println("Agent: "+id+", val: "+v+" turned to node: "+dest); } } } /** * a very simple random walk implementation! * @param g * @param src * @return */ private static int nextNode(directed_weighted_graph g, int src) { int ans = -1; Collection<edge_data> ee = g.getE(src); Iterator<edge_data> itr = ee.iterator(); int s = ee.size(); int r = (int)(Math.random()*s); int i=0; while(i<r) {itr.next();i++;} ans = itr.next().getDest(); return ans; } private void init(game_service game) { String g = game.getGraph(); String fs = game.getPokemons(); directed_weighted_graph gg = game.getJava_Graph_Not_to_be_used(); //gg.init(g); _ar = new Arena(); _ar.setGraph(gg); _ar.setPokemons(Arena.json2Pokemons(fs)); _win = new MyFrame("test Ex2"); _win.setSize(1000, 700); _win.update(_ar); _win.show(); String info = game.toString(); JSONObject line; try { line = new JSONObject(info); JSONObject ttt = line.getJSONObject("GameServer"); int rs = ttt.getInt("agents"); System.out.println(info); System.out.println(game.getPokemons()); int src_node = 0; // arbitrary node, you should start at one of the pokemon ArrayList<CL_Pokemon> cl_fs = Arena.json2Pokemons(game.getPokemons()); for(int a = 0;a<cl_fs.size();a++) { Arena.updateEdge(cl_fs.get(a),gg);} for(int a = 0;a<rs;a++) { int ind = a%cl_fs.size(); CL_Pokemon c = cl_fs.get(ind); int nn = c.get_edge().getDest(); if(c.getType()<0 ) {nn = c.get_edge().getSrc();} game.addAgent(nn); } } catch (JSONException e) {e.printStackTrace();} } }
f136107535951a4a2a02c11609074a27aa28d4a6
4c9d35da30abf3ec157e6bad03637ebea626da3f
/eclipse/libs_src/org/ripple/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPublicKey.java
c4c9bbb47e6b4c43450d1242a778cf78a507bf88
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
youweixue/RipplePower
9e6029b94a057e7109db5b0df3b9fd89c302f743
61c0422fa50c79533e9d6486386a517565cd46d2
refs/heads/master
2020-04-06T04:40:53.955070
2015-04-02T12:22:30
2015-04-02T12:22:30
33,860,735
0
0
null
2015-04-13T09:52:14
2015-04-13T09:52:11
null
UTF-8
Java
false
false
4,688
java
package org.ripple.bouncycastle.pqc.jcajce.provider.rainbow; import java.security.PublicKey; import org.ripple.bouncycastle.asn1.DERNull; import org.ripple.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.ripple.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.ripple.bouncycastle.pqc.asn1.RainbowPublicKey; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowParameters; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; import org.ripple.bouncycastle.pqc.crypto.rainbow.util.RainbowUtil; import org.ripple.bouncycastle.pqc.jcajce.provider.util.KeyUtil; import org.ripple.bouncycastle.pqc.jcajce.spec.RainbowPublicKeySpec; import org.ripple.bouncycastle.util.Arrays; /** * This class implements CipherParameters and PublicKey. * <p/> * The public key in Rainbow consists of n - v1 polynomial components of the * private key's F and the field structure of the finite field k. * <p/> * The quadratic (or mixed) coefficients of the polynomials from the public key * are stored in the 2-dimensional array in lexicographical order, requiring n * * (n + 1) / 2 entries for each polynomial. The singular terms are stored in a * 2-dimensional array requiring n entries per polynomial, the scalar term of * each polynomial is stored in a 1-dimensional array. * <p/> * More detailed information on the public key is to be found in the paper of * Jintai Ding, Dieter Schmidt: Rainbow, a New Multivariable Polynomial * Signature Scheme. ACNS 2005: 164-175 (http://dx.doi.org/10.1007/11496137_12) */ public class BCRainbowPublicKey implements PublicKey { private static final long serialVersionUID = 1L; private short[][] coeffquadratic; private short[][] coeffsingular; private short[] coeffscalar; private int docLength; // length of possible document to sign private RainbowParameters rainbowParams; /** * Constructor * * @param docLength * @param coeffQuadratic * @param coeffSingular * @param coeffScalar */ public BCRainbowPublicKey(int docLength, short[][] coeffQuadratic, short[][] coeffSingular, short[] coeffScalar) { this.docLength = docLength; this.coeffquadratic = coeffQuadratic; this.coeffsingular = coeffSingular; this.coeffscalar = coeffScalar; } /** * Constructor (used by the {@link RainbowKeyFactorySpi}). * * @param keySpec * a {@link RainbowPublicKeySpec} */ public BCRainbowPublicKey(RainbowPublicKeySpec keySpec) { this(keySpec.getDocLength(), keySpec.getCoeffQuadratic(), keySpec .getCoeffSingular(), keySpec.getCoeffScalar()); } public BCRainbowPublicKey(RainbowPublicKeyParameters params) { this(params.getDocLength(), params.getCoeffQuadratic(), params .getCoeffSingular(), params.getCoeffScalar()); } /** * @return the docLength */ public int getDocLength() { return this.docLength; } /** * @return the coeffQuadratic */ public short[][] getCoeffQuadratic() { return coeffquadratic; } /** * @return the coeffSingular */ public short[][] getCoeffSingular() { short[][] copy = new short[coeffsingular.length][]; for (int i = 0; i != coeffsingular.length; i++) { copy[i] = Arrays.clone(coeffsingular[i]); } return copy; } /** * @return the coeffScalar */ public short[] getCoeffScalar() { return Arrays.clone(coeffscalar); } /** * Compare this Rainbow public key with another object. * * @param other * the other object * @return the result of the comparison */ public boolean equals(Object other) { if (other == null || !(other instanceof BCRainbowPublicKey)) { return false; } BCRainbowPublicKey otherKey = (BCRainbowPublicKey) other; return docLength == otherKey.getDocLength() && RainbowUtil.equals(coeffquadratic, otherKey.getCoeffQuadratic()) && RainbowUtil.equals(coeffsingular, otherKey.getCoeffSingular()) && RainbowUtil.equals(coeffscalar, otherKey.getCoeffScalar()); } public int hashCode() { int hash = docLength; hash = hash * 37 + Arrays.hashCode(coeffquadratic); hash = hash * 37 + Arrays.hashCode(coeffsingular); hash = hash * 37 + Arrays.hashCode(coeffscalar); return hash; } /** * @return name of the algorithm - "Rainbow" */ public final String getAlgorithm() { return "Rainbow"; } public String getFormat() { return "X.509"; } public byte[] getEncoded() { RainbowPublicKey key = new RainbowPublicKey(docLength, coeffquadratic, coeffsingular, coeffscalar); AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier( PQCObjectIdentifiers.rainbow, DERNull.INSTANCE); return KeyUtil.getEncodedSubjectPublicKeyInfo(algorithmIdentifier, key); } }
eb4856f8d030ce25ed5e224414900e121d3d6e0c
2300fd352045bcf7e01d68d099e98df37248da7e
/java-analyzer-core/src/test/resources/testClasses/annotation/SimpleClassWithWhenStep.java
ffdefc52664e298fe294023af630437dd4b06354
[ "Apache-2.0" ]
permissive
Augurk/Augurk.JavaAnalyzer
9501bffd3c6574e07ce88e6ec13f050c73658b44
91d912516254b16827cc5d82577c91c0c7f67271
refs/heads/master
2020-05-27T23:06:44.085967
2019-06-11T10:39:31
2019-06-11T10:39:31
188,814,708
0
0
Apache-2.0
2019-06-11T10:39:32
2019-05-27T09:36:45
Java
UTF-8
Java
false
false
217
java
import cucumber.api.java.en.When; public class SimpleClassWithWhenStep { @When("When step without call") public void whenStepWithoutCall() { } public void thisMethodShouldNotBePickedUp() { } }
7f9088656854a10c8ed6b127aed316932b8246c8
bf6e078eb4475bacdf529d10b81006d77e010bed
/app/src/androidTest/java/at/sw2015/teamturingapp/test/XMLParserTest.java
93668648ef255715c9d0ba3375d93631844c0b0d
[]
no_license
VanessaStanje/TeamTuringApp
095d5f2d4a2f21d6d37062bb65e662447a48d672
88bb8e63396c6d6db94e5338c1f20d3855874c54
refs/heads/master
2020-05-17T18:32:01.741981
2015-06-14T12:16:44
2015-06-14T12:16:44
34,199,855
0
0
null
null
null
null
UTF-8
Java
false
false
6,373
java
package at.sw2015.teamturingapp.test; import java.io.InputStream; import java.util.Vector; import android.os.Environment; import android.test.ActivityInstrumentationTestCase2; import com.robotium.solo.Solo; import org.w3c.dom.NodeList; import at.sw2015.teamturingapp.MainGameActivity; import at.sw2015.teamturingapp.R; import at.sw2015.teamturingapp.Utils.TMConfiguration; import at.sw2015.teamturingapp.Utils.XMLParser; public class XMLParserTest extends ActivityInstrumentationTestCase2<MainGameActivity>{ private Solo mySolo; public XMLParserTest(){ super(MainGameActivity.class); } public void setUp() throws Exception { super.setUp(); mySolo = new Solo(getInstrumentation(), getActivity()); } public void tearDown() throws Exception { } public void testXMLReadRawInput() throws Exception { InputStream in = mySolo.getCurrentActivity().getResources().openRawResource(R.raw.tmtestconfig); org.w3c.dom.Document new_doc = XMLParser.readRawXMLInput(in); assertNotNull(new_doc); NodeList tmname = new_doc.getElementsByTagName("TMNAME"); assertEquals(1, tmname.getLength()); NodeList author = new_doc.getElementsByTagName("AUTHOR"); assertEquals(1,author.getLength()); NodeList tape_count = new_doc.getElementsByTagName("TAPE_COUNT"); assertEquals(1,tape_count.getLength()); NodeList initial_states = new_doc.getElementsByTagName("INITIAL_STATE"); assertEquals(1,initial_states.getLength()); NodeList heads = new_doc.getElementsByTagName("H"); assertEquals(1,heads.getLength()); NodeList tapes = new_doc.getElementsByTagName("T"); assertEquals(1,tapes.getLength()); NodeList rules = new_doc.getElementsByTagName("R"); assertEquals(7,rules.getLength()); } public void testReadTMConfig() throws Exception { InputStream in = mySolo.getCurrentActivity().getResources().openRawResource(R.raw.tmtestconfig); org.w3c.dom.Document raw_xml_input = XMLParser.readRawXMLInput(in); TMConfiguration new_tm_config = XMLParser.readTMConfig(raw_xml_input); assertNotNull(new_tm_config); assertEquals(new_tm_config.getAuthor(),"Lukas Gregori and Vanessa Stanje"); assertEquals(new_tm_config.getTapeCount(),1); assertEquals(new_tm_config.getInitialState(),"S0"); assertEquals(new_tm_config.getHeadPositions().size(),1); assertEquals((int)new_tm_config.getHeadPositions().get(0),0); assertEquals(new_tm_config.getAllTapes().size(),1); assertEquals(new_tm_config.getAllTapes().get(0),"0-1-0-1-0-1"); assertEquals(new_tm_config.getAllGoals().get(0),"1-0-1-0-1-0"); assertEquals(new_tm_config.getAllRules().size(),7); Vector<String> rule1 = new_tm_config.getAllRules().get(0); Vector<String> rule2 = new_tm_config.getAllRules().get(1); Vector<String> rule3 = new_tm_config.getAllRules().get(2); assertEquals(rule1.size(),5); assertEquals(rule2.size(),5); assertEquals(rule3.size(),5); assertEquals(rule1.get(0),"S0"); assertEquals(rule1.get(1),"0"); assertEquals(rule1.get(2),"1"); assertEquals(rule1.get(3),"R"); assertEquals(rule1.get(4),"S0"); assertEquals(rule2.get(0),"S0"); assertEquals(rule2.get(1),"1"); assertEquals(rule2.get(2),"0"); assertEquals(rule2.get(3),"R"); assertEquals(rule2.get(4),"S1"); assertEquals(rule3.get(0),"S1"); assertEquals(rule3.get(1),"0"); assertEquals(rule3.get(2),"1"); assertEquals(rule3.get(3),"R"); assertEquals(rule3.get(4),"S1"); } public void testAddNewRule(){ XMLParser.addNewRule("S7-1-0-R-S8"); org.w3c.dom.Document raw_xml_input = XMLParser. readXMLInputFromSD(MainGameActivity.curr_tm_file_name_path); TMConfiguration new_tm_config = null; try { new_tm_config = XMLParser.readTMConfig(raw_xml_input); }catch (Exception e) { e.printStackTrace(); } assertNotNull(new_tm_config); Vector<Vector<String>> all_rules = new_tm_config.getAllRules(); assertTrue(all_rules.get(7).get(0).equalsIgnoreCase("S7")); assertTrue(all_rules.get(7).get(1).equalsIgnoreCase("1")); assertTrue(all_rules.get(7).get(2).equalsIgnoreCase("0")); assertTrue(all_rules.get(7).get(3).equalsIgnoreCase("R")); assertTrue(all_rules.get(7).get(4).equalsIgnoreCase("S8")); } public void testRemoveRule(){ XMLParser.removeRule(0); org.w3c.dom.Document raw_xml_input = XMLParser. readXMLInputFromSD(MainGameActivity.curr_tm_file_name_path); TMConfiguration new_tm_config = null; try { new_tm_config = XMLParser.readTMConfig(raw_xml_input); }catch (Exception e) { e.printStackTrace(); } assertNotNull(new_tm_config); Vector<Vector<String>> all_rules = new_tm_config.getAllRules(); assertTrue(all_rules.size() == 6); assertTrue(all_rules.get(0).get(0).equalsIgnoreCase("S0")); assertTrue(all_rules.get(1).get(0).equalsIgnoreCase("S1")); } public void testCreateTM(){ assertTrue(XMLParser.writeNewTM("NewTMTest","Myself","S0","1","0","0-0-0-0-0","0-1-0-1-0")); org.w3c.dom.Document raw_xml_input = XMLParser. readXMLInputFromSD(Environment. getExternalStorageDirectory() + "/TMConfigs/" + "NewTMTest.xml"); assertNotNull(raw_xml_input); TMConfiguration new_tm_config; try { new_tm_config = XMLParser.readTMConfig(raw_xml_input); assertNotNull(new_tm_config); assertEquals(new_tm_config.getAuthor(),"Myself"); assertEquals(""+new_tm_config.getHeadPositions().get(0),"0"); assertEquals(new_tm_config.getCurrentState(),"S0"); assertEquals(""+new_tm_config.getTapeCount(),"1"); assertEquals(new_tm_config.getAllTapes().get(0),"0-0-0-0-0"); assertEquals(new_tm_config.getAllGoals().get(0),"0-1-0-1-0"); }catch (Exception e) { e.printStackTrace(); } } }
931ee7561b5d4755d48cfb50bd97c9adab2aa22a
a847c37b97364914660df43e42b32ef898147677
/ArrayListsBoxingChallenge/src/com/vinothmasilamani/Transaction.java
fad68fbd2a13f0096d5c5091cfb4455d6edca13e
[]
no_license
mvinothanand/JavaExercises
3926bd085da4bb703370d760f6a3ae552224dcfd
69382ae92cfef55a43a7dadfa7747b1c09431935
refs/heads/master
2021-09-03T07:27:22.429197
2018-01-07T00:19:33
2018-01-07T00:19:33
114,501,581
0
0
null
null
null
null
UTF-8
Java
false
false
130
java
package com.vinothmasilamani; public class Transaction { private int transactionId; private double transactionAmount; }
857037f30ead958b239b7731810d2651f9803310
87808da5b7e0a5ff0470668aa306996044211145
/Android/app/src/main/java/net/lonelywood/architecture/android/components/photocomponent/PhotoTakerActivity.java
6cb32b97e8f4734d7a41e4d5fde96480d42640f3
[ "MS-PL" ]
permissive
Lonelywood/Android-Samples-IsolateComponents
9ee07df53fab604d5022fd46e46567a5624304c7
d284cb049f4b7fb43d594c0de81325453627e06a
refs/heads/master
2021-01-17T19:15:43.289521
2019-01-23T12:42:03
2019-01-23T12:42:03
71,640,754
0
0
null
null
null
null
UTF-8
Java
false
false
2,063
java
package net.lonelywood.architecture.android.components.photocomponent; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; public class PhotoTakerActivity extends AppCompatActivity { public static final String ExtraFileName = "fileName"; private static List<PhotoTakerListener> listeners = new ArrayList<>(); private String mFileName; private final int RequestImageCapture = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mFileName = savedInstanceState.getString(ExtraFileName); } else { mFileName = getIntent().getExtras().getString(ExtraFileName); } Uri uri = Uri.parse(mFileName); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, RequestImageCapture); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RequestImageCapture) { if (resultCode == RESULT_CANCELED){ for (PhotoTakerListener listener: listeners) { listener.onPhotoTaken(false, null); } } else if (resultCode == RESULT_OK){ for (PhotoTakerListener listener: listeners){ listener.onPhotoTaken(true, mFileName); } } } finish(); } public static void addListener(PhotoTakerListener listener){ listeners.add(listener); } public static void removeListener(PhotoTakerListener listener) { listeners.remove(listener); } }
d682e0dbbcfd40720124c789bf0657b74dee3f87
f4e12aaf765a6f97378fdb1f71a96a65e3de6b84
/app/src/main/java/com/ziv/recyclerview/listview/vertical/VerticalListAdapter.java
394e33ad5d4452eff3d96bc48c26dda32637fd2a
[]
no_license
Ziv-Android/MyRecyclerView
a085c82afba91f5eb6d75fa95c5d81968a800d9b
f1ece0468af6f5bd00f676456a78e40cad90ef0e
refs/heads/master
2020-06-14T07:23:44.236386
2016-11-30T18:13:13
2016-11-30T18:13:13
75,213,753
0
0
null
null
null
null
UTF-8
Java
false
false
1,613
java
package com.ziv.recyclerview.listview.vertical; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ziv.recyclerview.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Vertical List View Adapter * Created by ziv on 16-11-29. */ public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.VerticalListViewHolder> { private Context mContext; private List<String> mData; public VerticalListAdapter(Context context, List list) { mContext = context; mData = list; } @Override public VerticalListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false); ButterKnife.bind(this, view); VerticalListViewHolder holder = new VerticalListViewHolder(view); return holder; } @Override public void onBindViewHolder(VerticalListViewHolder holder, int position) { holder.contextTxt.setText(mData.get(position)); } @Override public int getItemCount() { return mData.size(); } class VerticalListViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.txt_context) TextView contextTxt; public VerticalListViewHolder(View itemView) { super(itemView); contextTxt = (TextView) itemView.findViewById(R.id.txt_context); } } }
3bfa43162ff3682c29dfdedefdae4f6b8cace2e6
86a4f4a2dc3f38c0b3188d994950f4c79f036484
/src/android/support/v4/app/Fragment.java
019ecb0ddc2989d3a3ef96a2489087b6ff39a18f
[]
no_license
reverseengineeringer/com.cbs.app
8f6f3532f119898bfcb6d7ddfeb465eae44d5cd4
7e588f7156f36177b0ff8f7dc13151c451a65051
refs/heads/master
2021-01-10T05:08:31.000287
2016-03-19T20:39:17
2016-03-19T20:39:17
54,283,808
0
0
null
null
null
null
UTF-8
Java
false
false
34,055
java
package android.support.v4.app; import android.app.Activity; import android.content.ComponentCallbacks; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import android.support.v4.util.DebugUtils; import android.support.v4.util.SimpleArrayMap; import android.support.v4.view.LayoutInflaterCompat; import android.util.AttributeSet; import android.util.SparseArray; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.view.animation.Animation; import java.io.FileDescriptor; import java.io.PrintWriter; public class Fragment implements ComponentCallbacks, View.OnCreateContextMenuListener { static final int ACTIVITY_CREATED = 2; static final int CREATED = 1; static final int INITIALIZING = 0; static final int RESUMED = 5; static final int STARTED = 4; static final int STOPPED = 3; static final Object USE_DEFAULT_TRANSITION = new Object(); private static final SimpleArrayMap<String, Class<?>> sClassMap = new SimpleArrayMap(); boolean mAdded; Boolean mAllowEnterTransitionOverlap; Boolean mAllowReturnTransitionOverlap; View mAnimatingAway; Bundle mArguments; int mBackStackNesting; boolean mCalled; boolean mCheckedForLoaderManager; FragmentManagerImpl mChildFragmentManager; ViewGroup mContainer; int mContainerId; boolean mDeferStart; boolean mDetached; Object mEnterTransition = null; SharedElementCallback mEnterTransitionCallback = null; Object mExitTransition = null; SharedElementCallback mExitTransitionCallback = null; int mFragmentId; FragmentManagerImpl mFragmentManager; boolean mFromLayout; boolean mHasMenu; boolean mHidden; FragmentHostCallback mHost; boolean mInLayout; int mIndex = -1; View mInnerView; LoaderManagerImpl mLoaderManager; boolean mLoadersStarted; boolean mMenuVisible = true; int mNextAnim; Fragment mParentFragment; Object mReenterTransition = USE_DEFAULT_TRANSITION; boolean mRemoving; boolean mRestored; boolean mResumed; boolean mRetainInstance; boolean mRetaining; Object mReturnTransition = USE_DEFAULT_TRANSITION; Bundle mSavedFragmentState; SparseArray<Parcelable> mSavedViewState; Object mSharedElementEnterTransition = null; Object mSharedElementReturnTransition = USE_DEFAULT_TRANSITION; int mState = 0; int mStateAfterAnimating; String mTag; Fragment mTarget; int mTargetIndex = -1; int mTargetRequestCode; boolean mUserVisibleHint = true; View mView; String mWho; public static Fragment instantiate(Context paramContext, String paramString) { return instantiate(paramContext, paramString, null); } public static Fragment instantiate(Context paramContext, String paramString, Bundle paramBundle) { try { Class localClass2 = (Class)sClassMap.get(paramString); Class localClass1 = localClass2; if (localClass2 == null) { localClass1 = paramContext.getClassLoader().loadClass(paramString); sClassMap.put(paramString, localClass1); } paramContext = (Fragment)localClass1.newInstance(); if (paramBundle != null) { paramBundle.setClassLoader(paramContext.getClass().getClassLoader()); mArguments = paramBundle; } return paramContext; } catch (ClassNotFoundException paramContext) { throw new InstantiationException("Unable to instantiate fragment " + paramString + ": make sure class name exists, is public, and has an empty constructor that is public", paramContext); } catch (InstantiationException paramContext) { throw new InstantiationException("Unable to instantiate fragment " + paramString + ": make sure class name exists, is public, and has an empty constructor that is public", paramContext); } catch (IllegalAccessException paramContext) { throw new InstantiationException("Unable to instantiate fragment " + paramString + ": make sure class name exists, is public, and has an empty constructor that is public", paramContext); } } static boolean isSupportFragmentClass(Context paramContext, String paramString) { try { Class localClass2 = (Class)sClassMap.get(paramString); Class localClass1 = localClass2; if (localClass2 == null) { localClass1 = paramContext.getClassLoader().loadClass(paramString); sClassMap.put(paramString, localClass1); } boolean bool = Fragment.class.isAssignableFrom(localClass1); return bool; } catch (ClassNotFoundException paramContext) {} return false; } public void dump(String paramString, FileDescriptor paramFileDescriptor, PrintWriter paramPrintWriter, String[] paramArrayOfString) { paramPrintWriter.print(paramString); paramPrintWriter.print("mFragmentId=#"); paramPrintWriter.print(Integer.toHexString(mFragmentId)); paramPrintWriter.print(" mContainerId=#"); paramPrintWriter.print(Integer.toHexString(mContainerId)); paramPrintWriter.print(" mTag="); paramPrintWriter.println(mTag); paramPrintWriter.print(paramString); paramPrintWriter.print("mState="); paramPrintWriter.print(mState); paramPrintWriter.print(" mIndex="); paramPrintWriter.print(mIndex); paramPrintWriter.print(" mWho="); paramPrintWriter.print(mWho); paramPrintWriter.print(" mBackStackNesting="); paramPrintWriter.println(mBackStackNesting); paramPrintWriter.print(paramString); paramPrintWriter.print("mAdded="); paramPrintWriter.print(mAdded); paramPrintWriter.print(" mRemoving="); paramPrintWriter.print(mRemoving); paramPrintWriter.print(" mResumed="); paramPrintWriter.print(mResumed); paramPrintWriter.print(" mFromLayout="); paramPrintWriter.print(mFromLayout); paramPrintWriter.print(" mInLayout="); paramPrintWriter.println(mInLayout); paramPrintWriter.print(paramString); paramPrintWriter.print("mHidden="); paramPrintWriter.print(mHidden); paramPrintWriter.print(" mDetached="); paramPrintWriter.print(mDetached); paramPrintWriter.print(" mMenuVisible="); paramPrintWriter.print(mMenuVisible); paramPrintWriter.print(" mHasMenu="); paramPrintWriter.println(mHasMenu); paramPrintWriter.print(paramString); paramPrintWriter.print("mRetainInstance="); paramPrintWriter.print(mRetainInstance); paramPrintWriter.print(" mRetaining="); paramPrintWriter.print(mRetaining); paramPrintWriter.print(" mUserVisibleHint="); paramPrintWriter.println(mUserVisibleHint); if (mFragmentManager != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mFragmentManager="); paramPrintWriter.println(mFragmentManager); } if (mHost != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mHost="); paramPrintWriter.println(mHost); } if (mParentFragment != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mParentFragment="); paramPrintWriter.println(mParentFragment); } if (mArguments != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mArguments="); paramPrintWriter.println(mArguments); } if (mSavedFragmentState != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mSavedFragmentState="); paramPrintWriter.println(mSavedFragmentState); } if (mSavedViewState != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mSavedViewState="); paramPrintWriter.println(mSavedViewState); } if (mTarget != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mTarget="); paramPrintWriter.print(mTarget); paramPrintWriter.print(" mTargetRequestCode="); paramPrintWriter.println(mTargetRequestCode); } if (mNextAnim != 0) { paramPrintWriter.print(paramString); paramPrintWriter.print("mNextAnim="); paramPrintWriter.println(mNextAnim); } if (mContainer != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mContainer="); paramPrintWriter.println(mContainer); } if (mView != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mView="); paramPrintWriter.println(mView); } if (mInnerView != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mInnerView="); paramPrintWriter.println(mView); } if (mAnimatingAway != null) { paramPrintWriter.print(paramString); paramPrintWriter.print("mAnimatingAway="); paramPrintWriter.println(mAnimatingAway); paramPrintWriter.print(paramString); paramPrintWriter.print("mStateAfterAnimating="); paramPrintWriter.println(mStateAfterAnimating); } if (mLoaderManager != null) { paramPrintWriter.print(paramString); paramPrintWriter.println("Loader Manager:"); mLoaderManager.dump(paramString + " ", paramFileDescriptor, paramPrintWriter, paramArrayOfString); } if (mChildFragmentManager != null) { paramPrintWriter.print(paramString); paramPrintWriter.println("Child " + mChildFragmentManager + ":"); mChildFragmentManager.dump(paramString + " ", paramFileDescriptor, paramPrintWriter, paramArrayOfString); } } public final boolean equals(Object paramObject) { return super.equals(paramObject); } Fragment findFragmentByWho(String paramString) { if (paramString.equals(mWho)) { return this; } if (mChildFragmentManager != null) { return mChildFragmentManager.findFragmentByWho(paramString); } return null; } public final FragmentActivity getActivity() { if (mHost == null) { return null; } return (FragmentActivity)mHost.getActivity(); } public boolean getAllowEnterTransitionOverlap() { if (mAllowEnterTransitionOverlap == null) { return true; } return mAllowEnterTransitionOverlap.booleanValue(); } public boolean getAllowReturnTransitionOverlap() { if (mAllowReturnTransitionOverlap == null) { return true; } return mAllowReturnTransitionOverlap.booleanValue(); } public final Bundle getArguments() { return mArguments; } public final FragmentManager getChildFragmentManager() { if (mChildFragmentManager == null) { instantiateChildFragmentManager(); if (mState < 5) { break label31; } mChildFragmentManager.dispatchResume(); } for (;;) { return mChildFragmentManager; label31: if (mState >= 4) { mChildFragmentManager.dispatchStart(); } else if (mState >= 2) { mChildFragmentManager.dispatchActivityCreated(); } else if (mState > 0) { mChildFragmentManager.dispatchCreate(); } } } public Context getContext() { if (mHost == null) { return null; } return mHost.getContext(); } public Object getEnterTransition() { return mEnterTransition; } public Object getExitTransition() { return mExitTransition; } public final FragmentManager getFragmentManager() { return mFragmentManager; } public final Object getHost() { if (mHost == null) { return null; } return mHost.onGetHost(); } public final int getId() { return mFragmentId; } public LayoutInflater getLayoutInflater(Bundle paramBundle) { paramBundle = mHost.onGetLayoutInflater(); getChildFragmentManager(); LayoutInflaterCompat.setFactory(paramBundle, mChildFragmentManager.getLayoutInflaterFactory()); return paramBundle; } public LoaderManager getLoaderManager() { if (mLoaderManager != null) { return mLoaderManager; } if (mHost == null) { throw new IllegalStateException("Fragment " + this + " not attached to Activity"); } mCheckedForLoaderManager = true; mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, true); return mLoaderManager; } public final Fragment getParentFragment() { return mParentFragment; } public Object getReenterTransition() { if (mReenterTransition == USE_DEFAULT_TRANSITION) { return getExitTransition(); } return mReenterTransition; } public final Resources getResources() { if (mHost == null) { throw new IllegalStateException("Fragment " + this + " not attached to Activity"); } return mHost.getContext().getResources(); } public final boolean getRetainInstance() { return mRetainInstance; } public Object getReturnTransition() { if (mReturnTransition == USE_DEFAULT_TRANSITION) { return getEnterTransition(); } return mReturnTransition; } public Object getSharedElementEnterTransition() { return mSharedElementEnterTransition; } public Object getSharedElementReturnTransition() { if (mSharedElementReturnTransition == USE_DEFAULT_TRANSITION) { return getSharedElementEnterTransition(); } return mSharedElementReturnTransition; } public final String getString(int paramInt) { return getResources().getString(paramInt); } public final String getString(int paramInt, Object... paramVarArgs) { return getResources().getString(paramInt, paramVarArgs); } public final String getTag() { return mTag; } public final Fragment getTargetFragment() { return mTarget; } public final int getTargetRequestCode() { return mTargetRequestCode; } public final CharSequence getText(int paramInt) { return getResources().getText(paramInt); } public boolean getUserVisibleHint() { return mUserVisibleHint; } public View getView() { return mView; } public final boolean hasOptionsMenu() { return mHasMenu; } public final int hashCode() { return super.hashCode(); } void initState() { mIndex = -1; mWho = null; mAdded = false; mRemoving = false; mResumed = false; mFromLayout = false; mInLayout = false; mRestored = false; mBackStackNesting = 0; mFragmentManager = null; mChildFragmentManager = null; mHost = null; mFragmentId = 0; mContainerId = 0; mTag = null; mHidden = false; mDetached = false; mRetaining = false; mLoaderManager = null; mLoadersStarted = false; mCheckedForLoaderManager = false; } void instantiateChildFragmentManager() { mChildFragmentManager = new FragmentManagerImpl(); mChildFragmentManager.attachController(mHost, new FragmentContainer() { public View onFindViewById(int paramAnonymousInt) { if (mView == null) { throw new IllegalStateException("Fragment does not have a view"); } return mView.findViewById(paramAnonymousInt); } public boolean onHasView() { return mView != null; } }, this); } public final boolean isAdded() { return (mHost != null) && (mAdded); } public final boolean isDetached() { return mDetached; } public final boolean isHidden() { return mHidden; } final boolean isInBackStack() { return mBackStackNesting > 0; } public final boolean isInLayout() { return mInLayout; } public final boolean isMenuVisible() { return mMenuVisible; } public final boolean isRemoving() { return mRemoving; } public final boolean isResumed() { return mResumed; } public final boolean isVisible() { return (isAdded()) && (!isHidden()) && (mView != null) && (mView.getWindowToken() != null) && (mView.getVisibility() == 0); } public void onActivityCreated(Bundle paramBundle) { mCalled = true; } public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) {} @Deprecated public void onAttach(Activity paramActivity) { mCalled = true; } public void onAttach(Context paramContext) { mCalled = true; if (mHost == null) {} for (paramContext = null;; paramContext = mHost.getActivity()) { if (paramContext != null) { mCalled = false; onAttach(paramContext); } return; } } public void onConfigurationChanged(Configuration paramConfiguration) { mCalled = true; } public boolean onContextItemSelected(MenuItem paramMenuItem) { return false; } public void onCreate(Bundle paramBundle) { mCalled = true; } public Animation onCreateAnimation(int paramInt1, boolean paramBoolean, int paramInt2) { return null; } public void onCreateContextMenu(ContextMenu paramContextMenu, View paramView, ContextMenu.ContextMenuInfo paramContextMenuInfo) { getActivity().onCreateContextMenu(paramContextMenu, paramView, paramContextMenuInfo); } public void onCreateOptionsMenu(Menu paramMenu, MenuInflater paramMenuInflater) {} public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) { return null; } public void onDestroy() { mCalled = true; if (!mCheckedForLoaderManager) { mCheckedForLoaderManager = true; mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); } if (mLoaderManager != null) { mLoaderManager.doDestroy(); } } public void onDestroyOptionsMenu() {} public void onDestroyView() { mCalled = true; } public void onDetach() { mCalled = true; } public void onHiddenChanged(boolean paramBoolean) {} @Deprecated public void onInflate(Activity paramActivity, AttributeSet paramAttributeSet, Bundle paramBundle) { mCalled = true; } public void onInflate(Context paramContext, AttributeSet paramAttributeSet, Bundle paramBundle) { mCalled = true; if (mHost == null) {} for (paramContext = null;; paramContext = mHost.getActivity()) { if (paramContext != null) { mCalled = false; onInflate(paramContext, paramAttributeSet, paramBundle); } return; } } public void onLowMemory() { mCalled = true; } public boolean onOptionsItemSelected(MenuItem paramMenuItem) { return false; } public void onOptionsMenuClosed(Menu paramMenu) {} public void onPause() { mCalled = true; } public void onPrepareOptionsMenu(Menu paramMenu) {} public void onRequestPermissionsResult(int paramInt, String[] paramArrayOfString, int[] paramArrayOfInt) {} public void onResume() { mCalled = true; } public void onSaveInstanceState(Bundle paramBundle) {} public void onStart() { mCalled = true; if (!mLoadersStarted) { mLoadersStarted = true; if (!mCheckedForLoaderManager) { mCheckedForLoaderManager = true; mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); } if (mLoaderManager != null) { mLoaderManager.doStart(); } } } public void onStop() { mCalled = true; } public void onViewCreated(View paramView, Bundle paramBundle) {} public void onViewStateRestored(Bundle paramBundle) { mCalled = true; } void performActivityCreated(Bundle paramBundle) { if (mChildFragmentManager != null) { mChildFragmentManager.noteStateNotSaved(); } mCalled = false; onActivityCreated(paramBundle); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onActivityCreated()"); } if (mChildFragmentManager != null) { mChildFragmentManager.dispatchActivityCreated(); } } void performConfigurationChanged(Configuration paramConfiguration) { onConfigurationChanged(paramConfiguration); if (mChildFragmentManager != null) { mChildFragmentManager.dispatchConfigurationChanged(paramConfiguration); } } boolean performContextItemSelected(MenuItem paramMenuItem) { if (!mHidden) { if (onContextItemSelected(paramMenuItem)) {} while ((mChildFragmentManager != null) && (mChildFragmentManager.dispatchContextItemSelected(paramMenuItem))) { return true; } } return false; } void performCreate(Bundle paramBundle) { if (mChildFragmentManager != null) { mChildFragmentManager.noteStateNotSaved(); } mCalled = false; onCreate(paramBundle); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onCreate()"); } if (paramBundle != null) { paramBundle = paramBundle.getParcelable("android:support:fragments"); if (paramBundle != null) { if (mChildFragmentManager == null) { instantiateChildFragmentManager(); } mChildFragmentManager.restoreAllState(paramBundle, null); mChildFragmentManager.dispatchCreate(); } } } boolean performCreateOptionsMenu(Menu paramMenu, MenuInflater paramMenuInflater) { boolean bool2 = false; boolean bool3 = false; if (!mHidden) { boolean bool1 = bool3; if (mHasMenu) { bool1 = bool3; if (mMenuVisible) { bool1 = true; onCreateOptionsMenu(paramMenu, paramMenuInflater); } } bool2 = bool1; if (mChildFragmentManager != null) { bool2 = bool1 | mChildFragmentManager.dispatchCreateOptionsMenu(paramMenu, paramMenuInflater); } } return bool2; } View performCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) { if (mChildFragmentManager != null) { mChildFragmentManager.noteStateNotSaved(); } return onCreateView(paramLayoutInflater, paramViewGroup, paramBundle); } void performDestroy() { if (mChildFragmentManager != null) { mChildFragmentManager.dispatchDestroy(); } mCalled = false; onDestroy(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onDestroy()"); } } void performDestroyView() { if (mChildFragmentManager != null) { mChildFragmentManager.dispatchDestroyView(); } mCalled = false; onDestroyView(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onDestroyView()"); } if (mLoaderManager != null) { mLoaderManager.doReportNextStart(); } } void performLowMemory() { onLowMemory(); if (mChildFragmentManager != null) { mChildFragmentManager.dispatchLowMemory(); } } boolean performOptionsItemSelected(MenuItem paramMenuItem) { if (!mHidden) { if ((mHasMenu) && (mMenuVisible) && (onOptionsItemSelected(paramMenuItem))) {} while ((mChildFragmentManager != null) && (mChildFragmentManager.dispatchOptionsItemSelected(paramMenuItem))) { return true; } } return false; } void performOptionsMenuClosed(Menu paramMenu) { if (!mHidden) { if ((mHasMenu) && (mMenuVisible)) { onOptionsMenuClosed(paramMenu); } if (mChildFragmentManager != null) { mChildFragmentManager.dispatchOptionsMenuClosed(paramMenu); } } } void performPause() { if (mChildFragmentManager != null) { mChildFragmentManager.dispatchPause(); } mCalled = false; onPause(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onPause()"); } } boolean performPrepareOptionsMenu(Menu paramMenu) { boolean bool2 = false; boolean bool3 = false; if (!mHidden) { boolean bool1 = bool3; if (mHasMenu) { bool1 = bool3; if (mMenuVisible) { bool1 = true; onPrepareOptionsMenu(paramMenu); } } bool2 = bool1; if (mChildFragmentManager != null) { bool2 = bool1 | mChildFragmentManager.dispatchPrepareOptionsMenu(paramMenu); } } return bool2; } void performReallyStop() { if (mChildFragmentManager != null) { mChildFragmentManager.dispatchReallyStop(); } if (mLoadersStarted) { mLoadersStarted = false; if (!mCheckedForLoaderManager) { mCheckedForLoaderManager = true; mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); } if (mLoaderManager != null) { if (!mHost.getRetainLoaders()) { break label83; } mLoaderManager.doRetain(); } } return; label83: mLoaderManager.doStop(); } void performResume() { if (mChildFragmentManager != null) { mChildFragmentManager.noteStateNotSaved(); mChildFragmentManager.execPendingActions(); } mCalled = false; onResume(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onResume()"); } if (mChildFragmentManager != null) { mChildFragmentManager.dispatchResume(); mChildFragmentManager.execPendingActions(); } } void performSaveInstanceState(Bundle paramBundle) { onSaveInstanceState(paramBundle); if (mChildFragmentManager != null) { Parcelable localParcelable = mChildFragmentManager.saveAllState(); if (localParcelable != null) { paramBundle.putParcelable("android:support:fragments", localParcelable); } } } void performStart() { if (mChildFragmentManager != null) { mChildFragmentManager.noteStateNotSaved(); mChildFragmentManager.execPendingActions(); } mCalled = false; onStart(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onStart()"); } if (mChildFragmentManager != null) { mChildFragmentManager.dispatchStart(); } if (mLoaderManager != null) { mLoaderManager.doReportStart(); } } void performStop() { if (mChildFragmentManager != null) { mChildFragmentManager.dispatchStop(); } mCalled = false; onStop(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onStop()"); } } public void registerForContextMenu(View paramView) { paramView.setOnCreateContextMenuListener(this); } public final void requestPermissions(String[] paramArrayOfString, int paramInt) { if (mHost == null) { throw new IllegalStateException("Fragment " + this + " not attached to Activity"); } mHost.onRequestPermissionsFromFragment(this, paramArrayOfString, paramInt); } final void restoreViewState(Bundle paramBundle) { if (mSavedViewState != null) { mInnerView.restoreHierarchyState(mSavedViewState); mSavedViewState = null; } mCalled = false; onViewStateRestored(paramBundle); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onViewStateRestored()"); } } public void setAllowEnterTransitionOverlap(boolean paramBoolean) { mAllowEnterTransitionOverlap = Boolean.valueOf(paramBoolean); } public void setAllowReturnTransitionOverlap(boolean paramBoolean) { mAllowReturnTransitionOverlap = Boolean.valueOf(paramBoolean); } public void setArguments(Bundle paramBundle) { if (mIndex >= 0) { throw new IllegalStateException("Fragment already active"); } mArguments = paramBundle; } public void setEnterSharedElementCallback(SharedElementCallback paramSharedElementCallback) { mEnterTransitionCallback = paramSharedElementCallback; } public void setEnterTransition(Object paramObject) { mEnterTransition = paramObject; } public void setExitSharedElementCallback(SharedElementCallback paramSharedElementCallback) { mExitTransitionCallback = paramSharedElementCallback; } public void setExitTransition(Object paramObject) { mExitTransition = paramObject; } public void setHasOptionsMenu(boolean paramBoolean) { if (mHasMenu != paramBoolean) { mHasMenu = paramBoolean; if ((isAdded()) && (!isHidden())) { mHost.onSupportInvalidateOptionsMenu(); } } } final void setIndex(int paramInt, Fragment paramFragment) { mIndex = paramInt; if (paramFragment != null) { mWho = (mWho + ":" + mIndex); return; } mWho = ("android:fragment:" + mIndex); } public void setInitialSavedState(SavedState paramSavedState) { if (mIndex >= 0) { throw new IllegalStateException("Fragment already active"); } if ((paramSavedState != null) && (mState != null)) {} for (paramSavedState = mState;; paramSavedState = null) { mSavedFragmentState = paramSavedState; return; } } public void setMenuVisibility(boolean paramBoolean) { if (mMenuVisible != paramBoolean) { mMenuVisible = paramBoolean; if ((mHasMenu) && (isAdded()) && (!isHidden())) { mHost.onSupportInvalidateOptionsMenu(); } } } public void setReenterTransition(Object paramObject) { mReenterTransition = paramObject; } public void setRetainInstance(boolean paramBoolean) { if ((paramBoolean) && (mParentFragment != null)) { throw new IllegalStateException("Can't retain fragements that are nested in other fragments"); } mRetainInstance = paramBoolean; } public void setReturnTransition(Object paramObject) { mReturnTransition = paramObject; } public void setSharedElementEnterTransition(Object paramObject) { mSharedElementEnterTransition = paramObject; } public void setSharedElementReturnTransition(Object paramObject) { mSharedElementReturnTransition = paramObject; } public void setTargetFragment(Fragment paramFragment, int paramInt) { mTarget = paramFragment; mTargetRequestCode = paramInt; } public void setUserVisibleHint(boolean paramBoolean) { if ((!mUserVisibleHint) && (paramBoolean) && (mState < 4)) { mFragmentManager.performPendingDeferredStart(this); } mUserVisibleHint = paramBoolean; if (!paramBoolean) {} for (paramBoolean = true;; paramBoolean = false) { mDeferStart = paramBoolean; return; } } public boolean shouldShowRequestPermissionRationale(String paramString) { if (mHost != null) { return mHost.onShouldShowRequestPermissionRationale(paramString); } return false; } public void startActivity(Intent paramIntent) { if (mHost == null) { throw new IllegalStateException("Fragment " + this + " not attached to Activity"); } mHost.onStartActivityFromFragment(this, paramIntent, -1); } public void startActivityForResult(Intent paramIntent, int paramInt) { if (mHost == null) { throw new IllegalStateException("Fragment " + this + " not attached to Activity"); } mHost.onStartActivityFromFragment(this, paramIntent, paramInt); } public String toString() { StringBuilder localStringBuilder = new StringBuilder(128); DebugUtils.buildShortClassTag(this, localStringBuilder); if (mIndex >= 0) { localStringBuilder.append(" #"); localStringBuilder.append(mIndex); } if (mFragmentId != 0) { localStringBuilder.append(" id=0x"); localStringBuilder.append(Integer.toHexString(mFragmentId)); } if (mTag != null) { localStringBuilder.append(" "); localStringBuilder.append(mTag); } localStringBuilder.append('}'); return localStringBuilder.toString(); } public void unregisterForContextMenu(View paramView) { paramView.setOnCreateContextMenuListener(null); } public static class InstantiationException extends RuntimeException { public InstantiationException(String paramString, Exception paramException) { super(paramException); } } public static class SavedState implements Parcelable { public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator() { public final Fragment.SavedState createFromParcel(Parcel paramAnonymousParcel) { return new Fragment.SavedState(paramAnonymousParcel, null); } public final Fragment.SavedState[] newArray(int paramAnonymousInt) { return new Fragment.SavedState[paramAnonymousInt]; } }; final Bundle mState; SavedState(Bundle paramBundle) { mState = paramBundle; } SavedState(Parcel paramParcel, ClassLoader paramClassLoader) { mState = paramParcel.readBundle(); if ((paramClassLoader != null) && (mState != null)) { mState.setClassLoader(paramClassLoader); } } public int describeContents() { return 0; } public void writeToParcel(Parcel paramParcel, int paramInt) { paramParcel.writeBundle(mState); } } } /* Location: * Qualified Name: android.support.v4.app.Fragment * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
6345fadbf9c56ba5a7c253e726d6c6cbb4f6ceed
8447f701c7af517eccd1709b529469296c46ac4f
/Google/WiggleSort.java
d84591f31f852f3875a876c04e894930a5d3c4e3
[]
no_license
Mango0917/CodingPractice
048945a2cb3dccde089680ff43e1340c153bd202
68a68c5f42e4a2e611285260944b99ca20b24ac5
refs/heads/master
2021-09-07T13:38:01.400741
2018-02-23T17:23:26
2018-02-23T17:23:26
116,010,987
0
0
null
null
null
null
UTF-8
Java
false
false
675
java
/* Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. */ class Solution { public void wiggleSort(int[] nums) { for(int i=0;i<nums.length;i++){ if(i%2==1){ if(nums[i-1]>nums[i])swap(nums,i); } else{ if(i!=0 && nums[i-1]<nums[i]) swap(nums,i); } } } public int[] swap(int[] nums, int i){ int temp; temp=nums[i]; nums[i]=nums[i-1]; nums[i-1]=temp; return nums; } }
5eaaf5f7e66cf1d3d4bc75cf472d721951db464c
996faa208054e85da0e73bad42bce699736f48de
/app/src/test/java/com/cokus/fangdouyu/ExampleUnitTest.java
159eadaf5c9209077989ffeff38a46c7352ec494
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
you839215622/fangDouYu
c96035ea0b0fa445efc619fd0ea375ddad3fd648
9b488004eef1f7ecc9b728e3320289a775c9bf1e
refs/heads/master
2021-01-20T13:42:14.763014
2017-04-28T02:50:08
2017-04-28T02:50:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
312
java
package com.cokus.fangdouyu; 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); } }
d8050e7169be36afaed59e1cd9fff6333599016c
6f18f08f97b47dd37114162a03d91aefc4f51e42
/ezimgur/src/com/ezimgur/view/component/TouchImageView.java
4419334d01facdad47b5607d753698593d744489
[]
no_license
eggman87/ezimgur-open
d1f6bee8f26bea802a127481cb7b8ae19aed57d4
0a5e99af6788a2faaa98d90929f404ad029cea79
refs/heads/master
2021-06-28T02:36:35.795949
2017-02-02T22:50:21
2017-02-02T22:50:21
13,837,313
0
1
null
null
null
null
UTF-8
Java
false
false
12,404
java
package com.ezimgur.view.component; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.*; import android.widget.ImageView; import com.ezimgur.R; import com.ezimgur.instrumentation.Log; import com.ezimgur.view.fragment.ImageViewerFragment; import com.ezimgur.view.listener.SwipeGestureDetector; /** * EggmanProjects * Author: Matthew Harris * Date: 10/2/12 * Time: 7:38 PM */ public class TouchImageView extends ImageView{ Matrix matrix = new Matrix(); static final float MIN_ZOOM = 0.9f; // We can be in one of these 3 states static final int NONE = 0; static final int DRAG = 1; static final int ZOOM = 2; int mode = NONE; // Remember some things for zooming PointF last = new PointF(); PointF start = new PointF(); float minScale = 1f; float maxScale = 8f; float[] m; float redundantXSpace, redundantYSpace; float width, height; static final int CLICK = 3; public float saveScale = 1f; float right, bottom, origWidth, origHeight, bmWidth, bmHeight; ScaleGestureDetector mScaleDetector; private OnTouchListener extraTouchListener; private OnTouchListener activityTouchListener; //private List<String> mMenuItems; private String mMenuTitle; private boolean mContextMenuEnabled = false; private boolean mCenterOnMeasure = false; public TouchImageView(Context context) { super(context); initView(context); } public TouchImageView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public TouchImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); } public void setActivityTouchListener(OnTouchListener listener) { activityTouchListener = listener; } @Override public void createContextMenu(ContextMenu menu) { super.createContextMenu(menu); } private void initView(Context context){ super.setClickable(true); new ContextThemeWrapper(getContext(), R.style.Theme_ezimgur_Dialog); mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); matrix.setTranslate(1f, 1f); m = new float[9]; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setLongClickable(true); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); //forward events to extra listeners. if (extraTouchListener != null) { extraTouchListener.onTouch(v, event); } if (activityTouchListener != null) { activityTouchListener.onTouch(v, event); } matrix.getValues(m); float x = m[Matrix.MTRANS_X]; float y = m[Matrix.MTRANS_Y]; PointF curr = new PointF(event.getX(), event.getY()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(event.getX(), event.getY()); start.set(last); mode = DRAG; break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { cancelLongPress(); float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; float scaleWidth = Math.round(origWidth * saveScale); float scaleHeight = Math.round(origHeight * saveScale); if (scaleWidth < width) { deltaX = 0; if (y + deltaY > 0) deltaY = -y; else if (y + deltaY < -bottom) deltaY = -(y + bottom); } else if (scaleHeight < height) { deltaY = 0; if (x + deltaX > 0) deltaX = -x; else if (x + deltaX < -right) deltaX = -(x + right); } else { if (x + deltaX > 0) deltaX = -x; else if (x + deltaX < -right) deltaX = -(x + right); if (y + deltaY > 0) deltaY = -y; else if (y + deltaY < -bottom) deltaY = -(y + bottom); } matrix.postTranslate(deltaX, deltaY); last.set(curr.x, curr.y); } break; case MotionEvent.ACTION_UP: mode = NONE; int xDiff = (int) Math.abs(curr.x - start.x); int yDiff = (int) Math.abs(curr.y - start.y); if (xDiff < CLICK && yDiff < CLICK) performClick(); break; case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; } setImageMatrix(matrix); invalidate(); return true; // indicate event was handled } }); } public void setExtraTouchListener(OnTouchListener listener) { extraTouchListener = listener; } public void setOnFlingListener(SwipeGestureDetector.GestureListener listener) { final GestureDetector gestureDetector = new GestureDetector(this.getContext(), new SwipeGestureDetector(listener)); extraTouchListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }; } public void setContextMenuTitle(String title) { mMenuTitle = title; } ImageViewerFragment.ContextMenuProvider mContextMenuProvider; public void setContextMenuProvider(ImageViewerFragment.ContextMenuProvider provider){ mContextMenuProvider = provider; mContextMenuEnabled = true; } @Override public void onCreateContextMenu(ContextMenu menu) { if (mContextMenuEnabled) { menu.setHeaderTitle(mMenuTitle); for (String menuItem : mContextMenuProvider.getMenuItems(false)) { menu.add(menuItem); } } super.onCreateContextMenu(menu); } public boolean onDoubleTap(MotionEvent e) { if (saveScale < 1.1f ) { mode = ZOOM; calculateImageScale(saveScale * 1.5f, e.getX(), e.getY()); return true; } else { centerImage(); return true; } } private void centerImage() { mode = NONE; float scale; float scaleX = (float)width / (float)bmWidth; float scaleY = (float)height / (float)bmHeight; scale = Math.min(scaleX, scaleY); matrix.setScale(scale, scale); setImageMatrix(matrix); saveScale = 1f; // Center the image redundantYSpace = (float)height - (scale * (float)bmHeight) ; redundantXSpace = (float)width - (scale * (float)bmWidth); redundantYSpace /= (float)2; redundantXSpace /= (float)2; matrix.postTranslate(redundantXSpace, redundantYSpace); origWidth = width - 2 * redundantXSpace; origHeight = height - 2 * redundantYSpace; right = width * saveScale - width - (2 * redundantXSpace * saveScale); bottom = height * saveScale - height - (2 * redundantYSpace * saveScale); setImageMatrix(matrix); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); if (bm == null) return; bmWidth = bm.getWidth(); bmHeight = bm.getHeight(); centerImage(); } @Override public ScaleType getScaleType() { return ScaleType.CENTER_INSIDE; } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); bmHeight = drawable.getMinimumHeight(); bmWidth = drawable.getMinimumWidth(); } private boolean calculateImageScale(float mScaleFactor, float targetX, float targetY) { float origScale = saveScale; saveScale *= mScaleFactor; if (saveScale > maxScale) { saveScale = maxScale; mScaleFactor = maxScale / origScale; } else if (saveScale < minScale) { saveScale = minScale; mScaleFactor = minScale / origScale; } right = width * saveScale - width - (2 * redundantXSpace * saveScale); bottom = height * saveScale - height - (2 * redundantYSpace * saveScale); if (origWidth * saveScale <= width || origHeight * saveScale <= height) { matrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2); if (mScaleFactor < 1) { matrix.getValues(m); float x = m[Matrix.MTRANS_X]; float y = m[Matrix.MTRANS_Y]; if (mScaleFactor < 1) { if (Math.round(origWidth * saveScale) < width) { if (y < -bottom) matrix.postTranslate(0, -(y + bottom)); else if (y > 0) matrix.postTranslate(0, -y); } else { if (x < -right) matrix.postTranslate(-(x + right), 0); else if (x > 0) matrix.postTranslate(-x, 0); } } } } else { matrix.postScale(mScaleFactor, mScaleFactor, targetX, targetY); matrix.getValues(m); float x = m[Matrix.MTRANS_X]; float y = m[Matrix.MTRANS_Y]; if (mScaleFactor < 1) { if (x < -right) matrix.postTranslate(-(x + right), 0); else if (x > 0) matrix.postTranslate(-x, 0); if (y < -bottom) matrix.postTranslate(0, -(y + bottom)); else if (y > 0) matrix.postTranslate(0, -y); } } return true; } public float getMaxZoom() { return maxScale; } public void setMaxZoom(float x) { maxScale = x; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScaleBegin(ScaleGestureDetector detector) { mode = ZOOM; return true; } @Override public boolean onScale(ScaleGestureDetector detector) { float mScaleFactor = (float)Math.min(Math.max(.95f, detector.getScaleFactor()), 1.05); calculateImageScale(mScaleFactor, detector.getFocusX(), detector.getFocusY()); return true; } } @Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = MeasureSpec.getSize(widthMeasureSpec); height = MeasureSpec.getSize(heightMeasureSpec); if (mCenterOnMeasure){ centerImage(); } } /** * use if you set the image after it is already hidden. */ public void centerImageOnMeasure(boolean centerImageOnMeasure){ mCenterOnMeasure = centerImageOnMeasure; } public boolean isZoomedIn() { return saveScale > 1f; } }
e10cd73c268d8163ae6bd3e92597812111a42c37
9fe64ec7f752000c4509f172f6d20f6758d91e8c
/src/factory/ShapeFactory.java
35ea4d4da0fc60fec3187f71e34a02e8d233e906
[]
no_license
tangbl93/DesignPatternTut
fbdb4cb254aef42646d8d446fa76a2c5e9bc1892
bf4433852bb1d077857363cb3bf39c2f1ec535a9
refs/heads/master
2021-03-01T10:35:12.200481
2020-03-10T12:04:58
2020-03-10T12:04:58
245,778,305
0
0
null
null
null
null
UTF-8
Java
false
false
474
java
package factory; public class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("RECTANGLE")) { return new Rectangle(); } else if (shapeType.equalsIgnoreCase("SQUARE")) { return new Square(); } return null; } }
0536d7fb47007ba70bc8ad4eac60b4cace907f3c
f990de9d583ee5bbd77187cfd1c07b68f61fc4d1
/Java/td/DS1/src/Main.java
3cabf82e1c6c8ba5bc5e242ec3ce5046cd6f2458
[]
no_license
RomainCocogne/Elec4
16fa08d9ecb69333ee018f178a7e31ee8bea0fa6
cfe5109c07666fa86cebf29dc13a7daa2350bb6f
refs/heads/master
2020-10-01T01:09:12.576108
2020-06-04T16:12:18
2020-06-04T16:12:18
227,416,564
1
1
null
null
null
null
UTF-8
Java
false
false
80
java
public class Main { public static void main(String[] args) { } }
d0de1619b2a806fd382e48c29954a3c17bb8b6cf
5242baef1c9abeb8a48dac33b033f0a8c78c05f8
/app/src/androidTest/java/com/mojasoft/mojakomik/ExampleInstrumentedTest.java
7d8ab2f1b2eabf4ed252c1d029a0b3926ecbb2f0
[]
no_license
adityamarimo/Moja-Komik
7a2ea62a893ad3f4d0198cd23b32899c9489ddc3
43a11dc790ae146653b89faf9bec8f52791ca8aa
refs/heads/master
2022-12-24T03:04:40.330374
2020-10-10T02:49:35
2020-10-10T02:49:35
302,800,385
0
0
null
null
null
null
UTF-8
Java
false
false
758
java
package com.mojasoft.mojakomik; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.mojasoft.mojakomik", appContext.getPackageName()); } }
b7c05b374b2221ce1d9a6403545fa79f8c7701eb
44499e7b5cdeaf46548def854b4794716cdd4c81
/gradle-runner-agent/src/test/resources/testProjects/init_since_8.gradle/projectS/src/test/java/test/My2Test.java
08d70beeae05fd5f2c7f76ef9483ed4532484ca6
[ "Apache-2.0" ]
permissive
JetBrains/teamcity-gradle
bfc3b9160f221211ebc9b998403c4069736db4fb
a973f737121e2e8fb201114536fed16fa452c09f
refs/heads/master
2023-08-31T00:43:17.453757
2023-08-30T08:27:30
2023-08-30T08:27:30
163,502,780
8
8
Apache-2.0
2023-08-07T09:53:59
2018-12-29T10:40:13
Java
UTF-8
Java
false
false
171
java
package test; import org.junit.Test; public class My2Test { @Test public void test1() throws Exception { } @Test public void test2() throws Exception { } }
61b32c5d97414dcb4f9a297810bdeba4434e7d31
b5bdfcdd3fd35bbca50129cd69d62a9ef5f063c8
/jhotdraw7/src/main/java/org/jhotdraw/app/MDIApplication.java
517792f2eba2ff9020617d51acf35aa2c9ce5a9f
[]
no_license
ilyessou/jhotDrawReleases
49fa0980bc78dba886cfa6b21cb14cd9a4be0af2
68c1467294cce5c46ac9d84fcad06d814e01436d
refs/heads/master
2021-01-10T10:19:22.178508
2015-12-03T01:06:30
2015-12-03T01:06:30
47,295,653
0
0
null
null
null
null
UTF-8
Java
false
false
25,131
java
/* * @(#)MDIApplication.java * * Copyright (c) 1996-2010 by the original authors of JHotDraw and all its * contributors. All rights reserved. * * You may not use, copy or modify this file, except in compliance with the * license agreement you entered into with the copyright holders. For details * see accompanying license terms. */ package org.jhotdraw.app; import edu.umd.cs.findbugs.annotations.Nullable; import org.jhotdraw.app.action.app.AbstractPreferencesAction; import org.jhotdraw.app.action.window.ToggleToolBarAction; import org.jhotdraw.app.action.window.FocusWindowAction; import org.jhotdraw.app.action.window.ArrangeWindowsAction; import org.jhotdraw.app.action.window.MaximizeWindowAction; import org.jhotdraw.app.action.window.MinimizeWindowAction; import org.jhotdraw.app.action.file.SaveFileAsAction; import org.jhotdraw.app.action.file.SaveFileAction; import org.jhotdraw.app.action.file.PrintFileAction; import org.jhotdraw.app.action.file.NewFileAction; import org.jhotdraw.app.action.file.OpenFileAction; import org.jhotdraw.app.action.file.CloseFileAction; import org.jhotdraw.app.action.file.OpenDirectoryAction; import org.jhotdraw.app.action.file.ExportFileAction; import org.jhotdraw.app.action.edit.AbstractFindAction; import org.jhotdraw.app.action.edit.ClearSelectionAction; import org.jhotdraw.app.action.edit.CopyAction; import org.jhotdraw.app.action.edit.CutAction; import org.jhotdraw.app.action.edit.DeleteAction; import org.jhotdraw.app.action.edit.DuplicateAction; import org.jhotdraw.app.action.edit.PasteAction; import org.jhotdraw.app.action.edit.RedoAction; import org.jhotdraw.app.action.edit.SelectAllAction; import org.jhotdraw.app.action.edit.UndoAction; import org.jhotdraw.app.action.app.AboutAction; import org.jhotdraw.app.action.app.OpenApplicationFileAction; import org.jhotdraw.app.action.app.ExitAction; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import org.jhotdraw.gui.*; import org.jhotdraw.util.*; import org.jhotdraw.util.prefs.*; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.io.*; import java.net.URI; import java.util.*; import java.util.prefs.*; import javax.swing.*; import javax.swing.event.*; import org.jhotdraw.app.action.*; import org.jhotdraw.app.action.file.ClearFileAction; import org.jhotdraw.app.action.file.ClearRecentFilesMenuAction; import org.jhotdraw.app.action.file.LoadDirectoryAction; import org.jhotdraw.app.action.file.LoadFileAction; import org.jhotdraw.app.action.file.NewWindowAction; import org.jhotdraw.net.URIUtil; /** * {@code MDIApplication} handles the lifecycle of multiple {@link View}s * using a Windows multiple document interface (MDI). * <p> * This user interface created by this application follows the guidelines given * in the * <a href="http://msdn.microsoft.com/en-us/library/aa511258.aspx" * >Windows User Experience Interaction Guidelines</a>. * <p> * An application consists of a parent {@code JFrame} which holds a {@code JDesktopPane}. * The views reside in {@code JInternalFrame}s inside of the {@code JDesktopPane}. * The parent frame also contains a menu bar, toolbars and palette windows for * the views. * <p> * The life cycle of the application is tied to the parent {@code JFrame}. * Closing the parent {@code JFrame} quits the application. * * The parent frame has the following standard menus: * <pre> * File Edit Window Help</pre> * * The <b>file menu</b> has the following standard menu items: * <pre> * Clear ({@link ClearFileAction#ID}}) * New ({@link NewFileAction#ID}}) * New Window ({@link NewWindowAction#ID}}) * Load... ({@link LoadFileAction#ID}}) * Open... ({@link OpenFileAction#ID}}) * Load Directory... ({@link LoadDirectoryAction#ID}}) * Open Directory... ({@link OpenDirectoryAction#ID}}) * Load Recent &gt; "Filename" ({@link org.jhotdraw.app.action.file.LoadRecentFileAction#ID}) * Open Recent &gt; "Filename" ({@link org.jhotdraw.app.action.file.OpenRecentFileAction#ID}) * - * Close ({@link CloseFileAction#ID}) * Save ({@link SaveFileAction#ID}) * Save As... ({@link SaveFileAsAction#ID}) * Export... ({@link ExportFileAction#ID}) * Print... ({@link PrintFileAction#ID}) * - * Exit ({@link ExitAction#ID}) * </pre> * * The <b>edit menu</b> has the following standard menu items: * <pre> * Undo ({@link UndoAction#ID}}) * Redo ({@link RedoAction#ID}}) * - * Cut ({@link CutAction#ID}}) * Copy ({@link CopyAction#ID}}) * Paste ({@link PasteAction#ID}}) * Duplicate ({@link DuplicateAction#ID}}) * Delete... ({@link DeleteAction#ID}}) * - * Select All ({@link SelectAllAction#ID}}) * Clear Selection ({@link ClearSelectionAction#ID}}) * - * Find ({@link AbstractFindAction#ID}}) * - * Settings ({@link AbstractPreferencesAction#ID}) * </pre> * * The <b>window menu</b> has the following standard menu items: * <pre> * Arrange Cascade ({@link ArrangeWindowsAction#CASCADE_ID}) * Arrange Vertical ({@link ArrangeWindowsAction#VERTICAL_ID}) * Arrange Horizontal ({@link ArrangeWindowsAction#HORIZONTAL_ID}) * - * "Filename" ({@link FocusWindowAction}) * - * "Toolbar" ({@link ToggleToolBarAction}) * </pre> * * The <b>help menu</b> has the following standard menu items: * <pre> * About ({@link AboutAction#ID}) * </pre> * * The menus provided by the {@code ApplicationModel} are inserted between * the file menu and the window menu. In case the application model supplies * a menu with the title "Edit" or "Help", the standard menu items are added * with a seperator to the end of the menu. * * * * @author Werner Randelshofer. * @version $Id$ */ public class MDIApplication extends AbstractApplication { private JFrame parentFrame; private JScrollPane scrollPane; private JMDIDesktopPane desktopPane; private Preferences prefs; private LinkedList<Action> toolBarActions; /** Creates a new instance. */ public MDIApplication() { } @Override public void init() { super.init(); initLookAndFeel(); prefs = PreferencesUtil.userNodeForPackage((getModel() == null) ? getClass() : getModel().getClass()); initLabels(); parentFrame = new JFrame(getName()); parentFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); parentFrame.setPreferredSize(new Dimension(600, 400)); desktopPane = new JMDIDesktopPane(); desktopPane.setTransferHandler(new DropFileTransferHandler()); scrollPane = new JScrollPane(); scrollPane.setViewportView(desktopPane); toolBarActions = new LinkedList<Action>(); setActionMap(createModelActionMap(model)); parentFrame.getContentPane().add( wrapDesktopPane(scrollPane, toolBarActions)); parentFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent evt) { getAction(null, ExitAction.ID).actionPerformed( new ActionEvent(parentFrame, ActionEvent.ACTION_PERFORMED, "windowClosing")); } }); parentFrame.setJMenuBar(createMenuBar(null)); PreferencesUtil.installFramePrefsHandler(prefs, "parentFrame", parentFrame); parentFrame.setVisible(true); model.initApplication(this); } protected ActionMap createModelActionMap(ApplicationModel mo) { ActionMap rootMap = new ActionMap(); rootMap.put(AboutAction.ID, new AboutAction(this)); rootMap.put(ExitAction.ID, new ExitAction(this)); rootMap.put(ClearRecentFilesMenuAction.ID, new ClearRecentFilesMenuAction(this)); rootMap.put(MaximizeWindowAction.ID, new MaximizeWindowAction(this, null)); rootMap.put(MinimizeWindowAction.ID, new MinimizeWindowAction(this, null)); rootMap.put(ArrangeWindowsAction.VERTICAL_ID, new ArrangeWindowsAction(desktopPane, Arrangeable.Arrangement.VERTICAL)); rootMap.put(ArrangeWindowsAction.HORIZONTAL_ID, new ArrangeWindowsAction(desktopPane, Arrangeable.Arrangement.HORIZONTAL)); rootMap.put(ArrangeWindowsAction.CASCADE_ID, new ArrangeWindowsAction(desktopPane, Arrangeable.Arrangement.CASCADE)); ActionMap moMap = mo.createActionMap(this, null); moMap.setParent(rootMap); return moMap; } @Override protected ActionMap createViewActionMap(View v) { ActionMap intermediateMap = new ActionMap(); intermediateMap.put(FocusWindowAction.ID, new FocusWindowAction(v)); ActionMap vMap = model.createActionMap(this, v); vMap.setParent(intermediateMap); intermediateMap.setParent(getActionMap(null)); return vMap; } @Override public void launch(String[] args) { super.launch(args); } @Override public void configure(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "false"); System.setProperty("com.apple.macos.useScreenMenuBar", "false"); System.setProperty("apple.awt.graphics.UseQuartz", "false"); System.setProperty("swing.aatext", "true"); } protected void initLookAndFeel() { try { String lafName = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(lafName); } catch (Exception e) { e.printStackTrace(); } if (UIManager.getString("OptionPane.css") == null) { UIManager.put("OptionPane.css", "<head>" + "<style type=\"text/css\">" + "b { font: 13pt \"Dialog\" }" + "p { font: 11pt \"Dialog\"; margin-top: 8px }" + "</style>" + "</head>"); } } @Override public void show(final View v) { if (!v.isShowing()) { v.setShowing(true); final JInternalFrame f = new JInternalFrame(); f.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE); f.setClosable(getAction(v, CloseFileAction.ID) != null); f.setMaximizable(true); f.setResizable(true); f.setIconifiable(false); f.setSize(new Dimension(400, 400)); updateViewTitle(v, f); PreferencesUtil.installInternalFramePrefsHandler(prefs, "view", f, desktopPane); Point loc = new Point(desktopPane.getInsets().left, desktopPane.getInsets().top); boolean moved; do { moved = false; for (Iterator i = views().iterator(); i.hasNext();) { View aView = (View) i.next(); if (aView != v && aView.isShowing() && SwingUtilities.getRootPane(aView.getComponent()).getParent(). getLocation().equals(loc)) { Point offset = SwingUtilities.convertPoint(SwingUtilities.getRootPane(aView.getComponent()), 0, 0, SwingUtilities.getRootPane(aView.getComponent()).getParent()); loc.x += Math.max(offset.x, offset.y); loc.y += Math.max(offset.x, offset.y); moved = true; break; } } } while (moved); f.setLocation(loc); //paletteHandler.add(f, v); f.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(final InternalFrameEvent evt) { getAction(v, CloseFileAction.ID).actionPerformed( new ActionEvent(f, ActionEvent.ACTION_PERFORMED, "windowClosing")); } @Override public void internalFrameClosed(final InternalFrameEvent evt) { v.stop(); } }); v.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if (name == View.HAS_UNSAVED_CHANGES_PROPERTY || name == View.URI_PROPERTY) { updateViewTitle(v, f); } } }); f.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if (name.equals("selected")) { if (evt.getNewValue().equals(Boolean.TRUE)) { setActiveView(v); } else { if (v == getActiveView()) { setActiveView(null); } } } } }); //f.setJMenuBar(createMenuBar(v)); f.getContentPane().add(v.getComponent()); f.setVisible(true); desktopPane.add(f); if (desktopPane.getComponentCount() == 1) { try { f.setMaximum(true); } catch (PropertyVetoException ex) { // ignore veto } } f.toFront(); try { f.setSelected(true); } catch (PropertyVetoException e) { // Don't care. } v.getComponent().requestFocusInWindow(); v.start(); } } @Override public void hide(View v) { if (v.isShowing()) { JInternalFrame f = (JInternalFrame) SwingUtilities.getRootPane(v.getComponent()).getParent(); if (getActiveView() == v) { setActiveView(null); } f.setVisible(false); f.remove(v.getComponent()); // Setting the JMenuBar to null triggers action disposal of // actions in the openRecentMenu and the windowMenu. This is // important to prevent memory leaks. f.setJMenuBar(null); desktopPane.remove(f); f.dispose(); } } @Override public boolean isSharingToolsAmongViews() { return true; } @Override public Component getComponent() { return parentFrame; } /** * Returns the wrapped desktop pane. */ protected Component wrapDesktopPane(Component c, LinkedList<Action> toolBarActions) { if (getModel() != null) { int id = 0; for (JToolBar tb : new ReversedList<JToolBar>(getModel().createToolBars(this, null))) { id++; JPanel panel = new JPanel(new BorderLayout()); panel.add(tb, BorderLayout.NORTH); panel.add(c, BorderLayout.CENTER); c = panel; PreferencesUtil.installToolBarPrefsHandler(prefs, "toolbar." + id, tb); toolBarActions.addFirst(new ToggleToolBarAction(tb, tb.getName())); } } return c; } /** * Creates a menu bar. */ protected JMenuBar createMenuBar(@Nullable View v) { JMenuBar mb = new JMenuBar(); // Get menus from application model JMenu fileMenu = null; JMenu editMenu = null; JMenu helpMenu = null; JMenu viewMenu = null; JMenu windowMenu = null; String fileMenuText = labels.getString("file.text"); String editMenuText = labels.getString("edit.text"); String viewMenuText = labels.getString("view.text"); String windowMenuText = labels.getString("window.text"); String helpMenuText = labels.getString("help.text"); LinkedList<JMenu> ll = new LinkedList<JMenu>(); getModel().getMenuBuilder().addOtherMenus(ll, this, v); for (JMenu mm : ll) { String text = mm.getText(); if (text == null) { mm.setText("-null-"); } else if (text.equals(fileMenuText)) { fileMenu = mm; continue; } else if (text.equals(editMenuText)) { editMenu = mm; continue; } else if (text.equals(viewMenuText)) { viewMenu = mm; continue; } else if (text.equals(windowMenuText)) { windowMenu = mm; continue; } else if (text.equals(helpMenuText)) { helpMenu = mm; continue; } mb.add(mm); } // Create missing standard menus if (fileMenu == null) { fileMenu = createFileMenu(v); } if (editMenu == null) { editMenu = createEditMenu(v); } if (viewMenu == null) { viewMenu = createViewMenu(v); } if (windowMenu == null) { windowMenu = createWindowMenu(v); } if (helpMenu == null) { helpMenu = createHelpMenu(v); } // Insert standard menus into menu bar if (fileMenu != null) { mb.add(fileMenu, 0); } if (editMenu != null) { mb.add(editMenu, Math.min(1, mb.getComponentCount())); } if (viewMenu != null) { mb.add(viewMenu, Math.min(2, mb.getComponentCount())); } if (windowMenu != null) { mb.add(windowMenu); } if (helpMenu != null) { mb.add(helpMenu); } return mb; } @Override @Nullable public JMenu createFileMenu(View view) { JMenu m; m = new JMenu(); labels.configureMenu(m, "file"); MenuBuilder mb = model.getMenuBuilder(); mb.addClearFileItems(m, this, view); mb.addNewFileItems(m, this, view); mb.addNewWindowItems(m, this, view); mb.addLoadFileItems(m, this, view); mb.addOpenFileItems(m, this, view); if (getAction(view, LoadFileAction.ID) != null ||// getAction(view, OpenFileAction.ID) != null ||// getAction(view, LoadDirectoryAction.ID) != null ||// getAction(view, OpenDirectoryAction.ID) != null) { m.add(createOpenRecentFileMenu(view)); } maybeAddSeparator(m); mb.addCloseFileItems(m, this, view); mb.addSaveFileItems(m, this, view); mb.addExportFileItems(m, this, view); mb.addPrintFileItems(m, this, view); mb.addOtherFileItems(m, this, view); maybeAddSeparator(m); mb.addExitItems(m, this, view); return (m.getItemCount() == 0) ? null : m; } /** * Updates the title of a view and displays it in the given frame. * * @param v The view. * @param f The frame. */ protected void updateViewTitle(View v, JInternalFrame f) { URI uri = v.getURI(); String title; if (uri == null) { title = labels.getString("unnamedFile"); } else { title = URIUtil.getName(uri); } if (v.hasUnsavedChanges()) { title += "*"; } v.setTitle(labels.getFormatted("internalFrame.title", title, getName(), v.getMultipleOpenId())); f.setTitle(v.getTitle()); } @Override @Nullable public JMenu createViewMenu(final View view) { JMenu m = new JMenu(); labels.configureMenu(m, "view"); MenuBuilder mb = model.getMenuBuilder(); mb.addOtherViewItems(m, this, view); return (m.getItemCount() > 0) ? m : null; } @Override @Nullable public JMenu createWindowMenu(View view) { JMenu m; JMenuItem mi; m = new JMenu(); JMenu windowMenu = m; labels.configureMenu(m, "window"); addAction(m, view, ArrangeWindowsAction.CASCADE_ID); addAction(m, view, ArrangeWindowsAction.VERTICAL_ID); addAction(m, view, ArrangeWindowsAction.HORIZONTAL_ID); maybeAddSeparator(m); for (View pr : views()) { addAction(m, view, FocusWindowAction.ID); } if (toolBarActions.size() > 0) { maybeAddSeparator(m); for (Action a : toolBarActions) { JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(a); ActionUtil.configureJCheckBoxMenuItem(cbmi, a); addMenuItem(m, cbmi); } } MenuBuilder mb = model.getMenuBuilder(); mb.addOtherWindowItems(m, this, view); addPropertyChangeListener(new WindowMenuHandler(windowMenu, view)); return (m.getItemCount() == 0) ? null : m; } @Override @Nullable public JMenu createEditMenu(View view) { JMenu m; JMenuItem mi; Action a; m = new JMenu(); labels.configureMenu(m, "edit"); MenuBuilder mb = model.getMenuBuilder(); mb.addUndoItems(m, this, view); maybeAddSeparator(m); mb.addClipboardItems(m, this, view); maybeAddSeparator(m); mb.addSelectionItems(m, this, view); maybeAddSeparator(m); mb.addFindItems(m, this, view); maybeAddSeparator(m); mb.addOtherEditItems(m, this, view); maybeAddSeparator(m); mb.addPreferencesItems(m, this, view); return (m.getItemCount() == 0) ? null : m; } @Override public JMenu createHelpMenu(View view) { JMenu m = new JMenu(); labels.configureMenu(m, "help"); MenuBuilder mb = model.getMenuBuilder(); mb.addHelpItems(m, this, view); mb.addAboutItems(m, this, view); return (m.getItemCount() == 0) ? null : m; } /** Updates the menu items in the "Window" menu. */ private class WindowMenuHandler implements PropertyChangeListener { private JMenu windowMenu; @Nullable private View view; public WindowMenuHandler(JMenu windowMenu, @Nullable View view) { this.windowMenu = windowMenu; this.view = view; MDIApplication.this.addPropertyChangeListener(this); updateWindowMenu(); } @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if (name == VIEW_COUNT_PROPERTY || name == "paletteCount") { updateWindowMenu(); } } protected void updateWindowMenu() { JMenu m = windowMenu; m.removeAll(); m.add(getAction(view, ArrangeWindowsAction.CASCADE_ID)); m.add(getAction(view, ArrangeWindowsAction.VERTICAL_ID)); m.add(getAction(view, ArrangeWindowsAction.HORIZONTAL_ID)); m.addSeparator(); for (Iterator i = views().iterator(); i.hasNext();) { View pr = (View) i.next(); if (getAction(pr, FocusWindowAction.ID) != null) { m.add(getAction(pr, FocusWindowAction.ID)); } } if (toolBarActions.size() > 0) { m.addSeparator(); for (Action a : toolBarActions) { JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(a); ActionUtil.configureJCheckBoxMenuItem(cbmi, a); m.add(cbmi); } } } } /** This transfer handler opens a new view for each dropped file. */ private class DropFileTransferHandler extends TransferHandler { @Override public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { Action a = getAction(null, OpenApplicationFileAction.ID); if (a == null) { return false; } for (DataFlavor f : transferFlavors) { if (f.isFlavorJavaFileListType()) { return true; } } return false; } @Override public boolean importData(JComponent comp, Transferable t) { Action a = getAction(null, OpenApplicationFileAction.ID); if (a == null) { return false; } try { @SuppressWarnings("unchecked") java.util.List<File> files = (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); for (final File f : files) { a.actionPerformed(new ActionEvent(desktopPane, ActionEvent.ACTION_PERFORMED, f.toString())); } return true; } catch (UnsupportedFlavorException ex) { return false; } catch (IOException ex) { return false; } } } }
00d95b00de61ed29236b0b65a551e36af171ac5a
3d6c20dc57a8eb1a015c5d2353a515f29525a1d6
/October31Swing/src/Page870/Sketcher.java
00d269f2c332ce47ff534b1369927099fb02c2c1
[]
no_license
nparvez71/NetbeanSoftware
b9e5c93addc2583790c69f53c650c29665e16721
1e18ff07914c4c4530bcfd93693d838bea8f9641
refs/heads/master
2020-03-13T19:14:53.285683
2018-04-29T04:34:07
2018-04-29T04:34:07
131,249,843
0
0
null
null
null
null
UTF-8
Java
false
false
1,954
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 Page870; /** * * @author J2EE-33 */ // Sketching application import java.awt.Toolkit; import java.awt.Dimension; import javax.swing.SwingUtilities; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; public class Sketcher { public static void main(String[] args) { theApp = new Sketcher(); SwingUtilities.invokeLater( new Runnable() { // Anonymous Runnable class object public void run() { // Run method executed in thread theApp.creatGUI(); // Call static GUI creator } } ); } // Method to create the application GUI private void creatGUI() { window = new SketchFrame("Sketcher"); // Create the app window Toolkit theKit = window.getToolkit(); // Get the window toolkit Dimension wndSize = theKit.getScreenSize(); // Get screen size // Set the position to screen center & size to half screen size window.setBounds(wndSize.width/4, wndSize.height/4, // Position wndSize.width/2, wndSize.height/2); // Size window.addWindowListener(new WindowHandler());// Add window listener window.setVisible(true); } // Handler class for window events class WindowHandler extends WindowAdapter { // Handler for window closing event public void windowClosing(WindowEvent e) { window.dispose(); // Release the window resources System.exit(0); // End the application } } private SketchFrame window; // The application window private static Sketcher theApp; // The application object }
4d179944142a42ee2db1758ecb1e8b0b03e941dc
98c3f3daee02d9e311472a2463478e80a2e78721
/src/test/java/com/youzan/nsq/client/configs/ControlConfigTestcase.java
f0540d8468a6fd0b01bafbd3ef37d72b1c4d7159
[]
no_license
Patty-Chen/nsqJavaSDK
0954af00750dca13e5c72604f8c35fd614d74929
d9ff57cf8bce6f7f943ccc06b6ffcd11b7226c5e
refs/heads/master
2020-05-23T01:58:56.103685
2018-11-27T03:46:38
2018-11-27T03:46:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,952
java
package com.youzan.nsq.client.configs; import com.youzan.nsq.client.entity.lookup.AbstractControlConfig; import com.youzan.nsq.client.entity.lookup.SeedLookupdAddress; import com.youzan.util.HostUtil; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; /** * Created by lin on 16/12/14. */ public class ControlConfigTestcase { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ConfigAccessAgent.class); protected final static String controlCnfStr = "{" + "\"previous\":[\"http://global.s.qima-inc.com:4161\"]," + "\"current\":[\"http://sqs.s.qima-inc.com:4161\", \"http://sqs.s.qima-inc.com:4161\"]," + "\"gradation\":{" + "\"*\":{\"percent\":10.0}," + "\"bc-pifa0\":{\"percent\":10.0}," + "\"bc-pifa1\":{\"percent\":20.0}," + "\"bc-pifa2\":{\"percent\":30.0}" + "}" + "}"; protected final static String controlCnfStrContainHost = "{" + "\"previous\":[\"http://global.s.qima-inc.com:4161\"]," + "\"current\":[\"http://sqs.s.qima-inc.com:4161\", \"http://sqs.s.qima-inc.com:4161\"]," + "\"gradation\":{" + "\"*\":{\"percent\":10.0}," + "\"bc-pifa0\":{\"percent\":10.0}," + "\"bc-pifa1\":{\"percent\":20.0}," + "\"%s\":{\"percent\":50.0}," + "\"bc-pifa2\":{\"percent\":30.0}" + "}" + "}"; protected final static String invalidControlCnfStr = "{" + "\"previous\":[\"http://global.s.qima-inc.com:4161\"]," + "\"current\":[]," + "\"gradation\":{" + "\"bc-pifa0\":{\"percent\":10.0}," + "\"bc-pifa1\":{\"percent\":20.0}," + "\"bc-pifa2\":{\"percent\":30.0}" + "}" + "}"; @Test public void testCreateControlConfig() { try { logger.info("[testCreateControlConfig] starts."); AbstractControlConfig ctrlCnf = AbstractControlConfig.create(controlCnfStr); Assert.assertTrue(ctrlCnf.isValid()); AbstractControlConfig.Gradation aGradation = ctrlCnf.getGradation(); Assert.assertEquals(aGradation.getPercentage().getFactor(), 10d); List<SeedLookupdAddress> curSeedRefs = ctrlCnf.getCurrentReferences(); Assert.assertEquals(curSeedRefs.size(), 2); for (SeedLookupdAddress aSeed : curSeedRefs) { Assert.assertNotNull(aSeed); Assert.assertEquals("http://sqs.s.qima-inc.com:4161", aSeed.getAddress()); Assert.assertEquals("http://sqs.s.qima-inc.com:4161", aSeed.getClusterId()); String lookupdNonexist = aSeed.punchLookupdAddressStr(false); Assert.assertNull(lookupdNonexist); } List<SeedLookupdAddress> preSeedRefs = ctrlCnf.getPreviousReferences(); Assert.assertEquals(preSeedRefs.size(), 1); for (SeedLookupdAddress aSeed : preSeedRefs) { Assert.assertNotNull(aSeed); Assert.assertEquals("http://global.s.qima-inc.com:4161", aSeed.getAddress()); Assert.assertEquals("http://global.s.qima-inc.com:4161", aSeed.getClusterId()); String lookupdNonexist = aSeed.punchLookupdAddressStr(false); Assert.assertNull(lookupdNonexist); } }finally { logger.info("[testCreateControlConfig] ends."); } } @Test public void testFetchGradation(){ try { logger.info("[testFetchGradation] starts."); String hostname = HostUtil.getHostname(); if (null == hostname) { logger.warn("host name not found for current host. Testcase skipped"); return; } String ctrlCnfWHostname = String.format(controlCnfStrContainHost, hostname); AbstractControlConfig ctrlCnf = AbstractControlConfig.create(ctrlCnfWHostname); Assert.assertTrue(ctrlCnf.isValid()); AbstractControlConfig.Gradation aGradation = ctrlCnf.getGradation(); double factor = aGradation.getPercentage().getFactor(); Assert.assertEquals(factor, 50d); }finally { logger.info("[testFetchGradation] ends."); } } @Test public void testParseInvalidControlConfig() { try{ logger.info("[testParseInvalidControlConfig] starts"); AbstractControlConfig ctrlCnf = AbstractControlConfig.create(invalidControlCnfStr); Assert.assertNull(ctrlCnf); }finally { logger.info("[testParseInvalidControlConfig] ends."); } } }
886ccac171ee3cdfb04fe2dc34687b4a29a0955e
950b7c69f30440c1028bc5182eb12fdcd25b3947
/item-service/src/main/java/com/giordanbetat/projectcloud/service/ItemService.java
e721441ed1acc7efe63eab9d69007b76e92cfc5f
[]
no_license
giordanbetat/microservices-ribbon
4e0947f8ecb7375cd4d8f155d09a7c8cc2b9a399
ea87ad7dfd04756bea60e86d2ba36bfc584c964b
refs/heads/master
2022-11-10T08:28:59.354472
2020-07-04T21:08:21
2020-07-04T21:08:21
277,184,592
0
0
null
null
null
null
UTF-8
Java
false
false
238
java
package com.giordanbetat.projectcloud.service; import java.util.List; import com.giordanbetat.projectcloud.model.Item; public interface ItemService { public List<Item> findAll(); public Item findById(Long id, Integer amount); }
97b97881bf72d2247b7e7078a09ae04edc9233d5
9fb6ffcd5d5073bdf45549fb2a9c235b2cf63df3
/src/example/programmers/Hash3.java
509a23fb71fef0ac4e443c311933d04bea0f61bb
[]
no_license
RATSENO/algorithm
29339e33c5e992777c6c63f2484831701cd9360e
0f70d6ea37d802a8af0912aba215d2648a7ef7da
refs/heads/master
2021-07-14T05:00:52.761431
2021-05-06T05:11:47
2021-05-06T05:11:47
246,300,783
0
0
null
null
null
null
UTF-8
Java
false
false
587
java
package example.programmers; import java.util.HashMap; public class Hash3 { public int solution(String[][] clothes) { int answer = 1; HashMap<String, Integer> map = new HashMap<>(); for(int i = 0; i < clothes.length; i++) { if(map.get(clothes[i][1]) == null) map.put(clothes[i][1], 1); else map.put(clothes[i][1], map.get(clothes[i][1]) + 1); } for(String keys: map.keySet()) { answer *= (map.get(keys) + 1); } answer -= 1; return answer; } }
0368c2adeae0fc9bdbd3619890ca8ac9d9d4003a
93f3578669fb0d0030a550316aebe0d7b4221631
/rpc-supplychain/src/main/java/cn/com/glsx/supplychain/mapper/am/StatementSellJbwyMapper.java
298332f186a5c4946d591f062eef1143c4a86985
[]
no_license
shanghaif/supplychain
4d7de62809b6c88ac5080a85a77fc4bf3d856db8
c36c771b0304c5739de98bdfc322c0082a9e523d
refs/heads/master
2023-02-09T19:01:35.562699
2021-01-05T09:39:11
2021-01-05T09:39:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
413
java
package cn.com.glsx.supplychain.mapper.am; import org.apache.ibatis.annotations.Mapper; import org.oreframework.datasource.mybatis.mapper.OreMapper; import com.github.pagehelper.Page; import cn.com.glsx.supplychain.model.am.StatementSellJbwy; @Mapper public interface StatementSellJbwyMapper extends OreMapper<StatementSellJbwy>{ Page<StatementSellJbwy> pageStatementSellJbwy(StatementSellJbwy record); }
f3dc0c2e3244a6f579cec4b4f4154f63b382ae1f
b77a71ac21bbd168c9a51e052d802e2e136f2ec5
/4-ambient/build/generated/source/r/debug/android/support/graphics/drawable/R.java
612ccee9dbae7e4b0686417bceea643d79ad91a8
[ "Apache-2.0" ]
permissive
CptDoucheWizard/watchface
f9558d17639343bb363966e3551b8e2572483f5e
211c8609e8da4f57ce2e895f9641013bbec22317
refs/heads/master
2021-04-15T18:37:27.018772
2018-03-21T08:57:47
2018-03-21T08:57:47
126,149,526
0
0
null
null
null
null
UTF-8
Java
false
false
7,621
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.graphics.drawable; public final class R { public static final class attr { public static final int font = 0x7f040092; public static final int fontProviderAuthority = 0x7f040094; public static final int fontProviderCerts = 0x7f040095; public static final int fontProviderFetchStrategy = 0x7f040096; public static final int fontProviderFetchTimeout = 0x7f040097; public static final int fontProviderPackage = 0x7f040098; public static final int fontProviderQuery = 0x7f040099; public static final int fontStyle = 0x7f04009a; public static final int fontWeight = 0x7f04009b; } public static final class bool { public static final int abc_action_bar_embed_tabs = 0x7f050000; } public static final class color { public static final int notification_action_color_filter = 0x7f060061; public static final int notification_icon_bg_color = 0x7f060062; public static final int ripple_material_light = 0x7f060071; public static final int secondary_text_default_material_light = 0x7f060073; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f07005d; public static final int compat_button_inset_vertical_material = 0x7f07005e; public static final int compat_button_padding_horizontal_material = 0x7f07005f; public static final int compat_button_padding_vertical_material = 0x7f070060; public static final int compat_control_corner_material = 0x7f070061; public static final int notification_action_icon_size = 0x7f070084; public static final int notification_action_text_size = 0x7f070085; public static final int notification_big_circle_margin = 0x7f070086; public static final int notification_content_margin_start = 0x7f070087; public static final int notification_large_icon_height = 0x7f070088; public static final int notification_large_icon_width = 0x7f070089; public static final int notification_main_column_padding_top = 0x7f07008a; public static final int notification_media_narrow_margin = 0x7f07008b; public static final int notification_right_icon_size = 0x7f07008c; public static final int notification_right_side_padding_top = 0x7f07008d; public static final int notification_small_icon_background_padding = 0x7f07008e; public static final int notification_small_icon_size_as_large = 0x7f07008f; public static final int notification_subtext_size = 0x7f070090; public static final int notification_top_pad = 0x7f070091; public static final int notification_top_pad_large_text = 0x7f070092; } public static final class drawable { public static final int notification_action_background = 0x7f0800a0; public static final int notification_bg = 0x7f0800a1; public static final int notification_bg_low = 0x7f0800a2; public static final int notification_bg_low_normal = 0x7f0800a3; public static final int notification_bg_low_pressed = 0x7f0800a4; public static final int notification_bg_normal = 0x7f0800a5; public static final int notification_bg_normal_pressed = 0x7f0800a6; public static final int notification_icon_background = 0x7f0800a7; public static final int notification_template_icon_bg = 0x7f0800a8; public static final int notification_template_icon_low_bg = 0x7f0800a9; public static final int notification_tile_bg = 0x7f0800aa; public static final int notify_panel_notification_icon_bg = 0x7f0800ab; } public static final class id { public static final int action_container = 0x7f0a000e; public static final int action_divider = 0x7f0a0010; public static final int action_image = 0x7f0a0011; public static final int action_text = 0x7f0a0017; public static final int actions = 0x7f0a0018; public static final int async = 0x7f0a0021; public static final int blocking = 0x7f0a0025; public static final int chronometer = 0x7f0a002f; public static final int forever = 0x7f0a0045; public static final int icon = 0x7f0a0049; public static final int icon_group = 0x7f0a004a; public static final int info = 0x7f0a004e; public static final int italic = 0x7f0a004f; public static final int line1 = 0x7f0a0053; public static final int line3 = 0x7f0a0054; public static final int normal = 0x7f0a0060; public static final int notification_background = 0x7f0a0061; public static final int notification_main_column = 0x7f0a0062; public static final int notification_main_column_container = 0x7f0a0063; public static final int right_icon = 0x7f0a006b; public static final int right_side = 0x7f0a006c; public static final int text = 0x7f0a0090; public static final int text2 = 0x7f0a0091; public static final int time = 0x7f0a0094; public static final int title = 0x7f0a0095; } public static final class integer { public static final int status_bar_notification_info_maxnum = 0x7f0b0009; } public static final class layout { public static final int notification_action = 0x7f0d0023; public static final int notification_action_tombstone = 0x7f0d0024; public static final int notification_template_custom_big = 0x7f0d002b; public static final int notification_template_icon_group = 0x7f0d002c; public static final int notification_template_part_chronometer = 0x7f0d0030; public static final int notification_template_part_time = 0x7f0d0031; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f0f0053; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f100103; public static final int TextAppearance_Compat_Notification_Info = 0x7f100104; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f100106; public static final int TextAppearance_Compat_Notification_Time = 0x7f100109; public static final int TextAppearance_Compat_Notification_Title = 0x7f10010b; public static final int Widget_Compat_NotificationActionContainer = 0x7f100187; public static final int Widget_Compat_NotificationActionText = 0x7f100188; } public static final class styleable { public static final int[] FontFamily = { 0x7f040094, 0x7f040095, 0x7f040096, 0x7f040097, 0x7f040098, 0x7f040099 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x7f040092, 0x7f04009a, 0x7f04009b }; public static final int FontFamilyFont_font = 0; public static final int FontFamilyFont_fontStyle = 1; public static final int FontFamilyFont_fontWeight = 2; } }
6caab0509fb6b74006930be52a8109b016c21d09
1c4979426fe1f450ec0234a483ada6d30f681baa
/src/main/java/com/learning/example/basic/dao/BookRepository.java
4623d4927bbf9b64a87e9d4c085870c76cd89f95
[]
no_license
pijush-github/spring-rest-springboot
b385b7b63bbe905239774dd5416944ed1f90dea3
beb23434003a751f935a3d6f497fe24cad7e199a
refs/heads/master
2022-11-17T21:46:29.199972
2020-07-11T21:54:49
2020-07-11T21:54:49
278,940,944
0
0
null
null
null
null
UTF-8
Java
false
false
285
java
package com.learning.example.basic.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.learning.example.basic.entity.Book; @Repository public interface BookRepository extends JpaRepository<Book, Long> { }
7e4b7972e96d182f200e9931a0493679905d31f2
d4fb8f5bd84fe76de0875a27a431b057d95bc239
/core/src/main/java/com/caitiaobang/core/app/tools/nice_spinner/SpinnerTextFormatter.java
38e0e453683371e24430b421aa913918639e6d50
[]
no_license
printlybyte/yf_trajectory
6fd81606fefd402a0d0daf76288b4695ed3dea1e
923f55609e02b0fe0ff516c4939a9ce9e0b5199f
refs/heads/master
2020-06-29T21:53:18.103278
2020-04-08T08:44:50
2020-04-08T08:44:50
200,633,905
0
2
null
null
null
null
UTF-8
Java
false
false
162
java
package com.caitiaobang.core.app.tools.nice_spinner; import android.text.Spannable; public interface SpinnerTextFormatter<T> { Spannable format(T item); }
908b47e30e16a45542de5b575b07ba0b3c58258f
8d6345720d1a26e6f4c55c36f2bb7f2d829f27ce
/hounder/releases/2.0/src/com/flaptor/hounder/crawler/modules/boost/ABoostCondition.java
c7c10bef92dfbb4edce0ea7fc3f87c850fe4dca7
[]
no_license
jhandl/hounder
b0087c35171b748aef3e28d75c351f40ad3a9a8e
e85dc63a41775e2c857069240f8f3770a1e82927
refs/heads/master
2021-01-01T17:22:25.654991
2012-03-29T14:48:53
2012-03-29T14:48:53
32,349,306
1
0
null
null
null
null
UTF-8
Java
false
false
1,936
java
/* Copyright 2008 Flaptor (flaptor.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.flaptor.hounder.crawler.modules.boost; import com.flaptor.hounder.crawler.modules.FetchDocument; import com.flaptor.util.Config; import com.flaptor.util.Execute; /** * @author Flaptor Development Team */ public abstract class ABoostCondition extends ABoostModule { public static enum Type {UrlPattern, Keyword , UrlPatternAndKeyword}; public ABoostCondition(Config config) { super(config); } public static ABoostCondition getBoostCondition (Config config, Type type) { ABoostCondition cond = null; switch (type) { case UrlPattern: cond = new UrlPatternBoostCondition(config); break; case Keyword: cond = new KeywordBoostCondition(config); break; case UrlPatternAndKeyword: cond = new CompositeBoostCondition(new UrlPatternBoostCondition(config), new KeywordBoostCondition(config)); break; } if (null == cond) { throw new IllegalArgumentException("Unknown boost condition: "+type); } return cond; } public abstract boolean eval (FetchDocument doc); public boolean hasValue(FetchDocument doc) {return false;} public double getValue (FetchDocument doc) {return 0;} public abstract void close(); }
[ "spike@a752c494-98d9-11de-9e98-d1f6c90d23ca" ]
spike@a752c494-98d9-11de-9e98-d1f6c90d23ca
657259560d658133bbd605adfc3b62cc9c39d848
4b8c86a4287efc56edd5df63061f0ce922b500f7
/src/com/hexun/HeXunLiCai.java
0b6fd9c842750e3f6fbc45433b42a789ff06bfb5
[]
no_license
li-shanglai/NewsAppSpider
e5ac6fb24910d4cac7a60b0ed74ab1518875dbae
2295903b7b3f7a70daf09d4c45b556daf249c810
refs/heads/master
2022-08-22T11:09:39.377559
2017-08-31T01:52:42
2017-08-31T01:52:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,477
java
package com.hexun; import com.db.DBHelper; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.Spider; import us.codecraft.webmagic.processor.PageProcessor; /** * 和讯理财数据获取 * @author lishanglai * */ public class HeXunLiCai implements PageProcessor { private Site site = Site.me().setRetryTimes(3).setSleepTime(2000); @Override public Site getSite() { return site; } @Override public void process(Page page) { //指定抓取html页面的符合此正则的所有链接 page.addTargetRequests(page.getHtml().links().regex("(http://money.hexun.com/[^>]*.html)").all()); page.putField("author", page.getUrl().regex("http://money.hexun.com/[^>]*.html").toString()); //指定抓取好class属性为标签的子标签下的文本内容 //标题 page.putField("name", page.getHtml().xpath("//div[@class='articleName']/h1/text()").toString()); if (page.getResultItems().get("name")==null){ //skip this page page.setSkip(true); } //内容 page.putField("readme", page.getHtml().xpath("//div[@class='art_contextBox']/tidyText()")); //来源 page.putField("resource", page.getHtml().xpath("//div[@class='art_contextBox']/p/text()")); //图片链接http://i0.hexun.com/2017-08-30/190652015.jpg page.putField("img", page.getHtml().links().regex("(http://i0.hexun.com/[^>]*.jpg)").all()); System.out.println("---------------------------------->" + page.getResultItems().get("name")); System.out.println("---------------------------------->" + page.getResultItems().get("resource")); System.out.println("---------------------------------->" + page. getResultItems().get("readme")); System.out.println("---------------------------------->" + page. getResultItems().get("img")); if (page.getResultItems().get("name") != null) { String sql = "INSERT INTO hexunlicai SET url_hx='"+ page.getResultItems().get("author") +"',title_hx='"+page.getResultItems().get("name")+"',article_hx='"+page. getResultItems().get("readme")+"',source_hx='"+page.getResultItems().get("resource")+"',img_hx='"+page.getResultItems().get("img")+"'"; DBHelper.insert(sql); } } public static void main(String[] args) { Spider.create(new HeXunLiCai()).addUrl("http://money.hexun.com/zxkd/index.html").thread(5).run(); } }
3d666a52f5c7e01767444116a23c20a71b222759
1e763679ba14000c67efaa1d39405aa54abd8c83
/src/prueba_1/Prueba_1.java
abb69c9674ed199d8051eaa80720da3866ac834f
[]
no_license
ejcrfrz/Prueba_1
8a7f0c113ef8fe2d38474a9cf979b296ab116629
5d23ca31a34cfafa9207d2d89212c3b5b2c4152e
refs/heads/master
2022-06-06T13:41:10.092021
2020-05-04T16:53:53
2020-05-04T16:53:53
261,219,484
0
0
null
null
null
null
UTF-8
Java
false
false
501
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 prueba_1; /** * * @author EDUARDO */ public class Prueba_1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("AHHHHHHHHHHHHHHHHHHHHHHHHHHH"); } }
f4aff22776c4db672ed1efcbd4500e00a459edf1
0f742b64a43c2c0660515b1a5ef6500c07b362db
/TextBoxPanelTalksToPaintModel.java
aae362f5fc49b76c14ee6e66b787617d491225e3
[]
no_license
hardeepdhatt99/PaintProject
c0dae3e421e11c9ad1b7cd3e555271de7ac55406
d61e7b6f4e00ef8a7ae058dfcae856865dbd43b0
refs/heads/master
2022-04-24T14:28:47.554685
2020-04-26T17:02:28
2020-04-26T17:02:28
259,083,726
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package ca.utoronto.utm.paint; import java.util.Observable; import javax.swing.JButton; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class TextBoxPanelTalksToPaintModel extends Observable implements ChangeListener{ private String text; public TextBoxPanelTalksToPaintModel() { this.text = ""; } public String getText() { return this.text; } public void setText(String s) { this.text = s; this.setChanged(); this.notifyObservers(this.text); } @Override public void stateChanged(ChangeEvent e) { JButton source = (JButton)e.getSource(); this.text = (String) source.getText(); this.setChanged(); this.notifyObservers(this.text); } }
3ece5300446be28cbde5e044110a37c6531afdc9
3a3659892663f88c247fa2c27b09632460e606c9
/Shopkeeper/src/com/qiaoxi/bean/Global.java
2503c38ba8522898a8899bf87bfd35644fe3fab8
[]
no_license
dikechong/AndroidWork-1
db95d798cf1e1b371e1961aef1731f247ae356de
89960d20b987e09662d9da453e5344f70a70d7d5
refs/heads/master
2020-07-14T06:46:01.367405
2016-04-13T14:22:20
2016-04-13T14:22:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,274
java
package com.qiaoxi.bean; import java.util.HashMap; import java.util.Map; import android.R.integer; import android.app.Fragment; import android.widget.TextView; /** * Created by shiyan on 2016/3/21. */ public class Global { public static Fragment fragment1; public static Fragment fragment2; public static TextView headcount; public static Map<String,Boolean> map; public static Map<String,String> areamap = new HashMap<String, String>(); public static Map<String,String> areamapback = new HashMap<String, String>(); public static String cookie; public static String discount; public static int frag1checkedid; public static boolean areasaved; public static boolean inforssaved; public static String ordernumber; public static String waiterid; public static String deskid; //public static Double al = 0.0;//已经支付的 //用于和dailog传值 public static String shouldPay; public static String discountPay; public static String alreadyPay; public static String leftToPay; public static String giveBack; public static void ClearDataForPayDetail(){ shouldPay = "0"; discountPay = "0"; alreadyPay = "0"; leftToPay = "0"; giveBack = "0"; } }
7c249af77f9bb521ca90c808a0dfbf97d5275e42
774738ae7e40e17e726f3b5ae3b212b863d29d14
/app/src/main/java/com/yy/www/template/function/main/home/itembinder/ItemBannerBinder.java
1a200b947ccd3eb59ce66136cb9db458c1e43a90
[]
no_license
yyBetter/AndroidTemplate
4443942eb346e145e2390f4773b2443e56f4c7f1
932abb5ba86d37e2c50cfc0b9e6bcba60f082d14
refs/heads/master
2021-01-22T22:39:26.314557
2017-03-27T10:43:49
2017-03-27T10:43:49
85,565,044
0
0
null
null
null
null
UTF-8
Java
false
false
1,474
java
package com.yy.www.template.function.main.home.itembinder; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; import com.yy.www.template.R; import com.yy.www.template.function.main.home.bean.ItemBanner; import butterknife.BindView; import butterknife.ButterKnife; import me.drakeet.multitype.ItemViewBinder; /** * Created by yangyu on 2017/3/26. */ public class ItemBannerBinder extends ItemViewBinder<ItemBanner, ItemBannerBinder.ViewHolder> { @NonNull @Override protected ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) { return new ViewHolder(inflater.inflate(R.layout.item_banner, parent, false)); } @Override protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull ItemBanner itemBanner) { Context context = holder.itemView.getContext(); Picasso.with(context) .load(itemBanner.bannerBeen.get(0).getImg()) .into(holder.ivBanner); } class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.iv_Banner) ImageView ivBanner; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
4464f4910abc1f619101cab5c8bdb6a2a909c645
f047bd8b32365fa0b82995f756472febc5b90bcb
/core/src/main/java/ace/ucv/licenta/core/App.java
5e6717d09b1c928a69f554b4f63aae9f724caa5b
[]
no_license
BeniaminSavu/licenta
01135d9e19be5f5aeb8ebcdc8fba2281fe4374d8
aa3ce5cc9ff781233cb0ef2b6dc46204478f1967
refs/heads/master
2021-06-24T15:42:34.849898
2018-07-20T05:25:56
2018-07-20T05:25:56
141,666,953
0
0
null
null
null
null
UTF-8
Java
false
false
462
java
package ace.ucv.licenta.core; import javax.swing.UIManager; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } String[] contextPaths = new String[] { "applicationContext.xml" }; new ClassPathXmlApplicationContext(contextPaths); } }
9a848eddb5c24e99f3f9dd5e7b2c17185622891f
87dc525324d0959eb203192a5a401cd1de78f808
/boletin21/Boletin21.java
e2a4145c3ef51b5477ec060ac19ad917b26969f2
[]
no_license
orlando142526/boletin21
56f4d56ca36de8379195eeb22958cfb65170f261
7f1c1a73f5a049df29c0154d17fa990b8b631b1b
refs/heads/master
2021-01-30T16:22:12.073911
2020-02-27T11:30:15
2020-02-27T11:30:15
243,503,380
0
0
null
null
null
null
UTF-8
Java
false
false
1,033
java
package boletin21; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author DANIELCASTELAO\oyagualendara */ public class Boletin21 { public static void main(String[] args) { // TODO code application logic here ArrayList<Libros> listaLibros = new ArrayList(); int opcion; Metodos obx = new Metodos(); do { opcion = Integer.parseInt(JOptionPane.showInputDialog("***MENU****\n 1 --> Engadir Libro\n 2 --> Amosar Libros\n 3 --> Borrar Libros\n 4 --> Buscar Libros\n 5 --> Modificar Libros")); switch (opcion) { case 1: listaLibros.add(obx.crearLibros()); break; case 2: obx.amosar(listaLibros); break; case 3: obx.borrarLibros(listaLibros); break; case 4: obx.buscarLibros(listaLibros); break; case 5: obx.modificarLibros(listaLibros); break; } } while (opcion != 6); } }
12601151e1b8ced7634b20e90c2efdf54925b2de
13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3
/crash-reproduction-ws/results/XWIKI-14263-59-29-Single_Objective_GGA-WeightedSum/com/xpn/xwiki/internal/template/InternalTemplateManager_ESTest.java
4f272533642b9319364803d33feaf6e1d3b82d97
[ "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
584
java
/* * This file was automatically generated by EvoSuite * Wed Apr 01 08:19:15 UTC 2020 */ package com.xpn.xwiki.internal.template; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class InternalTemplateManager_ESTest extends InternalTemplateManager_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
8c5c88ffa7d0bf4632362d58429ce34d0501d337
d1fc24dea56b3e654a8615fde82770a9365aa233
/test/com/hstclair/jaskell/collections/TestFunctionalSpliterator.java
c3ae60bbae0e995e32054170e8a44198f1c5a8eb
[]
no_license
richardy2012/jaskell-2
1cb8cc890e09b351318e617a813a8fbef0b00a2a
3f1894f9629f302afd793e7adf73d2614bda5808
refs/heads/master
2020-12-28T23:04:41.911743
2015-08-09T19:37:11
2015-08-09T19:37:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,213
java
package com.hstclair.jaskell.collections; import com.hstclair.jaskell.function.Consumer; import com.hstclair.jaskell.function.Expression; import com.hstclair.jaskell.function.Function; import org.junit.Test; import java.util.Spliterator; import static org.junit.Assert.assertEquals; /** * @author hstclair * @since 7/26/15 2:42 PM */ public class TestFunctionalSpliterator { class Mock implements FunctionalSpliterator<Object> { Function<Consumer<Object>, Boolean> tryAdvanceFunction = (it) -> false; Consumer<Consumer<Object>> forEachRemainingConsumer = (it) -> {}; Expression<Spliterator<Object>> trySplitExpression = () -> null; Expression<Long> estimateSizeExpression = () -> Long.MAX_VALUE; Expression<Integer> characteristicsExpression = () -> FunctionalSpliteratorImpl.DEFAULT_CHARACTERISTICS; int tryAdvanceInvoked; int forEachRemainingInvoked; int trySplitInvoked; int estimateSizeInvoked; int characteristicsInvoked; public int totalMethodsInvoked() { return tryAdvanceInvoked + forEachRemainingInvoked + trySplitInvoked + estimateSizeInvoked + characteristicsInvoked; } @Override public boolean tryAdvance(Consumer<? super Object> action) { tryAdvanceInvoked++; return tryAdvanceFunction.apply(action); } @Override public void forEachRemaining(Consumer<? super Object> action) { forEachRemainingInvoked++; forEachRemainingConsumer.accept(action); } @Override public Spliterator<Object> trySplit() { trySplitInvoked++; return trySplitExpression.evaluate(); } @Override public long estimateSize() { estimateSizeInvoked++; return estimateSizeExpression.evaluate(); } @Override public int characteristics() { characteristicsInvoked++; return characteristicsExpression.evaluate(); } } @Test public void testTryAdvanceJavaConsumer() { int[] invoked = new int[] { 0 }; Object expected = new Object(); java.util.function.Consumer<Object> consumer = (it) -> { invoked[0]++; assertEquals(expected, it); }; Mock instance = new Mock(); instance.tryAdvanceFunction = (it) -> { it.accept(expected); return false; }; instance.tryAdvance(consumer); assertEquals(1, instance.tryAdvanceInvoked); assertEquals(1, instance.totalMethodsInvoked()); assertEquals(1, invoked[0]); } @Test public void testForEachRemainingJavaConsumer() { int[] invoked = new int[] { 0 }; Object expected = new Object(); java.util.function.Consumer<Object> consumer = (it) -> { invoked[0]++; assertEquals(expected, it); }; Mock instance = new Mock(); instance.forEachRemainingConsumer = (it) -> it.accept(expected); instance.forEachRemaining(consumer); assertEquals(1, instance.forEachRemainingInvoked); assertEquals(1, instance.totalMethodsInvoked()); assertEquals(1, invoked[0]); } }
a38c72f0ed85bc7b0854a101e6631c22afefa336
50fc368d42fe9a5887f01949ddd5621f483d3262
/src/main/java/Pages/TradesBlotter/GridPanel.java
6497d4f1cd86d6d1dd7b686cb9a8e31c675e3e66
[]
no_license
SergeyKvyatkovsky/UI-test-project-Focus
67e577ca34f3c124fa7ba1cd12fd8aae5ee3909d
f4b35d2f46e8c6c8018504e353ba2ef09cae2540
refs/heads/master
2023-07-09T01:08:14.790690
2018-12-06T17:57:36
2018-12-06T17:57:36
135,302,238
0
0
null
2023-09-01T21:23:13
2018-05-29T13:43:07
Java
UTF-8
Java
false
false
1,835
java
package Pages.TradesBlotter; import Core.IPage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.List; public class GridPanel extends IPage{ final static String TABLE = "//div[starts-with(@id, 'tblTrades')]"; final static String CHILD_DIV = "./td/div"; By listDivFirstColumn = By.xpath(TABLE + "//td[1]/div[contains(@class, 'x-grid-cell')]"); By spanFirstColumnHeader = By.xpath(TABLE + "//span[contains(@class, 'x-column-header')][1]"); //Заголовки таблицы By listSpanColumnHeaders = By.xpath(TABLE + "//span[contains(@class, 'x-column-header')]"); By listDivGridCell = By.xpath(TABLE + "//td"); By rows = By.xpath(TABLE + "//tr[starts-with(@class, 'x-grid-row')]"); public GridPanel(WebDriver driver) { super(driver); } public GridPanel sortColumn(){ waitFor(spanFirstColumnHeader); click(spanFirstColumnHeader); return this; } //Получение текста эл-тов из первого столбца public List<String> getTextFromColumns(){ List<String> list = new ArrayList<String>(); for (int i = 0; i<getSizeOfElements(listDivFirstColumn); i++) { list.add(getElement(listDivFirstColumn, i).getText()); } return list; } public List<String> getValuesFromColumn(String columnName){ int index = getIndexFromList(listSpanColumnHeaders, columnName); int rowsCount = getSizeOfElements(rows); List<String> values = new ArrayList<String>(); for (int i=0; i<rowsCount; i++){ values.add(getElement(rows, i).findElements(By.xpath(CHILD_DIV)).get(index).getText()); } return values; } }
13d7d53d6fb5e90fb71e9919eb7dc3a289355762
3634eded90370ff24ee8f47ccfa19e388d3784ad
/src/main/java/org/jsoup/select/StructuralEvaluator.java
61dac804c6e3e312f8e37ea2608249b87f98a210
[]
no_license
xiaofans/ResStudyPro
8bc3c929ef7199c269c6250b390d80739aaf50b9
ac3204b27a65e006ebeb5b522762848ea82d960b
refs/heads/master
2021-01-25T05:09:52.461974
2017-06-06T12:12:41
2017-06-06T12:12:41
93,514,258
0
0
null
null
null
null
UTF-8
Java
false
false
4,163
java
package org.jsoup.select; import java.util.Iterator; import org.jsoup.nodes.Element; abstract class StructuralEvaluator extends Evaluator { Evaluator evaluator; static class Root extends Evaluator { Root() { } public boolean matches(Element root, Element element) { return root == element; } } static class Has extends StructuralEvaluator { public Has(Evaluator evaluator) { this.evaluator = evaluator; } public boolean matches(Element root, Element element) { Iterator it = element.getAllElements().iterator(); while (it.hasNext()) { Element e = (Element) it.next(); if (e != element && this.evaluator.matches(root, e)) { return true; } } return false; } public String toString() { return String.format(":has(%s)", new Object[]{this.evaluator}); } } static class ImmediateParent extends StructuralEvaluator { public ImmediateParent(Evaluator evaluator) { this.evaluator = evaluator; } public boolean matches(Element root, Element element) { if (root == element) { return false; } Element parent = element.parent(); if (parent == null || !this.evaluator.matches(root, parent)) { return false; } return true; } public String toString() { return String.format(":ImmediateParent%s", new Object[]{this.evaluator}); } } static class ImmediatePreviousSibling extends StructuralEvaluator { public ImmediatePreviousSibling(Evaluator evaluator) { this.evaluator = evaluator; } public boolean matches(Element root, Element element) { if (root == element) { return false; } Element prev = element.previousElementSibling(); if (prev == null || !this.evaluator.matches(root, prev)) { return false; } return true; } public String toString() { return String.format(":prev%s", new Object[]{this.evaluator}); } } static class Not extends StructuralEvaluator { public Not(Evaluator evaluator) { this.evaluator = evaluator; } public boolean matches(Element root, Element node) { return !this.evaluator.matches(root, node); } public String toString() { return String.format(":not%s", new Object[]{this.evaluator}); } } static class Parent extends StructuralEvaluator { public Parent(Evaluator evaluator) { this.evaluator = evaluator; } public boolean matches(Element root, Element element) { if (root == element) { return false; } for (Element parent = element.parent(); parent != root; parent = parent.parent()) { if (this.evaluator.matches(root, parent)) { return true; } } return false; } public String toString() { return String.format(":parent%s", new Object[]{this.evaluator}); } } static class PreviousSibling extends StructuralEvaluator { public PreviousSibling(Evaluator evaluator) { this.evaluator = evaluator; } public boolean matches(Element root, Element element) { if (root == element) { return false; } for (Element prev = element.previousElementSibling(); prev != null; prev = prev.previousElementSibling()) { if (this.evaluator.matches(root, prev)) { return true; } } return false; } public String toString() { return String.format(":prev*%s", new Object[]{this.evaluator}); } } StructuralEvaluator() { } }
54f3905a272b91dd777cace2d1dcdc925bec530b
1c501361178ad81a2fc3e436ed6afdc4fea8f12a
/src/main/java/com/astrokids/model/Cartao.java
81b8fca623048cbe2b8f5b7533a2b914e3202a64
[]
no_license
Marco-Andre90/astro-kids-back-end
5710f0c45ed4f305d2390e9b2ffbc17ec38b5bcd
6072cb2ea48c67afa588e86ad8ec5c8ca41c92bf
refs/heads/master
2023-04-12T20:20:15.651609
2021-05-01T18:32:53
2021-05-01T18:32:53
320,947,919
1
0
null
null
null
null
UTF-8
Java
false
false
644
java
package com.astrokids.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class Cartao { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idCartao; private String nomeCartao; private String descricao; private String caminhoImg; }
0692b977002f47a3388397266f26ede8eb17c859
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/hibernate-orm/2019/4/BytecodeEnhancerRunner.java
4801752bc50c3e6b1f07526a968123305fb5a59b
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
4,832
java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.testing.bytecode.enhancement; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.hibernate.bytecode.enhance.spi.EnhancementContext; import org.hibernate.bytecode.enhance.spi.Enhancer; import org.hibernate.cfg.Environment; import org.hibernate.testing.junit4.CustomRunner; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import org.junit.runners.ParentRunner; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; /** * @author Luis Barreiro */ public class BytecodeEnhancerRunner extends Suite { private static final RunnerBuilder CUSTOM_RUNNER_BUILDER = new RunnerBuilder() { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { return new CustomRunner( testClass ); } }; public BytecodeEnhancerRunner(Class<?> klass) throws ClassNotFoundException, InitializationError { super( CUSTOM_RUNNER_BUILDER, klass, enhanceTestClass( klass ) ); } private static Class<?>[] enhanceTestClass(Class<?> klass) throws ClassNotFoundException { String packageName = klass.getPackage().getName(); List<Class<?>> classList = new ArrayList<>(); try { if ( klass.isAnnotationPresent( CustomEnhancementContext.class ) ) { for ( Class<? extends EnhancementContext> contextClass : klass.getAnnotation( CustomEnhancementContext.class ).value() ) { EnhancementContext enhancementContextInstance = contextClass.getConstructor().newInstance(); classList.add( getEnhancerClassLoader( enhancementContextInstance, packageName ).loadClass( klass.getName() ) ); } } else { classList.add( getEnhancerClassLoader( new EnhancerTestContext(), packageName ).loadClass( klass.getName() ) ); } } catch ( IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e ) { // This is unlikely, but if happens throw runtime exception to fail the test throw new RuntimeException( e ); } return classList.toArray( new Class<?>[]{} ); } // --- // private static ClassLoader getEnhancerClassLoader(EnhancementContext context, String packageName) { return new ClassLoader() { private final String debugOutputDir = System.getProperty( "java.io.tmpdir" ); private final Enhancer enhancer = Environment.getBytecodeProvider().getEnhancer( context ); @SuppressWarnings( "ResultOfMethodCallIgnored" ) @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if ( !name.startsWith( packageName ) ) { return getParent().loadClass( name ); } Class c = findLoadedClass( name ); if ( c != null ) { return c; } try ( InputStream is = getResourceAsStream( name.replace( '.', '/' ) + ".class" ) ) { if ( is == null ) { throw new ClassNotFoundException( name + " not found" ); } byte[] original = new byte[is.available()]; try ( BufferedInputStream bis = new BufferedInputStream( is ) ) { bis.read( original ); } byte[] enhanced = enhancer.enhance( name, original ); if ( enhanced == null ) { return defineClass( name, original, 0, original.length ); } File f = new File( debugOutputDir + File.separator + name.replace( ".", File.separator ) + ".class" ); f.getParentFile().mkdirs(); f.createNewFile(); try ( FileOutputStream out = new FileOutputStream( f ) ) { out.write( enhanced ); } return defineClass( name, enhanced, 0, enhanced.length ); } catch ( Throwable t ) { throw new ClassNotFoundException( name + " not found", t ); } } }; } @Override protected void runChild(Runner runner, RunNotifier notifier) { // This is ugly but, for now, ORM class loading is inconsistent. // It sometimes use ClassLoaderService which takes into account AvailableSettings.CLASSLOADERS, and sometimes // ReflectHelper#classForName() which uses the TCCL. // See https://hibernate.atlassian.net/browse/HHH-13136 for more information. ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( ( (ParentRunner<?>) runner ).getTestClass().getJavaClass().getClassLoader() ); super.runChild( runner, notifier ); } finally { Thread.currentThread().setContextClassLoader( originalClassLoader ); } } }
ff5b508a4dcd8a3aa6a696eb2661ce81bf46f86a
e190aafdf55b70f2ece56c08d1ab7f631964b807
/src/main/java/com/genestimate/webapp/model/PrintingType.java
cde4c2ed75e8d4f947353b0d8d284d87870d673d
[]
no_license
kaiszg/genestimate-web-App
b78c6883ddbe14075dad31d385b2cd11fe99d42b
c03e330dfce2089d44b1896f09a251d426358345
refs/heads/master
2021-01-11T19:27:09.858017
2017-02-06T18:48:44
2017-02-06T18:48:44
79,370,284
0
0
null
null
null
null
UTF-8
Java
false
false
2,116
java
package com.genestimate.webapp.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; /** * Created by Kais on 14.01.2017. */ @Entity @Table(name = "PRINTING_TYPE", schema = "PUBLIC") public class PrintingType { private int id; private String name; @JsonIgnore private List<ComponentProperties> componentsProperties; @JsonIgnore private List<Properties> properties; @Id @GeneratedValue @Column(name = "ID") public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PrintingType that = (PrintingType) o; if (id != that.id) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return componentsProperties != null ? componentsProperties.equals(that.componentsProperties) : that.componentsProperties == null; } @Override public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (componentsProperties != null ? componentsProperties.hashCode() : 0); return result; } @OneToMany(mappedBy = "printingType", fetch = FetchType.LAZY) public List<ComponentProperties> getComponentsProperties() { return componentsProperties; } public void setComponentsProperties(List<ComponentProperties> componentsProperties) { this.componentsProperties = componentsProperties; } @OneToMany(mappedBy = "coverRawMaterial", fetch = FetchType.EAGER) public List<Properties> getProperties() { return properties; } public void setProperties(List<Properties> properties) { this.properties = properties; } }
e048a184a0b95f63526d2713ead664ae7284dc85
c5aa46699989e7bc6830e8bae8a72ee763a3ba93
/src/main/java/ciclo3_Reto3/Reto3/Controller/custom/CountClient.java
90ca4000744a006f6bc4b33bb3b79b60691af209
[]
no_license
angiemoreno-mt/ciclo3
ba179b54f0fa11df0bd6f70a56091ba22f986b17
884aec5afeb977814052fd5acfb8e7d16a042509
refs/heads/main
2023-08-23T05:52:29.476669
2021-11-04T00:01:45
2021-11-04T00:01:45
418,351,874
0
0
null
null
null
null
UTF-8
Java
false
false
859
java
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package ciclo3_Reto3.Reto3.Controller.custom; import org.hibernate.annotations.common.util.impl.Log; import ciclo3_Reto3.Reto3.Model.Cliente; /** * * @author Angie Moreno */ public class CountClient { private Long total; private Cliente client; public CountClient(Long total, Cliente client) { this.total = total; this.client = client; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public Cliente getClient() { return client; } public void setClient(Cliente client) { this.client = client; } }
643ae8482e98b15c07b1160f2975585aa3741cad
e91215d41d22de71d7698c529bc6660bbb145636
/bookstore/src/com/localhost/bookstore/book/web/servlet/BookServlet.java
919b4afa6a71ea5f1a7713e14f776557cf85ff53
[]
no_license
leonhoou/the-practice-of-javaweb
e533ecbe37f65253f33ca943db53451a8d9f938e
ad71b8d4b2b2a871bd79636605837f6b30a72c62
refs/heads/master
2021-06-16T03:59:44.885900
2017-03-14T14:23:33
2017-03-14T14:23:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,872
java
package com.localhost.bookstore.book.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.localhost.bookstore.book.dao.BookDao; import com.localhost.bookstore.util.BaseServlet; public class BookServlet extends BaseServlet { private BookDao bookDao = new BookDao(); /** * 查询所有图书 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { request.setAttribute("bookList", bookDao.findAll()); return "forward:/jsps/book/list.jsp"; } catch (Exception e) { throw new RuntimeException(e); } } /** * 按照category查询图书 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String findByCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int cid = Integer.valueOf(request.getParameter("cid")).intValue(); try { request.setAttribute("bookList", bookDao.findByCategory(cid)); return "forward:/jsps/book/list.jsp"; } catch (Exception e) { throw new RuntimeException(e); } } /** * 查看图书详细信息 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String load(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int bid = Integer.valueOf(request.getParameter("bid")).intValue(); try { request.setAttribute("book", bookDao.findByBid(bid)); return "forward:/jsps/book/desc.jsp"; } catch (Exception e) { throw new RuntimeException(e); } } }
d7efb4bca2dd868d87e7e3404a276b2f93851b09
ce1a7c1663a6b23f258e9eab34c1493658f5ca27
/src/com/manik/project/Constants/LazyListConstants.java
4a108fde4d854f612ecd6000987d1e1c135525af
[]
no_license
manik001git/project2
9b08637017689ed5f4144834375acf587a5fc60a
fbb5cb73bf7ec5438e259b7e7d02287837e90272
refs/heads/master
2021-04-04T21:07:05.459836
2020-03-19T12:51:38
2020-03-19T12:51:38
248,487,658
0
0
null
null
null
null
UTF-8
Java
false
false
161
java
//$Id$ package com.manik.project.Constants; public interface LazyListConstants { public static final int START = 0; public static final int HYDRATED = 1; }
fa8c5c46af28cc434149cf4bae75ea61d0340c78
3b89c15c4374c9cc6b4696723be787da1dccbd9d
/app/src/androidTest/java/com/btmura/android/reddit/text/MarkdownFormatter_TablesTest.java
5b48b92855f6bd632eb689f4994dcafd366c14a7
[ "Apache-2.0" ]
permissive
firozanawar/fallingForReddit
b89465786ce8e80ab3525db19ee823c402b85265
c6af19edeb00caa063dc26300ad692684a9b4532
refs/heads/master
2020-03-21T05:35:18.305335
2016-01-22T09:12:13
2016-01-22T09:12:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,843
java
/* * Copyright (C) 2013 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.text; import com.btmura.android.reddit.text.MarkdownFormatter.Tables; public class MarkdownFormatter_TablesTest extends AbstractFormatterTest { public void testPattern_singleLine() { matcher = Tables.PATTERN.matcher("a|b|c"); assertFalse(matcher.find()); } public void testPattern_emptyLastColumn() { matcher = Tables.PATTERN.matcher("h1|h2|h3\n-|-|-\na|b|"); assertTrue(matcher.find()); assertEquals(0, matcher.start()); assertEquals(19, matcher.end()); assertFalse(matcher.find()); } public void testPattern_surrounded() { matcher = Tables.PATTERN.matcher("hello\nh1|h2|h3\n-|-|-\na|b|c\nbye"); assertTrue(matcher.find()); assertEquals(6, matcher.start()); assertEquals(27, matcher.end()); assertFalse(matcher.find()); } public void testPattern_noJustificationDashes() { matcher = Tables.PATTERN.matcher("h1|h2|h3\n||\na|b|c"); assertTrue(matcher.find()); assertEquals(0, matcher.start()); assertEquals(17, matcher.end()); assertFalse(matcher.find()); } public void testPattern_missingJustificationRow() { matcher = Tables.PATTERN.matcher("h1|h2|h3\na|b|c\nd|e|f"); assertFalse(matcher.find()); } }
23f4474258b6b8a9a01bdc3fc4701585dadf56e0
24c4d53e1974ad7c025b6bcf71d7f7d7f4c1ed71
/securing-angular-client/pkce/src/main/java/fr/janua/controller/HeroController.java
dd85cbe8faf35a238f2bd688411bc346cb8de6bc
[]
no_license
Urban-And-Co/keycloak-training-apps
0605db308dc7f2c8469b72713c0d69a55afa6ea6
4a7e4388ce7dce57f488f96aaf488ac3c1ecc1b2
refs/heads/master
2022-07-05T22:03:38.785479
2020-05-14T16:00:18
2020-05-14T16:00:18
262,059,786
0
0
null
null
null
null
UTF-8
Java
false
false
689
java
package fr.janua.controller; import fr.janua.model.Hero; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Arrays; @CrossOrigin("*") @RestController @RequestMapping("/api/heroes") public class HeroController { private List<Hero> someHeroes = Arrays.asList(new Hero(1, "Ken"), new Hero(2, "Yannick"), new Hero(3, "Pieter")); @GetMapping public List<Hero> heroes() { return someHeroes; } @GetMapping("/{id}") public Hero hero(@PathVariable("id") String id) { return someHeroes.stream().filter(h -> Integer.toString(h.getId()).equals(id)).findFirst().orElse(null); } }
504374ecfeec1cc4b395941cab9f4ad2ec53b538
473b76b1043df2f09214f8c335d4359d3a8151e0
/benchmark/bigclonebenchdata_partial/16005064.java
5a279f115c370a0f368bf198ffe5eb0323975a6e
[]
no_license
whatafree/JCoffee
08dc47f79f8369af32e755de01c52d9a8479d44c
fa7194635a5bd48259d325e5b0a190780a53c55f
refs/heads/master
2022-11-16T01:58:04.254688
2020-07-13T20:11:17
2020-07-13T20:11:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,224
java
class c16005064 { private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } } }
320e7c9bdec39a3b4746db2b4047639935655a5a
05854bef8cc3153c4f643d5938272bfccebb6a8c
/src/main/java/com/zc/lambdas/function/FunctionTest.java
41737b87a0a4e311750f3cc84c9be663279f35bd
[]
no_license
kuaile-zc/hello
c402cb86fc0ce71e775c61bdc926c83c1d0f23ba
c354fcd76eda1704668489893eea7c60056abcdd
refs/heads/master
2022-06-21T09:31:51.209426
2022-05-19T09:52:56
2022-05-19T09:52:56
173,756,706
0
0
null
2022-05-19T09:52:56
2019-03-04T14:08:33
Java
UTF-8
Java
false
false
4,353
java
package com.zc.lambdas.function; import java.util.function.BiFunction; import java.util.function.Function; /** * @author CoreyChen Zhang * @date 2021/5/27 14:13 * @modified */ public class FunctionTest { public static void main(String[] args) { FunctionTest t1 = new FunctionTest(); // Function函数的使用 Integer addResult = t1.compute(3, value -> value + value); System.out.println("加法结果:" + addResult); // Function函数的使用 String changeStr = t1.compute1(3, String::valueOf); System.out.println("加法结果:" + changeStr); Integer subResult = t1.compute(3, value -> value - 1); System.out.println("减法结果:" + subResult); Integer multipResult = t1.compute(3, value -> value * value); System.out.println("乘法结果:" + multipResult); Integer divisionResult = t1.compute(6, value -> value / 3); System.out.println("除法结果:" + divisionResult); // 使用compose场景, 从右向左处理, 这里就是 (6 * 6) + 10 = 46 Integer composeResult = t1.computeForCompose(6, value -> value + 10, value -> value * value); System.out.println("Function compose 结果:" + composeResult); // 使用andThen场景, 从左向右处理, 这里就是(3 + 20) - 10 = 13 Integer andThenResult = t1.computeForAndThen(3, value -> value + 20, value -> value - 10); System.out.println("Function andThen 结果:" + andThenResult); // 使用 BiFunctioin场景, 这里是 2 + 3 = 5 Integer biFuncResult = t1.computeForBiFunction(2, 3, (v1, v2) -> v1 + v2); System.out.println("BiFunction 结果:" + biFuncResult); // 使用 BiFunctioin andThen场景, 这里是 (2 * 3) + 6 = 12 Integer biFuncAndThenResult = t1.computeForBiFunctionAndThen(2, 3, (v1, v2) -> v1 * v2, v1 -> v1 + 6); System.out.println("BiFunction andThen 结果:" + biFuncAndThenResult); } /** * @param num * @param function * @return * @desc 使用JDK8 Function函数 */ private Integer compute(Integer num, Function<Integer, Integer> function) { Integer result = function.apply(num); return result; } /** * @param num * @param function * @return * @desc 使用JDK8 Function函数 */ private String compute1(Integer num, Function<Integer, String> function) { String result = function.apply(num); return result; } /** * @param num * @param function1 * @param function2 * @return * @desc 使用compose函数,简单的说,就是从右向左处理。 */ private Integer computeForCompose(Integer num, Function<Integer, Integer> function1, Function<Integer, Integer> function2) { return function1.compose(function2).apply(num); } /** * @param num * @param function1 * @param function2 * @return * @desc 使用andThen函数,简单的说,就是从左向右处理。 */ private Integer computeForAndThen(Integer num, Function<Integer, Integer> function1, Function<Integer, Integer> function2) { return function1.andThen(function2).apply(num); } /** * @param num1 * @param nuum2 * @param biFunction * @return * @desc 使用BiFunction */ private Integer computeForBiFunction(Integer num1, Integer num2, BiFunction<Integer, Integer, Integer> biFunction) { return biFunction.apply(num1, num2); } /** * @param num1 * @param num2 * @param biFunction * @param function * @return * @desc 使用BiFunction andThen方法 */ private Integer computeForBiFunctionAndThen(Integer num1, Integer num2, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) { return biFunction.andThen(function).apply(num1, num2); } }
82910709ee236d3bfb65e75ec21f06ae1cea725f
8e8278cfcd01882f48cd13acc57c03bd6472cb7e
/snap-dexmaker/src/main/java/org/snapscript/dx/Code.java
8aa29eadd982b28d149f330cf8a09e7d29b2c647
[]
no_license
snapscript/snap-archive
e66d9a240f4c2a6e4b21434def7a45a74445f8a7
9838eddc5a2cfff5315b1f2f3839fd72f65ed658
refs/heads/master
2021-01-22T01:12:06.122986
2018-10-26T01:41:45
2018-10-26T01:41:45
102,211,593
0
0
null
null
null
null
UTF-8
Java
false
false
37,183
java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.snapscript.dx; import static org.snapscript.dx.rop.code.Rop.BRANCH_GOTO; import static org.snapscript.dx.rop.code.Rop.BRANCH_NONE; import static org.snapscript.dx.rop.code.Rop.BRANCH_RETURN; import static org.snapscript.dx.rop.type.Type.BT_BYTE; import static org.snapscript.dx.rop.type.Type.BT_CHAR; import static org.snapscript.dx.rop.type.Type.BT_INT; import static org.snapscript.dx.rop.type.Type.BT_SHORT; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.snapscript.dx.rop.code.BasicBlockList; import org.snapscript.dx.rop.code.Insn; import org.snapscript.dx.rop.code.PlainCstInsn; import org.snapscript.dx.rop.code.PlainInsn; import org.snapscript.dx.rop.code.RegisterSpecList; import org.snapscript.dx.rop.code.Rop; import org.snapscript.dx.rop.code.Rops; import org.snapscript.dx.rop.code.SourcePosition; import org.snapscript.dx.rop.code.ThrowingCstInsn; import org.snapscript.dx.rop.code.ThrowingInsn; import org.snapscript.dx.rop.cst.CstInteger; import org.snapscript.dx.rop.type.StdTypeList; /** * Builds a sequence of instructions. * * <h3>Locals</h3> * All data manipulation takes place in local variables. Each parameter gets its * own local by default; access these using {@link #getParameter * getParameter()}. Non-static methods and constructors also have a {@code this} * parameter; it's available as {@link #getThis getThis()}. Allocate a new local * variable using {@link #newLocal newLocal()}, and assign a default value to it * with {@link #loadConstant loadConstant()}. Copy a value from one local to * another with {@link #move move()}. * * <p>Every local variable has a fixed type. This is either a primitive type (of * any size) or a reference type. This class emits instructions appropriate to * the types they operate on. Not all operations are local on all types; * attempting to emit such an operation will fail with an unchecked exception. * * <h3>Math and Bit Operations</h3> * Transform a single value into another related value using {@link * #op(UnaryOp,Local,Local) op(UnaryOp, Local, Local)}. Transform two values * into a third value using {@link #op(BinaryOp,Local,Local,Local) op(BinaryOp, * Local, Local, Local)}. In either overload the first {@code Local} parameter * is where the result will be sent; the other {@code Local} parameters are the * inputs. * * <h3>Comparisons</h3> * There are three different comparison operations each with different * constraints: * <ul> * <li>{@link #compareLongs compareLongs()} compares two locals each * containing a {@code long} primitive. This is the only operation that * can compare longs. The result of the comparison is written to another * {@code int} local.</li> * <li>{@link #compareFloatingPoint compareFloatingPoint()} compares two * locals; both {@code float} primitives or both {@code double} * primitives. This is the only operation that can compare floating * point values. This comparison takes an extra parameter that sets * the desired result if either parameter is {@code NaN}. The result of * the comparison is wrtten to another {@code int} local. * <li>{@link #compare compare()} compares two locals. The {@link * Comparison#EQ} and {@link Comparison#NE} options compare either * {@code int} primitives or references. The other options compare only * {@code int} primitives. This comparison takes a {@link Label} that * will be jumped to if the comparison is true. If the comparison is * false the next instruction in sequence will be executed. * </ul> * There's no single operation to compare longs and jump, or to compare ints and * store the result in a local. Accomplish these goals by chaining multiple * operations together. * * <h3>Branches, Labels and Returns</h3> * Basic control flow is expressed using jumps and labels. Each label must be * marked exactly once and may be jumped to any number of times. Create a label * using its constructor: {@code new Label()}, and mark it using {@link #mark * mark(Label)}. All jumps to a label will execute instructions starting from * that label. You can jump to a label that hasn't yet been marked (jumping * forward) or to a label that has already been marked (jumping backward). Jump * unconditionally with {@link #jump jump(Label)} or conditionally based on a * comparison using {@link #compare compare()}. * * <p>Most methods should contain a return instruction. Void methods * should use {@link #returnVoid()}; non-void methods should use {@link * #returnValue returnValue()} with a local whose return type matches the * method's return type. Constructors are considered void methods and should * call {@link #returnVoid()}. Methods may make multiple returns. Methods * containing no return statements must either loop infinitely or throw * unconditionally; it is not legal to end a sequence of instructions without a * jump, return or throw. * * <h3>Throwing and Catching</h3> * This API uses labels to handle thrown exceptions, errors and throwables. Call * {@link #addCatchClause addCatchClause()} to register the target label and * throwable class. All statements that follow will jump to that catch clause if * they throw a {@link Throwable} assignable to that type. Use {@link * #removeCatchClause removeCatchClause()} to unregister the throwable class. * * <p>Throw an throwable by first assigning it to a local and then calling * {@link #throwValue throwValue()}. Control flow will jump to the nearest label * assigned to a type assignable to the thrown type. In this context, "nearest" * means the label requiring the fewest stack frames to be popped. * * <h3>Calling methods</h3> * A method's caller must know its return type, name, parameters, and invoke * kind. Lookup a method on a type using {@link TypeId#getMethod * TypeId.getMethod()}. This is more onerous than Java language invokes, which * can infer the target method using the target object and parameters. There are * four invoke kinds: * <ul> * <li>{@link #invokeStatic invokeStatic()} is used for static methods.</li> * <li>{@link #invokeDirect invokeDirect()} is used for private instance * methods and for constructors to call their superclass's * constructor.</li> * <li>{@link #invokeInterface invokeInterface()} is used to invoke a method * whose declaring type is an interface.</li> * <li>{@link #invokeVirtual invokeVirtual()} is used to invoke any other * method. The target must not be static, private, a constructor, or an * interface method.</li> * <li>{@link #invokeSuper invokeSuper()} is used to invoke the closest * superclass's virtual method. The target must not be static, private, * a constructor method, or an interface method.</li> * <li>{@link #newInstance newInstance()} is used to invoke a * constructor.</li> * </ul> * All invoke methods take a local for the return value. For void methods this * local is unused and may be null. * * <h3>Field Access</h3> * Read static fields using {@link #sget sget()}; write them using {@link * #sput sput()}. For instance values you'll need to specify the declaring * instance; use {@link #getThis getThis()} in an instance method to use {@code * this}. Read instance values using {@link #iget iget()} and write them with * {@link #iput iput()}. * * <h3>Array Access</h3> * Allocate an array using {@link #newArray newArray()}. Read an array's length * with {@link #arrayLength arrayLength()} and its elements with {@link #aget * aget()}. Write an array's elements with {@link #aput aput()}. * * <h3>Types</h3> * Use {@link #cast cast()} to perform either a <strong>numeric cast</strong> or * a <strong>type cast</strong>. Interrogate the type of a value in a local * using {@link #instanceOfType instanceOfType()}. * * <h3>Synchronization</h3> * Acquire a monitor using {@link #monitorEnter monitorEnter()}; release it with * {@link #monitorExit monitorExit()}. It is the caller's responsibility to * guarantee that enter and exit calls are balanced, even in the presence of * exceptions thrown. * * <strong>Warning:</strong> Even if a method has the {@code synchronized} flag, * dex requires instructions to acquire and release monitors manually. A method * declared with {@link java.lang.reflect.Modifier#SYNCHRONIZED SYNCHRONIZED} * but without manual calls to {@code monitorEnter()} and {@code monitorExit()} * will not be synchronized when executed. */ public final class Code { private final MethodId<?, ?> method; /** * All allocated labels. Although the order of the labels in this list * shouldn't impact behavior, it is used to determine basic block indices. */ private final List<Label> labels = new ArrayList<Label>(); /** * The label currently receiving instructions. This is null if the most * recent instruction was a return or goto. */ private Label currentLabel; /** true once we've fixed the positions of the parameter registers */ private boolean localsInitialized; private final Local<?> thisLocal; /** * The parameters on this method. If this is non-static, the first parameter * is 'thisLocal' and we have to offset the user's indices by one. */ private final List<Local<?>> parameters = new ArrayList<Local<?>>(); private final List<Local<?>> locals = new ArrayList<Local<?>>(); private SourcePosition sourcePosition = SourcePosition.NO_INFO; private final List<TypeId<?>> catchTypes = new ArrayList<TypeId<?>>(); private final List<Label> catchLabels = new ArrayList<Label>(); private StdTypeList catches = StdTypeList.EMPTY; Code(DexMaker.MethodDeclaration methodDeclaration) { this.method = methodDeclaration.method; if (methodDeclaration.isStatic()) { thisLocal = null; } else { thisLocal = Local.get(this, method.declaringType); parameters.add(thisLocal); } for (TypeId<?> parameter : method.parameters.types) { parameters.add(Local.get(this, parameter)); } this.currentLabel = new Label(); adopt(this.currentLabel); this.currentLabel.marked = true; } /** * Allocates a new local variable of type {@code type}. It is an error to * allocate a local after instructions have been emitted. */ public <T> Local<T> newLocal(TypeId<T> type) { if (localsInitialized) { throw new IllegalStateException("Cannot allocate locals after adding instructions"); } Local<T> result = Local.get(this, type); locals.add(result); return result; } /** * Returns the local for the parameter at index {@code index} and of type * {@code type}. */ public <T> Local<T> getParameter(int index, TypeId<T> type) { if (thisLocal != null) { index++; // adjust for the hidden 'this' parameter } return coerce(parameters.get(index), type); } /** * Returns the local for {@code this} of type {@code type}. It is an error * to call {@code getThis()} if this is a static method. */ public <T> Local<T> getThis(TypeId<T> type) { if (thisLocal == null) { throw new IllegalStateException("static methods cannot access 'this'"); } return coerce(thisLocal, type); } @SuppressWarnings("unchecked") // guarded by an equals check private <T> Local<T> coerce(Local<?> local, TypeId<T> expectedType) { if (!local.type.equals(expectedType)) { throw new IllegalArgumentException( "requested " + expectedType + " but was " + local.type); } return (Local<T>) local; } /** * Assigns registers to locals. From the spec: * "the N arguments to a method land in the last N registers of the * method's invocation frame, in order. Wide arguments consume two * registers. Instance methods are passed a this reference as their * first argument." * * In addition to assigning registers to each of the locals, this creates * instructions to move parameters into their initial registers. These * instructions are inserted before the code's first real instruction. */ void initializeLocals() { if (localsInitialized) { throw new AssertionError(); } localsInitialized = true; int reg = 0; for (Local<?> local : locals) { reg += local.initialize(reg); } int firstParamReg = reg; List<Insn> moveParameterInstructions = new ArrayList<Insn>(); for (Local<?> local : parameters) { CstInteger paramConstant = CstInteger.make(reg - firstParamReg); reg += local.initialize(reg); moveParameterInstructions.add(new PlainCstInsn(Rops.opMoveParam(local.type.ropType), sourcePosition, local.spec(), RegisterSpecList.EMPTY, paramConstant)); } labels.get(0).instructions.addAll(0, moveParameterInstructions); } /** * Returns the number of registers to hold the parameters. This includes the * 'this' parameter if it exists. */ int paramSize() { int result = 0; for (Local<?> local : parameters) { result += local.size(); } return result; } // labels /** * Assigns {@code target} to this code. */ private void adopt(Label target) { if (target.code == this) { return; // already adopted } if (target.code != null) { throw new IllegalArgumentException("Cannot adopt label; it belongs to another Code"); } target.code = this; labels.add(target); } /** * Start defining instructions for the named label. */ public void mark(Label label) { adopt(label); if (label.marked) { throw new IllegalStateException("already marked"); } label.marked = true; if (currentLabel != null) { jump(label); // blocks must end with a branch, return or throw } currentLabel = label; } /** * Transfers flow control to the instructions at {@code target}. It is an * error to jump to a label not marked on this {@code Code}. */ public void jump(Label target) { adopt(target); addInstruction(new PlainInsn(Rops.GOTO, sourcePosition, null, RegisterSpecList.EMPTY), target); } /** * Registers {@code catchClause} as a branch target for all instructions * in this frame that throw a class assignable to {@code toCatch}. This * includes methods invoked from this frame. Deregister the clause using * {@link #removeCatchClause removeCatchClause()}. It is an error to * register a catch clause without also {@link #mark marking it} in the same * {@code Code} instance. */ public void addCatchClause(TypeId<? extends Throwable> toCatch, Label catchClause) { if (catchTypes.contains(toCatch)) { throw new IllegalArgumentException("Already caught: " + toCatch); } adopt(catchClause); catchTypes.add(toCatch); catches = toTypeList(catchTypes); catchLabels.add(catchClause); } /** * Deregisters the catch clause label for {@code toCatch} and returns it. */ public Label removeCatchClause(TypeId<? extends Throwable> toCatch) { int index = catchTypes.indexOf(toCatch); if (index == -1) { throw new IllegalArgumentException("No catch clause: " + toCatch); } catchTypes.remove(index); catches = toTypeList(catchTypes); return catchLabels.remove(index); } /** * Throws the throwable in {@code toThrow}. */ public void throwValue(Local<? extends Throwable> toThrow) { addInstruction(new ThrowingInsn(Rops.THROW, sourcePosition, RegisterSpecList.make(toThrow.spec()), catches)); } private StdTypeList toTypeList(List<TypeId<?>> types) { StdTypeList result = new StdTypeList(types.size()); for (int i = 0; i < types.size(); i++) { result.set(i, types.get(i).ropType); } return result; } private void addInstruction(Insn insn) { addInstruction(insn, null); } /** * @param branch the branches to follow; interpretation depends on the * instruction's branchingness. */ private void addInstruction(Insn insn, Label branch) { if (currentLabel == null || !currentLabel.marked) { throw new IllegalStateException("no current label"); } currentLabel.instructions.add(insn); switch (insn.getOpcode().getBranchingness()) { case BRANCH_NONE: if (branch != null) { throw new IllegalArgumentException("unexpected branch: " + branch); } return; case BRANCH_RETURN: if (branch != null) { throw new IllegalArgumentException("unexpected branch: " + branch); } currentLabel = null; break; case BRANCH_GOTO: if (branch == null) { throw new IllegalArgumentException("branch == null"); } currentLabel.primarySuccessor = branch; currentLabel = null; break; case Rop.BRANCH_IF: if (branch == null) { throw new IllegalArgumentException("branch == null"); } splitCurrentLabel(branch, Collections.<Label>emptyList()); break; case Rop.BRANCH_THROW: if (branch != null) { throw new IllegalArgumentException("unexpected branch: " + branch); } splitCurrentLabel(null, new ArrayList<Label>(catchLabels)); break; default: throw new IllegalArgumentException(); } } /** * Closes the current label and starts a new one. * * @param catchLabels an immutable list of catch labels */ private void splitCurrentLabel(Label alternateSuccessor, List<Label> catchLabels) { Label newLabel = new Label(); adopt(newLabel); currentLabel.primarySuccessor = newLabel; currentLabel.alternateSuccessor = alternateSuccessor; currentLabel.catchLabels = catchLabels; currentLabel = newLabel; currentLabel.marked = true; } // instructions: locals /** * Copies the constant value {@code value} to {@code target}. The constant * must be a primitive, String, Class, TypeId, or null. */ public <T> void loadConstant(Local<T> target, T value) { Rop rop = value == null ? Rops.CONST_OBJECT_NOTHROW : Rops.opConst(target.type.ropType); if (rop.getBranchingness() == BRANCH_NONE) { addInstruction(new PlainCstInsn(rop, sourcePosition, target.spec(), RegisterSpecList.EMPTY, Constants.getConstant(value))); } else { addInstruction(new ThrowingCstInsn(rop, sourcePosition, RegisterSpecList.EMPTY, catches, Constants.getConstant(value))); moveResult(target, true); } } /** * Copies the value in {@code source} to {@code target}. */ public <T> void move(Local<T> target, Local<T> source) { addInstruction(new PlainInsn(Rops.opMove(source.type.ropType), sourcePosition, target.spec(), source.spec())); } // instructions: unary and binary /** * Executes {@code op} and sets {@code target} to the result. */ public <T> void op(UnaryOp op, Local<T> target, Local<T> source) { addInstruction(new PlainInsn(op.rop(source.type), sourcePosition, target.spec(), source.spec())); } /** * Executes {@code op} and sets {@code target} to the result. For most * binary operations, the types of {@code a} and {@code b} must be the same. * Shift operations (like {@link BinaryOp#SHIFT_LEFT}) require {@code b} to * be an {@code int}, even when {@code a} is a {@code long}. */ public <T1, T2> void op(BinaryOp op, Local<T1> target, Local<T1> a, Local<T2> b) { Rop rop = op.rop(StdTypeList.make(a.type.ropType, b.type.ropType)); RegisterSpecList sources = RegisterSpecList.make(a.spec(), b.spec()); if (rop.getBranchingness() == BRANCH_NONE) { addInstruction(new PlainInsn(rop, sourcePosition, target.spec(), sources)); } else { addInstruction(new ThrowingInsn(rop, sourcePosition, sources, catches)); moveResult(target, true); } } // instructions: branches /** * Compare ints or references. If the comparison is true, execution jumps to * {@code trueLabel}. If it is false, execution continues to the next * instruction. */ public <T> void compare(Comparison comparison, Label trueLabel, Local<T> a, Local<T> b) { adopt(trueLabel); // TODO: ops to compare with zero/null: just omit the 2nd local in StdTypeList.make() Rop rop = comparison.rop(StdTypeList.make(a.type.ropType, b.type.ropType)); addInstruction(new PlainInsn(rop, sourcePosition, null, RegisterSpecList.make(a.spec(), b.spec())), trueLabel); } /** * Compare floats or doubles. This stores -1 in {@code target} if {@code * a < b}, 0 in {@code target} if {@code a == b} and 1 in target if {@code * a > b}. This stores {@code nanValue} in {@code target} if either value * is {@code NaN}. */ public <T extends Number> void compareFloatingPoint( Local<Integer> target, Local<T> a, Local<T> b, int nanValue) { Rop rop; if (nanValue == 1) { rop = Rops.opCmpg(a.type.ropType); } else if (nanValue == -1) { rop = Rops.opCmpl(a.type.ropType); } else { throw new IllegalArgumentException("expected 1 or -1 but was " + nanValue); } addInstruction(new PlainInsn(rop, sourcePosition, target.spec(), RegisterSpecList.make(a.spec(), b.spec()))); } /** * Compare longs. This stores -1 in {@code target} if {@code * a < b}, 0 in {@code target} if {@code a == b} and 1 in target if {@code * a > b}. */ public void compareLongs(Local<Integer> target, Local<Long> a, Local<Long> b) { addInstruction(new PlainInsn(Rops.CMPL_LONG, sourcePosition, target.spec(), RegisterSpecList.make(a.spec(), b.spec()))); } // instructions: fields /** * Copies the value in instance field {@code fieldId} of {@code instance} to * {@code target}. */ public <D, V> void iget(FieldId<D, V> fieldId, Local<V> target, Local<D> instance) { addInstruction(new ThrowingCstInsn(Rops.opGetField(target.type.ropType), sourcePosition, RegisterSpecList.make(instance.spec()), catches, fieldId.constant)); moveResult(target, true); } /** * Copies the value in {@code source} to the instance field {@code fieldId} * of {@code instance}. */ public <D, V> void iput(FieldId<D, V> fieldId, Local<D> instance, Local<V> source) { addInstruction(new ThrowingCstInsn(Rops.opPutField(source.type.ropType), sourcePosition, RegisterSpecList.make(source.spec(), instance.spec()), catches, fieldId.constant)); } /** * Copies the value in the static field {@code fieldId} to {@code target}. */ public <V> void sget(FieldId<?, V> fieldId, Local<V> target) { addInstruction(new ThrowingCstInsn(Rops.opGetStatic(target.type.ropType), sourcePosition, RegisterSpecList.EMPTY, catches, fieldId.constant)); moveResult(target, true); } /** * Copies the value in {@code source} to the static field {@code fieldId}. */ public <V> void sput(FieldId<?, V> fieldId, Local<V> source) { addInstruction(new ThrowingCstInsn(Rops.opPutStatic(source.type.ropType), sourcePosition, RegisterSpecList.make(source.spec()), catches, fieldId.constant)); } // instructions: invoke /** * Calls the constructor {@code constructor} using {@code args} and assigns * the new instance to {@code target}. */ public <T> void newInstance(Local<T> target, MethodId<T, Void> constructor, Local<?>... args) { if (target == null) { throw new IllegalArgumentException(); } addInstruction(new ThrowingCstInsn(Rops.NEW_INSTANCE, sourcePosition, RegisterSpecList.EMPTY, catches, constructor.declaringType.constant)); moveResult(target, true); invokeDirect(constructor, null, target, args); } /** * Calls the static method {@code method} using {@code args} and assigns the * result to {@code target}. * * @param target the local to receive the method's return value, or {@code * null} if the return type is {@code void} or if its value not needed. */ public <R> void invokeStatic(MethodId<?, R> method, Local<? super R> target, Local<?>... args) { invoke(Rops.opInvokeStatic(method.prototype(true)), method, target, null, args); } /** * Calls the non-private instance method {@code method} of {@code instance} * using {@code args} and assigns the result to {@code target}. * * @param method a non-private, non-static, method declared on a class. May * not be an interface method or a constructor. * @param target the local to receive the method's return value, or {@code * null} if the return type is {@code void} or if its value not needed. */ public <D, R> void invokeVirtual(MethodId<D, R> method, Local<? super R> target, Local<? extends D> instance, Local<?>... args) { invoke(Rops.opInvokeVirtual(method.prototype(true)), method, target, instance, args); } /** * Calls {@code method} of {@code instance} using {@code args} and assigns * the result to {@code target}. * * @param method either a private method or the superclass's constructor in * a constructor's call to {@code super()}. * @param target the local to receive the method's return value, or {@code * null} if the return type is {@code void} or if its value not needed. */ public <D, R> void invokeDirect(MethodId<D, R> method, Local<? super R> target, Local<? extends D> instance, Local<?>... args) { invoke(Rops.opInvokeDirect(method.prototype(true)), method, target, instance, args); } /** * Calls the closest superclass's virtual method {@code method} of {@code * instance} using {@code args} and assigns the result to {@code target}. * * @param target the local to receive the method's return value, or {@code * null} if the return type is {@code void} or if its value not needed. */ public <D, R> void invokeSuper(MethodId<D, R> method, Local<? super R> target, Local<? extends D> instance, Local<?>... args) { invoke(Rops.opInvokeSuper(method.prototype(true)), method, target, instance, args); } /** * Calls the interface method {@code method} of {@code instance} using * {@code args} and assigns the result to {@code target}. * * @param method a method declared on an interface. * @param target the local to receive the method's return value, or {@code * null} if the return type is {@code void} or if its value not needed. */ public <D, R> void invokeInterface(MethodId<D, R> method, Local<? super R> target, Local<? extends D> instance, Local<?>... args) { invoke(Rops.opInvokeInterface(method.prototype(true)), method, target, instance, args); } private <D, R> void invoke(Rop rop, MethodId<D, R> method, Local<? super R> target, Local<? extends D> object, Local<?>... args) { addInstruction(new ThrowingCstInsn(rop, sourcePosition, concatenate(object, args), catches, method.constant)); if (target != null) { moveResult(target, false); } } // instructions: types /** * Tests if the value in {@code source} is assignable to {@code type}. If it * is, {@code target} is assigned to 1; otherwise {@code target} is assigned * to 0. */ public void instanceOfType(Local<?> target, Local<?> source, TypeId<?> type) { addInstruction(new ThrowingCstInsn(Rops.INSTANCE_OF, sourcePosition, RegisterSpecList.make(source.spec()), catches, type.constant)); moveResult(target, true); } /** * Performs either a numeric cast or a type cast. * * <h3>Numeric Casts</h3> * Converts a primitive to a different representation. Numeric casts may * be lossy. For example, converting the double {@code 1.8d} to an integer * yields {@code 1}, losing the fractional part. Converting the integer * {@code 0x12345678} to a short yields {@code 0x5678}, losing the high * bytes. The following numeric casts are supported: * * <p><table border="1"> * <tr><th>From</th><th>To</th></tr> * <tr><td>int</td><td>byte, char, short, long, float, double</td></tr> * <tr><td>long</td><td>int, float, double</td></tr> * <tr><td>float</td><td>int, long, double</td></tr> * <tr><td>double</td><td>int, long, float</td></tr> * </table> * * <p>For some primitive conversions it will be necessary to chain multiple * cast operations. For example, to go from float to short one would first * cast float to int and then int to short. * * <p>Numeric casts never throw {@link ClassCastException}. * * <h3>Type Casts</h3> * Checks that a reference value is assignable to the target type. If it is * assignable it is copied to the target local. If it is not assignable a * {@link ClassCastException} is thrown. */ public void cast(Local<?> target, Local<?> source) { if (source.getType().ropType.isReference()) { addInstruction(new ThrowingCstInsn(Rops.CHECK_CAST, sourcePosition, RegisterSpecList.make(source.spec()), catches, target.type.constant)); moveResult(target, true); } else { addInstruction(new PlainInsn(getCastRop(source.type.ropType, target.type.ropType), sourcePosition, target.spec(), source.spec())); } } private Rop getCastRop(org.snapscript.dx.rop.type.Type sourceType, org.snapscript.dx.rop.type.Type targetType) { if (sourceType.getBasicType() == BT_INT) { switch (targetType.getBasicType()) { case BT_SHORT: return Rops.TO_SHORT; case BT_CHAR: return Rops.TO_CHAR; case BT_BYTE: return Rops.TO_BYTE; } } return Rops.opConv(targetType, sourceType); } // instructions: arrays /** * Sets {@code target} to the length of the array in {@code array}. */ public <T> void arrayLength(Local<Integer> target, Local<T> array) { addInstruction(new ThrowingInsn(Rops.ARRAY_LENGTH, sourcePosition, RegisterSpecList.make(array.spec()), catches)); moveResult(target, true); } /** * Assigns {@code target} to a newly allocated array of length {@code * length}. The array's type is the same as {@code target}'s type. */ public <T> void newArray(Local<T> target, Local<Integer> length) { addInstruction(new ThrowingCstInsn(Rops.opNewArray(target.type.ropType), sourcePosition, RegisterSpecList.make(length.spec()), catches, target.type.constant)); moveResult(target, true); } /** * Assigns the element at {@code index} in {@code array} to {@code target}. */ public void aget(Local<?> target, Local<?> array, Local<Integer> index) { addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition, RegisterSpecList.make(array.spec(), index.spec()), catches)); moveResult(target, true); } /** * Assigns {@code source} to the element at {@code index} in {@code array}. */ public void aput(Local<?> array, Local<Integer> index, Local<?> source) { addInstruction(new ThrowingInsn(Rops.opAput(source.type.ropType), sourcePosition, RegisterSpecList.make(source.spec(), array.spec(), index.spec()), catches)); } // instructions: return /** * Returns from a {@code void} method. After a return it is an error to * define further instructions after a return without first {@link #mark * marking} an existing unmarked label. */ public void returnVoid() { if (!method.returnType.equals(TypeId.VOID)) { throw new IllegalArgumentException("declared " + method.returnType + " but returned void"); } addInstruction(new PlainInsn(Rops.RETURN_VOID, sourcePosition, null, RegisterSpecList.EMPTY)); } /** * Returns the value in {@code result} to the calling method. After a return * it is an error to define further instructions after a return without * first {@link #mark marking} an existing unmarked label. */ public void returnValue(Local<?> result) { if (!result.type.equals(method.returnType)) { // TODO: this is probably too strict. throw new IllegalArgumentException("declared " + method.returnType + " but returned " + result.type); } addInstruction(new PlainInsn(Rops.opReturn(result.type.ropType), sourcePosition, null, RegisterSpecList.make(result.spec()))); } private void moveResult(Local<?> target, boolean afterNonInvokeThrowingInsn) { Rop rop = afterNonInvokeThrowingInsn ? Rops.opMoveResultPseudo(target.type.ropType) : Rops.opMoveResult(target.type.ropType); addInstruction(new PlainInsn(rop, sourcePosition, target.spec(), RegisterSpecList.EMPTY)); } // instructions; synchronized /** * Awaits the lock on {@code monitor}, and acquires it. */ public void monitorEnter(Local<?> monitor) { addInstruction(new ThrowingInsn(Rops.MONITOR_ENTER, sourcePosition, RegisterSpecList.make(monitor.spec()), catches)); } /** * Releases the held lock on {@code monitor}. */ public void monitorExit(Local<?> monitor) { addInstruction(new ThrowingInsn(Rops.MONITOR_ENTER, sourcePosition, RegisterSpecList.make(monitor.spec()), catches)); } // produce BasicBlocks for dex BasicBlockList toBasicBlocks() { if (!localsInitialized) { initializeLocals(); } cleanUpLabels(); BasicBlockList result = new BasicBlockList(labels.size()); for (int i = 0; i < labels.size(); i++) { result.set(i, labels.get(i).toBasicBlock()); } return result; } /** * Removes empty labels and assigns IDs to non-empty labels. */ private void cleanUpLabels() { int id = 0; for (Iterator<Label> i = labels.iterator(); i.hasNext();) { Label label = i.next(); if (label.isEmpty()) { i.remove(); } else { label.compact(); label.id = id++; } } } private static RegisterSpecList concatenate(Local<?> first, Local<?>[] rest) { int offset = (first != null) ? 1 : 0; RegisterSpecList result = new RegisterSpecList(offset + rest.length); if (first != null) { result.set(0, first.spec()); } for (int i = 0; i < rest.length; i++) { result.set(i + offset, rest[i].spec()); } return result; } }
ef17113ff2f70c048264daadbd5abf04165c7441
f5452c217864a407625bcfdc2cff2ac2d3795c3a
/OtherCompany/src/TrinaryTree.java
259ec69b63213f1500f348691c84679d3bd4085b
[]
no_license
srxiaoj/LeetCode_HW
da82aec4cf93125a7802f1a7b2d7ba094a36ef92
095772f45c8b29562b7818dd223c4fd3a99bd86d
refs/heads/master
2020-04-16T18:08:49.122785
2020-04-07T00:49:41
2020-04-07T00:49:41
49,519,084
0
0
null
null
null
null
UTF-8
Java
false
false
3,221
java
public class TrinaryTree { class Node { Node left; Node right; Node middle; int val; Node(int val) { this.val = val; } } Node root; public TrinaryTree() { this.root = null; } public TrinaryTree(Node root) { this.root = root; } //insertHelper a value to the appropriate position in the tree. public void insert(int val) { if (root != null) { root = insertHelper(root, val); } else { root = new Node(val); } } public Node insertHelper(Node node, int val) { if (node == null) { node = new Node(val); } else if (val < node.val) { node.left = insertHelper(node.left, val); } else if (val == node.val) { node.middle = insertHelper(node.middle, val); } else { node.right = insertHelper(node.right, val); } return node; } //deleteHelper a value from the tree. public void delete(int val) { root = deleteHelper(root, val); } public Node deleteHelper(Node node, int val) { if (node == null) { System.out.println("The node " + val + " doesn't exist"); return null; } else if (val < node.val) { node.left = deleteHelper(node.left, val); } else if (val > node.val) { node.right = deleteHelper(node.right, val); } else { if (node.middle != null) { node.middle = deleteHelper(node.middle, val); } else if (node.right != null) { node.val = getMin(node.right).val; node.right = deleteHelper(node.right, getMin(node.right).val); } else { node = node.left; } } return node; } // find min as helper function to deleteHelper private Node getMin(Node node) { if (node != null) { while (node.left != null) { node = node.left; } } return node; } // pre-order traverse the tree and print the value public void print(Node root) { if (root == null) return; if (root != null) { System.out.println("Node value: " + root.val); print(root.left); print(root.middle); print(root.right); } } public void print() { print(root); } public static void main(String[] args) { TrinaryTree tree = new TrinaryTree(); tree.insert(5); tree.insert(4); tree.insert(9); tree.insert(5); tree.insert(7); tree.insert(2); tree.insert(2); //preorder traversal, the sequence should be 5422597 System.out.println("Preorder traversal: "); tree.print(); tree.delete(5); tree.delete(7); tree.delete(5); tree.delete(4); // the sequence should be 542297 System.out.println("After deleteHelper 5:"); tree.print(); // deleteHelper a node not exited tree.delete(10); System.out.println("After deleteHelper 10:"); } }
b3968d75554f22895189a6c00f81ea8912097268
94c4e9779877c30f6f2fe3e4e47ee23740be3e77
/zenofAS/launcher/src/main/java/com/cooeeui/brand/zenlauncher/wallpaper/model/ListInfo.java
fcf12bf87879d455c55637efb89018a6c0dc39d3
[]
no_license
MatrixYang/testproject
53705220185c3d1058749cbda84f24ead88a1af5
b501fd3dbe3d4d280c1c59c98df3720fe4b11313
refs/heads/master
2021-01-01T17:46:08.161020
2017-07-24T05:42:47
2017-07-24T05:42:47
98,152,924
1
0
null
null
null
null
UTF-8
Java
false
false
1,508
java
package com.cooeeui.brand.zenlauncher.wallpaper.model; import java.util.ArrayList; import java.util.List; //每个tab对应的model public class ListInfo { private String tabid; private String enname; private String cnname; private String twname; private String typeid; private List<ItemInfo> itemList = new ArrayList<ItemInfo>(); public String getTabid() { return tabid; } public void setTabid( String tabid) { this.tabid = tabid; } public String getEnname() { return enname; } public void setEnname( String enname) { this.enname = enname; } public String getCnname() { return cnname; } public void setCnname( String cnname) { this.cnname = cnname; } public String getTwname() { return twname; } public void setTwname( String twname) { this.twname = twname; } public List<ItemInfo> getItemList() { return itemList; } public void setItemList( List<ItemInfo> itemList) { this.itemList = itemList; } public String getTypeid() { return typeid; } public void setTypeid( String typeid) { this.typeid = typeid; } @Override public String toString() { String sb = "tabid:" + tabid + ";enname" + enname + ";cnname" + ";twname" + twname + ";typeid" + typeid; return sb; } }
601ad0b064d26fcb0e7a98becc1ae9a0ca068c06
753356b6bcbd53b1bb5eea9d516e23e290621ff6
/Demo_Paypal/src/com/example/demo_paypal/Data_TB_StoreInfo.java
764595a553a7bb5b0c066334ef34b0ed8db1bd1d
[]
no_license
Sophia-Gao/AndroidPaypal
52df2ad1883c37d98140d6d44a588994faac5357
894380e4c916d8364673be47c14c96c4c34015be
refs/heads/master
2021-01-10T15:42:23.867187
2015-11-25T08:48:08
2015-11-25T08:48:08
46,848,784
2
0
null
null
null
null
UTF-8
Java
false
false
2,325
java
package com.example.demo_paypal; import java.io.Serializable; public class Data_TB_StoreInfo implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String id; private String mStoreProImageURL; // 商品图片 private String mStoreProName; // 商品名 private float mStoreProPrice; // 商品价格 paypal private int mStoreProNum; // 商品数量 paypal private String sku; // sku paypal private int mProductType; // sku paypal private String mVariantId; public Data_TB_StoreInfo(String id, String mStoreProImageURL, String mStoreProName, float mStoreProPrice, int mStoreProNum) { super(); this.id = id; this.mStoreProNum = mStoreProNum; this.mStoreProImageURL = mStoreProImageURL; this.mStoreProName = mStoreProName; this.mStoreProPrice = mStoreProPrice; } public Data_TB_StoreInfo() { super(); } public String getId() { return id; } public void setId(String Id) { this.id = Id; } public String getmStoreProImageURL() { return mStoreProImageURL; } public void setmStoreProImageURL(String mStoreProImageURL) { this.mStoreProImageURL = mStoreProImageURL; } public String getmStoreProName() { return mStoreProName; } public void setmStoreProName(String mStoreProName) { this.mStoreProName = mStoreProName; } public float getmStoreProPrice() { return mStoreProPrice; } public void setmStoreProNum(int mStoreProNum) { this.mStoreProNum = mStoreProNum; } public int getmStoreProNum() { return mStoreProNum; } public void setmStoreProPrice(float mStoreProPrice) { this.mStoreProPrice = mStoreProPrice; } public void setSku(String sku) { this.sku=sku; } public String getSku(){ return this.sku; } public void setProductType(int mProductType) { this.mProductType=mProductType; } public int getProductType(){ return this.mProductType; } public void setVariantId(String mVariantId) { this.mVariantId=mVariantId; } public String getVariantId(){ return this.mVariantId; } }
f268ad19e546495b7f7c37356a1f7dc8b26df419
c2745516073be0e243c2dff24b4bb4d1d94d18b8
/sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/implementation/KustoPoolChildResourcesClientImpl.java
95e98fd8ec22c52f02b96d73321bc69c12a07f8b
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "CC0-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later" ]
permissive
milismsft/azure-sdk-for-java
84b48d35e3fca8611933b3f86929788e5e8bceed
f4827811c870d09855417271369c592412986861
refs/heads/master
2022-09-25T19:29:44.973618
2022-08-17T14:43:22
2022-08-17T14:43:22
90,779,733
1
0
MIT
2021-12-21T21:11:58
2017-05-09T18:37:49
Java
UTF-8
Java
false
false
13,369
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.Post; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.synapse.fluent.KustoPoolChildResourcesClient; import com.azure.resourcemanager.synapse.fluent.models.CheckNameResultInner; import com.azure.resourcemanager.synapse.models.DatabaseCheckNameRequest; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in KustoPoolChildResourcesClient. */ public final class KustoPoolChildResourcesClientImpl implements KustoPoolChildResourcesClient { /** The proxy service used to perform REST calls. */ private final KustoPoolChildResourcesService service; /** The service client containing this operation class. */ private final SynapseManagementClientImpl client; /** * Initializes an instance of KustoPoolChildResourcesClientImpl. * * @param client the instance of the service client containing this operation class. */ KustoPoolChildResourcesClientImpl(SynapseManagementClientImpl client) { this.service = RestProxy .create(KustoPoolChildResourcesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for SynapseManagementClientKustoPoolChildResources to be used by the * proxy service to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "SynapseManagementCli") private interface KustoPoolChildResourcesService { @Headers({"Content-Type: application/json"}) @Post( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces" + "/{workspaceName}/kustoPools/{kustoPoolName}/checkNameAvailability") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<CheckNameResultInner>> checkNameAvailability( @HostParam("$host") String endpoint, @PathParam("workspaceName") String workspaceName, @PathParam("kustoPoolName") String kustoPoolName, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("api-version") String apiVersion, @BodyParam("application/json") DatabaseCheckNameRequest resourceName, @HeaderParam("Accept") String accept, Context context); } /** * Checks that the Kusto Pool child resource name is valid and is not already in use. * * @param workspaceName The name of the workspace. * @param kustoPoolName The name of the Kusto pool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Kusto Pool child resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the result returned from a check name availability request along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<CheckNameResultInner>> checkNameAvailabilityWithResponseAsync( String workspaceName, String kustoPoolName, String resourceGroupName, DatabaseCheckNameRequest resourceName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (workspaceName == null) { return Mono.error(new IllegalArgumentException("Parameter workspaceName is required and cannot be null.")); } if (kustoPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter kustoPoolName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } else { resourceName.validate(); } final String apiVersion = "2021-06-01-preview"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .checkNameAvailability( this.client.getEndpoint(), workspaceName, kustoPoolName, this.client.getSubscriptionId(), resourceGroupName, apiVersion, resourceName, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Checks that the Kusto Pool child resource name is valid and is not already in use. * * @param workspaceName The name of the workspace. * @param kustoPoolName The name of the Kusto pool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Kusto Pool child resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the result returned from a check name availability request along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<CheckNameResultInner>> checkNameAvailabilityWithResponseAsync( String workspaceName, String kustoPoolName, String resourceGroupName, DatabaseCheckNameRequest resourceName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (workspaceName == null) { return Mono.error(new IllegalArgumentException("Parameter workspaceName is required and cannot be null.")); } if (kustoPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter kustoPoolName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } else { resourceName.validate(); } final String apiVersion = "2021-06-01-preview"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .checkNameAvailability( this.client.getEndpoint(), workspaceName, kustoPoolName, this.client.getSubscriptionId(), resourceGroupName, apiVersion, resourceName, accept, context); } /** * Checks that the Kusto Pool child resource name is valid and is not already in use. * * @param workspaceName The name of the workspace. * @param kustoPoolName The name of the Kusto pool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Kusto Pool child resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the result returned from a check name availability request on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<CheckNameResultInner> checkNameAvailabilityAsync( String workspaceName, String kustoPoolName, String resourceGroupName, DatabaseCheckNameRequest resourceName) { return checkNameAvailabilityWithResponseAsync(workspaceName, kustoPoolName, resourceGroupName, resourceName) .flatMap( (Response<CheckNameResultInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); } /** * Checks that the Kusto Pool child resource name is valid and is not already in use. * * @param workspaceName The name of the workspace. * @param kustoPoolName The name of the Kusto pool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Kusto Pool child resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the result returned from a check name availability request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CheckNameResultInner checkNameAvailability( String workspaceName, String kustoPoolName, String resourceGroupName, DatabaseCheckNameRequest resourceName) { return checkNameAvailabilityAsync(workspaceName, kustoPoolName, resourceGroupName, resourceName).block(); } /** * Checks that the Kusto Pool child resource name is valid and is not already in use. * * @param workspaceName The name of the workspace. * @param kustoPoolName The name of the Kusto pool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Kusto Pool child resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the result returned from a check name availability request along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CheckNameResultInner> checkNameAvailabilityWithResponse( String workspaceName, String kustoPoolName, String resourceGroupName, DatabaseCheckNameRequest resourceName, Context context) { return checkNameAvailabilityWithResponseAsync( workspaceName, kustoPoolName, resourceGroupName, resourceName, context) .block(); } }
80968388dab0759ccdd517345c230c277d40f84b
0933335063a148da6a879b15a2b1108c1adc551e
/backend/truck-service/src/main/java/com/rua/truckservice/conf/WebConfig.java
a30800086531faa13a60a87692a74deec1967296
[]
no_license
ruimda/servicecare
52c2c9738f7a77efea213385b4440402f8dd7be6
4c4b8627b91e15543eda0f862c09aec9c8a72f72
refs/heads/master
2021-05-24T08:18:07.370870
2020-04-13T11:26:39
2020-04-13T11:26:39
253,467,208
0
0
null
null
null
null
UTF-8
Java
false
false
523
java
package com.rua.truckservice.conf; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET"); } }
07580a7ec1c0caafd0e6296877e2926dc5febb7e
d9cb7f8efeb2280075c8e9ed50114fd1c4a6c7a9
/updateemaildao.java
ee4335095204c6ca220ff5dd37b9daaf5b304a90
[]
no_license
harilakshmipathi/Inernet-Banking
981f5697155d8563662773b8ab4f9173ae804bdf
65f3497add0a197bfca926fc83b185f02476ad7d
refs/heads/master
2020-05-31T13:39:11.155697
2019-06-05T02:24:23
2019-06-05T02:24:23
190,310,719
0
0
null
null
null
null
UTF-8
Java
false
false
1,325
java
package com.HSBCBank.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import com.HSBCBank.bean.updateemailbean; import com.HSBCBank.util.DBconnection; public class updateemaildao { public String authenticateUser(updateemailbean loginbean ) { String customerid =loginbean.getcustomerid(); String emailId= loginbean.getemailId(); System.out.println("in update email custid = " +customerid); Connection con = null; PreparedStatement st = null; try { con = DBconnection.createConnection(); System.out.println("dao 11111"); String query = "update customers set emailid = '"+loginbean.getemailId()+"'" + " Where customerid = "+ loginbean.getcustomerid(); System.out.println("dao 222222"+query); System.out.println("dao 333333"); st = con.prepareStatement(query); // st.setString(1, pass); System.out.println("before execute update..."); int i= st.executeUpdate(query); System.out.println("dao 44444444 "+i); if (i!=0) //Just to ensure data has been inserted into the database return "SUCCESS"; } catch(SQLException e) { e.printStackTrace(); } return "Oops.. Something went wrong there..!"; } }
efc3f467029b85f9b68b8d508394ace2e7f0f0ec
0bb8171cd0e3ebcabac54add3e95d2e6306d1c46
/src/reservations/models/airlines/SimpleJet.java
319befa0766c041eb2840666ef676e4463802210
[]
no_license
kezald/AirlineSystem
1883979c673d53d8722f4f3519a49e424985775e
6a792ddfc7d519d416ac1b948e8b8e89e8fe2ebf
refs/heads/master
2022-04-11T11:36:21.260039
2020-04-10T06:05:12
2020-04-10T06:05:12
254,557,159
0
0
null
null
null
null
UTF-8
Java
false
false
3,055
java
package reservations.models.airlines; import java.util.function.Predicate; import reservations.models.Flight; import reservations.models.seatdata.Seat; import reservations.models.seatdata.SeatType; import reservations.models.seatmaps.SeatMap; /** * A SimpleJet airline system class with corresponding * reservation policies * * @author Nikolai Kolbenev 15897074 * */ public class SimpleJet extends Airline { /** * Creates a new instance of SimpleJet object * @author Nikolai Kolbenev 15897074 */ public SimpleJet() { super.setAirlineName("SimpleJet"); } /** * All 4 steps are performed to reserve a seat. * The first 2 steps are combined together and described in "applyFirstReservationStage" method of class * "SeatReservationTemplates" * Depending on the result of the first 2 steps, the policy may decide * to go on with seat reservation and perform steps 3 and 4. * Step 3 is specific to the policy of an airline system itself * Step 4 is identical in both cases, which just terminates the process * * @param seatType The requested seat type * @param flight The Flight object with flight data * @return The reserved seat, if any, * otherwise null * @author Nikolai Kolbenev 15897074 */ @Override public Seat reserveFirstClass(Flight flight, SeatType seatType) { Seat primarySeat; SeatMap seatMap = flight.getSeatMap(); primarySeat = reservationTemplates.applyFirstReservationStage(flight.getSeatMap(), seatType, (requestedSeatType) -> seatMap.queryAvailableFirstClassSeat(requestedSeatType)); if (primarySeat == null) { Predicate<Seat> searchPolicy = seat -> (!seat.isReserved() && (seat.getSeatType() == SeatType.MIDDLE || seat.getSeatType() == SeatType.WINDOW) && seatMap.getNearbyFreeSeat(seat) != null); primarySeat = seatMap.findSpecificSeatInRange(seatMap.getNumberOfFirstClassRows(), seatMap.getNumberOfRows() - 1, searchPolicy); if (primarySeat == null) { seatMap.printMap(); reservationTemplates.printFailedReservation(); } else { primarySeat.setReserved(true); seatMap.getNearbyFreeSeat(primarySeat).setReserved(true); String reservationStatus = "All first class seats are reserved. Reserving seats from Economy class...\n\nSeats reserved: \n"; reservationStatus += primarySeat.getDescription(); reservationStatus += "\n" + seatMap.getNearbyFreeSeat(primarySeat).getDescription(); seatMap.printMap(); System.out.println(reservationStatus); } } return primarySeat; } /** * All 3 steps are performed to reserve a seat * These are described in "reserveEconomy" method of class * "SeatReservationTemplates" * * @param seatType The requested seat type * @param flight The Flight object with flight data * @return The reserved seat, if any, * otherwise null * @author Nikolai Kolbenev 15897074 */ @Override public Seat reserveEconomy(Flight flight, SeatType seatType) { return reservationTemplates.reserveEconomy(flight.getSeatMap(), seatType); } }
eab0fdf7433a62dc3750723be0fb88a2b717ae0b
fc9ca29110bfee85ab78383ddc8b6672ee25d1bd
/src/main/java/ConnectionDB/CajeroModelo.java
427835ca15402149cae68aae26a46be5c55ea7a5
[]
no_license
Chejohrpp/ProyectoFinal-IPC2
072cd8429e889f3326a9a16a55d44e96a1b75d45
df4da122371e35687ff1472ba53670aa86cad755
refs/heads/master
2023-01-21T12:57:11.607272
2020-11-17T09:58:28
2020-11-17T09:58:28
310,961,794
0
0
null
null
null
null
UTF-8
Java
false
false
7,821
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 ConnectionDB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import objetos.Cajero; import objetos.Gerente; /** * * @author sergi */ public class CajeroModelo { private static String ATRIBUTOS= Cajero.CODIGO_DB +","+Cajero.NOMBRE_DB+","+Cajero.TRUNO_DB+","+Cajero.DPI_DB+","+Cajero.DIRECCION_DB+","+Cajero.GENERO_DB+","+Cajero.PASSWORD_DB; private static String ATRIBUTOS_SIN_CODIGO= Cajero.NOMBRE_DB+","+Cajero.TRUNO_DB+","+Cajero.DPI_DB+","+Cajero.DIRECCION_DB+","+Cajero.GENERO_DB+","+Cajero.PASSWORD_DB; private static String ATRIBUTOS_SIN_PASSWORD = Cajero.CODIGO_DB +","+Cajero.NOMBRE_DB+","+Cajero.TRUNO_DB+","+Cajero.DPI_DB+","+Cajero.DIRECCION_DB+","+Cajero.GENERO_DB; private static String ADD_CAJERO = "INSERT INTO " + Cajero.CAJERO_DB_NAME +"( " + ATRIBUTOS +" ) VALUES(?,?,?,?,?,?,AES_ENCRYPT(?,?))"; private static String ADD_CAJERO_SIN_CODIGO = "INSERT INTO " + Cajero.CAJERO_DB_NAME +"( " + ATRIBUTOS_SIN_CODIGO +" ) VALUES(?,?,?,?,?,AES_ENCRYPT(?,?))"; private static String CAJEROS = "SELECT " + ATRIBUTOS_SIN_PASSWORD + ", cast(aes_decrypt("+Cajero.PASSWORD_DB +",?) as char) " + Cajero.PASSWORD_DB + " FROM " + Cajero.CAJERO_DB_NAME; private static String OBTENER_CAJERO = CAJEROS + " WHERE " + Cajero.CODIGO_DB +" =? LIMIT 1"; private static String MOD_CAJERO = "UPDATE " + Cajero.CAJERO_DB_NAME + " SET " + Cajero.NOMBRE_DB+"=?, "+Cajero.TRUNO_DB+"=?,"+Cajero.DPI_DB+"=?," +Cajero.DIRECCION_DB+"=?,"+Cajero.GENERO_DB+"=?,"+Cajero.PASSWORD_DB +"=AES_ENCRYPT(?,?) WHERE "+Cajero.CODIGO_DB+"=?"; private Connection connection = ConnectionDB.getInstance(); public CajeroModelo(){ } public void addCajero(Cajero cajero) throws SQLException{ PreparedStatement preSt = connection.prepareStatement(ADD_CAJERO); preSt.setInt(1, cajero.getCodigo()); preSt.setString(2, cajero.getNombre()); preSt.setString(3, cajero.getTurno()); preSt.setString(4, cajero.getDpi()); preSt.setString(5, cajero.getDireccion()); preSt.setString(6, cajero.getGenero()); preSt.setString(7, cajero.getPassword()); preSt.setString(8, Gerente.LLAVE); preSt.executeUpdate(); } public long addCajeroSinCodigo(Cajero cajero) throws SQLException{ PreparedStatement preSt = connection.prepareStatement(ADD_CAJERO_SIN_CODIGO,Statement.RETURN_GENERATED_KEYS); preSt.setString(1, cajero.getNombre()); preSt.setString(2, cajero.getTurno()); preSt.setString(3, cajero.getDpi()); preSt.setString(4, cajero.getDireccion()); preSt.setString(5, cajero.getGenero()); preSt.setString(6, cajero.getPassword()); preSt.setString(7, Gerente.LLAVE); preSt.executeUpdate(); ResultSet result = preSt.getGeneratedKeys(); if (result.first()) { return result.getLong(1); } return -1; } public void ModCajero(Cajero cajero) throws SQLException{ PreparedStatement preSt = connection.prepareStatement(MOD_CAJERO); preSt.setString(1, cajero.getNombre()); preSt.setString(2, cajero.getTurno()); preSt.setString(3, cajero.getDpi()); preSt.setString(4, cajero.getDireccion()); preSt.setString(5, cajero.getGenero()); preSt.setString(6, cajero.getPassword()); preSt.setString(7, Gerente.LLAVE); preSt.setInt(8, cajero.getCodigo()); preSt.executeUpdate(); } public Cajero verificarLogin(int codigo, String pass) throws SQLException { Cajero cajero = obtenerCajero(codigo); if (cajero != null && cajero.getPassword().equals(pass)) { return cajero; } return null; } public Cajero obtenerCajero(int codigo) throws SQLException { PreparedStatement preSt = connection.prepareStatement(OBTENER_CAJERO); preSt.setString(1, Gerente.LLAVE); preSt.setInt(2, codigo); ResultSet result = preSt.executeQuery(); Cajero cajero = null; while(result.next()){ cajero = new Cajero( result.getInt(Cajero.CODIGO_DB), result.getString(Cajero.NOMBRE_DB), result.getString(Cajero.TRUNO_DB), result.getString(Cajero.DPI_DB), result.getString(Cajero.DIRECCION_DB), result.getString(Cajero.GENERO_DB), result.getString(Cajero.PASSWORD_DB) ); } return cajero; } public List<Cajero> todosCajeros() throws SQLException { PreparedStatement preSt = connection.prepareStatement(CAJEROS); preSt.setString(1, Gerente.LLAVE); ResultSet result = preSt.executeQuery(); List<Cajero> cajeros = new LinkedList<>(); while(result.next()){ cajeros.add(new Cajero( result.getInt(Cajero.CODIGO_DB), result.getString(Cajero.NOMBRE_DB), result.getString(Cajero.TRUNO_DB), result.getString(Cajero.DPI_DB), result.getString(Cajero.DIRECCION_DB), result.getString(Cajero.GENERO_DB), result.getString(Cajero.PASSWORD_DB) )); } return cajeros; } //usamos para verificar si esta en el horario definido private static final String inputFormat = "HH:mm"; private Date date; private Date dateCompareOne; private Date dateCompareTwo; SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US); // turno matutino (6:00 a 14:30 hrs) //vespertino (13:00 a 22:00 hrs). public boolean verificarRequisitos(int codigo) throws SQLException{ Cajero cajero = obtenerCajero(codigo); String turno = cajero.getTurno(); String compareStringOne = "13:00"; String compareStringTwo = "22:00"; if (turno.equalsIgnoreCase("MATUTINO")) { compareStringOne = "6:00"; compareStringTwo = "14:30"; return compareDates(compareStringOne,compareStringTwo); } return compareDates(compareStringOne,compareStringTwo); } //camparamos la hora private boolean compareDates(String compareStringOne, String compareStringTwo){ Calendar now = Calendar.getInstance(); int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); date = parseDate(hour + ":" + minute); //System.out.println(date.toString()); dateCompareOne = parseDate(compareStringOne); //System.out.println(dateCompareOne); dateCompareTwo = parseDate(compareStringTwo); //System.out.println(dateCompareTwo); if (dateCompareOne.before(date) && dateCompareTwo.after(date)) { return true; } return false; } //transformamos la hora en formato simpleDateFormat private Date parseDate(String date) { try { return inputParser.parse(date); } catch (java.text.ParseException e) { return new Date(0); } } }
224d26ec3c4bcf9892cc3c65a133de769d68cdc4
403feadd9fd2461d1bad643cf377bed2f8fb0920
/Cursor.java
b4c31ad05ddf41f84d34c0bb1c2e45397ca81036
[]
no_license
Luis-3M/TextEditor
a72baa942f84a3e9acef71424e05c0552bea7db1
e78fe46b04061d63c26770903234044b1f330044
refs/heads/master
2020-12-31T06:47:02.043470
2017-03-29T16:40:24
2017-03-29T16:40:24
86,604,157
2
0
null
null
null
null
UTF-8
Java
false
false
428
java
package TextEditor; public class Cursor { private int x; private int y; Cursor() { x = y = 0; } /** * @return the x */ public int getX() { return x; } /** * @param x * the x to set */ public void setX(int x) { this.x = x; } /** * @return the y */ public int getY() { return y; } /** * @param y * the y to set */ public void setY(int y) { this.y = y; } }
1f2849af202762d894c9e553bdcbac4daf3c3fb9
f4d12123d6d171954e0c68815370dac9dc7bd7ea
/src/main/java/utilities/ScreenshtClass.java
0de37175c4aa6706a0f3f3375554a403bd99cda5
[]
no_license
satya-sirisha/Hybrid-Framework
02b0e49e19d4d9df504f9aa7aa6114f4bb4cf70c
b5443f2caf6a4421336120f9a3c539c7e1960f25
refs/heads/master
2020-03-19T02:46:52.112444
2018-06-01T02:52:35
2018-06-01T02:52:35
135,660,022
0
0
null
null
null
null
UTF-8
Java
false
false
1,091
java
package utilities; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import commonmethods.CommonMeths; import constantvalues.ConstantClassValues; import constantvalues.LocatorValues; public class ScreenshtClass { public static void takeEvidence(TakesScreenshot ts ,String picname) { try { SimpleDateFormat sf = new SimpleDateFormat("dd#MM#yy hh#mm#ss"); Date d = new Date(); File filedestination =new File(ConstantClassValues.Screenshtpath+picname+sf.format(d)+".jpeg" ); File filesrc = ts.getScreenshotAs(OutputType.FILE); FileUtils.moveFile(filesrc, filedestination); } catch (IOException e) { e.printStackTrace(); System.out.println("Screenshot is not working"); } } } //public static void main(String[] args) throws IOException { // takeEvidence((TakesScreenshot)CommonMeths.driver, LocatorValues.individual_LocatorValue); // //
75b2aadb6e671328eb2510a3e42c774d21ed86c1
ef8e918e86f50ba2d54b137e6e07430b5f24f7c6
/mafia-srv-demo/src/main/java/com/mafia/srv/demo/algorithm/hard/LargestAssociation.java
8aeaf78bc308dba2f5afd0e015a48d1241a24aec
[ "MIT" ]
permissive
slking1987/mafia
32bd264bb4ded5e7ee753ba9ecae82af0d89ddcf
f8a130fb63b6b299f5dbd7d5a5d5559583f07789
refs/heads/master
2021-01-22T19:59:22.368259
2017-07-07T07:36:19
2017-07-07T07:36:19
85,266,886
6
1
null
null
null
null
UTF-8
Java
false
false
2,383
java
package com.mafia.srv.demo.algorithm.hard; import java.util.*; /** * Created by shaolin on 2017/6/6. */ public class LargestAssociation { /** * 简单推荐算法, 购买过相同商品的客户的兴趣一致 * A客户与B客户都购买过商品item1, 则认为A客户也会对B客户购买的商品item4, item5感兴趣 * @param itemMatrix String[][] 各个客户购买商品的二维数组 * @return String[] 最大关联商品数组 * eg. [["item1","item2"],["item2","item3"],["item2","item4","item5"]] => ["item1","item2","item3","item4","item5"] * eg. [["item1","item2"],["item3","item4"],["item4","item5"]] => ["item3","item4","item5"] * eg. [["item1","item2"],["item3","item4"],["item5"]] => ["item1","item2"] */ public String[] solution2(String[][] itemMatrix) { // check // 获取所有关联组合 // 排序获得最大关联组合 return null; } private String[] getAsso(String[] itemArr, String[][] itemMatrix) { return null; } private String[] getAssoEasy(String[] itemArr, String[][] itemMatrix) { return null; } public String[] solution(String[][] itemAssociation) { // check if(itemAssociation == null || itemAssociation.length == 0) { return null; } String[] result = null; Map<Integer, Set<String>> assoMap = new LinkedHashMap<>(); for(int i = 0; i < itemAssociation.length; i ++) { Set<String> tempSet = new HashSet<>(); for(String tempItem : itemAssociation[i]) { tempSet.add(tempItem); } assoMap.put(i, tempSet); } Map<Integer, Set<String>> newAssoMap = new LinkedHashMap<>(); Map<Integer, Integer> keyMap = new HashMap<>(); for(Map.Entry<Integer, Set<String>> entry : assoMap.entrySet()) { Set<String> tempItemSet = new HashSet<>(); Set<String> itemSet = entry.getValue(); for(String item : itemSet) { for(Set<String> tempSet : assoMap.values()) { if(tempSet.contains(item)) tempItemSet.addAll(tempSet); } } newAssoMap.put(entry.getKey(), tempItemSet); keyMap.put(entry.getKey(), tempItemSet.size()); } return result; } }
4a3021fb8305fd2daeeb1a1fc656c3375c9e7c2c
afcc736dcb3bb07ac8f75e1c1246bd2953e91a70
/mall-coupon/src/main/java/com/sour/mall/coupon/service/ISpuBoundsService.java
677682d24c314a255597fd3c9b39c1ebecbcaeb7
[]
no_license
Sourlun/mail-springCloud
2b94ad5b1cb384f349c43fa5c1c71e36d5bf7555
6770cf3c93e50f2ba799ad5df7f9e77b7a0fa38a
refs/heads/master
2023-04-18T14:10:53.724733
2021-05-09T12:06:24
2021-05-09T12:06:24
339,382,321
0
0
null
null
null
null
UTF-8
Java
false
false
460
java
package com.sour.mall.coupon.service; import com.baomidou.mybatisplus.extension.service.IService; import com.sour.mall.common.utils.PageUtils; import com.sour.mall.coupon.entity.SpuBoundsEntity; import java.util.Map; /** * 商品spu积分设置 * * @author SourLun * @email [email protected] * @date 2021-02-17 21:39:23 */ public interface ISpuBoundsService extends IService<SpuBoundsEntity> { PageUtils queryPage(Map<String, Object> params); }
d9ba7735c7e813d438fcc0cf7e8c90124fbe7915
1cbfecff8a707dba24ad0e63ab5e344fc951a0ed
/shooter-core/src/com/mygdx/shooter/PlayerHome.java
922fe86d5d72d0357ba5b3edbd05dcef3ebe93c3
[]
no_license
laurencecharles/shooter_core
8379dd3cc8ce11914bbfb06f9d2533ee9bf64e5c
466f3ee59de66f7762492a95663036b9be0eca6e
refs/heads/master
2020-05-18T10:18:54.101498
2015-02-01T18:34:51
2015-02-01T18:34:51
29,793,573
0
0
null
null
null
null
UTF-8
Java
false
false
9,511
java
package com.mygdx.shooter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Scaling; public class PlayerHome extends CustomScreen { private FreeTypeFontGenerator generator = null; private Skin skin2 = null; private Skin skin; private Skin textboxskin = null; private TextureAtlas atlas = null; private Stage stage; private Stage temp; private Table table; private Table mainTable; private Label titleLabel; private Label nameLabel; private TextField nameField; private TextButton enter; private TextButton back; private BitmapFont button = null; private BitmapFont tLabel = null; private BitmapFont fLabel = null; private BitmapFont field = null; private Texture uiButton =null; private Texture uiCursor =null; private OrthographicCamera camera; @SuppressWarnings("deprecation") //suppresses deprecation warnings generated by "generateFont()" public PlayerHome() { setName("Player_HOME"); //Sets the current activity name //Implements the device's Back button functionality on this activity temp = new Stage(){ @Override public boolean keyDown(int keyCode) { if (keyCode == Keys.BACK) { ScreenManager.getInstance().show("MAIN_MENU", Screens.MAIN_MENU); } return super.keyDown(keyCode); } }; setStage(temp); stage = getStage(); //Configures camera settings camera = new OrthographicCamera(); camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); generator = ResourceManager.getGenerator(); //fetches font generator atlas = ResourceManager.getAtlas(); //fetches textureAtlas skin = ResourceManager.getDefaultSkin(); //fetches default skin skin2 = ResourceManager.getCustomSkin(); //fetches customized skin //Generates font size for objects containing text button = generator.generateFont(Gdx.graphics.getWidth()/24); tLabel = generator.generateFont(Gdx.graphics.getWidth()/10); fLabel = generator.generateFont(Gdx.graphics.getWidth()/25); field = generator.generateFont(Gdx.graphics.getWidth()/40); //Label style instantiations LabelStyle titleSkin = new LabelStyle(); LabelStyle formLabelSkin = new LabelStyle(); //Sets font size of various label styles titleSkin.font = tLabel; formLabelSkin.font = fLabel; //Configurations of text field style TextFieldStyle textfieldstyle = new TextFieldStyle(); textboxskin = new Skin(); uiButton = new Texture(Gdx.files.internal("ui/button.down.png")); uiCursor = new Texture(Gdx.files.internal("ui/cursor.png")); textboxskin.add("textfieldback", uiButton); textboxskin.add("cursor", uiCursor); textboxskin.add("font", field); textfieldstyle.background= textboxskin.getDrawable("textfieldback"); textfieldstyle.font=textboxskin.getFont("font"); textfieldstyle.fontColor= com.badlogic.gdx.graphics.Color.WHITE; textfieldstyle.cursor= textboxskin.getDrawable("cursor"); //Configurations of text button style TextButtonStyle textButtonStyle = new TextButtonStyle(); textButtonStyle.up = skin2.getDrawable("button.up"); textButtonStyle.down = skin2.getDrawable("button.down"); textButtonStyle.pressedOffsetX = 3; textButtonStyle.pressedOffsetX = -3; textButtonStyle.font= button; titleLabel = new Label("Player Login", titleSkin); //title label instantiation nameLabel = new Label("Username", formLabelSkin); nameField = new TextField ("", textfieldstyle); Gdx.input.setInputProcessor(stage); //attaches input process to current activity //Instantiation and configuration of "Enter" button enter = new TextButton("OK", textButtonStyle); enter.addListener(new ChangeListener() { public void changed (ChangeEvent event, Actor actor) { DataManager.setUsername(nameField.getText()); //sets the current player name String sID = DatabaseManager.getLastSessionID(); //fetches the current active session if (fieldsCompleted()==true){ //if all field have data //if player is scheduled to participate in current active session if (DatabaseManager.validPlayer(nameField.getText(), sID) == true && DatabaseManager.alreadyPlayed(nameField.getText(), sID) == false){ ScreenManager.getInstance().show("PLAYER_PROFILE", Screens.PLAYER_PROFILE); //switch to "Player Profile" activity } else if (DatabaseManager.validPlayer(nameField.getText(), sID) == false){ //if player is not on schedule, a dialog box provides the appropriate feedback new Dialog("", skin, "dialog") { protected void result (Object object) { } }.text("PlayerID invalid").button("Ok", true).show(stage); } else if (DatabaseManager.alreadyPlayed(nameField.getText(), sID) == true){ //if players has already particpated, a dialog box provides the appropriate feedback new Dialog("", skin, "dialog") { protected void result (Object object) { } }.text("Player assessment already completed").button("Ok", true).show(stage); } } else{ new Dialog("", skin, "dialog") { //if all fields are not completed, a dialog box provides the appropriate feedback protected void result (Object object) { } }.text("Please complete blank fields").button("Ok", true).show(stage); } } }); //Instantiation and configuration of "Back" button back = new TextButton("Back", textButtonStyle); back.addListener(new ChangeListener() { public void changed (ChangeEvent event, Actor actor) { ScreenManager.getInstance().show("MAIN_MENU", Screens.MAIN_MENU); //switch to "Main Menu" activity } }); //Instantiates tables and attaches labels, text fields and buttons mainTable = new Table(); mainTable.add(titleLabel); mainTable.row(); table = new Table(); table.add(nameLabel).align(Align.left).spaceRight(Gdx.graphics.getWidth()/75).spaceBottom(Gdx.graphics.getWidth()/50); table.add(nameField).width(nameLabel.getWidth()*(float)1.5).spaceBottom(Gdx.graphics.getWidth()/50); table.row(); table.add(enter).spaceTop(Gdx.graphics.getWidth()/50).spaceRight(Gdx.graphics.getWidth()/25); table.add(back).spaceTop(Gdx.graphics.getWidth()/50); mainTable.add(table); mainTable.pack(); //Centers the main table within the screen int xPos = (int) ( (Gdx.graphics.getWidth()/2) - (mainTable.getPrefWidth() / 2 ) ); int yPos = (int) ( (Gdx.graphics.getHeight()/2) - (mainTable.getPrefHeight() / 2 ) ); mainTable.setPosition(xPos, yPos); stage.addActor(ResourceManager.getBackImg()); //attaches background image to stage stage.addActor(mainTable); //attaches main table to the activity } //Returns false if any field is left empty public boolean fieldsCompleted(){ if (nameField.getText().equals("") ){ return false; } return true; } @Override public void render(float delta) { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); Table.drawDebug(stage); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void show() {} @Override //Disposes resources to mitigate memory leaks public void hide() { button.dispose(); tLabel.dispose(); fLabel.dispose(); textboxskin.dispose(); stage.dispose(); } @Override public void pause() {} @Override public void resume() {} @Override public void dispose() {} }
a4b3e9a83000eacb5c782d9a15deafb7a9844fc9
8707888cc23d6d6506113bceaf74b163233fd816
/data/src/main/java/com/suxiunet/data/factory/ResponseConverterFactory.java
c1a86f5c60974217382a56bc0564dca3b4d1b1a6
[]
no_license
chenzhi1217/SuxiuProject
bff52a9337c872fa43c77c5134e9093251c604a0
3cc71f58d93cc882a48bbecc43974f69157e1342
refs/heads/master
2021-09-19T09:10:17.623382
2018-07-26T03:32:22
2018-07-26T03:32:22
116,144,745
2
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package com.suxiunet.data.factory; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.suxiunet.data.converter.ResponseConverter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Retrofit; /** * author : chenzhi * time : 2018/02/02 * desc : 相应体转换器 */ public class ResponseConverterFactory extends Converter.Factory { public static ResponseConverterFactory create(Gson gson) { return new ResponseConverterFactory(gson); } private final Gson gson; private ResponseConverterFactory(Gson gson) { this.gson = gson; } @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); return new ResponseConverter<>(gson, adapter, type); } }
52a69838d9369084886d1cd86e84d3b2ffb399ec
3ef928b235d6efeca10af608ffdcdeca4d37bf31
/src/test/java/jaxb/test/Bar.java
31cb8d9ca23789c435d85547256f56ccfc50f2e2
[]
no_license
franciscophilip/jaxb-payload-poc
03f841e0dea00afc5ef47112ebf045b15365397a
c9ffa34b37cf858266ab7976f07a73664904e76e
refs/heads/master
2021-01-01T05:49:07.375502
2015-07-24T17:39:50
2015-07-24T17:39:50
39,615,950
0
0
null
null
null
null
UTF-8
Java
false
false
41
java
package jaxb.test; public class Bar { }
5c5dbe91d20ee1e5cabfcecf909c946aada7d0ba
276f2b0d78b06d0f58258f41138e7a19ffbccf00
/src/org/javacore/type/NumericType.java
aa164e258666b18524e3a28d14a4dcf0a0a467bf
[]
no_license
orb1t/ByteCodeSpecification
887c39935099a1174ab8f2716f18d63fcb4c653f
d5dc2bf7cc96c02e80e33f6170936d909f5a77e1
refs/heads/master
2020-03-18T13:47:22.964691
2017-09-18T21:25:16
2017-09-18T21:25:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
91
java
package org.javacore.type; /** */ public interface NumericType extends PrimitiveType { }
f022d3bc74ff921bcf15ff24f071b62587372cd2
5513bf376916dfcfb9295da6f1bb542dc0e4f19f
/src/com/company/Matrix/MatrixMultiplication.java
4f2f49bbc5931a5e121544ae02808b397cf02d1d
[]
no_license
srana6/Code_Bank_Practice_Questions
cd4874adbc50b8e8a9c81770657861403a3f398c
43570e52f81fd9fe59354420420b7232b1efa908
refs/heads/master
2020-12-13T20:50:31.342474
2017-11-30T15:52:28
2017-11-30T15:52:28
95,496,749
0
0
null
null
null
null
UTF-8
Java
false
false
1,009
java
package com.company.Matrix; import java.util.Arrays; /** * Created by macbook on 4/7/17. */ public class MatrixMultiplication { private int [][] resultMatrix = new int[2][3]; public void matrixMultiply(int[][] matrix1, int[][] matrix2){ for(int i=0;i<matrix1.length;i++){ for(int j=0;j<3;j++){ for(int k=0;k<2;k++){ resultMatrix[i][j] = resultMatrix[i][j] + (matrix1[i][k] * matrix2[k][j]); } } } for(int i=0;i<resultMatrix.length;i++){ for(int j=0;j<resultMatrix[0].length;j++){ System.out.println(resultMatrix[i][j]); } } } public static void main(String[] args){ int x[][] ={ { 1, 2 }, { 3, 4 } }; int y[][] ={ { 1, 2, 3 }, { 4, 5, 6 } }; MatrixMultiplication mm = new MatrixMultiplication(); mm.matrixMultiply(x,y); } }
8170d5821d8b58372a42b5d1446ecb7257a26dea
1a843aacf5dcda8cae2f87c2526c233f2a105af6
/dnnorthwind-server/src/main/java/com/dncomponents/northwind/model/Employee.java
350990ba65ec268e7d7649f599ad357673f4186f
[]
no_license
RaulPampliegaMayoral/dnnorthwind
27b52fa8abbedcd51a211683818a04e5a8d48cc2
8b24f5d742669d8295067b2c1e54d98210a8aaa1
refs/heads/master
2023-03-21T02:23:05.232015
2021-03-21T18:28:15
2021-03-21T18:28:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,698
java
package com.dncomponents.northwind.model; import com.dncomponents.northwind.dto.EmployeeDTO; import org.modelmapper.ModelMapper; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer employee_id; private String last_name; private String first_name; private String title; private String title_of_courtesy; private Date birth_date; private Date hire_date; private String address; private String city; private String region; private String postal_code; private String country; private String home_phone; private String extension; private String photo; private Integer reports_to; public static void main(String[] args) { EmployeeDTO dto = new EmployeeDTO(); Employee employee = new Employee(); dto.setBirth_date(new Date()); ModelMapper modelMapper = new ModelMapper(); modelMapper.map(dto, employee); System.out.println(dto.getBirth_date().equals(employee.birth_date)); int i = 0; i++; } public Integer getEmployee_id() { return employee_id; } public void setEmployee_id(Integer employee_id) { this.employee_id = employee_id; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitle_of_courtesy() { return title_of_courtesy; } public void setTitle_of_courtesy(String title_of_courtesy) { this.title_of_courtesy = title_of_courtesy; } public Date getBirth_date() { return birth_date; } public void setBirth_date(Date birth_date) { this.birth_date = birth_date; } public Date getHire_date() { return hire_date; } public void setHire_date(Date hire_date) { this.hire_date = hire_date; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getPostal_code() { return postal_code; } public void setPostal_code(String postal_code) { this.postal_code = postal_code; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getHome_phone() { return home_phone; } public void setHome_phone(String home_phone) { this.home_phone = home_phone; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public Integer getReports_to() { return reports_to; } public void setReports_to(Integer reports_to) { this.reports_to = reports_to; } }
cda4c985104b4cb2eb03768c1a87206eb61310af
f675d96714a999682f1883af2c4b18f8f41f0733
/sns-web/src/main/java/com/sky/sns/web/action/UserAction.java
5e09fbde63d772a1bd6aa8bb66cf62ab0bd3bf7c
[]
no_license
ejunjsh/sns
3d9382e4c7eea75bfd4990282b09fc566be9cc4e
a18c4640ca46ce8cce72ba52ed051115f7e4165e
refs/heads/master
2020-03-28T23:57:29.270146
2014-02-23T12:19:20
2014-02-23T12:19:20
107,090,063
1
0
null
null
null
null
UTF-8
Java
false
false
17,778
java
package com.sky.sns.web.action; import java.util.List; import com.sky.sns.mybatis.entity.*; import com.sky.sns.mybatis.iService.*; import com.sky.sns.web.utility.ImageUtils; import com.sky.sns.web.utility.WebContext; public class UserAction extends BasePageAction { /** * */ private static final long serialVersionUID = 2618506034475021502L; private IUserService userService; private IAnswerService answerService; private IQuestionService questionService; private IGroupPostService groupPostService; private IActivityService activityService; private IGroupService groupService; private IBlogService blogService; private IBlogCategoryService blogCategoryService; private INoticeService noticeService; private ITagService tagService; private IMessageService messageService; private IAlbumService albumService; private IPhotoService photoService; private User modifiedUser; private int errorIndex; private User spaceUser; private List<Answer> myAnswers; private List<Question> myQuestions; private List<GroupPost> myPosts; private List<Activity> myActivities; private List<Group> myGroups; private List<Blog> myBlogs; private List<BlogCategory> myBlogCategories; private List<Album> myAlbums; private List<Photo> myPhotos; private long categoryId=-1; private List<User> sideFollowingUsers; private List<User> sideFollowedUsers; private List<User> followingUsers; private List<User> followedUsers; private String curPage; private List<Notice> notices; private List<Tag> myTags; private User toUser; private Message message; private List<Message> messages; private Album album; private String tmpUrl; private void initialize() { this.spaceUser=userService.getUserDetailById(spaceUser.getId(),curUser==null?0:curUser.getId()); this.sideFollowingUsers=userService.getFollowing(spaceUser.getId(), 0, 0, 8); this.sideFollowedUsers=userService.getFollowed(spaceUser.getId(), 0, 0, 8); } public String notice() throws Exception { if(curUser!=null) { notices=noticeService.getNoticeByUserId(curUser.getId(), (int)getPageStart(), pageSize); recordCount=noticeService.countNoticeByUserId(curUser.getId()); noticeService.updateNoticeToRead(curUser.getId()); } return "notice"; } public String message() throws Exception { if(curUser!=null) { messages=messageService.getMessageByGroup(curUser.getId(), (int)getPageStart(), pageSize); recordCount=messageService.countMessageByGroup(curUser.getId()); } return "message"; } public String sendMessage() throws Exception { if(curUser!=null) { if(toUser!=null) { if(toUser.getId()>0) { toUser=userService.getUserById(toUser.getId()); } else { if(toUser.getNickName()!=null&&!toUser.getNickName().isEmpty()) { toUser=userService.getUserByNickName(toUser.getNickName()); } else { toUser=null; } } if(toUser!=null) { messages=messageService.getMessageByUserId(curUser.getId(),toUser.getId(), (int)getPageStart(), pageSize); recordCount= messageService.countMessageByUserId(curUser.getId(),toUser.getId()); messageService.updateMessageToRead(toUser.getId(), curUser.getId()); } } if(isPost()) { if(toUser!=null) { if(toUser.getId()!=curUser.getId()) { if(message!=null) { if(!message.getContent().isEmpty()) { message.setFromUserId(curUser.getId()); String group=messageService.getGroupByUserId(curUser.getId(), toUser.getId()); if(group!=null&&!group.isEmpty()) { message.setGroup(group); } else { message.setGroup(java.util.UUID.randomUUID().toString()); } message.setToUserId(toUser.getId()); messageService.insertMessage(message); setPrompt("发送成功"); return "goToSendMessage"; } else { setPrompt("请输入内容"); } } } else { setPrompt("不能发给自己哦"); } } else { setPrompt("昵称不存在"); } } } return "sendMessage"; } public String answer() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myAnswers=answerService.getAnswersByUserId(spaceUser.getId(), (int)getPageStart(), pageSize); } curPage="answer"; return curPage; } public String question() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myQuestions=questionService.getQuestionByUserId(spaceUser.getId(), (int)getPageStart(), pageSize); } curPage="question"; return curPage; } public String post() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myPosts=groupPostService.getGroupPostByUserId(spaceUser.getId(), pageSize,(int)getPageStart()); } curPage="post"; return curPage; } public String activity() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myActivities=activityService.getActivityByUserId(spaceUser.getId(), (int)getPageStart(), pageSize); } curPage="activity"; return curPage; } public String blog() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myBlogs=blogService.getMyBlogByCategoryId(spaceUser.getId(), categoryId==0?null:categoryId, (int)getPageStart(), pageSize); recordCount=blogService.countMyBlogByCategoryId(spaceUser.getId(), categoryId==0?null:categoryId); myBlogCategories=blogCategoryService.getBlogCategoryByUserId(spaceUser.getId()); } curPage="blog"; return curPage; } public String album() throws Exception { if(album==null||album.getId()==0) { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myAlbums=albumService.getAlbumsByUserId(spaceUser.getId(), (int)getPageStart(), pageSize); recordCount=albumService.countAlbumsByUserId(spaceUser.getId()); } curPage="albumList"; } else { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); album=albumService.getAlbumById(album.getId()); myPhotos=photoService.getPhotosByAlbumId(album.getId(),(int)getPageStart(), pageSize); recordCount=photoService.countPhotosByAlbumId(album.getId()); } curPage="albumDetail"; } return curPage; } public String following() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); followingUsers=userService.getFollowing(spaceUser.getId(), curUser==null?0:curUser.getId(), (int)getPageStart(), pageSize); } curPage="following"; return curPage; } public String follower() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); followedUsers=userService.getFollowed(spaceUser.getId(), curUser==null?0:curUser.getId(), (int)getPageStart(), pageSize); } curPage="follower"; return curPage; } public String group() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myGroups=groupService.getMyJoinedGroups(spaceUser.getId()); } curPage="group"; return curPage; } public String tag() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myTags=tagService.getMyTags(spaceUser.getId(), curUser==null?0:curUser.getId(), (int)getPageStart(), pageSize); } curPage="tag"; return curPage; } public void setAnswerService(IAnswerService answerService) { this.answerService = answerService; } public String avatar() throws Exception { if(isPost()) { if(tmpUrl!=null&&!tmpUrl.isEmpty()&&curUser!=null) { User savedUser=userService.getUserById(curUser.getId()); String url=ImageUtils.SaveToAvatar(tmpUrl, "avatar/"+curUser.getId(),curUser.getIsWaterMark()==1); List<Album> albums=albumService.getAlbumsByUserId(curUser.getId(),0, Integer.MAX_VALUE); Album album=null; for(Album a : albums) { if(a.getIsFixed()==1&&a.getTitle().equalsIgnoreCase("头像相册")) { album=a; break; } } if(album==null) { album=new Album(); album.setDescription("头像相册"); album.setIsFixed(1); album.setTitle("头像相册"); album.setUserId(curUser.getId()); albumService.insertAlbum(album); } Photo photo=new Photo(); photo.setAlbumId(album.getId()); photo.setDescription("头像"); photo.setTitle("头像"); photo.setUrl(url); photo.setUserId(curUser.getId()); photoService.insertPhoto(photo); savedUser.setPhotoId(photo.getId()); userService.updateUser(savedUser); //refresh session WebContext.removeCurrentUser(request); WebContext.setCurrentUser(request, savedUser); setPrompt("保存成功"); } } modifiedUser=userService.getUserById(curUser.getId()); return "avatar"; } public String index() throws Exception { if(spaceUser!=null&&spaceUser.getId()>0) { initialize(); myActivities=activityService.getActivityByUserId(spaceUser.getId(),0, 5); myBlogs=blogService.getMyBlogByCategoryId(spaceUser.getId(),(long) -1, 0, 5); } curPage="index"; return curPage; } public String profile() throws Exception { if(isPost()) { if(modifiedUser!=null&&curUser!=null) { if(modifiedUser.getNickName()==null||modifiedUser.getNickName().isEmpty()) { errorIndex=2; } else if(userService.getUserByNickNameExceptCurUser(modifiedUser.getNickName(),curUser.getId())!=null) { errorIndex=1; } else if(modifiedUser.getTitle()!=null&&!modifiedUser.getTitle().isEmpty()&&modifiedUser.getTitle().length()>100) { errorIndex=3; } else if(modifiedUser.getBlogUrl()!=null&&!modifiedUser.getBlogUrl().isEmpty()&&modifiedUser.getBlogUrl().length()>200) { errorIndex=4; } else if(modifiedUser.getDescription()!=null&&!modifiedUser.getDescription().isEmpty()&&modifiedUser.getDescription().length()>650) { errorIndex=5; } if(errorIndex>0) { return "profile"; } else { User savedUser=userService.getUserById(curUser.getId()); savedUser.setBlogUrl(modifiedUser.getBlogUrl()); savedUser.setDescription(modifiedUser.getDescription()); savedUser.setGender(modifiedUser.getGender()); savedUser.setIsWaterMark(modifiedUser.getIsWaterMark()); savedUser.setNickName(modifiedUser.getNickName()); savedUser.setTitle(modifiedUser.getTitle()); userService.updateUser(savedUser); //refresh session WebContext.removeCurrentUser(request); WebContext.setCurrentUser(request, savedUser); curUser=savedUser; setPrompt("保存成功"); } } } modifiedUser=userService.getUserById(curUser.getId()); return "profile"; } public String redirect() throws Exception { if(spaceUser!=null) { User user=userService.getUserByNickName(spaceUser.getNickName()); if(user!=null) { spaceUser.setId(user.getId()); } } return "redirect"; } public void setUserService(IUserService userService) { this.userService = userService; } public User getModifiedUser() { return modifiedUser; } public void setModifiedUser(User modifiedUser) { this.modifiedUser = modifiedUser; } public int getErrorIndex() { return errorIndex; } public User getSpaceUser() { return spaceUser; } public void setSpaceUser(User spaceUser) { this.spaceUser = spaceUser; } public List<Answer> getMyAnswers() { return myAnswers; } public void setMyAnswers(List<Answer> myAnswers) { this.myAnswers = myAnswers; } public List<User> getSideFollowingUsers() { return sideFollowingUsers; } public void setSideFollowingUsers(List<User> sideFollowingUsers) { this.sideFollowingUsers = sideFollowingUsers; } public List<User> getSideFollowedUsers() { return sideFollowedUsers; } public void setSideFollowedUsers(List<User> sideFollowedUsers) { this.sideFollowedUsers = sideFollowedUsers; } public List<User> getFollowingUsers() { return followingUsers; } public void setFollowingUsers(List<User> followingUsers) { this.followingUsers = followingUsers; } public List<User> getFollowedUsers() { return followedUsers; } public void setFollowedUsers(List<User> followedUsers) { this.followedUsers = followedUsers; } public List<Question> getMyQuestions() { return myQuestions; } public void setMyQuestions(List<Question> myQuestions) { this.myQuestions = myQuestions; } public void setQuestionService(IQuestionService questionService) { this.questionService = questionService; } public void setGroupPostService(IGroupPostService groupPostService) { this.groupPostService = groupPostService; } public List<GroupPost> getMyPosts() { return myPosts; } public void setMyPosts(List<GroupPost> myPosts) { this.myPosts = myPosts; } public List<Activity> getMyActivities() { return myActivities; } public void setMyActivities(List<Activity> myActivities) { this.myActivities = myActivities; } public void setActivityService(IActivityService activityService) { this.activityService = activityService; } public List<Group> getMyGroups() { return myGroups; } public void setMyGroups(List<Group> myGroups) { this.myGroups = myGroups; } public void setGroupService(IGroupService groupService) { this.groupService = groupService; } public List<Blog> getMyBlogs() { return myBlogs; } public void setMyBlogs(List<Blog> myBlogs) { this.myBlogs = myBlogs; } public void setBlogService(IBlogService blogService) { this.blogService = blogService; } public long getCategoryId() { return categoryId; } public void setCategoryId(long categoryId) { this.categoryId = categoryId; } public List<BlogCategory> getMyBlogCategories() { return myBlogCategories; } public void setMyBlogCategories(List<BlogCategory> myBlogCategories) { this.myBlogCategories = myBlogCategories; } public void setBlogCategoryService(IBlogCategoryService blogCategoryService) { this.blogCategoryService = blogCategoryService; } public String getCurPage() { return curPage; } public void setCurPage(String curPage) { this.curPage = curPage; } public List<Notice> getNotices() { return notices; } public void setNotices(List<Notice> notices) { this.notices = notices; } public void setNoticeService(INoticeService noticeService) { this.noticeService = noticeService; } public void setTagService(ITagService tagService) { this.tagService = tagService; } public List<Tag> getMyTags() { return myTags; } public void setMyTags(List<Tag> tags) { this.myTags = tags; } public void setMessageService(IMessageService messageService) { this.messageService = messageService; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } public User getToUser() { return toUser; } public void setToUser(User toUser) { this.toUser = toUser; } public void setAlbumService(IAlbumService albumService) { this.albumService = albumService; } public void setPhotoService(IPhotoService photoService) { this.photoService = photoService; } public List<Album> getMyAlbums() { return myAlbums; } public void setMyAlbums(List<Album> myAlbums) { this.myAlbums = myAlbums; } public List<Photo> getMyPhotos() { return myPhotos; } public void setMyPhotos(List<Photo> myPhotos) { this.myPhotos = myPhotos; } public Album getAlbum() { return album; } public void setAlbum(Album album) { this.album = album; } public String getTmpUrl() { return tmpUrl; } public void setTmpUrl(String tmpUrl) { this.tmpUrl = tmpUrl; } }
[ "shaojunjie@shaojunjie-Rev-1-0" ]
shaojunjie@shaojunjie-Rev-1-0
f21298e2a065c5f68018cb7e92ce3a287d39e0de
d544ddc4c2553f0a180aea02952a99a874203950
/wood-the-gathering-master/src/wood/strategy/WoodPlayerStrategy.java
d321df940a4115fd527583e8c29bbfb399147fa8
[]
no_license
adamac2/big-wood-strategy
17aac19915466bde04d9e59c2e85930b29c878c8
20676b877a9baef94c9bd556168e96ddc0cc187c
refs/heads/master
2022-12-12T07:40:41.991811
2019-03-03T22:45:03
2019-03-03T22:45:03
173,530,970
1
0
null
2022-12-08T01:39:34
2019-03-03T04:33:58
Java
UTF-8
Java
false
false
2,930
java
package wood.strategy; import wood.game.TurnAction; import wood.item.InventoryItem; import java.awt.*; import java.util.Random; public interface WoodPlayerStrategy { /** * Called at the start of every round * * @param boardSize The length and width of the square game board * @param maxInventorySize The maximum number of items that your player can carry at one time * @param winningScore The first player to reach this score wins the round * @param startTileLocation A Point representing your starting location in (x, y) coordinates * (0, 0) is the bottom left and (boardSize - 1, boardSize - 1) is the top right * @param isRedPlayer True if this strategy is the red player, false otherwise * @param random A random number generator, if your strategy needs random numbers you should use this. */ void initialize(int boardSize, int maxInventorySize, int winningScore, Point startTileLocation, boolean isRedPlayer, Random random); /** * The main part of your strategy, this method returns what action your player should do on this turn * * @param boardView A PlayerBoardView object representing all the information about the board and the other player * that your strategy is allowed to access * @param isRedTurn For use when two players attempt to move to the same spot on the same turn * If true: The red player will move to the spot, and the blue player will do nothing * If false: The blue player will move to the spot, and the red player will do nothing * @return The TurnAction that this strategy wants to perform on this game turn */ TurnAction getTurnAction(PlayerBoardView boardView, boolean isRedTurn); /** * Called when the player receives an item from performing a TurnAction that gives an item. * At the moment this is either picking up a seed or chopping wood * * @param itemReceived The item received from the player's TurnAction on their last turn */ void receiveItem(InventoryItem itemReceived); /** * Gets the name of this strategy. The amount of characters that can actually be displayed on a screen varies, * although by default at screen size 750 it's about 16-20 characters depending on character size * * @return The name of your strategy for use in the competition and rendering the scoreboard on the GUI */ String getName(); /** * Called at the end of every round to let players reset, and tell them how they did if the strategy does not * track that for itself * * @param pointsScored The total number of points this strategy scored * @param opponentPointsScored The total number of points the opponent's strategy scored */ void endRound(int pointsScored, int opponentPointsScored); }
cb36d0236e2e89f69abebf01096e9e9c9f4b7abe
3a63f53a7e527fc47a1eaeeba05dec5763400e78
/Tab/src/main/java/tab/App.java
548e9692579e9fd1721e2c00010d04052a9fbb26
[]
no_license
Check-8/Pub
9a4535c9cdb9e7ac0397c245d0705e001b79b48d
84d83fe3fc363c2a803b617e6e29be5826811a2d
refs/heads/master
2020-06-22T03:19:33.072925
2016-12-14T20:25:04
2016-12-14T20:25:04
74,758,239
0
0
null
null
null
null
UTF-8
Java
false
false
882
java
package tab; import javax.annotation.PostConstruct; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.stereotype.Component; @ComponentScan @EnableAutoConfiguration @EnableDiscoveryClient @EnableCircuitBreaker @Component @ImportResource("context.xml") @EnableScheduling public class App { public App() { } @PostConstruct public void init() { } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
7c4169563ab9b67f5555894dc3429bdfd87abc01
5c41afe41f647980ff7f7e48d5995a503e214124
/1.JavaSyntax/src/com/javarush/task/task09/task0916/Solution.java
f90d565bc4756fa9e02cbc1a446c934ce8629957
[]
no_license
darkpradoJava/JavaRushTasks
a56b27a30ed4f426a93703cb30f35804e4576043
cc5e6534a4448ae7ed12ecf5fe99627acc3f8965
refs/heads/master
2020-04-27T11:26:21.707881
2019-05-24T06:08:13
2019-05-24T06:08:13
174,295,357
1
0
null
null
null
null
UTF-8
Java
false
false
1,036
java
package com.javarush.task.task09.task0916; import java.io.IOException; import java.rmi.RemoteException; /* Перехват checked-исключений */ public class Solution { public static void main(String[] args) { handleExceptions(new Solution()); } public static void handleExceptions(Solution obj) { try { obj.method1(); obj.method2(); obj.method3(); } catch (NoSuchFieldException e) { System.out.println(e.getClass().getSimpleName()); } catch (RemoteException e) { System.out.println(e.getClass().getSimpleName()); } catch (IOException e) { System.out.println(e.getClass().getSimpleName()); } } public void method1() throws IOException { throw new IOException(); } public void method2() throws NoSuchFieldException { throw new NoSuchFieldException(); } public void method3() throws RemoteException { throw new RemoteException(); } }
f20b30f8b0146c6f1db68367654f2e7daff0db5e
d2af0f9193fdf3877f944f3e1ab4a1bab339e97e
/lab05/OwnersPets/src/java/DAO/OwnerDAO.java
bdb3eb634b21be28e5e301c11d42962085a38710
[]
no_license
daryashumeyko/rps
ea35fc0dcb6f5fc8952ca9b274e4efea977ef6d2
7a6631491abe1c0156014dd2c76a6029b8a2fdd0
refs/heads/master
2022-07-31T16:55:32.585144
2019-12-16T20:05:27
2019-12-16T20:05:27
219,556,976
0
0
null
2022-06-21T02:10:22
2019-11-04T17:23:22
Java
UTF-8
Java
false
false
3,265
java
package DAO; import entities.*; import java.sql.*; import java.util.LinkedList; import java.util.List; public class OwnerDAO extends AbstractDAO <Integer, Owner>{ @Override public List<Owner> getAll() { List<Owner> list = new LinkedList<>(); PreparedStatement ps = getPrepareStatement("select * from Owner;"); try { ResultSet rs = ps.executeQuery(); while (rs.next()) { Owner owner = new Owner(); owner.setId(rs.getLong(1)); owner.setName(rs.getString(2)); owner.setAddress(rs.getString(3)); list.add(owner); } } catch (SQLException e) { e.printStackTrace(); } finally { closePrepareStatement(ps); } return list; } @Override public boolean create(Owner owner) { PreparedStatement ps = getPrepareStatement("insert into Owner (name, address) VALUES (?, ?);"); try { ps.setString(1, owner.getName()); ps.setString(2, owner.getAddress()); int result = ps.executeUpdate(); if (result > 0) return true; } catch (SQLException e) { e.printStackTrace(); } finally { closePrepareStatement(ps); } return false; } // @Override // public Pet getEntityById(Integer id) { // Pet pet = new Pet(); // PreparedStatement ps = getPrepareStatement("select * from Orders where id=?;"); // try { // ps.setInt(1, id); // ResultSet rs = ps.executeQuery(); // if (rs.next()) { // pet.setId(rs.getLong(1)); // pet.setName(rs.getString(2)); // //pet.setBirthDate(rs.getDate(3)); // pet.setType(rs.getString(4)); // pet.setPetOwnerId(rs.getLong(5)); // } // } catch (SQLException e) { // e.printStackTrace(); // } finally { // closePrepareStatement(ps); // } // return pet; // } // @Override // public boolean update(Orders orders) { // PreparedStatement ps = getPrepareStatement("update Orders set orderNumber=?, personId=?, totalPrice=? WHERE id=?;"); //try { // ps.setString(1, orders.getOrderNumber()); // ps.setInt(2, orders.getPersonId()); // ps.setString(3, orders.getTotalPrice()); // ps.setInt(4, orders.getId()); // int result = ps.executeUpdate(); // if (result>0) return true; // // } catch (SQLException e) { // e.printStackTrace(); // } finally { // closePrepareStatement(ps); // } // return false; // } //@Override //public boolean delete(Integer id) { // PreparedStatement ps = getPrepareStatement("delete from Orders where id = ?;"); // // try { // ps.setInt(1, id); // // int result = ps.executeUpdate(); // if (result > 0) return true; // // } catch (SQLException e) { // e.printStackTrace(); // } finally { // closePrepareStatement(ps); // } // return false; // } }
1a5240e0e58f7bb187e9ea202a926fb89af11303
15c7c61d2cb11bed7ee9830ab5d040e9cc7d9529
/scr/com/servlet/ConveyEditUserServlet.java
4b72cb9f9c34076ba41467cb0ac3dd2be81cc3c9
[]
no_license
yueeezhang/ConferenceManager
e3652529644a21e7a71cece4e5d9cb6c644c0122
87dadeb48dafdcba31147b23ef7fe44941c72e64
refs/heads/master
2020-07-11T00:04:25.550134
2019-09-30T20:09:12
2019-09-30T20:09:12
204,405,417
0
0
null
null
null
null
UTF-8
Java
false
false
2,219
java
package com.servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import Conference.ApplyDetailAttr; import Conference.ConferenceAttr; import Factor.AdministratorFactorImp; import Person.UserAttr; /** * Servlet implementation class ConveyEditUserServlet */ @WebServlet("/ConveyEditUserServlet") public class ConveyEditUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ConveyEditUserServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); HttpSession session = request.getSession(); AdministratorFactorImp adminFactor = new AdministratorFactorImp(); String name = request.getParameter("edit"); if(name!=null){ UserAttr user = adminFactor.SearchUser(name); System.out.println(user.GetUID()); session.setAttribute("user", user); response.sendRedirect("User1/edit.jsp"); return; } String viewApply = request.getParameter("viewApply"); if(viewApply != null){ int UID = Integer.parseInt(viewApply); ArrayList<ApplyDetailAttr> applyList = adminFactor.ViewUserApply(UID); session.setAttribute("ApplyList", applyList); response.sendRedirect("User1/people.jsp"); return; } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request,response); } }
240a1b163b7a529423716e5b9946e527230dffc7
9e6f9493de73e5f80dd887f6372e75e520697d22
/src/main/java/com/solomka/Homework18TestingApplication.java
e9857b4e867cb240f6fa24f45d7ff303364741df
[]
no_license
solomkao/homework-18-testing
f547303ff9cd43b810af1a9d83845182e265f2e0
7a847bdfcdf4d7e692663f384b8e42476097a1a8
refs/heads/master
2023-02-28T21:56:26.637702
2021-02-03T18:09:37
2021-02-03T18:09:37
335,713,044
0
0
null
2021-02-06T12:46:53
2021-02-03T18:09:07
Java
UTF-8
Java
false
false
338
java
package com.solomka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Homework18TestingApplication { public static void main(String[] args) { SpringApplication.run(Homework18TestingApplication.class, args); } }
64e99b166a53ed73bbc07c64f9dbe07642d1b7d6
05ea019da84392f4e8a14bdd58af9918f992e9a7
/FrameworkFriends/src/framework/model/service/BaseApplicationService.java
0010faae0a3438ecafd392bfa515201e187a056a
[]
no_license
paraamigos/paraAmigos
263061640ff7a6cc34d592853c635dd0ade9bad4
009b224531bbcf7fe84733ec5768a986ab5b01da
refs/heads/master
2021-01-25T10:29:07.900880
2012-05-23T23:39:53
2012-05-23T23:39:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
25,774
java
package framework.model.service; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.Id; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import framework.annotation.SearchBean; import framework.reflection.BeansUtil; /** * Esta classe auxilia na implementa��o dos metodos b�sicos de CRUD, * para Application Services com suporte a seam. * Deve ser estendida pelos Services da aplica��o * * @author Luiz Alberto * */ public class BaseApplicationService implements Serializable { private static final long serialVersionUID = 258966534209860744L; public static final String SEARCH_SELECT_COUNT_CLAUSE = "select count(o) "; public static final String SEARCH_SELECT_CLAUSE = "select o "; public static final String PARAMETERS = "PARAMETERS"; public static final String QUERY = "QUERY"; private static final int FIRST = 0; @PersistenceContext protected EntityManager entityManager; private QueryParameters queryParams; private Object entity; private int count; /** * Atualiza um Entity Bean no banco * * @param entity Entity Bean */ public void update(Object entity) { try { entityManager.merge(entity); entityManager.flush(); } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * Deleta uma entidade da base de dados * * @param entity Entidade a ser deletada */ public void remove(Object entity) { try { entityManager.remove(entity); entityManager.flush(); } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * Persiste um Entity Bean no banco * * @param entity Entity Bean */ public void save(Object entity) { try { entityManager.persist(entity); entityManager.flush(); } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * M�todo utilizado para pesquisas atrav�s de CRUDBean * * @param <T> tipo parametrizado * @param entity Entity Bean * @param offset p�gina do banco * @return lista contendo todos os registros da entidade */ public <T> List<T> search(Object entity, String offset) { setEntity(entity); return search(offset, null); } /** * M�todo utilizado para pesquisas ordenadas atrav�s de CRUDBean * * @param <T> tipo parametrizado * @param entity Entity Bean * @param offset p�gina do banco * @param orderByProperty propriedade do Entity Bean pela qual ser� ordenada a query * @return lista contendo todos os registros da entidade */ public <T> List<T> search(Object entity, String offset, String orderByProperty) { setEntity(entity); return search(offset, orderByProperty); } /** * M�todo utilizado para pesquisas atrav�s de CRUDBean * * @param <T> tipo parametrizado * @param paramOffSet p�gina do banco * @param orderByProperty propriedade do Entity Bean pela qual ser� ordenada a query * @return lista contendo todos os registros da entidade */ public <T> List<T> search(String paramOffSet, String orderByProperty) { Map<Object,Object>query = getSearchQuery(orderByProperty); Object[] params = (Object[])query.get(PARAMETERS); String jpaql = (String) query.get(QUERY); boolean paging = isPaging(); List<T> resultList = null; if (paging) { int pageSize = getPagingSize(); int offset = 1; if (paramOffSet != null) { offset = Integer.parseInt(paramOffSet) + 1; } else { Map<Object,Object>queryCount = getSearchCountQuery(); Object[] paramsCount = (Object[])queryCount.get(PARAMETERS); String sqlCount = (String)queryCount.get(QUERY); List<Object>result = findByQuery(sqlCount, paramsCount); count = Integer.parseInt(result.get(FIRST).toString()); } int startIndex = ((offset - 1) * pageSize) + 1; int endIndex = ((offset - 1) * pageSize) + pageSize; resultList = findByQuery(jpaql, params, startIndex, endIndex); } else { resultList = findByQuery(jpaql, params); } return resultList; } /** * M�todo utilizado para pesquisas customizadas * * @param <T> tipo parametrizado * @param queryParams par�metros da query * @return lista contendo todos os registros da entidade */ @SuppressWarnings("unchecked") public <T> List<T> search(SearchParameters queryParams) { return (List<T>) ( queryParams.isQueryByExample() ? searchByExample((EntityParameters)queryParams) : search((QueryParameters)queryParams) ); } /** * M�todo utilizado para pesquisas customizadas * * @param <T> tipo parametrizado * @param queryParams par�metros da query * @return lista contendo todos os registros da entidade */ public <T> List<T> searchByExample(EntityParameters queryParams) { boolean paging = queryParams.isPaging(); String paramOffSet = queryParams.getOffset(); Object entity = queryParams.getEntity(); List<String>orderList = queryParams.getOrderList(); List<T> resultList = null; if (paging) { int pageSize = queryParams.getPagingSize(); int offset = 1; if (paramOffSet != null) { offset = Integer.parseInt(paramOffSet) + 1; } else { count = countByExample(entity); } int startIndex = ((offset - 1) * pageSize) + 1; int endIndex = ((offset - 1) * pageSize) + pageSize; resultList = findByExample(entity, orderList, startIndex, endIndex); } else { resultList = findByExample(entity, orderList); } return resultList; } /** * M�todo utilizado para pesquisas customizadas * * @param <T> tipo parametrizado * @param queryParams par�metros da query * @return lista contendo todos os registros da entidade */ public <T> List<T> search(QueryParameters queryParams) { this.queryParams = queryParams; Object[] params = queryParams.getParameters(); String jpaql = queryParams.getQuery(); boolean paging = queryParams.isPaging(); String paramOffSet = queryParams.getOffset(); List<T> resultList = null; if (paging) { int pageSize = queryParams.getPagingSize(); int offset = 1; if (paramOffSet != null) { offset = Integer.parseInt(paramOffSet) + 1; } else { Object[] paramsCount = queryParams.getParameters(); String sqlCount = queryParams.getCountQuery(); List<Object>result = findByQuery(sqlCount, paramsCount); count = Integer.parseInt(result.get(FIRST).toString()); } int startIndex = ((offset - 1) * pageSize) + 1; int endIndex = ((offset - 1) * pageSize) + pageSize; resultList = findByQuery(jpaql, params, startIndex, endIndex); } else { resultList = findByQuery(jpaql, params); } return resultList; } // /** // * M�todo utilizado para pesquisas customizadas e multi-listas // * // * @param queryParams par�metros da query // */ // public void searchMultiList(EntityParameters queryParams) { // multiListParams = new MultiListParameters(); // List<String>orderList = queryParams.getOrderList(); // String paramOffSet = queryParams.getOffset(); // boolean paging = queryParams.isPaging(); // Object entity = queryParams.getEntity(); // List resultList = null; // // if (paging) { // int pageSize = queryParams.getPagingSize(); // int offset = 1; // // if (paramOffSet != null) { // offset = Integer.parseInt(paramOffSet) + 1; // } else { // count = countByExample(entity); // } // int startIndex = ((offset - 1) * pageSize) + 1; // int endIndex = ((offset - 1) * pageSize) + pageSize; // resultList = findByExample(entity, orderList, startIndex, endIndex); // // } else { // resultList = findByExample(entity, orderList); // } // multiListParams.setQueryParams(queryParams); // multiListParams.setResultList(resultList); // } /** * Realiza consulta atrav�s de QBE (Query By Example) * * @param <T> tipo parametrizado * @param entity Entity Bean de exemplo com par�metros para query * @param orderList lista de atributos pelos quais ser� ordenada a query * @param startIndex �ndice inicial da pagina��o * @param endIndex �ndice final da pagina��o * @return lista contendo o resultado da query */ @SuppressWarnings("unchecked") public <T> List<T> findByExample(Object entity,List<String>orderList,int startIndex,int endIndex) { Criteria criterio = createCriteria(entity.getClass()); Example example = createExample(entity); List result = null; criterio.add(example); if (startIndex < 1) { startIndex = 1; } if ((endIndex - startIndex) < 0) { result = new ArrayList(); } else { criterio.setMaxResults(endIndex - startIndex + 1); criterio.setFirstResult(startIndex - 1); if (orderList != null) { for (String propertyName : orderList) { criterio.addOrder(Order.asc(propertyName)); } } result = criterio.list(); } return result; } /** * Realiza consulta atrav�s de QBE (Query By Example) * * @param <T> tipo parametrizado * @param entity Entity Bean de exemplo com par�metros para query * @param orderList lista de atributos pelos quais ser� ordenada a query * @return lista contendo o resultado da query */ @SuppressWarnings("unchecked") public <T> List<T> findByExample(Object entity, List<String>orderList) { Criteria criterio = createCriteria(entity.getClass()); Example example = createExample(entity); criterio.add(example); if (orderList != null) { for (String propertyName : orderList) { criterio.addOrder(Order.asc(propertyName)); } } return criterio.list(); } /** * Obtem o count atraves de QBE * * @param entity Entity Bean * @return total de registros da query */ protected int countByExample(Object entity) { Criteria criterio = createCriteria(entity.getClass()); Example example = createExample(entity); criterio.setProjection( Projections.projectionList().add( Projections.count(getEntityIdPropertyName(entity)) ) ); criterio.add(example); List result = criterio.list(); return !result.isEmpty() ? Integer.parseInt(result.get(FIRST).toString()) : 0; } /** * Retorna example a partir de um Entity Bean * * @param entity Entity Bean * @return example a partir de um Entity Bean */ private Example createExample(Object entity) { Example example = Example.create(entity); example.ignoreCase(); example.enableLike(MatchMode.ANYWHERE); return example; } // /** // * M�todo utilizado para pesquisas customizadas e multi-listas // * // * @param queryParams par�metros da query // */ // public void searchMultiList(QueryParameters queryParams) { // multiListParams = new MultiListParameters(); // this.queryParams = queryParams; // Object[] params = queryParams.getParameters(); // String jpaql = queryParams.getQuery(); // boolean paging = queryParams.isPaging(); // String paramOffSet = queryParams.getOffset(); // List resultList = null; // // if (paging) { // int pageSize = queryParams.getPagingSize(); // int offset = 1; // // if (paramOffSet != null) { // offset = Integer.parseInt(paramOffSet) + 1; // } else { // Object[] paramsCount = queryParams.getParameters(); // String sqlCount = queryParams.getCountQuery(); // List<Object>result = findByQuery(sqlCount, paramsCount); // count = Integer.parseInt(result.get(FIRST).toString()); // } // int startIndex = ((offset - 1) * pageSize) + 1; // int endIndex = ((offset - 1) * pageSize) + pageSize; // resultList = findByQuery(jpaql, params, startIndex, endIndex); // // } else { // resultList = findByQuery(jpaql, params); // } // multiListParams.setQueryParams(queryParams); // multiListParams.setResultList(resultList); // } /** * Recupera a query de consulta com base nas anota��es de pesquisa. * * @param orderByProperty propriedade do Entity Bean pela qual ser� ordenada a query * @return SQL de pesquisa com os filtros apropriados. */ public Map<Object,Object> getSearchQuery(String orderByProperty) { try { Map<Object,Object> searchQuery = new HashMap<Object, Object>(); List<Object> parameters = new ArrayList<Object>(); StringBuilder query = new StringBuilder(); query.append(SEARCH_SELECT_CLAUSE); query.append(getSearchQueryFromClause()); query.append(getSearchQueryWhereClause(parameters)); query.append(getSearchQueryOrderByClause(orderByProperty)); searchQuery.put(PARAMETERS, parameters.toArray()); searchQuery.put(QUERY, query.toString()); return searchQuery; } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * Recupera a query para recuperar o total de registros com base nas anota��es de pesquisa. * * @return SQL com os filtros apropriados. */ public Map<Object,Object> getSearchCountQuery(){ try { Map<Object,Object> searchQuery = new HashMap<Object, Object>(); List<Object> parameters = new ArrayList<Object>(); StringBuilder query = new StringBuilder(); query.append(SEARCH_SELECT_COUNT_CLAUSE); query.append(getSearchQueryFromClause()); query.append(getSearchQueryWhereClause(parameters)); searchQuery.put(PARAMETERS, parameters.toArray()); searchQuery.put(QUERY, query.toString()); return searchQuery; } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * Recupera a clausula "from" da query de consulta. * * @return Clausula "from". */ private String getSearchQueryFromClause() { return "from " + getEntityName() + " o "; } /** * Recupera o nome da entidade principal do bean. * * @return Nome da entidade principal do bean definida na anota��o da classe. */ public String getEntityName() { return entity.getClass().getSimpleName(); } /** * Recupera a clausula "where" da query de consulta. * * @param parameters guarda os parametros para a query * @return clausula "where". */ public String getSearchQueryWhereClause(List<Object> parameters) { QueryBuilderUtil queryBuilder = new QueryBuilderUtil(); queryBuilder.setEntity(entity); queryBuilder.setParameters(parameters); try { return queryBuilder.buildWhereClause(); } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * Recupera a clausula "order by" da query de consulta. * * @param orderByProperty propriedade do Entity Bean pela qual ser� ordenada a query * @return clausula "order by". */ private String getSearchQueryOrderByClause(String orderByProperty) { String orderBy = ""; if (orderByProperty != null) { orderBy = " order by o." + orderByProperty; } else { QueryBuilderUtil queryBuilder = new QueryBuilderUtil(); queryBuilder.setEntity(entity); orderBy = queryBuilder.buildOrderByClause(); } return orderBy; } /** * Localiza todos os registros de uma determinado objeto de forma ordenada * * @param <T> Tipo parametrizado * @param type Tipo da classe a ser localizada * @param orderBy Atributo pelo qual serao ordenados os registros * @return Lista ordenada contendo todos os registros de uma determinado objeto */ public <T> List<T> findAll(Class<T> type, String orderBy) { StringBuilder query = new StringBuilder("select o from ") .append(type.getSimpleName()) .append(" o "); String order = orderBy != null && !"".equals(orderBy.trim()) ? " order by o." + orderBy : ""; query.append(order); return findByQuery(query.toString(), null); } /** * Localiza todos os registros de uma determinado objeto de forma ordenada * * @param <T> Tipo parametrizado * @param type Tipo da classe a ser localizada * @return Lista ordenada contendo todos os registros de uma determinado objeto */ public <T> List<T> findAll(Class<T> type) { StringBuilder query = new StringBuilder("select o from ") .append(type.getSimpleName()) .append(" o "); return findByQuery(query.toString(), null); } /** * Localiza os registros de uma determinado objeto de acordo com os parametros e query passados * * @param <T> Tipo parametrizado * @param jpaql Query contendo a senten�a JPA-QL * @param params Par�metros para a query * @return Lista contendo os registros encontrados */ @SuppressWarnings("unchecked") public <T> List<T> findByQuery(String jpaql, Object[] params) { Query query = entityManager.createQuery(jpaql); setParameters(params, query); return query.getResultList(); } /** * Localiza os registros de uma determinado objeto de acordo com os parametros e query passados * * @param <T> tipo parametrizado * @param jpaql query contendo a senten�a JPA-QL * @param params par�metros para a query * @param startIndex �ndice inicial da pagina��o * @param endIndex �ndice final da pagina��o * @return Lista contendo os registros encontrados */ @SuppressWarnings("unchecked") public <T> List<T> findByQuery(String jpaql,Object[] params,int startIndex,int endIndex) { List result = null; if (startIndex < 1) { startIndex = 1; } if ((endIndex - startIndex) < 0) { result = new ArrayList(); } else { Query query = entityManager.createQuery(jpaql); setParameters(params, query); query.setMaxResults(endIndex - startIndex + 1); query.setFirstResult(startIndex - 1); result = query.getResultList(); } return result; } /** * Define os par�metros da query * * @param params par�metros da query * @param query query aonde os par�metros ser�o definidos */ private void setParameters(Object[] params, Query query) { if (params != null && params.length > 0) { int length = params.length; for (int i = 0; i < length; i++) { query.setParameter(i + 1, params[i]); } } } /** * Localiza os registros de uma determinado objeto de acordo com os parametros e query passados * * @param <T> Tipo parametrizado * @param name Named Query que contem a senten�a JPA-QL * @param params Par�metros para a query * @return Lista contendo os registros encontrados */ @SuppressWarnings("unchecked") public <T> List<T> findByNamedQuery(String name, Object[] params) { Query q = entityManager.createNamedQuery(name); if (params != null && params.length > 0) { int length = params.length; for (int i = 0; i < length; i++) { q.setParameter(i + 1, params[i]); } } return q.getResultList(); } /** * Obtém os dados de um unico EntityBean * de acordo com os parametros e query passados * * @param name named query que contem a sentença JPA-QL * @param params parâmetros para a query * @return EntityBean encontrado */ public Object findByNamedQueryOneResult(String name, Object[] params) { Query query = entityManager.createNamedQuery(name); Object result = null; try { setParameters(params, query); result = query.getSingleResult(); } catch (NoResultException e) { result = null; } return result; } /** * Obtém os dados de um unico EntityBean * de acordo com os parametros e query passados * * @param name named query que contem a sentença JPA-QL * @param params parâmetros para a query * @param setMaxResults se deve ser forçado numero maximo de registros para 1 * @return EntityBean encontrado */ public Object findByNamedQueryOneResult(String name, Object[] params, boolean setMaxResults) { Query query = entityManager.createNamedQuery(name); Object result = null; try { setParameters(params, query); if (setMaxResults) { query.setMaxResults(1); } result = query.getSingleResult(); } catch (NoResultException e) { result = null; } return result; } /** * Obtém os dados de um unico EntityBean * de acordo com os parametros e query passados * * @param jpaql query contendo a sentença JPA-QL * @param params parâmetros para a query * @return EntityBean encontrado */ public Object findByQueryOneResult(String jpaql, Object[] params) { Query query = entityManager.createQuery(jpaql); Object result = null; try { setParameters(params, query); result = query.getSingleResult(); } catch (NoResultException e) { result = null; } return result; } /** * Localiza uma entidade pelo id * * @param <T> Tipo parametrizado * @param classe Classe da entidade a ser localizada * @param id id da entidade * @return Entidade encontrada */ public <T>T findObject(Class<T> classe, Object id) { return entityManager.find(classe, id); } /** * Localiza uma entidade * * @param <T> tipo parametrizado * @param entity Entity Bean * @return Entidade encontrada */ @SuppressWarnings("unchecked") public <T>T findObject(Object entity) { try { Object id = getEntityId(entity); return (T) entityManager.find(entity.getClass(), id); } catch (Exception e) { throw new ApplicationServiceException(e); } } /** * Localiza o id do Entity Bean * * @param entity Entity Bean * @return id do Entity Bean */ public Object getEntityId(Object entity) { return BeansUtil.getEntityId(entity); } /** * Localiza o nome da propriedade id do Entity Bean * * @param entity Entity Bean * @return nome da propriedade id */ public String getEntityIdPropertyName(Object entity) { String propertyName = null; try { for (Field field : entity.getClass().getDeclaredFields()) { for (Annotation annotation : field.getAnnotations()) { if (annotation instanceof Id) { propertyName = field.getName(); } } } } catch (Exception e) { throw new ApplicationServiceException(e); } return propertyName; } /** * Pega o tamanho da paginacao. * * @return Quantidade de registros por pagina. */ public int getPagingSize() { int pagingSize = 0; for (Annotation annotation : entity.getClass().getAnnotations()) { if(annotation instanceof SearchBean){ pagingSize = ((SearchBean) annotation).pagingSize(); break; } } return pagingSize; } /** * Verifica se e paginado. * * @return True se tiver paginacao e false se nao tiver. */ public boolean isPaging() { boolean paging = true; for (Annotation annotation : entity.getClass().getAnnotations()) { if(annotation instanceof SearchBean){ paging = ((SearchBean) annotation).isPaging(); break; } } return paging; } /** * Define o Entity Bean * * @param entity Entity Bean */ public void setEntity(Object entity) { this.entity = entity; } /** * Retorna o total de registros da consulta * * @return o total de registros da consulta */ public int getCount() { return count; } /** * Define o total de registros da consulta * * @param count o total de registros da consulta */ public void setCount(int count) { this.count = count; } /** * Retorna os par�metros da query * * @return par�metros da query */ public QueryParameters getQueryParams() { return queryParams; } // /** // * Retorna os par�metros de multi-lista // * // * @return par�metros de multi-lista // */ // public MultiListParameters getMultiListParams() { // return multiListParams; // } /** * Retorna query por criterio * * @param classe Entity Bean Class * @return query por criterio */ protected Criteria createCriteria(Class<?> classe) { Session session = (Session) entityManager.getDelegate(); return session.createCriteria(classe); } /** * Retorna a classe do Entity Bean * * @return classe do Entity Bean */ public Class<?> getEntityClass() { return entity.getClass(); } /** * Set entityManager * * @param entityManager the entityManager to set */ public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } }
[ "Raphael@Raphael-PC" ]
Raphael@Raphael-PC
f5845ca2cc6960498e98d05365f8265ff6e9ce92
c71b4add1e98ba6a3ed3bb293d2c967ff369b091
/core/src/main/java/dev/punchcafe/vngine/chapter/ChapterConfigCache.java
62c11b7370052e42e164cafb7264c89aaf988092
[]
no_license
punchcafe/vNgine
9b5b7aaf02858309b3eb3e8a643c5fa5691f7243
336e0f2f74d3d2a064bc8bec784a480a8486716f
refs/heads/master
2023-09-06T08:00:49.232648
2021-10-06T22:44:45
2021-10-06T22:44:45
286,849,996
0
0
null
null
null
null
UTF-8
Java
false
false
483
java
package dev.punchcafe.vngine.chapter; import dev.punchcafe.vngine.config.yaml.ChapterConfig; import lombok.Builder; import lombok.Getter; import java.util.Map; import java.util.Optional; @Builder public class ChapterConfigCache { private final Map<String, ChapterConfig> chapterConfigMap; @Getter private final ChapterConfig firstChapter; public Optional<ChapterConfig> get(final String id) { return Optional.ofNullable(chapterConfigMap.get(id)); } }
5214485fba23627e85c3a691fe76e74a69f15546
33e8082481410ccbf1f5c01167e952b49b26ce45
/app/src/main/java/org/allseen/lsf/sampleapp/UpdateSceneElementNameAdapter.java
c3bfdb5f3b155e08641e5f16ca9904f503f5d530
[]
no_license
JunaidBabu/AllJoyn_LSF-sample
17b47eff81669e847a8fd3f37536e1abba2b4ca9
b113da7f11181b154ae480dd4b6c2aec53d7fbd3
refs/heads/master
2021-01-10T16:40:07.186444
2016-02-15T03:54:34
2016-02-15T03:54:34
51,729,292
1
0
null
null
null
null
UTF-8
Java
false
false
1,519
java
/* * Copyright (c) AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package org.allseen.lsf.sampleapp; import org.allseen.lsf.sdk.SceneElement; import org.allseen.lsf.sdk.LightingDirector; public class UpdateSceneElementNameAdapter extends UpdateItemNameAdapter { public UpdateSceneElementNameAdapter(SceneElement sceneElement, SampleAppActivity activity) { super(sceneElement, activity); } @Override protected String getDuplicateNameMessage() { return activity.getString(R.string.duplicate_name_message_scene_element); } @Override protected boolean duplicateName(String sceneElementName) { Util.isDuplicateName(LightingDirector.get().getSceneElements(), sceneElementName); return false; } }
f7073ec94ead275b5bcc065a5d2fc39047c2bc3c
bee3c5febdcf62ab9acf38fd9907baeb76847691
/src/main/java/com/fafamc/weblog/config/WebLogAspect.java
988cb90ee5aa20ed751a587668562c3edc21d871
[]
no_license
liuxue920/gaku920
2083921ffe1f1d00d0db79e88eb20604697548c2
96c6d87675e5cfa6ab00738cbc58a2e6b5fa2c2d
refs/heads/dev
2023-02-26T07:56:12.892584
2021-02-02T12:49:46
2021-02-02T12:49:46
290,436,708
1
0
null
2021-02-02T12:52:43
2020-08-26T08:12:33
Java
UTF-8
Java
false
false
3,997
java
package com.fafamc.weblog.config; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; /** * @Author gaku9 * @Create 2020/7/29 **/ @Slf4j @Aspect @Component @Profile({ "dev"}) public class WebLogAspect { /** 以自定义 @WebLog 注解为切点 */ @Pointcut("@annotation(com.fafamc.weblog.config.WebLog)") public void webLog() {} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 开始打印请求日志 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 获取 @WebLog 注解的描述信息 String methodDescription = getAspectLogDescription(joinPoint); // 打印请求相关参数 log.info("========================================== Start =========================================="); // 打印请求 url log.info("URL : {}", request.getRequestURL().toString()); // 打印描述信息 log.info("Description : {}", methodDescription); // 打印 Http method log.info("HTTP Method : {}", request.getMethod()); // 打印调用 controller 的全路径以及执行方法 log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); // 打印请求的 IP log.info("IP : {}", request.getRemoteAddr()); // 打印请求入参 log.info("Request Args : {}", ReflectionToStringBuilder.toString(joinPoint.getArgs(), ToStringStyle.DEFAULT_STYLE)); } public String getAspectLogDescription(JoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); StringBuilder description = new StringBuilder(""); for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { description.append(method.getAnnotation(WebLog.class).description()); break; } } } return description.toString(); } /** * 在切点之后织入 * @throws Throwable */ @After("webLog()") public void doAfter() throws Throwable { // 接口结束后换行,方便分割查看 log.info("=========================================== End ===========================================" ); } /** * 环绕 * @param proceedingJoinPoint * @return * @throws Throwable */ @Around("webLog()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = proceedingJoinPoint.proceed(); // 打印出参 // log.info("Response Args : {}", ReflectionToStringBuilder.toString(result, ToStringStyle.MULTI_LINE_STYLE)); // 执行耗时 log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime); return result; } }
3970e756f10e8ba3dadbb04c78323f3b61e6f8da
a225db77848d0f16e67e8b5926f4ea752fa96f64
/serenity-core/src/test/java/twolevelpackagerequirements/fruit/apples/PickingApples.java
8893ccb02c1549f4b1c578934d3cbb7826cb1ca4
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
AnshumanGo/serenity-core
cb3c1ee091aa627b0bed59a9d4d6d5196ad3037a
39330a5e92ec54ccb5d0c43c4f6aa4b97c75486b
refs/heads/master
2021-11-29T19:54:27.254991
2021-11-17T15:46:06
2021-11-17T15:46:06
219,955,490
1
1
NOASSERTION
2020-10-01T11:18:58
2019-11-06T09:09:01
HTML
UTF-8
Java
false
false
168
java
package twolevelpackagerequirements.fruit.apples; import net.thucydides.core.annotations.Narrative; @Narrative(text="Pick some apples") public class PickingApples {}
c9f00ef94cf2855a6bc399000a5c9d021f0bc7cb
0d602644590f25e3ead81879d5f5b2bbb5f2520a
/AndroidSwipeLayout/src/main/java/com/gkzxhn/androidswipelayout/activity/MyActivity.java
4d7d15e46f0292c0980d06fe98ba0334229a6cbb
[]
no_license
RaleighLuo/Sample
4a639a6551d57aa2303337f2a93b12cd08b35ab8
97b2513b7cb45579c81ab1da4b277a41ae4ba72a
refs/heads/master
2020-03-23T21:11:18.705151
2018-08-03T09:11:49
2018-08-03T09:11:49
142,087,969
0
0
null
null
null
null
UTF-8
Java
false
false
8,773
java
package com.gkzxhn.androidswipelayout.activity; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.gkzxhn.androidswipelayout.R; import com.gkzxhn.androidswipelayout.SwipeLayout; import com.nineoldandroids.view.ViewHelper; public class MyActivity extends Activity { private SwipeLayout sample1, sample2, sample3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // SwipeLayout swipeLayout = (SwipeLayout)findViewById(R.id.godfather); // swipeLayout.setDragEdge(SwipeLayout.DragEdge.Bottom); // Set in XML //sample1 sample1 = (SwipeLayout) findViewById(R.id.sample1); sample1.setShowMode(SwipeLayout.ShowMode.PullOut); View starBottView = sample1.findViewById(R.id.starbott); sample1.addDrag(SwipeLayout.DragEdge.Left, sample1.findViewById(R.id.bottom_wrapper)); sample1.addDrag(SwipeLayout.DragEdge.Right, sample1.findViewById(R.id.bottom_wrapper_2)); sample1.addDrag(SwipeLayout.DragEdge.Top, starBottView); sample1.addDrag(SwipeLayout.DragEdge.Bottom, starBottView); sample1.addRevealListener(R.id.delete, new SwipeLayout.OnRevealListener() { @Override public void onReveal(View child, SwipeLayout.DragEdge edge, float fraction, int distance) { } }); sample1.getSurfaceView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Click on surface", Toast.LENGTH_SHORT).show(); Log.d(MyActivity.class.getName(), "click on surface"); } }); sample1.getSurfaceView().setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(MyActivity.this, "longClick on surface", Toast.LENGTH_SHORT).show(); Log.d(MyActivity.class.getName(), "longClick on surface"); return true; } }); sample1.findViewById(R.id.star2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Star", Toast.LENGTH_SHORT).show(); } }); sample1.findViewById(R.id.trash2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Trash Bin", Toast.LENGTH_SHORT).show(); } }); sample1.findViewById(R.id.magnifier2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Magnifier", Toast.LENGTH_SHORT).show(); } }); sample1.addRevealListener(R.id.starbott, new SwipeLayout.OnRevealListener() { @Override public void onReveal(View child, SwipeLayout.DragEdge edge, float fraction, int distance) { View star = child.findViewById(R.id.star); float d = child.getHeight() / 2 - star.getHeight() / 2; ViewHelper.setTranslationY(star, d * fraction); ViewHelper.setScaleX(star, fraction + 0.6f); ViewHelper.setScaleY(star, fraction + 0.6f); } }); //sample2 sample2 = (SwipeLayout) findViewById(R.id.sample2); sample2.setShowMode(SwipeLayout.ShowMode.LayDown); sample2.addDrag(SwipeLayout.DragEdge.Right, sample2.findViewWithTag("Bottom2")); // sample2.setShowMode(SwipeLayout.ShowMode.PullOut); sample2.findViewById(R.id.star).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Star", Toast.LENGTH_SHORT).show(); } }); sample2.findViewById(R.id.trash).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Trash Bin", Toast.LENGTH_SHORT).show(); } }); sample2.findViewById(R.id.magnifier).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Magnifier", Toast.LENGTH_SHORT).show(); } }); sample2.findViewById(R.id.click).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Yo", Toast.LENGTH_SHORT).show(); } }); sample2.getSurfaceView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Click on surface", Toast.LENGTH_SHORT).show(); } }); //sample3 sample3 = (SwipeLayout) findViewById(R.id.sample3); sample3.addDrag(SwipeLayout.DragEdge.Top, sample3.findViewWithTag("Bottom3")); sample3.addRevealListener(R.id.bottom_wrapper_child1, new SwipeLayout.OnRevealListener() { @Override public void onReveal(View child, SwipeLayout.DragEdge edge, float fraction, int distance) { View star = child.findViewById(R.id.star); float d = child.getHeight() / 2 - star.getHeight() / 2; ViewHelper.setTranslationY(star, d * fraction); ViewHelper.setScaleX(star, fraction + 0.6f); ViewHelper.setScaleY(star, fraction + 0.6f); int c = (Integer) evaluate(fraction, Color.parseColor("#dddddd"), Color.parseColor("#4C535B")); child.setBackgroundColor(c); } }); sample3.findViewById(R.id.bottom_wrapper_child1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Yo!", Toast.LENGTH_SHORT).show(); } }); sample3.getSurfaceView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MyActivity.this, "Click on surface", Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.my, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_listview) { startActivity(new Intent(this, ListViewExample.class)); return true; } else if (id == R.id.action_gridview) { startActivity(new Intent(this, GridViewExample.class)); return true; } else if (id == R.id.action_nested) { startActivity(new Intent(this, NestedExample.class)); return true; } else if (id == R.id.action_recycler) { startActivity(new Intent(this, RecyclerViewExample.class)); } return super.onOptionsItemSelected(item); } /* Color transition method. */ public Object evaluate(float fraction, Object startValue, Object endValue) { int startInt = (Integer) startValue; int startA = (startInt >> 24) & 0xff; int startR = (startInt >> 16) & 0xff; int startG = (startInt >> 8) & 0xff; int startB = startInt & 0xff; int endInt = (Integer) endValue; int endA = (endInt >> 24) & 0xff; int endR = (endInt >> 16) & 0xff; int endG = (endInt >> 8) & 0xff; int endB = endInt & 0xff; return (int) ((startA + (int) (fraction * (endA - startA))) << 24) | (int) ((startR + (int) (fraction * (endR - startR))) << 16) | (int) ((startG + (int) (fraction * (endG - startG))) << 8) | (int) ((startB + (int) (fraction * (endB - startB)))); } }
b61e50194897fa79ac94f196c08253de88df749d
2c6ab521992f1079b02eb5873fc1410fdd81b720
/app/src/main/java/com/nansoft/find3r/models/Notificacion.java
dd0d44ea5e25fff5fbf1c777bd504e916804bca2
[]
no_license
Find3r/Android-Mobile-App
fdbdd3bfe112cc4d69ee29e31e27d9877812493a
d5d5238f39dbd475c32e38c2ab69451a5edafe38
refs/heads/master
2020-12-24T17:45:05.854272
2016-03-30T05:38:34
2016-03-30T05:38:34
53,459,168
0
0
null
null
null
null
UTF-8
Java
false
false
4,433
java
package com.nansoft.find3r.models; import com.google.gson.annotations.SerializedName; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; /** * Created by User on 7/5/2015. */ public class Notificacion { public String id; public String idnoticia; @SerializedName("__createdAt") public String __createdAt; public String descripcion; public String fecha; public String hora; public Notificacion(String id, String idnoticia, String descripcion, String fecha, String hora) { this.id = id; this.idnoticia = idnoticia; this.descripcion = descripcion; this.fecha = fecha; this.hora = hora; } public String getFechaCreacion() { //return getDiferenciaFecha(); SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat fromUser = new SimpleDateFormat("yyyy-MM-dd"); String fecha = "Sin definir"; try { fecha = myFormat.format(fromUser.parse(__createdAt.substring(0,10))); } catch (ParseException e) { } return fecha; } public String getDiferenciaFecha() { // Crear 2 instancias de Calendar Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); String fechaAux = getFechaCreacion(); // Establecer las fechas // año / mes / día cal2.set(Integer.parseInt(fechaAux.substring(6, 10)), Integer.parseInt(fechaAux.substring(3, 5)), Integer.parseInt(fechaAux.substring(0, 2))); // conseguir la representacion de la fecha en milisegundos long milis1 = cal1.getTimeInMillis(); long milis2 = cal2.getTimeInMillis(); // calcular la diferencia en milisengundos long diff = milis2 - milis1; long diffSeconds = diff / 1000; // calcular la diferencia en minutos long diffMinutes = diff / (60 * 1000); // calcular la diferencia en horas long diffHours = diff / (60 * 60 * 1000); // calcular la diferencia en dias long diffDays = diff / (24 * 60 * 60 * 1000); return String.valueOf(diffDays); } public long getDiferenciaSegundos() { // Crear 2 instancias de Calendar Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); String fechaAux = getFechaCreacion(); // Establecer las fechas // año / mes / día cal2.set(Integer.parseInt(fechaAux.substring(6, 10)), Integer.parseInt(fechaAux.substring(3, 5)), Integer.parseInt(fechaAux.substring(0, 2))); // conseguir la representacion de la fecha en milisegundos long milis1 = cal1.getTimeInMillis(); long milis2 = cal2.getTimeInMillis(); // calcular la diferencia en milisengundos long diff = milis2 - milis1; return diff / 1000; } public long getDiferenciaMinutos() { // calcular la diferencia en minutos return getDiferenciaSegundos() / (60 * 1000); } public long getDiferenciaHoras() { // calcular la diferencia en horas return getDiferenciaSegundos() / (60 * 60 * 1000); } public long getDiferenciaDias() { // calcular la diferencia en dias return getDiferenciaSegundos() / (24 * 60 * 60 * 1000); } public Calendar dif() { // Crear 2 instancias de Calendar Calendar c = Calendar.getInstance(); //fecha inicio Calendar fechaInicio = Calendar.getInstance(); //fecha fin Calendar fechaFin = new GregorianCalendar(); String fechaAux = getFechaCreacion(); // Establecer las fechas // año / mes / día fechaFin.set(Integer.parseInt(fechaAux.substring(6, 10)), Integer.parseInt(fechaAux.substring(3, 5)), Integer.parseInt(fechaAux.substring(0, 2))); //restamos las fechas como se puede ver son de tipo Calendar, //debemos obtener el valor long con getTime.getTime. c.setTimeInMillis( fechaFin.getTime().getTime() - fechaInicio.getTime().getTime()); //la resta provoca que guardamos este valor en c, //los milisegundos corresponde al tiempo en dias //asi sabemos cuantos dias return c; } }
1c60a5c66f339f6a374108cb95d910503fc5bea8
32ecc7b6458225f5261d4926aad1e7ed0aa865c2
/app/src/main/java/com/example/dell/toolbardemo/MainActivity.java
dcef5605694ef3cdd448b6055f429451a493a0ab
[]
no_license
lurenman/ToolBarDemo
3a9e97b010d3e9778b671e25693b981cdfa08c85
b2672f7361379f45f199ab5016e5f879a87223d3
refs/heads/master
2020-04-09T01:49:15.204190
2018-12-01T07:04:56
2018-12-01T07:04:56
159,918,253
0
0
null
null
null
null
UTF-8
Java
false
false
1,994
java
package com.example.dell.toolbardemo; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.dell.toolbardemo.activity.FirstTestActivity; import com.example.dell.toolbardemo.activity.SearchViewActivity; import com.example.dell.toolbardemo.activity.SecondTestActivity; public class MainActivity extends AppCompatActivity { private Context mContext; private Button btn_first_test; private Button btn_SearchView; private Button btn_SecondTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; initView(); initListener(); } private void initView() { btn_first_test = (Button) findViewById(R.id.btn_first_test); btn_SearchView = (Button) findViewById(R.id.btn_SearchView); btn_SecondTest = (Button) findViewById(R.id.btn_SecondTest); } private void initListener() { btn_first_test.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, FirstTestActivity.class); startActivity(intent); } }); btn_SearchView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, SearchViewActivity.class); startActivity(intent); } }); btn_SecondTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, SecondTestActivity.class); startActivity(intent); } }); } }
82f55bde5e74122674b1177cd454d58f4f6e2121
b78cddadf169cd02e0f1694fc7b1605fd9622c69
/app/src/main/java/com/example/anime/remote/AnimeService.java
cbaf6dd28c838c667f80b0afe6524c8ad1e4db22
[]
no_license
IchfanAskar/apikey_anime
7927323e1c0ffa6647e65bf24ca1e36a12a136e0
2dcf046b42b0e3bd006024d7c97bdeb2b655bbaa
refs/heads/master
2020-05-07T22:14:09.928750
2019-04-12T05:56:30
2019-04-12T05:56:30
180,937,869
0
0
null
null
null
null
UTF-8
Java
false
false
513
java
package com.example.anime.remote; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class AnimeService { private static final String BASE_URL = "https://myanimelist.net/animelist/"; public static ApiEndpoint getApi(){ final Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(BASE_URL) .build(); return retrofit.create(ApiEndpoint.class); } }
11f9c0c0b65ff2c47b72f9326dca150defa92b4c
4779dc9a98eb316e091db8876f6f824955519f0d
/msrshop-coupon/src/main/java/com/msr/msrshop/coupon/controller/SeckillSessionController.java
2aaf2d39ceefe7659d06cae08474c05b5aef3cd7
[]
no_license
yangguixue3/msrshop-bp
06270f6a7951334aec76762d8c16ea7eb3750744
1d5069f69ffd9213927bdc36d7104fb1300cc53e
refs/heads/master
2022-12-22T18:56:41.108901
2020-09-15T08:35:10
2020-09-15T08:35:10
293,226,154
1
0
null
null
null
null
UTF-8
Java
false
false
2,409
java
package com.msr.msrshop.coupon.controller; import java.util.Arrays; import java.util.Map; //权限认证的 //import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; 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 com.msr.msrshop.coupon.entity.SeckillSessionEntity; import com.msr.msrshop.coupon.service.SeckillSessionService; import com.msr.common.utils.PageUtils; import com.msr.common.utils.R; /** * 秒杀活动场次 * * @author yang * @email [email protected] * @date 2020-09-08 15:50:16 */ @RestController @RequestMapping("coupon/seckillsession") public class SeckillSessionController { @Autowired private SeckillSessionService seckillSessionService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("coupon:seckillsession:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = seckillSessionService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("coupon:seckillsession:info") public R info(@PathVariable("id") Long id){ SeckillSessionEntity seckillSession = seckillSessionService.getById(id); return R.ok().put("seckillSession", seckillSession); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("coupon:seckillsession:save") public R save(@RequestBody SeckillSessionEntity seckillSession){ seckillSessionService.save(seckillSession); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("coupon:seckillsession:update") public R update(@RequestBody SeckillSessionEntity seckillSession){ seckillSessionService.updateById(seckillSession); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("coupon:seckillsession:delete") public R delete(@RequestBody Long[] ids){ seckillSessionService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
[ "guixueyang3.gmail.com" ]
guixueyang3.gmail.com
75b5be29c644f7190396d26a22c0137adf324a50
9b8616f1d8bd87e0c3147327dd52ca84a89cb365
/src/main/java/com/kuang/interceptor/LoginHandlerInterceptor.java
b75264deb2d3ae010ad1697db33b6cc45acdb2d1
[]
no_license
zhang2014013936/springboot-web
85c5bf94e9a3ba33f90a660b2333ab85e4c40844
806ce399dcaa6be71c1a13df85cae976f1f67214
refs/heads/master
2021-02-18T14:02:15.198523
2020-03-05T15:53:13
2020-03-05T15:53:13
245,203,405
0
0
null
null
null
null
UTF-8
Java
false
false
852
java
package com.kuang.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginHandlerInterceptor implements HandlerInterceptor { // 判断是否拦截 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object loginUser = request.getSession().getAttribute("loginUser"); if (loginUser==null){ request.setAttribute("msg","没有权限,请先登录"); System.out.println("LoginHandlerInterceptor"); request.getRequestDispatcher("/index.html").forward(request,response); return false; }else { return true; } } }
5071abb89017c3a15ea3941d1ed0f511a0c6f15b
f83e003298c1071659389b3337be8af7d8225a3f
/4607/Frank_Hu.java
376b32d61611bcd218bdf398411646955aa75e3d
[]
no_license
ckxzero/UGAICPC
016331516e25759dd0d4e53db2e37ff8754b226b
7ec31767d68ffd5b502c5089d00ce031af014030
refs/heads/master
2021-01-20T23:21:11.427408
2014-05-23T19:25:01
2014-05-23T19:25:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,340
java
import java.util.Scanner; public class RobotProblem { static int cities = 0; // First array spot = city // Second array is cartesian point, there are two, the first is X and the // second is Y. static int[][] cityCartesians = new int[1000][2]; static int totalCable = 0; static int totalCitiesOnSamePlane = 0; static int[] penalty; static int penaltyScore; public static void takeInput() { Scanner myScanner = new Scanner(System.in); String s = myScanner.nextLine(); cities = Integer.parseInt(s); penalty = new int[cities + 3]; System.out.println(cities); cityCartesians[0][0] = 0; cityCartesians[0][1] = 0; penalty[0] = 0; penalty[cities - 1] = 0; for (int city = 1; city < cities + 1; city++) { cityCartesians[city][0] = myScanner.nextInt(); cityCartesians[city][1] = myScanner.nextInt(); penalty[city] = myScanner.nextInt(); } cityCartesians[cities + 1][0] = 100; cityCartesians[cities + 1][1] = 100; } public static double distance(int cityOne, int cityTwo) { Double s = Math.sqrt(Math.pow(cityCartesians[cityOne][0] - cityCartesians[cityTwo][0], 2) + Math.pow(cityCartesians[cityOne][1] - cityCartesians[cityTwo][1], 2)); if (s < 0) { s = -s; } else return s; return s; } public static void swap(int city, int k) { if (city == k || city == cities) { return; } for (int city1 = k; city1 <= cities; city1++) { cityCartesians[city1][0] = cityCartesians[city1 + 1][0]; cityCartesians[city1][1] = cityCartesians[city1 + 1][1]; } cities -= 1; penaltyScore += penalty[k + 2]; System.out.println("swapping " + city + " " + k + " penalty is " + penalty[city] + " Something is wrong?"); } public static void sort() { for (int city = 1; city < cities; city++) { System.out.println(city + " " + penalty[city] + " " + (city + 1) + " " + penalty[city + 1]); if (distance(city, city + 1) + distance(city + 1, city + 2) > (penalty[city + 1] + distance( city, city + 2))) { System.out.println("running swap with " + city + " " + (city + 1)); swap(city, city + 1); penaltyScore += penalty[city + 1]; } } } public static void process() { takeInput(); sort(); for (int city = 0; city < cities; city++) { for (int k = 0; k < cities; k++) { if (cityCartesians[city][1] == cityCartesians[k][1]) totalCitiesOnSamePlane++; } } for (int city = 0; city < cities; city++) { int currentLeastRopeCity = 0; for (int sameCityY = 0; sameCityY < totalCitiesOnSamePlane; sameCityY++) { if (distance(city, sameCityY) < currentLeastRopeCity && !penaltyIsMore(city, sameCityY)) { currentLeastRopeCity = sameCityY; } } for (int diffCityY = city; diffCityY > city; diffCityY--) { if (distance(diffCityY, city) < currentLeastRopeCity && !penaltyIsMore(diffCityY, city)) { currentLeastRopeCity = diffCityY; } } } } public static boolean penaltyIsMore(int city, int sameCityY) { if (penalty[city + 1] > distance(city, sameCityY) + 1) { return false; } return true; } public static void main(String[] asdf) { while (true) { process(); double distance = 0; System.out.println("cities"); for (int x = 0; x < cities + 2; x++) { System.out.println(x + " x " + cityCartesians[x][0]); System.out.println(x + " y " + cityCartesians[x][1]); System.out.println("penalty of " + x + " " + penalty[x]); } for (int city = 0; city < cities + 1; city += 1) { System.out.println("distance computed " + distance(city, city + 1)); distance += distance(city, city + 1); System.out.println("Distance after added " + distance); System.out.println("City co-ordinates x" + cityCartesians[city][0] + " y " + cityCartesians[city][1]); System.out.println("City + 1 co-ordinates x" + cityCartesians[city + 1][0] + " y " + cityCartesians[city + 1][1]); } System.out.println(penaltyScore); distance += cities + 1 + penaltyScore; System.out.println(cities); System.out.println("Final Distance " + distance + " this is the final score"); if (cities == 1) { cityCartesians[2][0] = 100; cityCartesians[2][1] = 100; System.out.print("Distance of One city "); System.out.println(distance(0, 1) + distance(1, 2) + 2); } } } }
ae004235ab9a13151528ab2eeefa93e30250c309
0f3cc4d8ffa9b258663ea58e47bfd39457cf1e25
/app/src/main/java/com/halfbyte/danv1/Contenido/CardAdapter.java
f71904239a54fefae57698be8a9e7fe866aa406d
[]
no_license
jase156/social_network_dan
5bf7061cf5c120a0d715aa80112f09c34b331840
83a323292f9e1360571663b7f0f355531577810f
refs/heads/master
2023-07-14T23:03:31.719741
2021-09-01T20:21:11
2021-09-01T20:21:11
402,191,057
0
0
null
null
null
null
UTF-8
Java
false
false
7,961
java
package com.halfbyte.danv1.Contenido; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Parcelable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.halfbyte.danv1.Comentarios.Comentario; import com.halfbyte.danv1.Comentarios.ComentarioAdapter; import com.halfbyte.danv1.Historia; import com.halfbyte.danv1.R; import java.util.ArrayList; import java.util.List; public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> { List<Card> mCards; Context context; private boolean isExpand=true; public CardAdapter (){ super(); mCards = new ArrayList<Card>(); Card card = new Card(); card.setmName("L"); card.setmFecha("06/08/2018"); card.setmTitulo("Empecé a odiarme a mí misma"); card.setmResumen("Mi vida es como una montaña rusa. Nunca sé cómo va a ir."); card.setmHistoria("Mi vida es como una montaña rusa. Nunca sé cómo va a ir.\n" + "\n" + "Este año empezó mal. En mi antiguo instituto empecé a darme cuenta de que no era tan bonito como imaginaba. Vinieron muchos problemas.\n" + "\n" + "En el instituto Ingeniero de la Cierva no tenía a nadie. Sólo me hablaban para insultarme. Empecé a odiarme a mí misma. \n" + "\n" + "Luego pude olvidar a gente que nunca debió estar en mi vida. Llegué a mi nuevo instituto y dos chicas maravillosas me acogieron. Yessi y Thais, os quiero. \n"); card.setmImagen(R.drawable.prueba2); mCards.add(card); card = new Card(); card.setmName("J"); card.setmFecha("28/07/2018"); card.setmTitulo("Mi vida es como una montaña rusa."); card.setmResumen("Este año empezó mal. En mi antiguo instituto empecé a darme cuenta de que no era tan bonito como imaginaba. Vinieron muchos problemas.\n"); card.setmHistoria("Mi vida es como una montaña rusa. Nunca sé cómo va a ir.\n" + "\n" + "Este año empezó mal. En mi antiguo instituto empecé a darme cuenta de que no era tan bonito como imaginaba. Vinieron muchos problemas.\n" + "\n" + "En el instituto Ingeniero de la Cierva no tenía a nadie. Sólo me hablaban para insultarme. Empecé a odiarme a mí misma. \n" + "\n" + "Luego pude olvidar a gente que nunca debió estar en mi vida. Llegué a mi nuevo instituto y dos chicas maravillosas me acogieron. Yessi y Thais, os quiero. \n"); card.setmImagen(R.drawable.prueba); mCards.add(card); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recycler_view_card_item,parent,false); context = parent.getContext(); ViewHolder viewHolder = new ViewHolder(v); return viewHolder; } @Override public void onBindViewHolder(final CardAdapter.ViewHolder holder, final int position) { final Card card = mCards.get(position); final List<Comentario> listComentarios = new ArrayList<Comentario>(); holder.inicial.setText(card.getmName()); holder.fecha.setText(card.getmFecha()); holder.mediaImage.setImageResource(card.getmImagen()); holder.tituloHistoria.setText(card.getmTitulo()); holder.resumen.setText(card.getmResumen()); holder.historia.setText(card.getmHistoria()); holder.collapse.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { holder.historia.setVisibility( isExpand ? View.VISIBLE : View.GONE); holder.collapse.setImageResource(isExpand ? R.drawable.ic_expand_less_black_36dp : R.drawable.ic_expand_more_black_36dp); holder.resumen.setVisibility(isExpand ? View.GONE : View.VISIBLE); holder.listaComentario.setVisibility(isExpand ? View.VISIBLE : View.GONE); isExpand = !isExpand; } }); holder.enviarComentario.setOnClickListener(new View.OnClickListener(){ boolean inicio = true; int comentarios=1; //comentarios ComentarioAdapter adaptadorComentario; @Override public void onClick(View v) { if(inicio){ adaptadorComentario = new ComentarioAdapter(); inicio = false; } holder.listaComentario.getLayoutParams().height=150*comentarios; comentarios++; holder.listaComentario.setAdapter(adaptadorComentario); String comentarioTexto = holder.comentario.getText().toString(); Comentario comentario = new Comentario(); comentario.setPersona("J"); comentario.setComentario(comentarioTexto); listComentarios.add(comentario); adaptadorComentario.agregar(comentario); holder.comentario.getText().clear(); holder.textoComentarios.setText(adaptadorComentario.getCount()==1 ? "Comentario" : "Comentarios"); holder.numeroComentarios.setText(adaptadorComentario.getCount()>0 ? ""+adaptadorComentario.getCount() : "" ); } }); holder.tituloHistoria.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(view.getContext(),Historia.class); intent.putExtra("titulo",card.getmTitulo()); intent.putExtra("texto", card.getmHistoria()); intent.putParcelableArrayListExtra("comentarios", (ArrayList<? extends Parcelable>) listComentarios); context.startActivity(intent); Activity mActivity = (Activity) context; mActivity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } }); } @Override public int getItemCount() { return mCards.size(); } class ViewHolder extends RecyclerView.ViewHolder{ public TextView inicial; public TextView fecha; public ImageView mediaImage; public TextView tituloHistoria; public TextView resumen; public TextView historia; public ImageButton collapse; private TextView numeroComentarios; private TextView textoComentarios; private ListView listaComentario; private EditText comentario; private ImageButton enviarComentario; public ViewHolder(View itemView) { super(itemView); inicial = itemView.findViewById(R.id.icon_text); fecha = itemView.findViewById(R.id.fecha_publicacion); mediaImage = itemView.findViewById(R.id.media_image); tituloHistoria = itemView.findViewById(R.id.titulo_historia); resumen = itemView.findViewById(R.id.sub_text); historia = itemView.findViewById(R.id.supporting_text); collapse = itemView.findViewById(R.id.expand_button); numeroComentarios = itemView.findViewById(R.id.txtNumeroComentarios); textoComentarios = itemView.findViewById(R.id.txtComentario); listaComentario = itemView.findViewById(R.id.lista_comentarios); comentario = itemView.findViewById(R.id.comenta); enviarComentario = itemView.findViewById(R.id.enviar_comentario); } } }
bb3e3d26c36606e721895c6a77195d4e07976ab1
dbccb82b5196815313c62b04d0839406f04b0e08
/src/main/java/kpi/iasa/introductorycampaign/domain/User.java
9e3b93427bb28d0fc779b9dc7bff4ce104304e97
[]
no_license
antonymorato/IntroductoryCampaign
e37da420f168c841621f3568e11acb801fb5947f
7ebc59cdca2cb94747600576d6243d5aafffd6b3
refs/heads/master
2022-04-11T21:57:51.748255
2020-04-01T10:34:59
2020-04-01T10:34:59
250,285,162
0
0
null
null
null
null
UTF-8
Java
false
false
1,346
java
package kpi.iasa.introductorycampaign.domain; import lombok.Data; import lombok.Getter; import lombok.Setter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.Collection; import java.util.Set; @Getter @Setter @Entity @Table(name = "usr") public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String username; private String password; private boolean active; @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return isActive(); } public void setUsername(String username) { this.username = username; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return getRoles(); } @ElementCollection(targetClass = Role.class,fetch = FetchType.EAGER) @CollectionTable(name = "user_role",joinColumns = @JoinColumn(name = "user_id")) @Enumerated(EnumType.STRING) private Set<Role> roles; }
4fb5023063123ad933923bf5e5c794002d7e8ef8
832adcdeb34c5ba6ba7d9ac6f1be01619711579d
/src/codingbat/functional2/NoNeg.java
986449d2d9d6432f9fef73fd7b6864171f6f7b87
[]
no_license
Duelist256/CoreJava
208d5281988350e3a178ddefbebdba21ed6473b9
1fb5461691a7ac47ebd97577a8d5dd22171adb74
refs/heads/master
2021-01-21T15:19:44.807973
2017-09-10T13:51:19
2017-09-10T13:51:19
95,383,213
1
0
null
null
null
null
UTF-8
Java
false
false
460
java
package codingbat.functional2; import java.util.ArrayList; import java.util.List; /** * Created by Duelist on 27.08.2017. */ public class NoNeg { public static List<Integer> noNeg(List<Integer> nums) { nums.removeIf(n -> n < 0); return nums; } public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(-2); System.out.println(noNeg(list)); } }
b15f5eadfdab29fbb4a35731e5de74ee92a0dc9f
15691ffc96ac9a2c7e92c363a5107dc41c29874e
/src/application/Main.java
ccad26d09b3fb5f2eb5b0865c4bbedfeb35cae8d
[]
no_license
sciemniak000/LSystems
55668c3096d758a29cca2e922948dffb2a5a0873
1bcd3515e625ead2f525df5ce28886f42dc793de
refs/heads/master
2020-07-06T04:24:28.874799
2019-08-17T21:34:19
2019-08-17T21:34:19
202,890,855
0
0
null
null
null
null
UTF-8
Java
false
false
14,671
java
package application; import java.io.File; import java.io.IOException; import java.nio.BufferOverflowException; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDecorator; import com.jfoenix.controls.JFXDialog; import com.jfoenix.controls.JFXDialogLayout; import com.jfoenix.controls.JFXRippler; import com.jfoenix.controls.JFXSpinner; import com.jfoenix.controls.JFXTextArea; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.effect.Light.Point; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; public class Main extends Application { private Task<Void> drawTreeTask; private Group canvasRoot; private static JFXSpinner spinner; private static StackPane root = new StackPane(); final double canvasWidth = 600; final double canvasHeight = 600; final double sceneWidth = 1200; final double sceneHeight = 700; final Rectangle selection = new Rectangle(); final Point anchor = new Point(); boolean dragFlag = false; int clickCounter = 0; ScheduledThreadPoolExecutor executor; ScheduledFuture<?> scheduledFuture; public Main() { executor = new ScheduledThreadPoolExecutor(1); executor.setRemoveOnCancelPolicy(true); } public static void main(String[] args) { spinner = new JFXSpinner(); Application.launch(args); } @Override public void start(Stage stage) { BorderPane layout = new BorderPane(); StackPane holder = new StackPane(); spinner.setRadius(20); spinner.setVisible(false); holder.getChildren().addAll(addCanvas(),spinner); holder.setStyle("-fx-background-color: rgba(0, 100, 100, 0.5);"); layout.setLeft(makeInput(stage)); layout.setCenter(holder); canvasRoot.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton().equals(MouseButton.PRIMARY) && !e.isControlDown()) { dragFlag = true; } } }); canvasRoot.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton().equals(MouseButton.PRIMARY) && !e.isControlDown()) { if (!dragFlag) { if (e.getClickCount() == 1) { scheduledFuture = executor.schedule(() -> singleClickAction(), 250, TimeUnit.MILLISECONDS); spinner.setVisible(true); } else if (e.getClickCount() > 1) { if (scheduledFuture != null && !scheduledFuture.isCancelled() && !scheduledFuture.isDone()) { scheduledFuture.cancel(false); doubleClickAction(); spinner.setVisible(false); } } } dragFlag = false; } else if(e.getButton().equals(MouseButton.SECONDARY) && !e.isControlDown()){ Thread t = drawTree(); try { t.join(); } catch (Exception er) { er.printStackTrace(); } Rewriter.get_rewriter().previousStep(); spinner.setVisible(false); } } }); canvasRoot.setOnMousePressed(event -> { MouseButton button = event.getButton(); if(button == MouseButton.MIDDLE ) { anchor.setX(event.getX()); anchor.setY(event.getY()); selection.setX(event.getX()); selection.setY(event.getY()); selection.setFill(Color.rgb(0, 0, 255, 0.2)); // transparent selection.setStroke(Color.BLUE); // border selection.getStrokeDashArray().add(10.0); canvasRoot.getChildren().add(selection); } }); canvasRoot.setOnMouseDragged(event -> { double width = Math.abs(event.getX() - anchor.getX()); double height = Math.abs(event.getY() - anchor.getY()); double delta = Math.abs(width - height); if (height < width) { selection.setWidth(height); selection.setHeight(height); selection.setX(Math.min(anchor.getX(), (event.getX()+delta))); selection.setY(Math.min(anchor.getY(), event.getY())); }else { selection.setWidth(width); selection.setHeight(width); selection.setX(Math.min(anchor.getX(), event.getX())); selection.setY(Math.min(anchor.getY(), (event.getY()+delta))); } }); canvasRoot.setOnMouseReleased(event -> { MouseButton button = event.getButton(); if(button == MouseButton.MIDDLE) { rescale(); canvasRoot.getChildren().remove(selection); selection.setWidth(0); selection.setHeight(0); } }); Rectangle clip = new Rectangle(canvasWidth, canvasHeight); clip.setLayoutX(0); clip.setLayoutY(0); canvasRoot.setClip(clip); root.getChildren().add(layout); JFXDecorator decorator = new JFXDecorator(stage, root); decorator.setCustomMaximize(true); stage.setScene(new Scene(decorator, sceneWidth, sceneHeight)); stage.setTitle("L-system"); stage.show(); } private void rescale() { double scale = canvasWidth * canvasWidth/selection.getWidth(); canvasRoot.setScaleX(scale); canvasRoot.setScaleY(scale); // canvasRoot.setLayoutX(selection.getX()); // canvasRoot.setLayoutY(selection.getY()); drawTree(); } private FlowPane makeInput(Stage stage) { FlowPane input = new FlowPane(); StackPane temp = new StackPane(); input.setPadding(new Insets(20, 10, 10, 10)); input.setVgap(8); input.setHgap(4); JFXTextArea in_area = new JFXTextArea(); JFXRippler rippler = new JFXRippler(in_area); temp.getChildren().addAll(in_area,rippler); in_area.setLabelFloat(true); in_area.setPromptText("Add Your Own Configuration"); JFXButton get_input = new JFXButton("Get input"); JFXButton get_file = new JFXButton("Get file"); JFXButton get_preset1 = new JFXButton("Preset 1"); JFXButton get_preset2 = new JFXButton("Preset 2"); JFXButton get_preset3 = new JFXButton("Preset 3"); JFXButton get_preset4 = new JFXButton("Preset 4"); JFXButton get_preset5 = new JFXButton("Preset 5"); JFXButton get_preset6 = new JFXButton("Preset 6"); JFXButton get_preset7 = new JFXButton("Preset 7"); Stream.of(get_input, get_file, get_preset1, get_preset2,get_preset3, get_preset4,get_preset5, get_preset6,get_preset7).forEach(button -> button.setStyle("-fx-padding: 0.7em 0.57em;\r\n" + " -fx-font-size: 14px;\r\n" + " -jfx-button-type: RAISED;\r\n" + " -fx-background-color: rgb(0,0,0);\r\n" + " -fx-pref-width: 500;\r\n" + " -fx-text-fill: WHITE;")); get_input.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { String new_text = in_area.getText(); drawTree(); if (new_text != null) { try { Parser.getParser().parse(new_text); spinner.setVisible(false); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } in_area.clear(); } } }); get_file.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Resource File"); fileChooser.getExtensionFilters().addAll( new ExtensionFilter("Text Files", "*.txt")); File selectedFile = fileChooser.showOpenDialog(stage); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss2.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss3.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset4.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss4.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset5.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss5.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset6.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss6.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); get_preset7.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { File selectedFile = new File("resources/miss7.txt"); if (selectedFile != null) { try { drawTree(); Parser.getParser().parse(selectedFile); spinner.setVisible(false); } catch (IOException e1) { e1.printStackTrace(); } } } }); input.getChildren().addAll(temp,get_input,get_file,get_preset1, get_preset2,get_preset3, get_preset4,get_preset5, get_preset6,get_preset7); in_area.setStyle("-fx-pref-width: 500;\r\n" + "-fx-background-color:WHITE"); return input; } private Node addCanvas() { FlowPane pane = new FlowPane(); canvasRoot = new Group(); drawTree(); pane.getChildren().add(canvasRoot); //pane.setStyle("-fx-background-color:RED"); pane.setMaxSize(500, 500); return pane; } private Thread drawTree(){ if(drawTreeTask != null && drawTreeTask.isDone()){ drawTreeTask.cancel(true); } drawTreeTask = new Task<Void>() { @Override protected Void call() throws Exception { try{ Platform.runLater(new Runnable() { @Override public void run() { canvasRoot.getChildren().clear(); } }); final Canvas canvas = new Canvas(canvasWidth, canvasHeight); GraphicsContext gcontext = canvas.getGraphicsContext2D(); gcontext.setLineWidth(0.3); Turtle turtleinstance = new Turtle(canvas, this); Rewriter.get_rewriter().setTurtle(turtleinstance); Platform.runLater(new Runnable() { @Override public void run() { canvasRoot.getChildren().add(canvas); } }); } catch (ThreadDeath e) { } catch(Throwable e){ e.printStackTrace(System.err); } return null; } @Override protected void succeeded() { } }; Thread thread = new Thread(drawTreeTask); thread.setDaemon(true); spinner.setVisible(true); thread.start(); return thread; } public void stop() { spinner.setVisible(false); executor.shutdown(); } private void singleClickAction() { spinner.setVisible(true); try { Thread t = drawTree(); t.join(); } catch (Exception e) { e.printStackTrace(); } Rewriter.get_rewriter().nextStep(); spinner.setVisible(false); } private void doubleClickAction() { canvasRoot.setScaleX(1); canvasRoot.setScaleY(1); } public static void showInfoDialog(String title, String text){ JFXDialogLayout content = new JFXDialogLayout(); content.setHeading(new Text(title)); content.setBody(new Text(text)); JFXDialog dialog = new JFXDialog(root, content, JFXDialog.DialogTransition.CENTER); JFXButton button = new JFXButton("Okay"); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { dialog.close(); } }); content.setActions(button); dialog.show(); } }
53595698d6b5a906b1442cac1648f7f40b199570
20649c101cc747537e4207e52e4e17af4ee88b8f
/app/src/main/java/in/techrebounce/recyclerviewexample/MainActivity.java
082b420cfed7ad330de25fd9024763d4bad0a20d
[]
no_license
sagarannaldas/RecyclerViewExample
ce667c5797818db570efced70c2feff920f971cb
7ca18759a360a27e15896580d5cc14653c9d8a2a
refs/heads/master
2023-02-26T09:09:32.805924
2021-01-28T08:11:35
2021-01-28T08:11:35
333,382,019
0
0
null
null
null
null
UTF-8
Java
false
false
3,548
java
package in.techrebounce.recyclerviewexample; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import java.util.ArrayList; import in.techrebounce.recyclerviewexample.Adapters.RecyclerViewAdapter; public class MainActivity extends AppCompatActivity { private ArrayList<String> mImages = new ArrayList<>(); private ArrayList<String> mImageNames = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initBitmaps(); initRecyclerView(); } private void initBitmaps(){ // add data to arraylists mImages.add("https://image.cnbcfm.com/api/v1/image/105377973-1533563328906rtx5qks4.jpg?v=1582149229"); mImages.add("https://static-27.sinclairstoryline.com/resources/media/e2ce44b6-28b0-45bc-916d-5aa927d18294-large16x9_200624_ap_lori_vallow.jpg?1608089244492"); mImages.add("https://s.hdnux.com/photos/01/13/75/36/19912634/3/rawImage.jpg"); mImages.add("https://www.gannett-cdn.com/presto/2020/12/15/USAT/18a4fc3b-1582-4596-add1-2f6e6990cd10-John_Tyreman_and_family_.jpg?crop=5243,2950,x0,y391&width=3200&height=1680&fit=bounds"); mImages.add("https://i.ytimg.com/vi/VLPDNo8PjIE/maxresdefault.jpg"); mImages.add("https://www.clickondetroit.com/resizer/mzHNWt5OwgelMoLFwsKSKJsB2ZA=/1600x900/smart/filters:format(jpeg):strip_exif(true):strip_icc(true):no_upscale(true):quality(65)/cloudfront-us-east-1.images.arcpublishing.com/gmg/KUFN33WMSFE7PAN4MO5LCYP3K4.jpg"); mImages.add("https://a57.foxnews.com/static.foxbusiness.com/foxbusiness.com/content/uploads/2020/12/0/0/Mark-Zuckerberg-and-Priscilla-Chan.jpg?ve=1&tl=1"); mImages.add("https://img.ksl.com/slc/2803/280399/28039930.jpeg?filter=ksl/responsive_story_lg"); mImages.add("https://a57.foxnews.com/static.foxbusiness.com/foxbusiness.com/content/uploads/2020/07/0/0/Alex-Rodriguez-2-Getty-Images.jpg?ve=1&tl=1"); mImages.add("https://www.wlbt.com/resizer/VucCNRrpsWrKO-B4odAHBjzAsl4=/1200x0/cloudfront-us-east-1.images.arcpublishing.com/raycom/MT4Z5AGOGJGZ7HUUP4SVEQNNII.jpg"); mImages.add("https://www.countynewscenter.com/wp-content/uploads/coronavirus-1600px.jpg"); mImages.add("https://www.denverpost.com/wp-content/uploads/2020/12/AFP_8X8824.jpg?w=1024&h=765"); mImages.add("https://d32r1sh890xpii.cloudfront.net/article/718x300/2020-12-15_j0nq9voimc.jpg"); mImages.add("https://www.kold.com/resizer/lWPeFyDD47zrJ_aFPHDH7TfTjIk=/1200x0/cloudfront-us-east-1.images.arcpublishing.com/raycom/VHFYR5HBDZBZZNAWGF2RO5ZV6I.PNG"); mImageNames.add("1"); mImageNames.add("2"); mImageNames.add("3"); mImageNames.add("4"); mImageNames.add("5"); mImageNames.add("6"); mImageNames.add("7"); mImageNames.add("8"); mImageNames.add("9"); mImageNames.add("10"); mImageNames.add("11"); mImageNames.add("12"); mImageNames.add("13"); mImageNames.add("14"); } private void initRecyclerView() { RecyclerView recyclerView = findViewById(R.id.recycler_view); RecyclerViewAdapter adapter = new RecyclerViewAdapter(mImageNames, mImages,this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); } }
d6e8efd5bd7e31918bfed9e53d90792a3e4735ec
b26f7b26f3b4eb7e0ab41bc7e5f0f3d51b62f6a8
/src/main/java/cat/udl/tennis/game/Score.java
e1bb3ed440f51892b5a86c646dff9c337a1828cb
[ "Apache-2.0" ]
permissive
mduenast/internationalization-java
d576bf007493f1bd0c3d767f13f4ba22a8e82988
d9ac296a3b1fd5c16e12d4806ef165b50cc110fb
refs/heads/master
2021-08-19T14:39:08.870964
2017-11-26T17:18:16
2017-11-26T17:18:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
502
java
package cat.udl.tennis.game; public class Score implements Comparable<Score> { private int value; public Score() { this.value = 0; } public void increment() { this.value++; } public void reset() { this.value = 0; } public int minus(Score score) { return this.value - score.value; } public int getValue() { return value; } public int compareTo(Score score) { return this.value - score.value; } }
1c75e7a6dd6080f2f8f5ddfae1b31c0fbfbce5b3
e35f13a081f38316719fef86660a9533c5cc10a1
/mvc/src/test/java/com/ascending/blair/service/AuthorityRepositoryTest.java
5b4ff4c6a20e8b0e258e5c9cdd672d794ebe4a8c
[]
no_license
liangblairshi/Online-Administration-System
8e4c62f69ff3768186518fdca0ed056611d66d14
3d53aa80a9cffd06d5cfe048edc5ba5f29efc6f1
refs/heads/master
2021-10-20T20:51:23.190105
2019-03-01T17:26:05
2019-03-01T17:26:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,434
java
package com.ascending.blair.service; import com.ascending.blair.config.AppConfig; import com.ascending.blair.domain.Authority; import com.ascending.blair.domain.User; import com.ascending.blair.repository.AuthorityRepository; import com.ascending.blair.repository.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; @WebAppConfiguration @ContextConfiguration(classes = {AppConfig.class}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("unit") public class AuthorityRepositoryTest { @Autowired private AuthorityRepository authorityRepository; @Autowired private UserRepository userRepository; @Test @Transactional public void findRoleByUserIdTest(){ // assertTrue(true); List<Authority> myList = new ArrayList<>(); Authority auth1 = new Authority(); Authority auth2 = new Authority(); Authority auth3 = new Authority(); User user1 = new User(); User user2 = new User(); auth1.setRole("ADMIN"); auth2.setRole("USER"); auth3.setRole("ADMIN"); user1.setFirstName("Lily"); user1.setLastName("Lee"); user1.setEmail("[email protected]"); user1.setPassword("ll123"); user1.setUsername("llily"); user2.setFirstName("Silas"); user2.setLastName("Black"); user2.setEmail("[email protected]"); user2.setPassword("sb123"); user2.setUsername("bsilas"); auth2.setUser(user1); userRepository.save(user1); userRepository.save(user2); auth1.setUser(user1); auth2.setUser(user1); auth3.setUser(user1); authorityRepository.save(auth1); authorityRepository.save(auth2); myList.add(auth1); myList.add(auth2); List<Authority> expected = authorityRepository.findByUser_Id(user1.getId()); assertEquals(myList, expected); } }
6c2cd8c3f342e8f09d445d93a9ac57d1108c7806
b1b039cf90b1d19d4e75f91032b09322ebd1b0d7
/pinyougou-pojo/src/main/java/com/pinyougou/pojo/TbSpecification.java
912b338c5a90b786e740e121a101aa7828b1c8a3
[]
no_license
yangzhishuai126/pinyougou
d57061723b7a2fb807e1409d6da6f2fa0dac7c89
ffb24cfc49d9c4f47166208ccc834743c8bd72e4
refs/heads/master
2020-03-28T06:03:53.203450
2018-09-07T11:09:54
2018-09-07T11:10:06
147,812,073
0
0
null
null
null
null
UTF-8
Java
false
false
540
java
package com.pinyougou.pojo; import java.io.Serializable; public class TbSpecification implements Serializable { private static final long serialVersionUID = -5963544798517861298L; private Long id; private String specName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSpecName() { return specName; } public void setSpecName(String specName) { this.specName = specName == null ? null : specName.trim(); } }