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
0274c0191379efcfe4073c815ca6994ec059a5aa
1e9c9f2a9639db7cdb032aae69cb4d99aef1d3a5
/codeChef/src/medium/unsolved/TeamFormation.java
7b2ec5ad2df905ff2c364a5f25afe0c1485d6c15
[ "MIT" ]
permissive
sagarnikam123/learnNPractice
f0da3f8acf653e56c591353ab342765a6831698c
1b3b0cb2cff2f478006626a4c37a99102acbb628
refs/heads/master
2023-02-04T11:21:18.211654
2023-01-24T14:47:52
2023-01-24T14:47:52
61,184,927
2
1
MIT
2022-03-06T11:07:18
2016-06-15T06:57:19
Python
UTF-8
Java
false
false
4,972
java
/** Team Formation Battle of the Chefs is coming up! It's a contest where different teams of different Chefs compete against each other. Our Chef wants to send one of the best teams from his entire staff. Selecting a good team is not about having the best people, but it is about having members who can cooperate and work well with each other. Chef is very aware of this fact. So he chooses the following strategy to decide a team. He lines up all his N cooks in a line. Each of these cooks has a skill level associated with him. Denote the level of the i-th cook as skill[i] for 1 ≤ i ≤ N. Let us make a few points on a team formation. A team can have any number of cooks. Each team should consist of consecutive cooks. So, for example, cooks with positions 3, 4, 5 can form a team, but cooks with positions 4, 5, 7, 8 can not. A team is a candidate team if the difference between the maximum skill and the minimum skill of the cooks in the team does not exceed the threshold C. A cook can be in 0 or more candidate teams. Which means that candidate teams can intersect. Two candidate teams are considered to be different if there exists at least one cook who is in one team but not in the other. Chef has not yet decided the team of what size he is going to send to the battle. To be precise we note, that the team size is the total number of cooks in it. For the given team size Chef wants to consider all candidate teams of this size according to the rules described above, evaluate them for himself and choose the best one. Denote the total number of candidate teams for the given size K as cand[K]. To increase the chances of choosing better team he wants the number of candidate teams to be as large as possible. But Chef is a human and can't evaluate too many teams. The maximal number of teams he can evaluate depends on many factors such as his mood or fatigue. We call it the Chef's limit. Denote the current Chef's limit as M. Since Chef still wants the total number of candidate teams to be as large as possible you need to find the team size K such that cand[K] ≤ M, among all such K find the value for which cand[K] is maximal and if such K is not unique find the minimal K among them. Since Chef's limit always changes according to his mood or fatigue you should find the required team size for several values of M. Chef also wants to know the total number of candidate teams for the size you will find. There will be Q values of M in all. In order to keep the input small the skills of the cooks will be given in the following way. Skills of the first X cooks are given in the input, where X = min(10000, N). If N > 10000 skills of the remaining cooks for 10000 < i ≤ N are calculated as skill[i] = (A * skill[i-1] + B * skill[i-2] + D) mod 230, where A, B and D are given in the input. Here mod denotes the modulo operation, that is, Y mod Z is the remainder of division of Y by Z. Input The first line of the input contains a single integer T, the number of test cases to follow. Each test case consists of 3 lines. The first line contains 6 space-separated integers N, C, Q, A, B and D. The second line contains X = min(N, 10000) space-separated integers, i-th integer among them represents the skill of the i-th cook, that is, the number skill[i]. The third line contains Q space-separated integers, the values of M for which you need to find the optimal team size and the number of candidate teams of this size. Output For each test case, output Q lines containing the optimal team size for the corresponding value of M and the number of candidate teams corresponding to this team size separated by a space. Constraints 1 ≤ T ≤ 5 1 ≤ N ≤ 500000 0 ≤ C < 230 1 ≤ Q ≤ 1000 0 ≤ A, B, D < 230 0 ≤ skill[i] < 230 for 1 ≤ i ≤ X 1 ≤ M ≤ N *********************************************************************************************************************** Example Input: 2 6 3 3 1 1 1 6 2 4 5 6 3 4 3 6 6 10 1 2 2 2 1 1000 1 1000 1 1000 4 Output: 2 4 3 3 1 6 2 0 Explanation Case 1. With team size 2, we have 4 candidate teams: {2, 4}, {4, 5}, {5, 6}, and {6, 3}. Here numbers denote the cooks' skills. With any other team size, the number of candidate teams is either less than 4 or greater than 4. Similarly, with team size 3, we have 3 candidate teams, which are {2, 4, 5}, {4, 5, 6} and {5, 6, 3}. With team size 1, we have 6 candidate teams with one member in each team. Case 2. With team size 1, we have 6 possible candidate teams. But 6 > 4. For all other team sizes, the total number of candidate teams is 0. Thus, the answer is the smallest size among them, i.e., 2. **********************************************************************************************************************/ package medium.unsolved; public class TeamFormation { public static void main(String[] args) { } }
[ "sagarnikam123@gmail.com" ]
sagarnikam123@gmail.com
0ce218f1f66546d57f579d511930826779f54a91
b8689d9a6f723be08baa1e0a2f534c0fbef8f63b
/src/main/java/com/njyb/gbdbase/service/common/engine/builder/componet/state/context/IndexSearchStateContext.java
59089f732be0a79e3a7a19170fa536a4999ba38e
[ "MIT" ]
permissive
Willie1234/Inforvellor
08a89421a2c5f559229aad4f5e6b9688eeb92448
7d251f2ae3e41a2385c5bfb10b6d80981dbb1099
refs/heads/master
2021-01-18T07:15:21.699827
2015-07-21T20:01:28
2015-07-21T20:01:28
39,401,972
0
0
null
2015-07-21T20:35:02
2015-07-20T18:43:45
Java
UTF-8
Java
false
false
1,809
java
package com.njyb.gbdbase.service.common.engine.builder.componet.state.context; import org.apache.lucene.search.IndexSearcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.njyb.gbdbase.model.datasearch.common.SearchPropertiesModel; import com.njyb.gbdbase.service.common.engine.builder.componet.state.ISearcherState; import com.njyb.gbdbase.service.common.engine.builder.componet.state.impl.AllCountryState; import com.njyb.gbdbase.service.common.engine.builder.componet.state.impl.SplitCountrySearchState; /** * 封装不同的状态对象 返回不同行为 上下文 * @author jiahp * */ @SuppressWarnings("all") public class IndexSearchStateContext { //处理不同的状态执行不同的行为 public static IndexSearcher requestIndexSearcher(String countryName,String indexpath,String[] fields, String[] values,SearchPropertiesModel propertiesMap){ return getISearcherState(countryName,propertiesMap).handleIndexSearcher(countryName,indexpath, fields, values); } /** * 根据国家名称 获取对应状态实例 * @param countryName * @return */ private static ISearcherState getISearcherState(String countryName,SearchPropertiesModel propertiesMap){ //注入状态接口 ISearcherState state=null; //针对美国 if (isSplit(countryName,propertiesMap)) { state=new SplitCountrySearchState(); } else{ state=new AllCountryState(); } return state; } /** * 判断什么时候该切分索引类型 * @param country * @return */ private static boolean isSplit(String country,SearchPropertiesModel propertiesMap){ String str=propertiesMap.getPropertiesMap().get("yyyy-mm").toString(); return str.contains(country); } }
[ "cherry.lee.dreamhigh@gmail.com" ]
cherry.lee.dreamhigh@gmail.com
1861c801eb0193e02d85bc77a697a6b80772e743
3bf3c37785698d67a7b40ddf765b24207e06c4b3
/src/main/java/com/java/refresh/beans/DtoBean.java
c7b7118ca619e7c8ccdf6a82fb69d85da4367b7b
[ "MIT" ]
permissive
medkannouch/java-refresh
c4c865fd31f97d62d78a70cb16b7a82ffbb7dfb4
ed8fc140a5b093f3225ce3b76ccb9826db1fc0ba
refs/heads/master
2020-04-09T15:04:41.141749
2018-12-05T15:11:38
2018-12-05T15:11:38
160,415,530
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
package com.java.refresh.beans; public class DtoBean { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public DtoBean(String message) { super(); this.message = message; } }
[ "medkannouch@gmail.com" ]
medkannouch@gmail.com
4005f9d588c48f22fa805227cd4916119586c595
9c27c47fb50998102721596c8b4c3f0183676239
/src/main/java/mil/tatrc/physiology/datamodel/patient/actions/SEAsthmaAttack.java
c4342c6a422f2b3ad517c6184c14067a1ec917c6
[ "MIT" ]
permissive
ScreenBasedSimulator/ScreenBasedSimulator2
6e8022a7479fc694b41f4cf5fc9f7bcd94fd006f
3f8d05c6a8847d01e6eca6e3f123e12f1604fce7
refs/heads/master
2021-01-10T15:36:52.695702
2016-04-04T15:58:22
2016-04-04T15:58:22
45,258,461
2
1
null
2016-02-16T21:27:33
2015-10-30T15:13:42
C++
UTF-8
Java
false
false
2,346
java
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. 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 mil.tatrc.physiology.datamodel.patient.actions; import mil.tatrc.physiology.datamodel.CDMSerializer; import mil.tatrc.physiology.datamodel.bind.AsthmaAttackData; import mil.tatrc.physiology.datamodel.properties.SEScalarFraction; public class SEAsthmaAttack extends SEPatientAction { protected SEScalarFraction severity; public SEAsthmaAttack() { severity = null; } public void copy(SEAsthmaAttack other) { if(this==other) return; super.copy(other); if (other.severity != null) getSeverity().set(other.getSeverity()); else if (severity != null) severity.invalidate(); } public void reset() { super.reset(); if (severity != null) severity.invalidate(); } public boolean load(AsthmaAttackData in) { super.load(in); getSeverity().load(in.getSeverity()); return true; } public AsthmaAttackData unload() { AsthmaAttackData data = CDMSerializer.objFactory.createAsthmaAttackData(); unload(data); return data; } protected void unload(AsthmaAttackData data) { super.unload(data); if (severity != null) data.setSeverity(severity.unload()); } public boolean hasSeverity() { return severity == null ? false : severity.isValid(); } public SEScalarFraction getSeverity() { if (severity == null) severity = new SEScalarFraction(); return severity; } public String toString() { if (severity != null) return "AsthmaAttack" + "\n\tSeverity: " + getSeverity(); else return "Action not specified properly"; } }
[ "codemysky@hotmail.com" ]
codemysky@hotmail.com
776c88b8b9728934d17a8c2da3d1f634ddbc6356
1b9e5be00015ea1880b242179df4bea8495bea04
/src/main/java/uk/ac/soton/ecs/hbd1g15/MyConvolution.java
8931cf2e168e61c23bb6e7435d97f44309ba1410
[]
no_license
HannahDadd/Image-Filtering-and-Hybrid-Images
da03e090597d34b69dcf7b74e1cf196335c0abbb
32999147f56d5b0e19e4c229fabbb75a1e4be629
refs/heads/master
2021-08-08T21:45:34.512001
2017-11-11T10:57:04
2017-11-11T10:57:04
109,005,938
0
0
null
null
null
null
UTF-8
Java
false
false
2,774
java
package uk.ac.soton.ecs.hbd1g15; import org.openimaj.image.FImage; import org.openimaj.image.processor.SinglebandImageProcessor; /** * Operator to perform a Convolution * */ public class MyConvolution implements SinglebandImageProcessor<Float, FImage> { private float[][] kernel; public MyConvolution(float[][] kernel) { this.kernel = kernel; } @Override public void processImage(FImage image) { // Check that both dimensions are odd if(this.kernel[0].length%2 == 0) { throw new IllegalArgumentException(this.kernel[0].length + " is even. Both dimensions of template must be odd."); } if(this.kernel[1].length%2 == 0) { throw new IllegalArgumentException(this.kernel[1].length + " is even. Both dimensions of template must be odd."); } // Create a temporary, completely black image float[][] temporaryImage = new float[image.getHeight()][image.getWidth()]; for (int y=0; y<image.getHeight(); y++) { for (int x=0; x<image.getWidth(); x++) { temporaryImage[y][x] = 0; } } FImage temporaryBufferImage = new FImage(temporaryImage); // Get the middle of the template distance int middleRowIndex = Math.floorDiv(this.kernel[0].length, 2); int middleColIndex = Math.floorDiv(this.kernel[1].length, 2); // Loop through each pixel in the image ignoring the border for(int x=0; x<image.getWidth(); x++) { for(int y=0; y<image.getHeight(); y++) { float sum = 0; // Loop through each coefficient in the template for(int templateX=0; templateX<this.kernel[0].length; templateX++) { for(int templateY=0; templateY< this.kernel[1].length; templateY++) { int pixelX = 0; int pixelY = 0; // When at the part of the template that cannot be filled loop round to the top if(x-middleRowIndex+templateX<0) { pixelX = image.getWidth()-Math.abs(x-middleRowIndex+templateX); } else if(x-middleRowIndex+templateX > image.getWidth()-1) { pixelX = 0 + x-middleRowIndex+templateX - image.getWidth(); } else { pixelX = x-middleRowIndex+templateX; } if(y-middleColIndex+templateY<0) { pixelY= image.getHeight()-Math.abs(y-middleColIndex+templateY); } else if(y-middleColIndex+templateY > image.getHeight()-1) { pixelY = 0 + y-middleColIndex+templateY - image.getHeight(); } else { pixelY = y-middleColIndex+templateY; } // Times each pixel value by the template value and add them all together sum = sum + image.getPixelNative(pixelX, pixelY) * this.kernel[templateX][templateY]; } } temporaryBufferImage.setPixelNative(x, y, sum); } } // Set the contents of temporary buffer image to the image. image.internalAssign(temporaryBufferImage); } }
[ "hannahbdadd@googlemail.com" ]
hannahbdadd@googlemail.com
7b99c3e37b1cb58f67da79d32c106f45133117d3
90d384310ef29d06eed6500f49fd9a0726b328f7
/src/java/LocalFuntionGlobal/SystemBean.java
f8a99d8061c6e7eb90e9dcd074f0729805d86b44
[]
no_license
chaunht-git1/WebHoibao
05e2376ef76b98c2c36b1478e7d7d6c2736fd641
15127e3070c5ff160d16efe62652a993865edfa2
refs/heads/master
2020-04-12T10:21:22.636879
2019-01-28T23:26:35
2019-01-28T23:26:35
162,427,553
0
0
null
null
null
null
UTF-8
Java
false
false
2,700
java
package LocalFuntionGlobal; import ConnectBean.ConnectionProvider; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; import javax.imageio.ImageIO; @ManagedBean public class SystemBean { public static void proMessage(String mess){ FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "", mess)); } public static void proMessError(String mess){ FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, mess, mess )); } public ResultSet layGiaTri1Para(String tablename,String colname,String outcolname,String prm1,Date prm2,Integer prm3 , int sttpara,int outvalue) throws SQLException{ ConnectionProvider.reconnectdbastatic(); Connection con=ConnectionProvider.getCon(); try { String sql; if (outvalue==0) { sql= " SELECT * FROM"+tablename+" WHERE "+colname+"= ? "; } else{ sql = " SELECT "+ outcolname+" FROM"+tablename+" WHERE "+colname+"= ? "; } // Tạo một câu SQL có 2 tham số (?) // String sql = strsql; // Tạo một đối tượng PreparedStatement. PreparedStatement pstm = con.prepareStatement(sql); // Sét đặt giá trị tham số thứ nhất (Dấu ? thứ nhất) // Kiem tra kieu du lieu cua bien truyen vao . switch (sttpara){ case 1: pstm.setString(1, prm1); break; case 2: pstm.setDate(1,(java.sql.Date)prm2 ); break; case 3: pstm.setInt(1, prm3); break; } ResultSet rs = pstm.executeQuery(); return rs; } catch (Exception e) { return null ; } } // Chuyen doi gia tri sang Buffimage public BufferedImage layImage (InputStream byteImage) throws IOException{ BufferedImage bf = null ; // InputStream in =new ByteInputStream(); bf=ImageIO.read(byteImage); return bf ; } }
[ "chaunht1980@gmail.com" ]
chaunht1980@gmail.com
fb4992f99ef2ffa39e2fb4636191cd59d0803934
4b3a5ae1fc3eb84d675db35369e85cfed8c1aa04
/src/剑指Offer/剑指Offer26/树的子结构/Solution.java
77c0a2a2d4ca4dd8f609fe1018b6b9a0aefed1f5
[]
no_license
aestheticJL/my-own-leetcode-record
cd00ce3e42ac557c2f869cf2108ed7c2932b1a35
d3ec15ca7cf6bdbd81112a04431409dd06215494
refs/heads/master
2021-05-29T00:29:15.442317
2020-10-21T05:21:15
2020-10-21T05:21:15
254,294,665
0
0
null
null
null
null
UTF-8
Java
false
false
1,421
java
/* 剑指 Offer 26. 树的子结构 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A: 3 / \ 4 5 / \ 1 2 给定的树 B: 4 / 1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= 10000 ###解题思路 递归 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:41.6 MB, 在所有 Java 提交中击败了100.00%的用户 */ package 剑指Offer.剑指Offer26.树的子结构; import tree.TreeNode; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSubStructure(TreeNode A, TreeNode B) { if (A == null || B == null) return false; return isChildTree(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B); } public boolean isChildTree(TreeNode A, TreeNode B) { if (B == null) return true; if (A == null) return false; return A.val == B.val && isChildTree(A.right, B.right) && isChildTree(A.left, B.left); } }
[ "m258789@126.com" ]
m258789@126.com
9430eee0aaf7e5386df2f575eedae5d66f71013f
0498b2a550adc40b48da03a5c7adcd7c3d3a037d
/errai-cdi/weld-integration/src/test/java/org/jboss/errai/cdi/event/server/MethodWithLocalService.java
efe5429c545e332a11d9aa56c376ed405df27400
[]
no_license
sinaisix/errai
ba5cd3db7a01f1a0829086635128d918f25c0122
7e7e0a387d02b7366cbed9947d6c969f21ac655f
refs/heads/master
2021-01-18T08:03:04.809057
2015-02-24T00:10:16
2015-02-24T00:14:28
31,277,838
1
0
null
2015-02-24T19:32:46
2015-02-24T19:32:46
null
UTF-8
Java
false
false
688
java
package org.jboss.errai.cdi.event.server; import javax.inject.Inject; import org.jboss.errai.bus.client.api.Local; import org.jboss.errai.bus.client.api.base.MessageBuilder; import org.jboss.errai.bus.client.api.messaging.Message; import org.jboss.errai.bus.client.api.messaging.MessageBus; import org.jboss.errai.bus.server.annotations.Service; import org.jboss.errai.common.client.protocols.MessageParts; public class MethodWithLocalService { @Inject private MessageBus bus; @Service @Local private void localMethodService(Message message) { MessageBuilder.createMessage(message.get(String.class, MessageParts.ReplyTo)).noErrorHandling().sendNowWith(bus); } }
[ "max.barkley@gmail.com" ]
max.barkley@gmail.com
5e15c37d66fc7b11a5144dd96cc3390d769d9d0d
459d1640ed1f959742ed0e444ea6fd059cdf925b
/projectzero/src/com/projectzero/demo/samplemain/sample/sampleImageHelper/ImageHelperActivity.java
e8fecf60baa760c0945cb3c344a6c3da971b01c9
[]
no_license
495055772/BaseProj
b34a55aa426b8901057886814a22ff0960295a09
8dfc4a2df618f360b0cb89b0e51ee166786d11e3
refs/heads/master
2020-04-06T03:41:20.395675
2015-04-16T05:31:22
2015-04-16T05:31:22
33,976,493
0
0
null
null
null
null
UTF-8
Java
false
false
1,800
java
package com.projectzero.demo.samplemain.sample.sampleImageHelper; import android.graphics.Bitmap; import android.os.Bundle; import android.widget.ImageView; import com.projectzero.demo.R; import com.projectzero.demo.base.BaseProjectActivity; import com.projectzero.library.helper.ImageHelper; import org.androidannotations.annotations.*; @EActivity(R.layout.sample__activity_sampleimagehelperactivity) public class ImageHelperActivity extends BaseProjectActivity { @ViewById(R.id.content_iv) ImageView mIv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @AfterViews void afterView() { // loadBitmap(); // loadBitmapInSampleBitmap(300, 300); loadBitmapInSampleBitmapUsePath(300, 300, true); } @Background void loadBitmap() { try { Bitmap bitmap = ImageHelper.getInstance(this).loadImage(ImageData.bigimages[0]); showUI(bitmap); } catch (Exception e) { e.printStackTrace(); } } @Background void loadBitmapInSampleBitmap(int w, int h) { try { Bitmap bitmap = ImageHelper.getInstance(this).loadImage(ImageData.bigimages[0], w, h); showUI(bitmap); } catch (Exception e) { e.printStackTrace(); } } @Background void loadBitmapInSampleBitmapUsePath(int w, int h, boolean isCut) { try { String url = ImageData.bigimages[0]; Bitmap bitmap = ImageHelper.getInstance(this).loadImage(url, w, h, isCut); showUI(bitmap); } catch (Exception e) { e.printStackTrace(); } } @UiThread void showUI(Bitmap bitmap) { mIv.setImageBitmap(bitmap); } }
[ "liumeng@hujiang.com" ]
liumeng@hujiang.com
86b8f3b4ea424b8f1aa0b2178ca7883969c2ce31
f24cb1e30ab8be1cedd72a00f6ac0a0ac297f316
/amanager/src/org/xclcharts/renderer/axis/XYAxis.java
c5aa78a3403a77791930bf4956571a75fad4ba04
[]
no_license
xueyuleiT/-app
b3ce8a73c41600e234b0e7e5e038ca741cfaed20
5f0f69ef46b1abe0e52aa57bb4041561f5d44620
refs/heads/master
2020-04-08T06:25:25.325204
2018-11-26T02:05:21
2018-11-26T02:05:21
159,096,019
0
0
null
null
null
null
UTF-8
Java
false
false
10,999
java
/** * Copyright 2014 XCL-Charts * * 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. * * @Project XCL-Charts * @Description Android图表基类库 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com) * @license http://www.apache.org/licenses/ Apache v2 License * @version 1.0 */ package org.xclcharts.renderer.axis; import java.util.List; import org.xclcharts.common.DrawHelper; import org.xclcharts.common.IFormatterTextCallBack; import org.xclcharts.common.MathHelper; import org.xclcharts.renderer.XChart; import org.xclcharts.renderer.XEnum; import android.graphics.Canvas; import android.graphics.Paint.Align; import android.util.Log; /** * @ClassName XYAxis * @Description XY坐标系类,定义了具体的绘制及格式回调函数的处理 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com) * */ public class XYAxis extends Axis { // 数据集 protected List<String> mDataSet = null; // 用于格式化标签的回调接口 private IFormatterTextCallBack mLabelFormatter; //标签显示位置,分别在轴的左边,中间,右边 private Align mTickMarksAlign = Align.RIGHT; //标签显示位置,分别在轴的上面,中间,底下 private XEnum.VerticalAlign mTickMarksPosition = XEnum.VerticalAlign.BOTTOM; //默认刻度线所占宽度 private int mTickMarksLength = 15; //刻度标记与轴的间距 private int mTickLabelMargin = 10; public XYAxis() { //设置轴线条粗细 //this.getAxisPaint().setStrokeWidth(5); } /** * 设置时刻度显示在上,中,下哪个地方,针对横轴 * @param position 上方,居中,下方 */ public void setVerticalTickPosition(XEnum.VerticalAlign position) { mTickMarksPosition = position; } /** * 返回轴上刻度线显示的位置 * @return 位置 */ public XEnum.VerticalAlign getVerticalTickPosition() { return mTickMarksPosition; } /** * 设置刻度靠左,中,右哪个位置显示,针对竖轴 * @param align 靠左,居中,靠右 */ public void setHorizontalTickAlign(Align align) { mTickMarksAlign = align; } public Align getHorizontalTickAlign() { return mTickMarksAlign; } /** * 设置标签的显示格式 * @param callBack 回调函数 */ public void setLabelFormatter(IFormatterTextCallBack callBack) { this.mLabelFormatter = callBack; } /** * 返回标签显示格式 * * @param value 传入当前值 * @return 显示格式 */ protected String getFormatterLabel(String text) { String itemLabel = ""; try { itemLabel = mLabelFormatter.textFormatter(text); } catch (Exception ex) { itemLabel = text; } return itemLabel; } /** * 竖轴坐标标签,依左,中,右,决定标签横向显示在相对中心点的位置 * @param centerX 轴上中点X坐标 * @param centerY 轴上中点X坐标 * @param text 标签文本 */ protected void renderHorizontalTick(XChart xchart,Canvas canvas, float centerX, float centerY, String text,boolean isTickVisible) { //Log.e("XYAxis","XYAxis renderHorizontalTick"); if (false == isShow())return; //Log.e("XYAxis","XYAxis renderHorizontalTick isShow == true"); float marksStartX = centerX; float markeStopX = centerX; float labelStartX = centerX; float labelStartY = centerY; switch (getHorizontalTickAlign()) { case LEFT: { if (isShowTickMarks()) { marksStartX = MathHelper.getInstance().sub(centerX,getTickMarksLength()); markeStopX = centerX; } if(this.isShowAxisLabels()) labelStartX = MathHelper.getInstance().sub(marksStartX , getTickLabelMargin()); break; } case CENTER: { if (isShowTickMarks()) { marksStartX = MathHelper.getInstance().sub(centerX , getTickMarksLength() / 2); markeStopX = MathHelper.getInstance().add(centerX , getTickMarksLength() / 2); } break; } case RIGHT: if (isShowTickMarks()) { marksStartX = centerX; markeStopX = MathHelper.getInstance().add(centerX , getTickMarksLength()); } if(this.isShowAxisLabels()) labelStartX = MathHelper.getInstance().add(markeStopX , getTickLabelMargin()); break; default: break; } //横轴刻度线 if (isShowTickMarks() && isTickVisible) { canvas.drawLine(marksStartX, centerY, MathHelper.getInstance().add(markeStopX, this.getAxisPaint().getStrokeWidth() / 2), centerY, getTickMarksPaint()); } //标签 // 当标签文本太长时,可以考虑分成多行显示如果实在太长,则开发用...来自己处理 if (isShowAxisLabels()) { int textHeight = DrawHelper.getInstance().getPaintFontHeight( getTickLabelPaint()); textHeight /=4; if(Align.LEFT == getHorizontalTickAlign()) //处理多行标签,待做 { float width = 0.0f; if (isShowTickMarks()) { width = markeStopX - xchart.getLeft(); }else{ //width = xchart.getPlotArea().getLeft() - xchart.getLeft(); width = MathHelper.getInstance().sub( xchart.getPlotArea().getLeft() , xchart.getLeft()); } //renderLeftAxisTickMaskLabel(canvas,centerX,centerY,text,width ); renderLeftAxisTickMaskLabel(canvas,labelStartX, labelStartY + textHeight,text,width ); }else{ //*/ DrawHelper.getInstance().drawRotateText( getFormatterLabel(text), labelStartX, labelStartY + textHeight, getTickLabelRotateAngle(), canvas, getTickLabelPaint()); } } } /** * 横轴坐标标签,决定标签显示在相对中心点的上方,中间还是底部位置 * @param centerX 轴上中点X坐标 * @param centerY 轴上中点Y坐标 * @param text 标签文本 */ protected void renderVerticalTick(Canvas canvas, float centerX, float centerY, String text,boolean isTickVisible) { if (false == isShow()) return; float marksStartY = centerY; float marksStopY = centerY; float labelsStartY = centerY; switch (getVerticalTickPosition()) { case TOP: { if (isShowTickMarks()) { marksStartY = MathHelper.getInstance().sub(centerY , getTickMarksLength()); marksStopY = centerY; } if(this.isShowAxisLabels()) { //DrawHelper.getInstance().getPaintFontHeight(getTickLabelPaint()) / 2 labelsStartY = MathHelper.getInstance().sub(marksStartY, getTickLabelMargin() ); } break; } case MIDDLE: { if (isShowTickMarks()) { marksStartY = MathHelper.getInstance().sub(centerY , getTickMarksLength() / 2); marksStopY = MathHelper.getInstance().add(centerY , getTickMarksLength() / 2); } break; } case BOTTOM: if (isShowTickMarks()) { marksStartY = centerY; //marksStopY = Math.round(centerY + getTickMarksLength()); marksStopY = MathHelper.getInstance().add(centerY , getTickMarksLength()); } if(this.isShowAxisLabels()) { labelsStartY = marksStopY + getTickLabelMargin() + DrawHelper.getInstance() .getPaintFontHeight(getTickLabelPaint()) / 3; } break; default: break; } if (isShowTickMarks() && isTickVisible) { float mstartX = MathHelper.getInstance().sub(marksStartY, getAxisPaint().getStrokeWidth() /2 ) ; //if( Float.compare(mstartX, xchart.getPlotArea().getLeft()) == -1) || // Float.compare(mstartX, xchart.getPlotArea().getRight()) == 1 ) //{ //}else{ canvas.drawLine(centerX, mstartX, // marksStartY - this.getAxisPaint().getStrokeWidth() / 2, centerX, marksStopY, getTickMarksPaint()); //} } if (isShowAxisLabels()) { //定制化显示格式 DrawHelper.getInstance().drawRotateText(getFormatterLabel(text), centerX, labelsStartY, getTickLabelRotateAngle(), canvas, getTickLabelPaint()); } } //只针对renderHorizontalTick(),处理标签文字太长,分多行显示的情况, // 即只有在竖向图左轴,并且标签靠左显示时,才会处理这个问题 private void renderLeftAxisTickMaskLabel(Canvas canvas, float centerX, float centerY, String text,float width) { if(!isShowAxisLabels())return; //格式化后的标签文本. String label = getFormatterLabel(text); //横向找宽度,竖向找高度,竖向的就不处理了。只搞横向多行的 double txtLength = DrawHelper.getInstance().getTextWidth(getTickLabelPaint(), label); if(txtLength <= width) { //标签绘制在一行中 DrawHelper.getInstance().drawRotateText(label,centerX, centerY, getTickLabelRotateAngle(), canvas,getTickLabelPaint()); }else{ //Multi line float txtHeight = DrawHelper.getInstance().getPaintFontHeight(getTickLabelPaint()); float charWidth =0.0f,totalWidth = 0.0f; float renderY = centerY; String lnString = ""; for(int i= 0; i< label.length();i++) { charWidth = DrawHelper.getInstance().getTextWidth( getTickLabelPaint(),label.substring(i, i+1)); totalWidth = MathHelper.getInstance().add(totalWidth,charWidth); if( Float.compare(totalWidth , width) == 1 ) { DrawHelper.getInstance().drawRotateText(lnString,centerX, renderY, getTickLabelRotateAngle(), canvas,getTickLabelPaint()); totalWidth = charWidth; renderY = MathHelper.getInstance().add(renderY,txtHeight); lnString = label.substring(i, i+1) ; }else{ lnString += label.substring(i, i+1) ; } } //end for if(lnString.length() > 0 ) { DrawHelper.getInstance().drawRotateText(lnString,centerX, renderY, getTickLabelRotateAngle(), canvas,getTickLabelPaint()); } } //end width if } /** * 返回轴刻度线长度 * @return 刻度线长度 */ public int getTickMarksLength() { return mTickMarksLength; } /** * 设置轴刻度线与标签间的间距 * @param margin 间距 */ public void setTickLabelMargin(int margin) { mTickLabelMargin = margin; } /** * 返回轴刻度线与标签间的间距 * @return 间距 */ public int getTickLabelMargin() { return mTickLabelMargin; } }
[ "joseph.zeng@ximalaya.com" ]
joseph.zeng@ximalaya.com
8a745629b209f74b53fcb253ba83c3bd738debb7
c58042921e6f7ca9a04edcc88793726ac0e80227
/src/main/model/EventManipulator.java
a4d756b4ee17207662a35deeeb4fd61f2dabc107
[]
no_license
seanRong/right-on-time
748b99d16db7149bdccf2291bf0bd709e4ae2615
557144c3ae26d31fa190a1aa440c35cc1095367c
refs/heads/master
2021-06-30T16:00:53.836142
2021-01-05T05:51:12
2021-01-05T05:51:12
210,281,955
0
0
null
null
null
null
UTF-8
Java
false
false
319
java
package model; import java.text.ParseException; import java.util.ArrayList; public interface EventManipulator { void modeChoice() throws ParseException, TooBusyException; void enterEvent() throws ParseException, TooBusyException; void editMode() throws ParseException, TooBusyException; }
[ "seanRong@users.noreply.github.com" ]
seanRong@users.noreply.github.com
8a8b95ffbebe58041b3840528e479fb35cd1b4e7
08acbd4d784c546159c13f1293f163e71a454c7b
/src/main/java/com/pim/lucas/repositories/CategoriaRepository.java
ac781d7314305435aedd08bcbcc15e698c1653a2
[]
no_license
lucasd-coder/pim_unip_2020_backend
aff19a0802acdca604de71ca11f3555c12748b34
101fd4e69bfff68c1b3ff6ac76aeddadbee2987e
refs/heads/master
2023-01-22T19:23:59.881032
2020-11-27T14:06:48
2020-11-27T14:06:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
289
java
package com.pim.lucas.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.pim.lucas.domain.Categoria; @Repository public interface CategoriaRepository extends JpaRepository<Categoria, Integer> { }
[ "lucasdasilva524@hotmail.com" ]
lucasdasilva524@hotmail.com
c36fc9e5ae7df4f5bfccc294374f417d9db6835a
fa78a16c51442bbfa676f7cd44a48ea3b8e51e3c
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutoCall.java
022255c848ce75bbac2f41b588a75d88cb79f598
[ "BSD-3-Clause" ]
permissive
rusclark16151/RUSerious
5f195e08ce383845c8c74950e4ccdf2426d6fcc8
d8ba16f467d69130b68a1c494fac2ed267e7a826
refs/heads/master
2023-04-09T05:22:20.809214
2021-04-15T02:24:41
2021-04-15T02:24:41
309,197,735
0
0
null
null
null
null
UTF-8
Java
false
false
1,207
java
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotorSimple; @Autonomous(name = "autoCall", group = "Example") public class AutoCall extends LinearOpMode { //bye DriveClass driveClass = new DriveClass(); @Override public void runOpMode() throws InterruptedException { driveClass.bottomLeft = hardwareMap.dcMotor.get("bottomLeft"); driveClass.bottomRight = hardwareMap.dcMotor.get("bottomRight"); driveClass.topLeft = hardwareMap.dcMotor.get("topLeft"); driveClass.topRight = hardwareMap.dcMotor.get("topRight"); driveClass.topLeft.setDirection(DcMotorSimple.Direction.REVERSE); driveClass.bottomLeft.setDirection(DcMotorSimple.Direction.REVERSE); waitForStart(); driveClass.Drive(1, 1, 1, 1); sleep(1000); driveClass.motorStop(); //turn driveClass.Drive(0.5, -0.5, .5, -.5); sleep(1000); driveClass.motorStop(); driveClass.Drive(1, 1, 1, 1); sleep(1000); driveClass.motorStop(); } }
[ "mcilwainmadelyn@gmail.com" ]
mcilwainmadelyn@gmail.com
ec71aa41da5f23b21816967385fb508f3bd522c1
20bf5d0963036a97c4d23ed40c0a2f01b439fdf1
/app/build/generated/source/r/debug/com/google/android/gms/wearable/R.java
1be064897f35fae2b8754b6a5368200868bcda58
[]
no_license
wcy419/android
d604567af4c9d76699083d96e8914ec48c4ad4af
4e2dc89012de79bb2569d7215f8930e074bec416
refs/heads/master
2021-01-20T05:32:22.127197
2017-03-04T02:14:42
2017-03-04T02:14:42
83,858,342
0
0
null
null
null
null
UTF-8
Java
false
false
21,945
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms.wearable; public final class R { public static final class attr { public static final int adSize = 0x7f010027; public static final int adSizes = 0x7f010028; public static final int adUnitId = 0x7f010029; public static final int ambientEnabled = 0x7f0100c1; public static final int appTheme = 0x7f0100f5; public static final int buttonSize = 0x7f0100d7; public static final int buyButtonAppearance = 0x7f0100fc; public static final int buyButtonHeight = 0x7f0100f9; public static final int buyButtonText = 0x7f0100fb; public static final int buyButtonWidth = 0x7f0100fa; public static final int cameraBearing = 0x7f0100b2; public static final int cameraTargetLat = 0x7f0100b3; public static final int cameraTargetLng = 0x7f0100b4; public static final int cameraTilt = 0x7f0100b5; public static final int cameraZoom = 0x7f0100b6; public static final int circleCrop = 0x7f0100b0; public static final int colorScheme = 0x7f0100d8; public static final int environment = 0x7f0100f6; public static final int fragmentMode = 0x7f0100f8; public static final int fragmentStyle = 0x7f0100f7; public static final int imageAspectRatio = 0x7f0100af; public static final int imageAspectRatioAdjust = 0x7f0100ae; public static final int liteMode = 0x7f0100b7; public static final int mapType = 0x7f0100b1; public static final int maskedWalletDetailsBackground = 0x7f0100ff; public static final int maskedWalletDetailsButtonBackground = 0x7f010101; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f010100; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f0100fe; public static final int maskedWalletDetailsLogoImageType = 0x7f010103; public static final int maskedWalletDetailsLogoTextColor = 0x7f010102; public static final int maskedWalletDetailsTextAppearance = 0x7f0100fd; public static final int scopeUris = 0x7f0100d9; public static final int uiCompass = 0x7f0100b8; public static final int uiMapToolbar = 0x7f0100c0; public static final int uiRotateGestures = 0x7f0100b9; public static final int uiScrollGestures = 0x7f0100ba; public static final int uiTiltGestures = 0x7f0100bb; public static final int uiZoomControls = 0x7f0100bc; public static final int uiZoomGestures = 0x7f0100bd; public static final int useViewLifecycle = 0x7f0100be; public static final int windowTransitionStyle = 0x7f0100a2; public static final int zOrderOnTop = 0x7f0100bf; } public static final class color { public static final int common_action_bar_splitter = 0x7f0b0012; public static final int common_google_signin_btn_text_dark = 0x7f0b0068; public static final int common_google_signin_btn_text_dark_default = 0x7f0b0013; public static final int common_google_signin_btn_text_dark_disabled = 0x7f0b0014; public static final int common_google_signin_btn_text_dark_focused = 0x7f0b0015; public static final int common_google_signin_btn_text_dark_pressed = 0x7f0b0016; public static final int common_google_signin_btn_text_light = 0x7f0b0069; public static final int common_google_signin_btn_text_light_default = 0x7f0b0017; public static final int common_google_signin_btn_text_light_disabled = 0x7f0b0018; public static final int common_google_signin_btn_text_light_focused = 0x7f0b0019; public static final int common_google_signin_btn_text_light_pressed = 0x7f0b001a; public static final int common_plus_signin_btn_text_dark = 0x7f0b006a; public static final int common_plus_signin_btn_text_dark_default = 0x7f0b001b; public static final int common_plus_signin_btn_text_dark_disabled = 0x7f0b001c; public static final int common_plus_signin_btn_text_dark_focused = 0x7f0b001d; public static final int common_plus_signin_btn_text_dark_pressed = 0x7f0b001e; public static final int common_plus_signin_btn_text_light = 0x7f0b006b; public static final int common_plus_signin_btn_text_light_default = 0x7f0b001f; public static final int common_plus_signin_btn_text_light_disabled = 0x7f0b0020; public static final int common_plus_signin_btn_text_light_focused = 0x7f0b0021; public static final int common_plus_signin_btn_text_light_pressed = 0x7f0b0022; public static final int place_autocomplete_prediction_primary_text = 0x7f0b0039; public static final int place_autocomplete_prediction_primary_text_highlight = 0x7f0b003a; public static final int place_autocomplete_prediction_secondary_text = 0x7f0b003b; public static final int place_autocomplete_search_hint = 0x7f0b003c; public static final int place_autocomplete_search_text = 0x7f0b003d; public static final int place_autocomplete_separator = 0x7f0b003e; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f0b0051; public static final int wallet_bright_foreground_holo_dark = 0x7f0b0052; public static final int wallet_bright_foreground_holo_light = 0x7f0b0053; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f0b0054; public static final int wallet_dim_foreground_holo_dark = 0x7f0b0055; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f0b0056; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f0b0057; public static final int wallet_highlighted_text_holo_dark = 0x7f0b0058; public static final int wallet_highlighted_text_holo_light = 0x7f0b0059; public static final int wallet_hint_foreground_holo_dark = 0x7f0b005a; public static final int wallet_hint_foreground_holo_light = 0x7f0b005b; public static final int wallet_holo_blue_light = 0x7f0b005c; public static final int wallet_link_text_light = 0x7f0b005d; public static final int wallet_primary_text_holo_light = 0x7f0b006e; public static final int wallet_secondary_text_holo_dark = 0x7f0b006f; } public static final class dimen { public static final int place_autocomplete_button_padding = 0x7f080070; public static final int place_autocomplete_powered_by_google_height = 0x7f080071; public static final int place_autocomplete_powered_by_google_start = 0x7f080072; public static final int place_autocomplete_prediction_height = 0x7f080073; public static final int place_autocomplete_prediction_horizontal_margin = 0x7f080074; public static final int place_autocomplete_prediction_primary_text = 0x7f080075; public static final int place_autocomplete_prediction_secondary_text = 0x7f080076; public static final int place_autocomplete_progress_horizontal_margin = 0x7f080077; public static final int place_autocomplete_progress_size = 0x7f080078; public static final int place_autocomplete_separator_start = 0x7f080079; } public static final class drawable { public static final int cast_ic_notification_0 = 0x7f02004b; public static final int cast_ic_notification_1 = 0x7f02004c; public static final int cast_ic_notification_2 = 0x7f02004d; public static final int cast_ic_notification_connecting = 0x7f02004e; public static final int cast_ic_notification_on = 0x7f02004f; public static final int common_full_open_on_phone = 0x7f020050; public static final int common_google_signin_btn_icon_dark = 0x7f020051; public static final int common_google_signin_btn_icon_dark_disabled = 0x7f020052; public static final int common_google_signin_btn_icon_dark_focused = 0x7f020053; public static final int common_google_signin_btn_icon_dark_normal = 0x7f020054; public static final int common_google_signin_btn_icon_dark_pressed = 0x7f020055; public static final int common_google_signin_btn_icon_light = 0x7f020056; public static final int common_google_signin_btn_icon_light_disabled = 0x7f020057; public static final int common_google_signin_btn_icon_light_focused = 0x7f020058; public static final int common_google_signin_btn_icon_light_normal = 0x7f020059; public static final int common_google_signin_btn_icon_light_pressed = 0x7f02005a; public static final int common_google_signin_btn_text_dark = 0x7f02005b; public static final int common_google_signin_btn_text_dark_disabled = 0x7f02005c; public static final int common_google_signin_btn_text_dark_focused = 0x7f02005d; public static final int common_google_signin_btn_text_dark_normal = 0x7f02005e; public static final int common_google_signin_btn_text_dark_pressed = 0x7f02005f; public static final int common_google_signin_btn_text_light = 0x7f020060; public static final int common_google_signin_btn_text_light_disabled = 0x7f020061; public static final int common_google_signin_btn_text_light_focused = 0x7f020062; public static final int common_google_signin_btn_text_light_normal = 0x7f020063; public static final int common_google_signin_btn_text_light_pressed = 0x7f020064; public static final int common_ic_googleplayservices = 0x7f020065; public static final int common_plus_signin_btn_icon_dark = 0x7f020066; public static final int common_plus_signin_btn_icon_dark_disabled = 0x7f020067; public static final int common_plus_signin_btn_icon_dark_focused = 0x7f020068; public static final int common_plus_signin_btn_icon_dark_normal = 0x7f020069; public static final int common_plus_signin_btn_icon_dark_pressed = 0x7f02006a; public static final int common_plus_signin_btn_icon_light = 0x7f02006b; public static final int common_plus_signin_btn_icon_light_disabled = 0x7f02006c; public static final int common_plus_signin_btn_icon_light_focused = 0x7f02006d; public static final int common_plus_signin_btn_icon_light_normal = 0x7f02006e; public static final int common_plus_signin_btn_icon_light_pressed = 0x7f02006f; public static final int common_plus_signin_btn_text_dark = 0x7f020070; public static final int common_plus_signin_btn_text_dark_disabled = 0x7f020071; public static final int common_plus_signin_btn_text_dark_focused = 0x7f020072; public static final int common_plus_signin_btn_text_dark_normal = 0x7f020073; public static final int common_plus_signin_btn_text_dark_pressed = 0x7f020074; public static final int common_plus_signin_btn_text_light = 0x7f020075; public static final int common_plus_signin_btn_text_light_disabled = 0x7f020076; public static final int common_plus_signin_btn_text_light_focused = 0x7f020077; public static final int common_plus_signin_btn_text_light_normal = 0x7f020078; public static final int common_plus_signin_btn_text_light_pressed = 0x7f020079; public static final int ic_plusone_medium_off_client = 0x7f02008f; public static final int ic_plusone_small_off_client = 0x7f020090; public static final int ic_plusone_standard_off_client = 0x7f020091; public static final int ic_plusone_tall_off_client = 0x7f020092; public static final int places_ic_clear = 0x7f0200a1; public static final int places_ic_search = 0x7f0200a2; public static final int powered_by_google_dark = 0x7f0200a3; public static final int powered_by_google_light = 0x7f0200a4; } public static final class id { public static final int adjust_height = 0x7f0c001e; public static final int adjust_width = 0x7f0c001f; public static final int android_pay = 0x7f0c0047; public static final int android_pay_dark = 0x7f0c003e; public static final int android_pay_light = 0x7f0c003f; public static final int android_pay_light_with_border = 0x7f0c0040; public static final int auto = 0x7f0c002b; public static final int book_now = 0x7f0c0037; public static final int buyButton = 0x7f0c0034; public static final int buy_now = 0x7f0c0038; public static final int buy_with = 0x7f0c0039; public static final int buy_with_google = 0x7f0c003a; public static final int cast_notification_id = 0x7f0c0004; public static final int classic = 0x7f0c0041; public static final int dark = 0x7f0c002c; public static final int donate_with = 0x7f0c003b; public static final int donate_with_google = 0x7f0c003c; public static final int google_wallet_classic = 0x7f0c0042; public static final int google_wallet_grayscale = 0x7f0c0043; public static final int google_wallet_monochrome = 0x7f0c0044; public static final int grayscale = 0x7f0c0045; public static final int holo_dark = 0x7f0c002e; public static final int holo_light = 0x7f0c002f; public static final int hybrid = 0x7f0c0020; public static final int icon_only = 0x7f0c0028; public static final int light = 0x7f0c002d; public static final int logo_only = 0x7f0c003d; public static final int match_parent = 0x7f0c0036; public static final int monochrome = 0x7f0c0046; public static final int none = 0x7f0c000f; public static final int normal = 0x7f0c000b; public static final int place_autocomplete_clear_button = 0x7f0c00a2; public static final int place_autocomplete_powered_by_google = 0x7f0c00a4; public static final int place_autocomplete_prediction_primary_text = 0x7f0c00a6; public static final int place_autocomplete_prediction_secondary_text = 0x7f0c00a7; public static final int place_autocomplete_progress = 0x7f0c00a5; public static final int place_autocomplete_search_button = 0x7f0c00a0; public static final int place_autocomplete_search_input = 0x7f0c00a1; public static final int place_autocomplete_separator = 0x7f0c00a3; public static final int production = 0x7f0c0030; public static final int sandbox = 0x7f0c0031; public static final int satellite = 0x7f0c0021; public static final int selectionDetails = 0x7f0c0035; public static final int slide = 0x7f0c001a; public static final int standard = 0x7f0c0029; public static final int strict_sandbox = 0x7f0c0032; public static final int terrain = 0x7f0c0022; public static final int test = 0x7f0c0033; public static final int wide = 0x7f0c002a; public static final int wrap_content = 0x7f0c0014; } public static final class integer { public static final int google_play_services_version = 0x7f0a0004; } public static final class layout { public static final int place_autocomplete_fragment = 0x7f030029; public static final int place_autocomplete_item_powered_by_google = 0x7f03002a; public static final int place_autocomplete_item_prediction = 0x7f03002b; public static final int place_autocomplete_progress = 0x7f03002c; } public static final class raw { public static final int gtm_analytics = 0x7f050001; } public static final class string { public static final int accept = 0x7f060050; public static final int auth_google_play_services_client_facebook_display_name = 0x7f060052; public static final int auth_google_play_services_client_google_display_name = 0x7f060053; public static final int cast_notification_connected_message = 0x7f060055; public static final int cast_notification_connecting_message = 0x7f060056; public static final int cast_notification_disconnect = 0x7f060057; public static final int common_google_play_services_api_unavailable_text = 0x7f060013; public static final int common_google_play_services_enable_button = 0x7f060014; public static final int common_google_play_services_enable_text = 0x7f060015; public static final int common_google_play_services_enable_title = 0x7f060016; public static final int common_google_play_services_install_button = 0x7f060017; public static final int common_google_play_services_install_text_phone = 0x7f060018; public static final int common_google_play_services_install_text_tablet = 0x7f060019; public static final int common_google_play_services_install_title = 0x7f06001a; public static final int common_google_play_services_invalid_account_text = 0x7f06001b; public static final int common_google_play_services_invalid_account_title = 0x7f06001c; public static final int common_google_play_services_network_error_text = 0x7f06001d; public static final int common_google_play_services_network_error_title = 0x7f06001e; public static final int common_google_play_services_notification_ticker = 0x7f06001f; public static final int common_google_play_services_restricted_profile_text = 0x7f060020; public static final int common_google_play_services_restricted_profile_title = 0x7f060021; public static final int common_google_play_services_sign_in_failed_text = 0x7f060022; public static final int common_google_play_services_sign_in_failed_title = 0x7f060023; public static final int common_google_play_services_unknown_issue = 0x7f060024; public static final int common_google_play_services_unsupported_text = 0x7f060025; public static final int common_google_play_services_unsupported_title = 0x7f060026; public static final int common_google_play_services_update_button = 0x7f060027; public static final int common_google_play_services_update_text = 0x7f060028; public static final int common_google_play_services_update_title = 0x7f060029; public static final int common_google_play_services_updating_text = 0x7f06002a; public static final int common_google_play_services_updating_title = 0x7f06002b; public static final int common_google_play_services_wear_update_text = 0x7f06002c; public static final int common_open_on_phone = 0x7f06002d; public static final int common_signin_button_text = 0x7f06002e; public static final int common_signin_button_text_long = 0x7f06002f; public static final int create_calendar_message = 0x7f060058; public static final int create_calendar_title = 0x7f060059; public static final int decline = 0x7f06005a; public static final int place_autocomplete_clear_button = 0x7f06003b; public static final int place_autocomplete_search_hint = 0x7f06003c; public static final int store_picture_message = 0x7f060062; public static final int store_picture_title = 0x7f060063; public static final int wallet_buy_button_place_holder = 0x7f06003e; } public static final class style { public static final int Theme_AppInvite_Preview = 0x7f0900f6; public static final int Theme_AppInvite_Preview_Base = 0x7f09001d; public static final int Theme_IAPTheme = 0x7f0900f7; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0900ff; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f090100; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f090101; public static final int WalletFragmentDefaultStyle = 0x7f090102; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f010027, 0x7f010028, 0x7f010029 }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] CustomWalletTheme = { 0x7f0100a2 }; public static final int CustomWalletTheme_windowTransitionStyle = 0; public static final int[] LoadingImageView = { 0x7f0100ae, 0x7f0100af, 0x7f0100b0 }; public static final int LoadingImageView_circleCrop = 2; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 0; public static final int[] MapAttrs = { 0x7f0100b1, 0x7f0100b2, 0x7f0100b3, 0x7f0100b4, 0x7f0100b5, 0x7f0100b6, 0x7f0100b7, 0x7f0100b8, 0x7f0100b9, 0x7f0100ba, 0x7f0100bb, 0x7f0100bc, 0x7f0100bd, 0x7f0100be, 0x7f0100bf, 0x7f0100c0, 0x7f0100c1 }; public static final int MapAttrs_ambientEnabled = 16; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_liteMode = 6; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 7; public static final int MapAttrs_uiMapToolbar = 15; public static final int MapAttrs_uiRotateGestures = 8; public static final int MapAttrs_uiScrollGestures = 9; public static final int MapAttrs_uiTiltGestures = 10; public static final int MapAttrs_uiZoomControls = 11; public static final int MapAttrs_uiZoomGestures = 12; public static final int MapAttrs_useViewLifecycle = 13; public static final int MapAttrs_zOrderOnTop = 14; public static final int[] SignInButton = { 0x7f0100d7, 0x7f0100d8, 0x7f0100d9 }; public static final int SignInButton_buttonSize = 0; public static final int SignInButton_colorScheme = 1; public static final int SignInButton_scopeUris = 2; public static final int[] WalletFragmentOptions = { 0x7f0100f5, 0x7f0100f6, 0x7f0100f7, 0x7f0100f8 }; public static final int WalletFragmentOptions_appTheme = 0; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int[] WalletFragmentStyle = { 0x7f0100f9, 0x7f0100fa, 0x7f0100fb, 0x7f0100fc, 0x7f0100fd, 0x7f0100fe, 0x7f0100ff, 0x7f010100, 0x7f010101, 0x7f010102, 0x7f010103 }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
[ "ch505@guest-wireless-upc-1602-10-120-033-237.usc.edu" ]
ch505@guest-wireless-upc-1602-10-120-033-237.usc.edu
4279076cbe1a6c6d43e2b408ee7fe4bab5015dac
99135aa72068876839d0d68a304d4abc1f858e26
/src/main/java/pl/oskarpolak/ormtest/models/services/UploadService.java
70082f8c3e90cb3d056a38b664e3eb0811826587
[]
no_license
vallerboy/ormtest
adb6b4d695ab0b22596a11f574ca45155aaad582
bd7473a8efe373f4e4720f4201ee1b93d8d2e5e3
refs/heads/master
2021-04-03T10:20:03.739181
2018-03-21T09:52:01
2018-03-21T09:52:01
124,556,785
0
0
null
null
null
null
UTF-8
Java
false
false
1,142
java
package pl.oskarpolak.ormtest.models.services; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @Service public class UploadService { private final static String LOGIN = "akademiakodu1"; private final static String PASSWORD = "akademia"; private final static String IP = "5.135.218.27"; private final static int PORT = 21; private FTPClient ftpClient; public UploadService() { ftpClient = new FTPClient(); } @Async public void upload(byte[] data, String name){ try { ftpClient.connect(IP, PORT); ftpClient.login(LOGIN, PASSWORD); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile(name, new ByteArrayInputStream(data)); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
[ "biuro@fivarto.pl" ]
biuro@fivarto.pl
3df657cd001f171233d2dea60c80757aaa5e0e65
86b57256d785efbbcda7b9871c6ea7c5f43275e6
/src/main/java/com/springsecurity/service/UsersService.java
8ecda40010a9fbf2bb871c67881cb4516b236866
[]
no_license
soumitrakumarmund/Actifydatalabs-Assignments-Springboot-Security-Three-Users
a87e0abc79d8076042f5978fdf69b27deac742f9
151a65bcf02877a103a978855c224bc39f4b21a2
refs/heads/master
2022-11-30T22:38:10.689423
2020-08-16T17:47:04
2020-08-16T17:47:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,082
java
package com.springsecurity.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.springsecurity.entity.AdminUser; import com.springsecurity.entity.BusinessUser; import com.springsecurity.entity.DevUser; import com.springsecurity.repository.AdminRepository; import com.springsecurity.repository.BusinessRepository; import com.springsecurity.repository.DevUsersRepository; @Service public class UsersService { @Autowired AdminRepository adminRepository; @Autowired BusinessRepository businessRepository; @Autowired DevUsersRepository devUsersRepository; public DevUser saveDevData(DevUser userDev) { return devUsersRepository.save(userDev); } public Optional<DevUser> getDevData(Integer id) { return devUsersRepository.findById(id); } public List<AdminUser> getAdminData() { return adminRepository.findAll(); } public Optional<BusinessUser> getBusinessData(Integer id) { return businessRepository.findById(id); } }
[ "soumitramund93@.gmai.com" ]
soumitramund93@.gmai.com
c567299024ec541ec566dde72e8f59dc23e7e2f8
a843b73c528ee12bc3108a72f34c6eba6c739324
/src/ua/i/mail100/iterator/iterator/ProfileIterator.java
1838724c6f32faf0efb69f3c17887e0a7bcaff43
[]
no_license
Antoninadan/Patterns
0b3eadcb61f15a50d3024de546b72fceb747d833
0aa7aa3d387494eecaa91201554b592aafc9e22f
refs/heads/master
2022-12-07T11:33:24.585573
2020-08-13T20:25:48
2020-08-13T20:25:48
264,946,647
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
package ua.i.mail100.iterator.iterator; import ua.i.mail100.iterator.model.Profile; public interface ProfileIterator { boolean hasNext(); Profile getNext(); void reset(); }
[ "mail100@i.ua" ]
mail100@i.ua
e5002fe33cc87e579f5f042a225d5fcae43f85ea
273fe3e12458fe6f6573b2df00d1394d1d32a048
/src/Client.java
10f9c8344c6a65d1c3b01bb14abcf9a40d47d5be
[]
no_license
sifrproject/lexicon_builder
fd9fcb8bb477677704b5a07c100d0fbc52c58aab
ce5bbdb76bf4ac612288ebe55784450cf0c7dc77
refs/heads/master
2021-01-01T05:40:57.765474
2015-06-01T20:45:30
2015-06-01T20:45:30
30,418,581
0
0
null
null
null
null
UTF-8
Java
false
false
9,442
java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVWriter; import java.util.List; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; public class Client { static final String REST_URL = "http://bioportal.lirmm.fr:8082/ontologies?&include=all"; static final String API_KEY = "759c2da4-f6e1-4b0b-94e9-842a2ab09d01"; static final ObjectMapper mapper = new ObjectMapper(); static HashMap<String , Terme>Termes = new HashMap<String, Terme>(); static Logger logRoot = Logger.getRootLogger(); static int nombre = 0 ; static long start; static long starta; //Delimiter used in CSV file // private static final String COMMA_DELIMITER = ","; private static final String NEW_LINE_SEPARATOR = "\n"; public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException { starta = System.nanoTime(); // Get the available resources String resourcesString = get(REST_URL ); JsonNode resources = jsonToNode(resourcesString); List<String> ontologies = new ArrayList<String>(); try { // Iterate looking for ontology in SIFR group for (JsonNode jsonNode : resources) { if(jsonNode.findValue("group").get(0).asText().contains("SIFR") ){ logRoot.info(jsonNode.findValue("@id").asText()); ontologies.add(jsonNode.findValue("@id").asText()); } } } catch (NullPointerException e) { // TODO: handle exception } // logRoot.info("Le nombre d'ontologie du Groupe SIFR est : " + ontologies.size()); try { String[] stf = null ; for (String url : ontologies) { System.out.println(url); start = System.nanoTime(); // Recuperer le nombre de pages Pagecount //String url=Ontologies.get(j); String cc =get( url+"/classes?page=1&pagesize=100&include_context=false&include_links=false"); JsonNode rsc = jsonToNode(cc); Integer pagecount = rsc.get("pageCount").asInt(); // System.out.println(pagecount); for (int i = 1; i < pagecount+1; i++) { String resourcesString1 = get(url+"/classes?page="+i+"&pagesize=100&include_context=false&include_links=false"); JsonNode resources1 = jsonToNode(resourcesString1); stf = resources1.get("collection").get(0).get("links").get("ontology").asText().split("/"); ; Iterator<JsonNode> link1 = resources1.get("collection").elements(); while(link1.hasNext()){ JsonNode jsnd =link1.next() ; charger(jsnd); } } // System.out.println(stf[stf.length-1]); writecsv(stf[stf.length-1]); Termes.clear(); } } catch (Exception e) { // TODO: handle exception } long duree = System.nanoTime() - starta; double seconds = (double)duree / 1000000000.0; logRoot.info("Temps Total"+ seconds/60); } private static void writecsv( String oname) throws IOException{ nombre = 0 ; FileOutputStream fos = new FileOutputStream("E:\\lab1\\"+ oname +".csv"); byte[] enc = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; fos.write(enc); OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); try { //Add a new line separator after the header //writer.append(NEW_LINE_SEPARATOR); //System.out.println(Termes.size()); Iterator<String> keySetIterator = Termes.keySet().iterator(); while(keySetIterator.hasNext()){ String key = keySetIterator.next(); Terme st =Termes.get(key); // logRoot.info(st.getPreflabel()+"//"+st.getId()); writer.append(String.valueOf(st.getPreflabel() + ";" + StringUtils.join(st.getIds(),",") )); //fileWriter.append(COMMA_DELIMITER); writer.append(NEW_LINE_SEPARATOR); for (String syn : st.getSynonymes()) { writer.append(String.valueOf(syn + ";" + StringUtils.join(st.getIds(),",") )); writer.append(NEW_LINE_SEPARATOR); } } } catch (Exception e) { System.out.println("Error in CsvFileWriter !!!"); e.printStackTrace(); } finally { try { writer.flush();; writer.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter !!!"); e.printStackTrace(); } } logRoot.info("CSV file was created successfully !!!" + oname); long duree = System.nanoTime() - start; double seconds = (double)duree / 1000000000.0; logRoot.info("Le Temps pour recuperer l'ontologie : " + oname + " est de "+ seconds +" secondes"); } private static void charger (JsonNode j) { Terme st = new Terme() ; String t = j.get("prefLabel").asText() ; /* t = t.replace("^", " ") ; t= t.replace("\"" ," ") ; t= Rules.deaccent(t); */ t= t.replace('"', ' ') ; t= t.replace("\"" ," ") ; t = t.trim() ; System.out.println(t); st.setPreflabel(t); st.addIds(j.get("@id").asText()); /* String[] stf = j.get("links").get("ontology").asText().split("/"); st.setOntologie(stf[stf.length-1]); */ Iterator<JsonNode> li = j.get("synonym").elements(); while(li.hasNext()){ JsonNode jsnd1 =li.next() ; if (!jsnd1.asText().matches("C\\d*")){ String tt = jsnd1.asText() ; /* tt = tt.replace("^", " ") ; tt= tt.replace("\"" ," ") ; tt= Rules.deaccent(tt);*/ tt= tt.replace("\"" ," ") ; tt= tt.replace('"', ' ') ; tt = tt.trim() ; System.out.println(tt); st.addSynonymes(StringUtils.normalizeSpace(tt)); } } if (Termes.keySet().contains(st.getPreflabel())){ Termes.get(st.getPreflabel()).addIds(j.get("@id").asText()); } else { Termes.put(st.getPreflabel(),st) ; } } private static JsonNode jsonToNode(String json) { JsonNode root = null; try { root = mapper.readTree(json); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return root; } private static String get(String urlToGet) { URL url; HttpURLConnection conn; BufferedReader rd; String line; String result = ""; try { url = new URL(urlToGet); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "apikey token=" + API_KEY); conn.setRequestProperty("Accept", "application/json"); rd = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result += line; } rd.close(); } catch (Exception e) { e.printStackTrace(); } return result; } }
[ "elghandour.chafik@gmail.com" ]
elghandour.chafik@gmail.com
c6ffb3db54c5ea39b87b193b7cc50ef5f6880c3d
4502671291b4d01533244d932a8e5d47f0c9b110
/joolun-wx/joolun-common/src/main/java/com/joolun/common/exception/user/UserException.java
b69d37986f76961b9bdcaaab515e3e2cea2c1a8d
[ "MIT" ]
permissive
liwenxin-222/zhixuanshangmao
27fceb87576dd468aa1f9d7e1d1877bbb64f06ad
ff380480de5ddc87423c542ce943a5791aa9a6d8
refs/heads/master
2023-06-06T02:25:28.770407
2021-06-26T05:54:18
2021-06-26T05:54:18
380,421,308
1
0
null
null
null
null
UTF-8
Java
false
false
361
java
package com.joolun.common.exception.user; import com.joolun.common.exception.BaseException; /** * 用户信息异常类 * * @author ruoyi */ public class UserException extends BaseException { private static final long serialVersionUID = 1L; public UserException(String code, Object[] args) { super("user", code, args, null); } }
[ "535382760@qq.com" ]
535382760@qq.com
42e6f47fbb3e6f278ee996a6d859ea75e4144174
009afecf13a4c6bc2cf367d7b83f5d8ac1e23450
/Common-Service/src/main/java/com/reactive/app/common/mail/service/PasswordManagementMailService.java
862bcb60624a99e1b7f5bcc13c9c07a72e38be0a
[ "Apache-2.0" ]
permissive
sankarkota555/Spring-Reactive-Microservices
1b603051a05b779a8ef70216dd0eb4afb148e451
bb391d855fe954323b0cb7dc8e291aa834508f30
refs/heads/master
2020-11-27T01:03:39.002316
2019-12-20T14:27:35
2019-12-20T14:27:35
229,251,390
0
1
null
null
null
null
UTF-8
Java
false
false
1,822
java
package com.reactive.app.common.mail.service; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.mail.MessagingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.reactive.app.common.constants.ContactType; import com.reactive.app.common.constants.MailConstants; import com.reactive.app.common.constants.MailTemplateConstants; import com.reactive.app.common.model.ContactDetails; import com.reactive.app.common.model.LoginEntity; import com.reactive.app.common.model.UserEntity; import freemarker.template.TemplateException; @Service public class PasswordManagementMailService { private static final Logger log = LoggerFactory.getLogger(PasswordManagementMailService.class); @Autowired private MailService mailService; @Async public void sendPasswordManagementMail(LoginEntity loginEntity, String mailBody) { UserEntity userEntity = loginEntity.getUserEntity(); Map<String, Object> model = new HashMap<>(); model.put("name", userEntity.getFirstName()); model.put("signature", "Reactive Team"); model.put("mailBody", mailBody); ContactDetails emailContact = userEntity.getContactDetails().stream() .filter(contact -> contact.getType().equals(ContactType.EMAILID)).findAny().orElseThrow(); try { mailService.sendMail(emailContact.getValue(), MailConstants.PASSWORD_MANAGEMENT_MAIL_SUBJECT, null, MailTemplateConstants.PASSWORD_MANAGEMENT_MAIL_TEMPLATE, model); } catch (MessagingException | IOException | TemplateException e) { log.error("Error while sending registration mail:", e); } } }
[ "sankar.kota555@gmail.com" ]
sankar.kota555@gmail.com
6399682dc2748e1bcbdd46345d2cd5d468eacb9f
b34654bd96750be62556ed368ef4db1043521ff2
/time_tracker_base_entry/trunk/src/java/main/com/topcoder/timetracker/entry/base/ParameterCheck.java
974b65977dae7abf95979ef44ae0336dc872d191
[]
no_license
topcoder-platform/tcs-cronos
81fed1e4f19ef60cdc5e5632084695d67275c415
c4ad087bb56bdaa19f9890e6580fcc5a3121b6c6
refs/heads/master
2023-08-03T22:21:52.216762
2019-03-19T08:53:31
2019-03-19T08:53:31
89,589,444
0
1
null
2019-03-19T08:53:32
2017-04-27T11:19:01
null
UTF-8
Java
false
false
2,361
java
/* * Copyright (C) 2007 TopCoder Inc., All Rights Reserved. */ package com.topcoder.timetracker.entry.base; /** * Helper class to do parameters check. * * @author TCSDEVELOPER * @version 1.0 */ public final class ParameterCheck { /** * Private ctor preventing this class from being instantiated. */ private ParameterCheck() { } /** * Checks if the given parameter is not positive and throws IAE if so. * * @param paramName name of the parameter * @param parameter parameter value to be checked * @throws IllegalArgumentException if parameter is not positive */ public static void checkNotPositive(String paramName, long parameter) { if (parameter <= 0) { throw new IllegalArgumentException(paramName + " is not positive"); } } /** * Checks and throws IllegalArgumentException if the parameter is null. * * @param paramName name of the parameter * @param param value of the parameter to be checked * * @throws IllegalArgumentException if given parameter is null */ public static void checkNull(String paramName, Object param) { if (param == null) { throw new IllegalArgumentException(paramName + " is null"); } } /** * Checks and throws IllegalArgumentException if the parameter is null or empty string. * * @param paramName name of the parameter * @param string string to be checked * * @throws IllegalArgumentException if given parameter is empty string. */ public static void checkNullEmpty(String paramName, String string) { checkNull(paramName, string); checkEmpty(paramName, string); } /** * Checks and throws IllegalArgumentException if the parameter is empty string(null is allowed). * * @param paramName name of the parameter * @param string string to be checked * * @throws IllegalArgumentException if given parameter is empty string */ public static void checkEmpty(String paramName, String string) { if (string != null) { if (string.trim().length() == 0) { throw new IllegalArgumentException(paramName + " is empty string"); } } } }
[ "Hacker_QC@fb370eea-3af6-4597-97f7-f7400a59c12a" ]
Hacker_QC@fb370eea-3af6-4597-97f7-f7400a59c12a
8544f5208c08a68e7cfabffd67d639010ea78151
750cc82e8345e440668ccbfef5a0e032080ba424
/src/main/java/vn/tech/website/store/repository/OrderRepository.java
fdbaea06de0570f9d6862a641e2886cd79c4f095
[]
no_license
hungvv2808/k2_tech_store
6bbae4cbdd2f5d092e1e1026e85cc332226d91f9
d565c373d81a266c2035ceca2a29755a400cdb9b
refs/heads/main
2023-05-06T00:41:55.468171
2021-05-27T17:03:20
2021-05-27T17:03:20
329,190,270
0
0
null
null
null
null
UTF-8
Java
false
false
420
java
package vn.tech.website.store.repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import vn.tech.website.store.model.Orders; public interface OrderRepository extends CrudRepository<Orders, Long>, OrderRepositoryCustom { @Query("select max(o.countCode) from Orders o") Long findMaxCountCode(); Orders getByOrdersId(Long orderId); }
[ "o2xallblue@gmail.com" ]
o2xallblue@gmail.com
7ed21fe780f0a75e45acb8b3d75476f24a270964
2e18370fdd5800ed0b337b975d3c67e282a83a6a
/src/main/java/rs/ac/singidunum/fir/cartraderbackend/dto/securityfeature/SecurityFeatureDTO.java
31f1aa686dfb17a54a3d66f65307b5e6f036ab07
[]
no_license
lukagajic/rma-cartrader-spring
1eab0d729ce1e509bcf2d46c8e48a490e2f8689d
936d351517659e54ab47557f5f795a7a22c01cf8
refs/heads/main
2023-06-24T04:23:49.853909
2021-07-13T10:11:06
2021-07-13T10:11:06
384,919,036
0
0
null
null
null
null
UTF-8
Java
false
false
705
java
package rs.ac.singidunum.fir.cartraderbackend.dto.securityfeature; import rs.ac.singidunum.fir.cartraderbackend.dto.category.CategoryDTO; public class SecurityFeatureDTO { private long id; private String name; private CategoryDTO category; public SecurityFeatureDTO() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public CategoryDTO getCategory() { return category; } public void setCategory(CategoryDTO category) { this.category = category; } }
[ "45518706+lukagajic@users.noreply.github.com" ]
45518706+lukagajic@users.noreply.github.com
05d569d8c4442c5e165a6b0525ba3602e0ac152a
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_38cf800745dc4a90ff17d80af91db33fbb712d5b/CacheServiceImpl/2_38cf800745dc4a90ff17d80af91db33fbb712d5b_CacheServiceImpl_s.java
e730e1eff2759583ca06ef2645eb844deccaa0e1
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
31,445
java
/* * Weblounge: Web Content Management System * Copyright (c) 2003 - 2011 The Weblounge Team * http://entwinemedia.com/weblounge * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ch.entwine.weblounge.cache.impl; import ch.entwine.weblounge.cache.CacheService; import ch.entwine.weblounge.cache.StreamFilter; import ch.entwine.weblounge.cache.impl.handle.TaggedCacheHandle; import ch.entwine.weblounge.common.Times; import ch.entwine.weblounge.common.impl.util.config.ConfigurationUtils; import ch.entwine.weblounge.common.request.CacheHandle; import ch.entwine.weblounge.common.request.CacheTag; import ch.entwine.weblounge.common.request.WebloungeRequest; import ch.entwine.weblounge.common.request.WebloungeResponse; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import net.sf.ehcache.Status; import net.sf.ehcache.config.CacheConfiguration; import net.sf.ehcache.config.Configuration; import net.sf.ehcache.config.ConfigurationFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletResponse; import javax.servlet.ServletResponseWrapper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Default implementation of the <code>CacheService</code> that is used to store * rendered pages and page elements so that they may be served out of the cache * upon the next request. * <p> * The service itself has no logic implemented besides configuring, starting and * stopping the cache. The actual caching is provided by the * <code>CacheManager</code>. */ public class CacheServiceImpl implements CacheService, ManagedService { /** Logging facility provided by log4j */ private static final Logger logger = LoggerFactory.getLogger(CacheServiceImpl.class); /** Path to cache configuration */ private static final String CACHE_MANAGER_CONFIG = "/ehcache/config.xml"; /** Name of the weblounge cache header */ private static final String CACHE_KEY_HEADER = "X-Cache-Key"; /** Configuration key prefix for content repository configuration */ public static final String OPT_PREFIX = "cache"; /** Configuration key for the enabled state of the cache */ public static final String OPT_ENABLE = OPT_PREFIX + ".enable"; /** The default value for "enable" configuration property */ private static final boolean DEFAULT_ENABLE = true; /** Configuration key for the cache identifier */ public static final String OPT_ID = OPT_PREFIX + ".id"; /** Configuration key for the cache name */ public static final String OPT_NAME = OPT_PREFIX + ".name"; /** Configuration key indicating that a clear() operation is required */ public static final String OPT_CLEAR = OPT_PREFIX + ".clear"; /** Configuration key for the path to the cache's disk store */ public static final String OPT_DISKSTORE_PATH = OPT_PREFIX + ".diskStorePath"; /** Configuration key for the persistence of the cache */ public static final String OPT_DISK_PERSISTENT = OPT_PREFIX + ".diskPersistent"; /** The default value for "disk persistent" configuration property */ private static final boolean DEFAULT_DISK_PERSISTENT = false; /** Configuration key for the overflow to disk setting */ public static final String OPT_OVERFLOW_TO_DISK = OPT_PREFIX + ".overflowToDisk"; /** The default value for "overflow to disk" configuration property */ private static final boolean DEFAULT_OVERFLOW_TO_DISK = true; /** Configuration key for the statistics setting */ public static final String OPT_ENABLE_STATISTICS = OPT_PREFIX + ".statistics"; /** The default value for "statistics enabled" configuration property */ private static final boolean DEFAULT_STATISTICS_ENABLED = true; /** Configuration key for the maximum number of elements in memory */ public static final String OPT_MAX_ELEMENTS_IN_MEMORY = OPT_PREFIX + ".maxElementsInMemory"; /** The default value for "max elements in memory" configuration property */ private static final int DEFAULT_MAX_ELEMENTS_IN_MEMORY = 1000; /** Configuration key for the maximum number of elements on disk */ public static final String OPT_MAX_ELEMENTS_ON_DISK = OPT_PREFIX + ".maxElementsOnDisk"; /** The default value for "max elements on disk" configuration property */ private static final int DEFAULT_MAX_ELEMENTS_ON_DISK = 0; /** Configuration key for the time to idle setting */ public static final String OPT_TIME_TO_IDLE = OPT_PREFIX + ".timeToIdle"; /** The default value for "seconds to idle" configuration property */ private static final int DEFAULT_TIME_TO_IDLE = 0; /** Configuration key for the time to live setting */ public static final String OPT_TIME_TO_LIVE = OPT_PREFIX + ".timeToLive"; /** The default value for "seconds to live" configuration property */ private static final int DEFAULT_TIME_TO_LIVE = (int) (Times.MS_PER_DAY / 1000); /** Make the cache persistent between reboots? */ protected boolean diskPersistent = DEFAULT_DISK_PERSISTENT; /** Write overflow elements from memory to disk? */ protected boolean overflowToDisk = DEFAULT_OVERFLOW_TO_DISK; /** Maximum number of elements in memory */ protected int maxElementsInMemory = DEFAULT_MAX_ELEMENTS_IN_MEMORY; /** Maximum number of elements in memory */ protected int maxElementsOnDisk = DEFAULT_MAX_ELEMENTS_ON_DISK; /** Number of seconds for an element to live from its last access time */ protected int timeToIdle = DEFAULT_TIME_TO_IDLE; /** Number of seconds for an element to live from its creation date */ protected int timeToLive = DEFAULT_TIME_TO_LIVE; /** Whether cache statistics are enabled */ protected boolean statisticsEnabled = DEFAULT_STATISTICS_ENABLED; /** Identifier for the default cache */ private static final String DEFAULT_CACHE = "site"; /** The ehache cache manager */ protected CacheManager cacheManager = null; /** True if the cache is enabled */ protected boolean enabled = true; /** The stream filter */ protected StreamFilter filter = null; /** Cache identifier */ protected String id = null; /** Cache name */ protected String name = null; /** Path to the local disk store */ protected String diskStorePath = null; /** * True to indicate that everything went fine with the setup of the disk store */ protected boolean diskStoreEnabled = true; /** Transactions that are currently being processed */ protected Map<String, CacheTransaction> transactions = null; /** * Creates a new cache with the given identifier and name. * * @param id * the cache identifier * @param name * the cache name * @param diskStorePath * the cache's disk store */ public CacheServiceImpl(String id, String name, String diskStorePath) { if (StringUtils.isBlank(id)) throw new IllegalArgumentException("Cache id cannot be blank"); if (StringUtils.isBlank(name)) throw new IllegalArgumentException("Cache name cannot be blank"); this.id = id; this.name = name; this.diskStorePath = diskStorePath; this.transactions = new HashMap<String, CacheTransaction>(); init(id, name, diskStorePath); } /** * Initializes the cache service with an identifier, a name and a path to the * local disk store (if applicable). * * @param id * the cache identifier * @param name * the cache name * @param diskStorePath * path to the local disk store */ private void init(String id, String name, String diskStorePath) { InputStream configInputStream = null; try { configInputStream = getClass().getClassLoader().getResourceAsStream(CACHE_MANAGER_CONFIG); Configuration cacheManagerConfig = ConfigurationFactory.parseConfiguration(configInputStream); cacheManagerConfig.getDiskStoreConfiguration().setPath(diskStorePath); cacheManager = new CacheManager(cacheManagerConfig); cacheManager.setName(id); } finally { IOUtils.closeQuietly(configInputStream); } // Check the path to the cache if (StringUtils.isNotBlank(diskStorePath)) { File file = new File(diskStorePath); try { if (!file.exists()) FileUtils.forceMkdir(file); if (!file.isDirectory()) throw new IOException(); if (!file.canWrite()) throw new IOException(); } catch (IOException e) { logger.warn("Unable to create disk store for cache '{}' at {}", id, diskStorePath); logger.warn("Persistent cache will be disabled for '{}'", id); diskPersistent = false; diskStoreEnabled = false; } } else { diskStoreEnabled = false; } // Configure the cache CacheConfiguration cacheConfig = new CacheConfiguration(); cacheConfig.setName(DEFAULT_CACHE); cacheConfig.setDiskPersistent(diskPersistent && diskStoreEnabled); cacheConfig.setOverflowToDisk(overflowToDisk && diskStoreEnabled); if (overflowToDisk && diskStoreEnabled) { cacheConfig.setDiskStorePath(diskStorePath); cacheConfig.setMaxElementsOnDisk(maxElementsOnDisk); } cacheConfig.setEternal(false); cacheConfig.setMaxElementsInMemory(maxElementsInMemory); cacheConfig.setStatistics(statisticsEnabled); cacheConfig.setTimeToIdleSeconds(timeToIdle); cacheConfig.setTimeToLiveSeconds(timeToLive); Cache cache = new Cache(cacheConfig); cacheManager.addCache(cache); if (overflowToDisk) logger.info("Cache extension for site '{}' created at {}", id, cacheManager.getDiskStorePath()); else logger.info("In-memory cache for site '{}' created"); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.cache.CacheService#shutdown() */ public void shutdown() { if (cacheManager == null) return; for (String cacheName : cacheManager.getCacheNames()) { Cache cache = cacheManager.getCache(cacheName); cache.dispose(); } cacheManager.shutdown(); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.cache.CacheService#getIdentifier() */ public String getIdentifier() { return id; } /** * Configures the caching service. Available options are: * <ul> * <li><code>size</code> - the maximum cache size</li> * <li><code>filters</code> - the name of the output filters</li> * </ul> * * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary) */ @SuppressWarnings("rawtypes") public void updated(Dictionary properties) throws ConfigurationException { if (properties == null) return; // Do we need to clear the cache? boolean clear = ConfigurationUtils.isTrue((String) properties.get(OPT_CLEAR), false); if (clear) { clear(); } // Disk persistence enabled = ConfigurationUtils.isTrue((String) properties.get(OPT_ENABLE), DEFAULT_ENABLE); logger.debug("Cache is {}", diskPersistent ? "enabled" : "disabled"); // Disk persistence diskPersistent = ConfigurationUtils.isTrue((String) properties.get(OPT_DISK_PERSISTENT), DEFAULT_DISK_PERSISTENT); logger.debug("Cache persistance between reboots is {}", diskPersistent ? "on" : "off"); // Statistics statisticsEnabled = ConfigurationUtils.isTrue((String) properties.get(OPT_ENABLE_STATISTICS), DEFAULT_STATISTICS_ENABLED); logger.debug("Cache statistics are {}", statisticsEnabled ? "enabled" : "disabled"); // Max elements in memory try { maxElementsInMemory = ConfigurationUtils.getValue((String) properties.get(OPT_MAX_ELEMENTS_IN_MEMORY), DEFAULT_MAX_ELEMENTS_IN_MEMORY); logger.debug("Cache will keep {} elements in memory", maxElementsInMemory > 0 ? "up to " + maxElementsInMemory : "all"); } catch (NumberFormatException e) { logger.warn("Value for cache setting '" + OPT_MAX_ELEMENTS_IN_MEMORY + "' is malformed: " + (String) properties.get(OPT_MAX_ELEMENTS_IN_MEMORY)); logger.warn("Cache setting '" + OPT_MAX_ELEMENTS_IN_MEMORY + "' set to default value of " + DEFAULT_MAX_ELEMENTS_IN_MEMORY); maxElementsInMemory = DEFAULT_MAX_ELEMENTS_IN_MEMORY; } // Max elements on disk try { maxElementsOnDisk = ConfigurationUtils.getValue((String) properties.get(OPT_MAX_ELEMENTS_ON_DISK), DEFAULT_MAX_ELEMENTS_ON_DISK); logger.debug("Cache will keep {} elements on disk", maxElementsOnDisk > 0 ? "up to " + maxElementsOnDisk : "all"); } catch (NumberFormatException e) { logger.warn("Value for cache setting '" + OPT_MAX_ELEMENTS_ON_DISK + "' is malformed: " + (String) properties.get(OPT_MAX_ELEMENTS_ON_DISK)); logger.warn("Cache setting '" + OPT_MAX_ELEMENTS_ON_DISK + "' set to default value of " + DEFAULT_MAX_ELEMENTS_ON_DISK); maxElementsOnDisk = DEFAULT_MAX_ELEMENTS_ON_DISK; } // Overflow to disk overflowToDisk = ConfigurationUtils.isTrue((String) properties.get(OPT_OVERFLOW_TO_DISK), DEFAULT_OVERFLOW_TO_DISK); // Time to idle try { timeToIdle = ConfigurationUtils.getValue((String) properties.get(OPT_TIME_TO_IDLE), DEFAULT_TIME_TO_IDLE); logger.debug("Cache time to idle is set to ", timeToIdle > 0 ? timeToIdle + "s" : "unlimited"); } catch (NumberFormatException e) { logger.warn("Value for cache setting '" + OPT_TIME_TO_IDLE + "' is malformed: " + (String) properties.get(OPT_TIME_TO_IDLE)); logger.warn("Cache setting '" + OPT_TIME_TO_IDLE + "' set to default value of " + DEFAULT_TIME_TO_IDLE); timeToIdle = DEFAULT_TIME_TO_IDLE; } // Time to live try { timeToLive = ConfigurationUtils.getValue((String) properties.get(OPT_TIME_TO_LIVE), DEFAULT_TIME_TO_LIVE); logger.debug("Cache time to live is set to ", timeToIdle > 0 ? timeToLive + "s" : "unlimited"); } catch (NumberFormatException e) { logger.warn("Value for cache setting '" + OPT_TIME_TO_LIVE + "' is malformed: " + (String) properties.get(OPT_TIME_TO_LIVE)); logger.warn("Cache setting '" + OPT_TIME_TO_LIVE + "' set to default value of " + DEFAULT_TIME_TO_LIVE); timeToLive = DEFAULT_TIME_TO_LIVE; } for (String cacheId : cacheManager.getCacheNames()) { Cache cache = cacheManager.getCache(cacheId); if (cache == null) continue; CacheConfiguration config = cache.getCacheConfiguration(); config.setOverflowToDisk(overflowToDisk && diskStoreEnabled); if (overflowToDisk && diskStoreEnabled) { config.setMaxElementsOnDisk(maxElementsOnDisk); config.setDiskPersistent(diskPersistent); } config.setStatistics(statisticsEnabled); config.setMaxElementsInMemory(maxElementsInMemory); config.setTimeToIdleSeconds(timeToIdle); config.setTimeToLiveSeconds(timeToLive); } } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#resetStatistics() */ public void resetStatistics() { for (String cacheId : cacheManager.getCacheNames()) { Cache cache = cacheManager.getCache(cacheId); cache.setStatisticsEnabled(false); cache.setStatisticsEnabled(true); } } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#clear() */ public void clear() { cacheManager.clearAll(); logger.info("Cache '{}' cleared", id); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#preload(ch.entwine.weblounge.common.request.CacheTag[]) */ public void preload(CacheTag[] tags) { if (tags == null || tags.length == 0) throw new IllegalArgumentException("Tags cannot be null or empty"); Cache cache = cacheManager.getCache(DEFAULT_CACHE); // Get the matching keys and load the elements into the cache Collection<Object> keys = getKeys(cache, tags); for (Object key : keys) { cache.load(key); } logger.info("Loaded first {} elements of cache '{}' into memory", keys.size(), id); } /** * Returns those keys from the given cache that contain at least all the tags * as defined in the <code>tags</code> array. * * @param cache * the cache * @param tags * the set of tags * @return the collection of matching keys */ private Collection<Object> getKeys(Cache cache, CacheTag[] tags) { // Create the parts of the key to look for List<String> keyParts = new ArrayList<String>(tags.length); for (CacheTag tag : tags) { StringBuffer b = new StringBuffer(tag.getName()).append(":").append(tag.getValue()); keyParts.add(b.toString()); } // Collect those keys that contain all relevant parts Collection<Object> keys = new ArrayList<Object>(); key: for (Object k : cache.getKeys()) { String key = k.toString(); for (String keyPart : keyParts) { if (!key.contains(keyPart)) continue key; } keys.add(k); } return keys; } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#createCacheableResponse(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public HttpServletResponse createCacheableResponse( HttpServletRequest request, HttpServletResponse response) { return new CacheableHttpServletResponse(response); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#startResponse(ch.entwine.weblounge.common.request.CacheTag[], * ch.entwine.weblounge.common.request.WebloungeRequest, * ch.entwine.weblounge.common.request.WebloungeResponse, long, long) */ public CacheHandle startResponse(CacheTag[] uniqueTags, WebloungeRequest request, WebloungeResponse response, long validTime, long recheckTime) { CacheHandle hdl = new TaggedCacheHandle(uniqueTags, validTime, recheckTime); return startResponse(hdl, request, response); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#startResponse(ch.entwine.weblounge.common.request.CacheHandle, * ch.entwine.weblounge.common.request.WebloungeRequest, * ch.entwine.weblounge.common.request.WebloungeResponse) */ public CacheHandle startResponse(CacheHandle handle, WebloungeRequest request, WebloungeResponse response) { // Check whether the response has been properly wrapped CacheableHttpServletResponse cacheableResponse = unwrapResponse(response); if (cacheableResponse == null) { throw new IllegalStateException("Cached response is not properly wrapped"); } // While disabled, don't do lookups but return immediately if (!enabled) { cacheableResponse.startTransaction(handle, filter); return handle; } // Make sure the cache is still alive if (cacheManager.getStatus() != Status.STATUS_ALIVE) { logger.debug("Cache '{}' has unexpected status '{}'", request.getSite().getIdentifier(), cacheManager.getStatus()); return null; } // Load the cache Cache cache = cacheManager.getCache(DEFAULT_CACHE); if (cache == null) throw new IllegalStateException("No cache found for site '" + id + "'"); // Try to load the content from the cache Element element = cache.get(handle.getKey()); // If it exists, write the contents back to the response if (element != null && element.getValue() != null) { try { logger.debug("Answering {} from cache '{}'", request, id); writeCacheEntry(element, handle, request, response); return null; } catch (IOException e) { logger.debug("Error writing cached response to client"); return null; } } // Make sure that there are no two transactions producing the same content. // If there is a transaction already working on specific content, have // this transaction simply wait for the outcome. synchronized (transactions) { CacheTransaction tx = transactions.get(handle.getKey()); if (tx != null) { try { logger.debug("Waiting for cache transaction {} to be finished", request); while (transactions.containsKey(handle.getKey())) { transactions.wait(); } } catch (InterruptedException e) { // Done sleeping! } } // The cache might have been shut down in the meantime if (cacheManager.getStatus() == Status.STATUS_ALIVE) { element = cache.get(handle.getKey()); } else { logger.debug("Cache '{}' changed status to '{}'", request.getSite().getIdentifier(), cacheManager.getStatus()); } if (element == null) { tx = cacheableResponse.startTransaction(handle, filter); transactions.put(handle.getKey(), tx); logger.debug("Starting work on cached version of {}", request); } } // If we were waiting for an active cache transaction, let's try again if (element != null && element.getValue() != null) { try { logger.debug("Answering {} from cache '{}'", request, id); writeCacheEntry(element, handle, request, response); return null; } catch (IOException e) { logger.warn("Error writing cached response to client"); return null; } } // Apparently, we need to get it done ourselves return handle; } /** * Writes the cache element to the response, setting the cache headers * according to the settings found on the element. * * @param element * the cache contents * @param handle * the cache handle * @param request * the request * @param response * the response * @throws IOException * if writing the cache contents to the response fails */ private void writeCacheEntry(Element element, CacheHandle handle, WebloungeRequest request, WebloungeResponse response) throws IOException { CacheEntry entry = (CacheEntry) element.getValue(); long clientCacheDate = request.getDateHeader("If-Modified-Since"); long validTimeInSeconds = (element.getExpirationTime() - System.currentTimeMillis()) / 1000; String eTag = request.getHeader("If-None-Match"); boolean isModified = !entry.notModified(clientCacheDate) && !entry.matches(eTag); // Write the response headers if (isModified) { response.setHeader("Cache-Control", "max-age=" + validTimeInSeconds + ", must-revalidate"); response.setContentType(entry.getContentType()); response.setContentLength(entry.getContent().length); entry.getHeaders().apply(response); } // Set the current date response.setDateHeader("Date", System.currentTimeMillis()); // This header must be set, otherwise it defaults to // "Thu, 01-Jan-1970 00:00:00 GMT" response.setDateHeader("Expires", element.getExpirationTime()); response.setHeader("Etag", entry.getETag()); // Add the X-Cache-Key header StringBuffer cacheKeyHeader = new StringBuffer(name); cacheKeyHeader.append(" (").append(handle.getKey()).append(")"); response.addHeader(CACHE_KEY_HEADER, cacheKeyHeader.toString()); // Check the headers first. Maybe we don't need to send anything but // a not-modified back if (isModified) { response.getOutputStream().write(entry.getContent()); } else { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } response.flushBuffer(); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#endResponse(ch.entwine.weblounge.common.request.WebloungeResponse) */ public boolean endResponse(WebloungeResponse response) { CacheableHttpServletResponse cacheableResponse = unwrapResponse(response); if (cacheableResponse == null) return false; // Discard any cached content while disabled if (!enabled) return true; // Make sure the cache is still available and active if (cacheManager.getStatus() != Status.STATUS_ALIVE) { logger.debug("Cache '{}' has unexpected status '{}'", cacheManager.getName(), cacheManager.getStatus()); return false; } // Load the cache Cache cache = cacheManager.getCache(DEFAULT_CACHE); if (cache == null) { logger.debug("Cache for {} was deactivated, response is not being cached", response); return false; } // Finish writing the element CacheTransaction tx = cacheableResponse.endOutput(); // Is the response ready to be cached? if (tx == null) { logger.debug("Response to {} was not associated with a transaction", response); return false; } // Important note: Do not return prior to this try block if there is a // transaction associated with the request. try { // Is the response ready to be cached? if (tx.isValid() && response.isValid() && response.getStatus() == HttpServletResponse.SC_OK) { logger.trace("Writing response for {} to the cache", response); CacheEntry entry = new CacheEntry(tx.getHandle(), tx.getContent(), tx.getHeaders()); Element element = new Element(entry.getKey(), entry); cache.put(element); response.setDateHeader("Expires", System.currentTimeMillis() + tx.getHandle().getExpireTime()); } else if (tx.isValid() && response.isValid()) { logger.trace("Skip caching of response for {} to the cache: {}", response, response.getStatus()); response.setDateHeader("Expires", System.currentTimeMillis() + tx.getHandle().getExpireTime()); } else { logger.debug("Response to {} was invalid and is not being cached", response); } return tx.isValid() && response.isValid(); } finally { // Mark the current transaction as finished and notify anybody who was // waiting for it to be finished synchronized (transactions) { transactions.remove(tx.getHandle().getKey()); logger.debug("Caching of {} finished", response); transactions.notifyAll(); } try { if (!response.isCommitted()) response.flushBuffer(); } catch (IOException e) { logger.warn("Error flusing response: " + e.getMessage()); } } } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#invalidate(ch.entwine.weblounge.common.request.WebloungeResponse) */ public void invalidate(WebloungeResponse response) { CacheableHttpServletResponse cacheableResponse = unwrapResponse(response); if (cacheableResponse == null || cacheableResponse.getTransaction() == null) return; cacheableResponse.invalidate(); CacheTransaction tx = cacheableResponse.getTransaction(); invalidate(tx.getHandle()); logger.debug("Removed {} from cache '{}'", response, id); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#invalidate(ch.entwine.weblounge.common.request.CacheTag[]) */ public void invalidate(CacheTag[] tags) { if (tags == null || tags.length == 0) throw new IllegalArgumentException("Tags cannot be null or empty"); // Load the cache Cache cache = cacheManager.getCache(DEFAULT_CACHE); // Remove the objects matched by the tags long removed = 0; for (Object key : getKeys(cache, tags)) { if (cache.remove(key)) removed++; } logger.debug("Removed {} elements from cache '{}'", removed, id); } /** * {@inheritDoc} * * @see ch.entwine.weblounge.common.request.ResponseCache#invalidate(ch.entwine.weblounge.common.request.CacheHandle) */ public void invalidate(CacheHandle handle) { if (handle == null) throw new IllegalArgumentException("Handle cannot be null"); // Make sure the cache is still available and active if (cacheManager.getStatus() != Status.STATUS_ALIVE) { logger.debug("Cache '{}' has unexpected status '{}'", cacheManager.getName(), cacheManager.getStatus()); return; } // Load the cache Cache cache = cacheManager.getCache(DEFAULT_CACHE); if (cache == null) { logger.debug("Cache for {} was deactivated, response is not being invalidated"); return; } cache.remove(handle.getKey()); // Mark the current transaction as finished and notify anybody that was // waiting for it to be finished synchronized (transactions) { transactions.remove(handle.getKey()); transactions.notifyAll(); } logger.debug("Removed {} from cache '{}'", handle.getKey(), id); } /** * Extracts the <code>CacheableServletResponse</code> from its wrapper(s). * * @param response * the original response * @return the wrapped <code>CacheableServletResponse</code> or * <code>null</code> if the response is not cacheable */ private static CacheableHttpServletResponse unwrapResponse( ServletResponse response) { while (response != null) { if (response instanceof CacheableHttpServletResponse) return (CacheableHttpServletResponse) response; if (!(response instanceof ServletResponseWrapper)) break; response = ((ServletResponseWrapper) response).getResponse(); } return null; } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return name; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
59f3eb1d3a9641d0bb220dd32e4fcf33dc944249
4e0531c99300350a5dca566814e27e8d95d3a3d2
/SkylineClient/src/businesslogic/guestbl/GuestController.java
f1b1432b0fab54125749fc96b039a53c85d85d93
[]
no_license
zeng-pan/bighomework
1aff947ff6e0a0e5ad484bdb49c9002cb50053df
8a32c214039c62ce8bd58ce25b4ecf1416148a78
refs/heads/master
2021-01-10T01:46:06.375388
2015-11-15T08:02:47
2015-11-15T08:02:47
46,209,569
0
0
null
null
null
null
UTF-8
Java
false
false
329
java
package businesslogic.guestbl; import businesslogicservice.GuestBLService; import vo.HistoryVO; public class GuestController implements GuestBLService { @Override public boolean showHistory(String code, HistoryVO history) { // TODO Auto-generated method stub History his=new History(code); return false; } }
[ "3222876588@qq.com" ]
3222876588@qq.com
2f220d0ac02e541d2e9f6ab7e4ed657a67cf1e94
55c1162c86452a410c94b9138f02b301aead331e
/blless/src/com/infoyb/manage/util/alipay/AlipayOrderItem.java
7c4be704db5df98d8dc960950b75117cd64d794b
[]
no_license
liuhp1641/beamzhang
45937ac06a680cc19298917e1c35134df1164c90
61766c2cb84ae05fc3f55bb1de00d7e02dc9d702
refs/heads/master
2021-01-10T08:44:19.856172
2016-01-30T12:58:14
2016-01-30T12:58:14
50,724,320
0
1
null
null
null
null
UTF-8
Java
false
false
2,777
java
package com.cm.manage.util.alipay; /*** * @describe 对应支付宝明细节点DetailItem中数据项 * @author sunjf * */ public class AlipayOrderItem { private String userSerialNo;//商户流水号 private String realName;//收款银行户名 private String bankCardNo;//收款银行卡号 private String bankName;//收款开户银行名称,如中国银行 private String bankProvince;//开户行所在省份 private String bankCity;//开户行所在城市 private String subBankName;//收款支行名称 private String amount;//收款金额 private String customerType;//对公对私 private String status;//状态 private String instructionId;//支付宝内部提现流水号 private String bankFlag;//是否退票 0 没有退票 1退票 private String dealMemo;//明细描述信息 private String userMemo;//用户原先提交的备注 public String getUserSerialNo() { return userSerialNo; } public void setUserSerialNo(String userSerialNo) { this.userSerialNo = userSerialNo; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getInstructionId() { return instructionId; } public void setInstructionId(String instructionId) { this.instructionId = instructionId; } public String getDealMemo() { return dealMemo; } public void setDealMemo(String dealMemo) { this.dealMemo = dealMemo; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getBankCardNo() { return bankCardNo; } public void setBankCardNo(String bankCardNo) { this.bankCardNo = bankCardNo; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankProvince() { return bankProvince; } public void setBankProvince(String bankProvince) { this.bankProvince = bankProvince; } public String getBankCity() { return bankCity; } public void setBankCity(String bankCity) { this.bankCity = bankCity; } public String getSubBankName() { return subBankName; } public void setSubBankName(String subBankName) { this.subBankName = subBankName; } public String getCustomerType() { return customerType; } public void setCustomerType(String customerType) { this.customerType = customerType; } public String getBankFlag() { return bankFlag; } public void setBankFlag(String bankFlag) { this.bankFlag = bankFlag; } public String getUserMemo() { return userMemo; } public void setUserMemo(String userMemo) { this.userMemo = userMemo; } }
[ "522501392@qq.com" ]
522501392@qq.com
3768673f3ca9676982bdf445b6fb8434bb78b66a
4d171dd2adc56c3d1a4c0ce99456938c9c59868f
/p2/BoggleDictionary.java
90005cda572d446ebe46aa89adf2e10f1bf97431
[]
no_license
HaseebNain/CS-221
002cc87aa075ee8341cd0ad18e34f8e95f54a4d0
cf7397a4931f2dc44d8e9595f60e9c60325423e7
refs/heads/master
2021-01-10T17:48:31.395634
2016-02-17T02:53:00
2016-02-17T02:53:00
51,888,338
0
0
null
null
null
null
UTF-8
Java
false
false
2,047
java
// BoggleDictionary.java import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.Scanner; import java.util.HashSet; import java.util.Iterator; /** A class that stores a dictionary containing words that can be used in a Boggle game. @author Teresa Cole @version CS221 */ public class BoggleDictionary { private HashSet<String> dictionary; /** Create the BoggleDictionary from the file dictionary.dat */ @SuppressWarnings("unchecked") public BoggleDictionary() throws Exception { ObjectInputStream dictFile = new ObjectInputStream( new FileInputStream( new File( "dictionary.dat"))); dictionary = (HashSet<String>)dictFile.readObject(); dictFile.close(); } /** Check to see if a string is in the dictionary to determine whether it * is a valid word. * @param word the string to check for * @return true if word is in the dictionary, false otherwise. */ public boolean contains( String word) { return dictionary.contains( word); } /** Get an iterator that returns all the words in the dictionary, one at a * time. * @return an iterator that can be used to get all the words in the * dictionary. */ public Iterator<String> iterator() { return dictionary.iterator(); } /** Main entry point */ static public void main(String[] args) { System.out.println( "BoggleDictionary Program "); Scanner kbd = new Scanner( System.in); BoggleDictionary theDictionary = null; try { theDictionary = new BoggleDictionary(); } catch (Exception ioe) { System.err.println( "error reading dictionary"); System.exit(1); } String word; /* while (kbd.hasNext()) { word = kbd.next(); if (theDictionary.contains( word)) System.out.println( word + " is in the dictionary"); else System.out.println( word + " is not in the dictionary"); } */ Iterator<String> iter = theDictionary.iterator(); for (int i=0; i<25; i++) System.out.println( iter.next()); } }
[ "haseebnain@u.boisestate.edu" ]
haseebnain@u.boisestate.edu
3a66e51dc95ace630317f6ca2cb989e306f9c660
449017514597684fe2cc515a2d66899a1cf13424
/geometry/CameraFocus.java
faa8212963294791712861dac9d0bbd8d444fe9f
[]
no_license
wgr523/Graphics
f5d7ca2bdaf6821e27308fe511763f28e32b8005
3e6d98731a33668839332d75c27346f8583fcb0e
refs/heads/master
2020-04-07T07:28:21.509657
2016-05-06T01:49:26
2016-05-06T01:49:26
58,172,060
0
0
null
null
null
null
UTF-8
Java
false
false
340
java
package geometry; public class CameraFocus extends Camera { double ape=.02;//光圈 @Override Point getView() { // TODO Auto-generated method stub double theta=Math.random()*Math.PI*2; double rad=Math.random()*ape; Point ret =new Point(view); ret.plus(new Point(0,rad*Math.cos(theta),rad*Math.sin(theta))); return ret; } }
[ "wgr54@126.com" ]
wgr54@126.com
3bda53818227e75870ffb6fbae1b979fe6af66f8
27f31c3ef8fbd6ff4463cafc92768d6ee2b2900d
/Infothek_tmj/src/li/tmj/ui/fx/PersonController.java
4d7cc571903d22013679817069304b92ec458d7d
[]
no_license
tmjGit/Infothek
a1002b121ce8eefe2128732e238e59aed2157224
20c1df10f2421a2ccc8da599deb2a943a971449d
refs/heads/master
2020-04-07T10:57:26.104334
2018-11-20T00:36:07
2018-11-20T00:36:07
158,306,908
0
0
null
null
null
null
UTF-8
Java
false
false
14,269
java
package li.tmj.ui.fx; import java.io.IOException; import java.net.URL; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import org.hibernate.Session; import org.pmw.tinylog.Logger; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import li.tmj.app.Application; import li.tmj.db.hibernate.DataHiberDAO; import li.tmj.db.hibernate.HibernateUtil; import li.tmj.db.model.Address; import li.tmj.db.model.Data; import li.tmj.db.model.Email; import li.tmj.db.model.Person; import li.tmj.db.model.Fone; import li.tmj.ui.fx.controls.ObjectCombobox; import li.tmj.ui.fx.model.Arrange; import li.tmj.ui.fx.model.Controls; import li.tmj.ui.fx.model.Place; import li.tmj.ui.fx.model.PlaceRelation; import li.tmj.ui.fx.model.Places; import li.tmj.ui.lang.Localization; public class PersonController implements Initializable { @FXML AnchorPane anchorPane; @FXML Button searchBt; @FXML Button menuBt; @FXML Button newWindowBt; @FXML Button submitBt; @FXML Label infoT; @FXML Label idT; @FXML TextField idFld; Controls controls; Places places; Person currentPerson; @Override public void initialize(URL location, ResourceBundle resources) { setFxText(); makeControls(anchorPane.getChildren()); objectOut(currentPerson); } private void setFxText() { searchBt.setText(Localization.get("Find")); menuBt.setText(Localization.get("Menu")); newWindowBt.setText(Localization.get("NewWindow")); submitBt.setText((Localization.get("Save"))); } private void makeControls(ObservableList<Node> list) { controls=makeControlsList(); places=makePlaces(); Arrange.arrangeControls(controls,places,list); } private Places makePlaces() { Places places=new Places(); Place p; int i,j,k; p=new Place(Application.FX_CONTROLS_DISTANCE,Application.FX_CONTROLS_DISTANCE,40,Application.FX_LINE_HEIGHT);//nameLabelT p.setHeightRelation(PlaceRelation.ABSOLUTE); k=places.add(p)-1;// ArrayList.add does not return the index as documented! It returns the index+1 or the new size or something like that! p=Place.createPlaceRightOf(k);//indivLabelT p.setWidth(70); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//nameIndivFld p.setWidth(200); j=places.add(p)-1; p=Place.createPlaceRightOf(j,Application.FX_CONTROLS_DISTANCE);//sexLabelT p.setWidth(60); j=places.add(p)-1; p=Place.createPlaceRightOf(j);// sexCb p.setWidth(80); j=places.add(p)-1; p=Place.createPlaceRightOf(j,Application.FX_CONTROLS_DISTANCE);//categoryLabelT; p.setWidth(55); j=places.add(p)-1; p=Place.createPlaceRightOf(j);//categoryCb; p.setWidth(90); places.add(p); p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//familyLabelT p.setHeight(Application.FX_LINE_HEIGHT); p.setHeightRelation(PlaceRelation.ABSOLUTE); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//nameFamPreCb p.setWidth(30); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//nameFamFld p.setWidth(places.get(2).getWidth()-places.get(8).getWidth()); //nameIndivFld - nameFamPreCb i=places.add(p)-1; p=Place.createPlaceRightOf(i,Application.FX_CONTROLS_DISTANCE);//birthLabelT; p.setWidth(places.get(3).getWidth());//sexLabelT i=places.add(p)-1; p=Place.createPlaceRightOf(i);//birthDayFld; p.setWidth(35); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//dot p.setWidth(10); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//birthMonthFld; p.setWidth(35); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//dot p.setWidth(10); i=places.add(p)-1; p=Place.createPlaceRightOf(i);//birthYearFld; p.setWidth(45); places.add(p); p=new Place(k,i,600,100);//addressView; p.setLeftRelation(PlaceRelation.BENEATH); p.setTopRelation(PlaceRelation.BENEATH,Application.FX_CONTROLS_DISTANCE); p.setHeightRelation(PlaceRelation.ABSOLUTE); i=places.add(p)-1; p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//phoneView; p.setHeight(100); p.setHeightRelation(PlaceRelation.ABSOLUTE); i=places.add(p)-1; p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//personView; p.setHeight(100); p.setHeightRelation(PlaceRelation.ABSOLUTE); i=places.add(p)-1; p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//emailView; p.setHeight(80); p.setHeightRelation(PlaceRelation.ABSOLUTE); i=places.add(p)-1; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//mediaView; // p.setHeight(80); // p.setHeightRelation(PlaceRelation.ABSOLUTE); // i=places.add(p)-1; // controls.add(new Label());//infoLabel; // controls.add(new TextField());//plzField; // controls.add(new TextField());//ortField; // controls.add(new TextField());//strasseField; // controls.add(new TextField());//telfonField; // controls.add(new TextField());//mobilField; // controls.add(new TextField());//emailField; // <TextField fx:id="telfonField" layoutX="602.0" layoutY="440.0" promptText="Telefon" /> // <TextField fx:id="mobilField" layoutX="441.0" layoutY="440.0" promptText="Mobil" /> // <TextField fx:id="emailField" layoutX="267.0" layoutY="440.0" promptText="email" /> // <TextField fx:id="plzField" layoutX="353.0" layoutY="492.0" promptText="PLZ" /> // <TextField fx:id="ortField" layoutX="518.0" layoutY="480.0" promptText="Ort" /> // <TextField fx:id="strasseField" layoutX="180.0" layoutY="505.0" promptText="Straße" /> // <Button fx:id="saveBt" layoutX="28.0" layoutY="505.0" mnemonicParsing="false" text="Save" /> return places; } private Controls makeControlsList(){ Controls controls=new Controls(); controls.add(new Label()// nameLabelT ,"Name");//language key controls.add(new Label(), "Individual");//indivLabelT; controls.add(new TextField());//nameIndivFld; controls.add(new Label(Localization.get("Sex")) );//sexLabelT; controls.add(new ObjectCombobox());//sexCb; controls.add(new Label(Localization.get( "Category")));//categoryLabelT; controls.add(new ObjectCombobox());//categoryCb; controls.add(new Label(Localization.get( "Family")));//familyLabelT; controls.add(new ObjectCombobox());//nameFamPreCb; controls.add(new TextField());//nameFamFld; controls.add(new Label(Localization.get("Birthday" )));//birthLabelT; controls.add(new TextField());//birthDayFld; controls.add(new Label(Localization.get(".")));//dot controls.add(new TextField());//birthMonthFld; controls.add(new Label(Localization.get(".")));//dot controls.add(new TextField());//birthYearFld; controls.add(new TableView<Address>());//addressView; controls.add(new TableView<Fone>());//phoneView; controls.add(new TableView<Person>());//personView; controls.add(new TableView<Email>());//emailView; // controls.add(new TableView<Media>());//mediaView; // controls.add(new Label());//infoLabel; // controls.add(new TextField());//plzField; // controls.add(new TextField());//ortField; // controls.add(new TextField());//strasseField; // controls.add(new TextField());//telfonField; // controls.add(new TextField());//mobilField; // controls.add(new TextField());//emailField; return controls; } @FXML private void menuBtAction(ActionEvent event) { try { FxScene.MAIN.showOnNewStage(); } catch (IOException e) { Logger.error(e,"Could not open new window!"); } // FxManager.closeMyStage(parent); } @FXML private void newWindowBtAction(ActionEvent event) { try { FxScene.PERSON.showOnNewStage(); } catch (IOException e) { Logger.error(e,"Could not open new window!"); } } @FXML private void searchBtAction(ActionEvent event) { Button b=(Button) event.getSource();//searchBt if(b.getText().equals(Localization.get("Find"))) { // invoking search mode idT.setText(Localization.get("Find")); searchBt.setText(Localization.get("Cancel")); submitBt.setText(Localization.get("Search")); idFld.setText(""); controls.clearFields(); info("Search mode started.");; }else { // canceling search idT.setText(Localization.get("ID")); searchBt.setText(Localization.get("Find")); submitBt.setText(Localization.get("Save")); if(null!=currentPerson) { objectOut(currentPerson); } info("Search canceled."); } } @FXML private void submitBtAction(ActionEvent event) { Button b=(Button) event.getSource();//submitBt b.setDisable(true);// Disable this function until we finished. searchBt.setDisable(true); if(b.getText().equals(Localization.get("Search"))) { // do a search doSearch(); }else if(b.getText().equals(Localization.get("Save"))) { // save information doSave(); } submitFinished(); } private void doSearch() { // Thread t=new Thread(()->{ System.out.println("if -> bla"); submitBt.setText("bla"); submitBt.setText(Localization.get("Searching"+"...")); // }); // t.start(); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Platform.runLater(() -> { // Runnable r=new Runnable() { // // @Override // public void run() { // // TODO Auto-generated method stub // // } // }; // Task t=new Task<V>() { // info("Searching..."); // DataHiberDAO dao=new DataHiberDAO(); // We want the visible feedback, first. // Person person = objectIn(); // So this cannot be outside the if. // System.out.println("Reading by example person="+person); // List<Data> persons=dao.read(person); // System.out.println("Found " + persons.size() + " persons="+persons); // currentPerson=(Person) persons.get(0);//erster Datensatz des Suchergebnisses // objectOut(currentPerson); // }); // t.start(); Runnable r=new Runnable() { @Override public void run() { info("Searching..."); DataHiberDAO dao=new DataHiberDAO(); // We want the visible feedback, first. Person person = objectIn(); // So this cannot be outside the if. System.out.println("Reading by example person="+person); List<Data> persons=dao.read(person); System.out.println("Found " + persons.size() + " persons="+persons); currentPerson=(Person) persons.get(0);//erster Datensatz des Suchergebnisses objectOut(currentPerson); } }; r.run(); // debug eigentlich im Thread ausführen! searchBt.setText(Localization.get("Find")); info("Searched."); } private void doSave() { submitBt.setText(Localization.get("Saving"+"...")); info("Saving..."); DataHiberDAO dao=new DataHiberDAO(); // We want the visible feedback, first. Person person = objectIn(); // So this cannot be outside the if. System.out.println("Saving person="+person); dao.save(person); info("Saved."); } private void submitFinished() { submitBt.setText(Localization.get("Save")); submitBt.setDisable(false);// We finished. searchBt.setDisable(false); } private void objectOut(Person person) { idT.setText("ID"); if(null==person) { idFld.setText(""); controls.setText(2, "");//nameIndivFld; controls.setText(8, "");//nameFamPreCb controls.setText(9, "");//nameFamFld; controls.setText(4, "");//sexCb; controls.setText(6, "");//categoryCb; controls.setText(11, "");//birthDayFld; controls.setText(13, "");//birthMonthFld; controls.setText(15, "");//birthYearFld; }else { idFld.setText(Integer.toString(person.getId())); controls.setText(2, person.getNameIndividual());//nameIndivFld; controls.setText(8, person.getNameFamilyPre());//nameFamPreCb controls.setText(9, person.getNameFamily());//nameFamFld; controls.setText(4, person.getSex());//nameFamPreCb controls.setText(6, person.getCategory());//nameFamPreCb controls.setText(11, Integer.toString(person.getBirthDay()));//birthDayFld; controls.setText(13, Integer.toString(person.getBirthMonth()));//birthMonthFld; controls.setText(15, Integer.toString(person.getBirthYear()));//birthYearFld; } // p=new Place(k,i,600,100);//addressView; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//phoneView; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//personView; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//emailView; } private Person objectIn() { Person person=new Person(); String s; s=idFld.getText(); if(!"".equals(s)) { person.setId(Integer.parseInt(s)); } s=controls.getText(2);//nameIndivFld if(!"".equals(s)) { person.setNameIndividual(s); } s=controls.getText(8);//nameFamPreFld if(!"".equals(s)) { person.setNameFamilyPre(s); } s=controls.getText(9);//nameFamFld if(!"".equals(s)) { person.setNameFamily(s); } s=controls.getText(4);//sexCb if(!"".equals(s)) { person.setSex(s); } s=controls.getText(6);//categoryCb if(!"".equals(s)) { person.setCategory(s); } s=controls.getText(11);//birthDayFld if(!"".equals(s)) { person.setBirthDay(Integer.parseInt(s)); } s=controls.getText(11);//birthMonthFld if(!"".equals(s)) { person.setBirthMonth(Integer.parseInt(s)); } s=controls.getText(11);//birthYearFld if(!"".equals(s)) { person.setBirthYear(Integer.parseInt(s)); } // p=new Place(k,i,600,100);//addressView; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//phoneView; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//personView; // p=Place.createPlaceBeneath(i,Application.FX_CONTROLS_DISTANCE);//emailView; return person; } private void info(String msg) { infoT.setText(LocalDateTime.now().toString()+" "+msg); } }
[ "git@tmj.li" ]
git@tmj.li
b742256f6dbbde14dd95895ebf6d7e88873983f6
71b2248643d253f2bde81e5736e294028672eac9
/src/java/lab3/model/TriangleAreaCalculatorStrategy.java
b8387585eabf367464fa383b28fe96ec9d262d62
[]
no_license
mpatel6/Calculator
dd4e6c334f2075e259ada08c0e33a8afe65ec71f
8bb6a3b015aa931a1bb3dc4564245289976cdc39
refs/heads/master
2021-01-18T15:14:42.754519
2015-09-14T01:51:08
2015-09-14T01:51:08
41,838,426
0
0
null
null
null
null
UTF-8
Java
false
false
1,197
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 lab3.model; /** * * @author Ankita */ public final class TriangleAreaCalculatorStrategy implements GeometricAreaCalculator { private String height, base; public TriangleAreaCalculatorStrategy() { } public TriangleAreaCalculatorStrategy(final String height, final String base) { setHeight(height); setBase(base); } public String getHeight() { return height; } public void setHeight(final String height) { if (height == null) { this.height = "0"; } else { this.height = height; } } public String getBase() { return base; } public void setBase(final String base) { if (base == null) { this.base = "0"; } else { this.base = base; } } @Override public double getArea() { return Double.parseDouble(height) * Double.parseDouble(base) * 0.5; } }
[ "Ankita@Ankita-PC" ]
Ankita@Ankita-PC
854789794b217d0e1d3f8bcb27d72298537870fb
edce86eb8f94f9533948db98e6419ebd69db3ab6
/Lib_IM/src/com/movit/platform/im/base/ChatBaseActivity.java
30bb8a41198ef44c18707e67eb22194ade31bc43
[]
no_license
Louanna/Bright
a14989715f632a6c2bbac8d3358c07fb38a3186c
c9068c2c7077551f2929c1737df18f02ab8601d4
refs/heads/master
2021-01-19T03:41:30.648800
2017-03-15T05:24:07
2017-03-15T05:24:07
84,407,948
0
0
null
null
null
null
UTF-8
Java
false
false
77,269
java
package com.movit.platform.im.base; import android.annotation.SuppressLint; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.movit.platform.cloud.activity.SkyDriveActivity; import com.movit.platform.common.application.BaseApplication; import com.movit.platform.common.constants.CommConstants; import com.movit.platform.common.entities.MessageBean; import com.movit.platform.common.entities.SerializableObj; import com.movit.platform.common.module.user.db.UserDao; import com.movit.platform.common.module.user.entities.UserInfo; import com.movit.platform.framework.core.okhttp.callback.StringCallback; import com.movit.platform.framework.helper.MFSPHelper; import com.movit.platform.framework.manager.HttpManager; import com.movit.platform.framework.utils.ActivityUtils; import com.movit.platform.framework.utils.Audio2Mp3Utils; import com.movit.platform.framework.utils.Base64Utils; import com.movit.platform.framework.utils.DateUtils; import com.movit.platform.framework.utils.DialogUtils; import com.movit.platform.framework.utils.FileUtils; import com.movit.platform.framework.utils.LogUtils; import com.movit.platform.framework.utils.PicUtils; import com.movit.platform.framework.utils.StringUtils; import com.movit.platform.framework.utils.ToastUtils; import com.movit.platform.framework.view.faceview.FacePageAdeapter; import com.movit.platform.framework.view.faceview.FaceViewPage; import com.movit.platform.framework.view.pageIndicator.CirclePageIndicator; import com.movit.platform.framework.widget.xlistview.XListView; import com.movit.platform.framework.widget.xlistview.XListView.IXListViewListener; import com.movit.platform.im.R; import com.movit.platform.im.activity.IMBaseActivity; import com.movit.platform.im.constants.IMConstants; import com.movit.platform.im.db.IMDBFactory; import com.movit.platform.im.db.RecordsManager; import com.movit.platform.im.helper.ServiceHelper; import com.movit.platform.im.manager.MessageManager; import com.movit.platform.im.manager.XmppManager; import com.movit.platform.im.module.group.entities.Group; import com.movit.platform.im.module.location.MapViewActivity; import com.movit.platform.im.module.single.activity.ChatActivity; import com.movit.platform.im.module.single.adapter.ChatAdapter; import com.movit.platform.im.utils.JSONConvert; import com.movit.platform.im.widget.CurEditText; import com.movit.platform.im.widget.TextChangedListener; import com.qd.recorder.FFmpegRecorderActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; @SuppressLint("InflateParams") @SuppressWarnings({"unchecked", "deprecation"}) public abstract class ChatBaseActivity extends IMBaseActivity implements OnTouchListener, OnClickListener, IXListViewListener, ChatClickListener, TextChangedListener.CurKeyClickedListener, MessageManager.OnSendMsgProcessListener { //获取相册图片 protected final int REQUEST_CODE_SEND_PIC_ALBUM = 1; //通过相机拍照获取图片 protected final int REQUEST_CODE_SEND_PIC_CAMERA = REQUEST_CODE_SEND_PIC_ALBUM + 1; //获取视频 protected final int REQUEST_CODE_SEND_VIDEO = REQUEST_CODE_SEND_PIC_CAMERA + 1; //获取文件 protected final int REQUEST_CODE_SEND_FILE = REQUEST_CODE_SEND_VIDEO + 1; //获取文档管理文件 protected final int REQUEST_CODE_SEND_FILE_2 = REQUEST_CODE_SEND_FILE + 1; //分享文档 protected final int REQUEST_CODE_SHARE_FILE = REQUEST_CODE_SEND_FILE_2 + 1; //定位 protected final int REQUEST_CODE_LOCATION = REQUEST_CODE_SHARE_FILE + 1; //选取相册图片 protected final int REQUEST_CODE_SELECTED_PIC = REQUEST_CODE_LOCATION + 1; //跳转到聊天详情页面 protected final int REQUEST_CODE_CHAT_DETAIL_PAGE = REQUEST_CODE_SELECTED_PIC + 1; //跳转到ImageViewPager页面 public final int REQUEST_CODE_VIEWPAGER_PAGE = REQUEST_CODE_CHAT_DETAIL_PAGE + 1; //记录当前聊天窗口中,从db获取到的状态为isSending的聊天记录 protected static JSONArray curUnSendRecords; // 对话ListView protected XListView mMsgListView; //群聊界面@提示 protected TextView tv_tips; private LinearLayout mFaceRoot;// 表情父容器 private FaceViewPage mfaceViewPage; private LinearLayout mMenuRoot;// 菜单父容器 private ViewPager mMenuViewPager;// 菜单选择ViewPager private boolean mIsFaceShow = false;// 是否显示表情 private boolean mIsVoiceShow = false;// 是否语音输入 private boolean mIsMenuShow = false;// 是否显示菜单 private Button mFaceSwitchBtn;// 切换表情的button private Button mSendMsgBtn;// 发送消息button private Button mVoiceBtn;// 语音 private Button mAddMoreBtn;// 更多,上传图片等 private Button mVoiceSpeakBtn;// 按住 说话 protected CurEditText mChatEditText;// 消息输入框 protected TextView mTopTitle;// 标题栏 protected ImageView mTopLeftImage, mTopRightImage; private WindowManager.LayoutParams mWindowNanagerParams; private InputMethodManager mInputMethodManager; private LinearLayout voice_rcd_hint_rcding, voice_rcd_hint_tooshort, voice_rcd_hint_cancle; private View chat_voice_popup; private Audio2Mp3Utils _2Mp3util = null; private String voiceFileNameRaw; private String voiceFileNameMp3; private int flag = 1; private long startVoiceT, endVoiceT; protected ImageView volume; protected ImageView scImage; private Uri imageUri;// The Uri to store the big protected String currentTime; //如果是单聊,则sessionObjId为friendId //如果是群聊,则sessionObjId为groupId protected String sessionObjId; //是否需要刷新页面列表 protected boolean isRefresh = false; protected List<MessageBean> message_pool = new ArrayList<>(); protected ChatAdapter chatAdapter; protected int ctype; protected int groupType; protected Context mContext; protected ServiceHelper tools; protected DialogUtils proDialogUtil; protected RecordsManager recordsManager; private CompleteReceiver completeReceiver; public MessageBean message; public static Map<Long, String> downloadMap = new HashMap<>(); public static Map<String, String> msgIdMap = new HashMap<>(); //增加耳边听语音 private Sensor mSensor; private AudioManager mAudioManager; private SensorManager mSensorManager; private SensorEventListener mEventListener; private File mVideoFile; private File mThumbnailFile; static final String VIDEO_FILE_EXTENSION = ".mp4"; static final String VIDEO_FILE_POSTFIX = "temp_video" + VIDEO_FILE_EXTENSION; static final String THUMBNAIL_FILE_EXTENSION = ".jpg"; static final String THUMBNAIL_FILE_POSTFIX = "temp_thumbnail" + THUMBNAIL_FILE_EXTENSION; private boolean isRoll= false; @SuppressLint("HandlerLeak") protected Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case CommConstants.MSG_SEND_SUCCESS: // 刷新界面 MessageBean messageDataObj = (MessageBean) msg.obj; for (int i = message_pool.size() - 1; i >= 0; i--) { if (message_pool.get(i).getMsgId() .equals(messageDataObj.getMsgId()) && message_pool.get(i).getIsSend() == CommConstants.MSG_SEND_PROGRESS) { message_pool.get(i) .setIsSend(CommConstants.MSG_SEND_SUCCESS); message_pool.get(i).setContent( messageDataObj.getContent()); chatAdapter.refreshChatData(message_pool); } } boolean flag = false; for (int j = 0; j < IMConstants.contactListDatas.size(); j++) { MessageBean bean = IMConstants.contactListDatas.get(j); if ((bean.getFriendId().equalsIgnoreCase(sessionObjId) && bean.getCtype() == ctype && ctype == 0) || (bean.getRoomId().equalsIgnoreCase(sessionObjId) && bean.getCtype() == ctype && ctype == 1)) { IMConstants.contactListDatas.remove(j); IMConstants.contactListDatas.add(0, message_pool.get(message_pool.size() - 1)); flag = true; break; } } if (!flag) { IMConstants.contactListDatas .add(0, message_pool.get(message_pool.size() - 1)); } break; case CommConstants.MSG_SEND_FAIL: // 刷新界面 MessageBean messageDataObj2 = (MessageBean) msg.obj; for (int i = message_pool.size() - 1; i >= 0; i--) { if (message_pool.get(i).getMsgId() .equals(messageDataObj2.getMsgId()) && message_pool.get(i).getIsSend() == CommConstants.MSG_SEND_PROGRESS) { message_pool.get(i).setIsSend(CommConstants.MSG_SEND_FAIL); chatAdapter.refreshChatData(message_pool); } } //更新本地聊天记录,只修改发送状态 recordsManager.updateRecord(null, CommConstants.MSG_SEND_FAIL, messageDataObj2.getMsgId()); break; case CommConstants.MSG_SEND_RESEND: final int postion = (Integer) msg.obj; try { if (XmppManager.getInstance().isConnected()) { MessageBean failedMessageBean = message_pool.get(postion); if (failedMessageBean.getIsSend() == CommConstants.MSG_SEND_FAIL) { //更新UI failedMessageBean.setIsSend(CommConstants.MSG_SEND_PROGRESS); chatAdapter.refreshChatData(message_pool); //重新发送 MessageManager.getInstance(mContext).reSendMessage(failedMessageBean); //更新本地聊天记录,只修改发送状态 recordsManager.updateRecord(null, CommConstants.MSG_SEND_PROGRESS, failedMessageBean.getMsgId()); } } } catch (Exception e) { e.printStackTrace(); } break; default: break; } super.handleMessage(msg); } }; private boolean hasNewMes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.im_activity_chat_base); hasNewMes = getIntent().getBooleanExtra("hasNewMes", false); tools = new ServiceHelper(); proDialogUtil = DialogUtils.getInstants(); recordsManager = IMDBFactory.getInstance(this).getRecordsManager(); initView();// 初始化view initFacePage();// 初始化表情页面 initMenuPage();// 初始化菜单页面 completeReceiver = new CompleteReceiver(); /** register download success broadcast **/ registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); // 初始化数据 initData(); initTopBar(); initListAdapter(); chatAdapter.setShareFileListener(new ChatAdapter.ShareFileListener() { @Override public void shareFile(MessageBean messageBean) { message = messageBean; Intent intent = new Intent(); intent.putExtra("TITLE", getString(R.string.select_contacts)); intent.putExtra("ACTION", "forward"); ((BaseApplication) getApplication()).getUIController(). onIMOrgClickListener(ChatBaseActivity.this, intent, REQUEST_CODE_SHARE_FILE); } }); mMsgListView.setAdapter(chatAdapter); mMsgListView.setSelection(chatAdapter.getCount() - 1); mMsgListView.setPullRefreshEnable(true); mMsgListView.setPullLoadEnable(false); initAudioAndSensor(); } private void initAudioAndSensor() { mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //TYPE_PROXIMITY是距离传感器类型,当然你还可以换成其他的,比如光线传感器 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float mProximiny = event.values[0]; if (mProximiny == mSensor.getMaximumRange()) { //扬声器播放模式 setModeNormal(); } else { //听筒播放模式 setInCallBySdk(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; } @Override protected void onResume() { super.onResume(); refreshUnReadCount(); mSensorManager.registerListener(mEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL); if (XmppManager.getInstance().isConnected()&&XmppManager.getInstance().getConnection().isAuthenticated()) { sendEnterSession(); } else { /** * add by zoro.qian * 延迟2秒,等待Xmpp连接成功 */ handler.postDelayed(new Runnable() { @Override public void run() { sendEnterSession(); } }, 2 * 1000); } } @Override protected void onPause() { super.onPause(); unRegistListener(); } @Override public void onDestroy() { super.onDestroy(); this.unregisterReceiver(completeReceiver); IMConstants.CHATTING_ID = ""; IMConstants.CHATTING_TYPE = ""; } @Override public void onBackPressed() { IMConstants.CHATTING_ID = ""; IMConstants.CHATTING_TYPE = ""; if (null != chatAdapter) { chatAdapter.stopPlayVoice(); } finish(); } //听筒播放模式 private void setInCallBySdk() { if (mAudioManager == null) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (mAudioManager.getMode() != AudioManager.MODE_IN_COMMUNICATION) { mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); } try { Class clazz = Class.forName("android.media.AudioSystem"); Method m = clazz.getMethod("setForceUse", new Class[]{int.class, int.class}); m.invoke(null, 1, 1); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { if (mAudioManager.getMode() != AudioManager.MODE_IN_CALL) { mAudioManager.setMode(AudioManager.MODE_IN_CALL); } } if (mAudioManager.isSpeakerphoneOn()) { mAudioManager.setSpeakerphoneOn(false); mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.STREAM_VOICE_CALL); } } //扬声器播放模式 private void setModeNormal() { if (mAudioManager == null) { return; } mAudioManager.setSpeakerphoneOn(true); mAudioManager.setMode(AudioManager.MODE_NORMAL); if (!mAudioManager.isSpeakerphoneOn()) { mAudioManager.setSpeakerphoneOn(true); mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.STREAM_VOICE_CALL); } } private void unRegistListener() { if (mSensorManager != null) { mSensorManager.unregisterListener(mEventListener); } } protected abstract void initData(); protected abstract void initTopBar(); protected abstract void initListAdapter(); protected abstract void sendMessageIfNotNull(); protected abstract void sendVoiceMessage(String content); protected abstract void sendPicMessage(String content); protected abstract void sendEmail(); protected abstract void sendEnterSession(); protected abstract void sendMeeting(); protected abstract void sendVideoMessage(String content); protected abstract void sendFile(String content, String msgType); protected abstract void sendLocation(String content); protected abstract void showAtTips(MessageBean msgBean, String atMessage); protected abstract String getGetMessageListURL(MessageBean bean); protected abstract List<MessageBean> getMessageListFromLocalDB(MessageBean messageBean); @Override public void onRefresh() { if (isRefresh) return; if (!message_pool.isEmpty()) { List<MessageBean> messageBeans = getMessageListFromLocalDB(message_pool.get(0)); if ((null != messageBeans && messageBeans.size() == 20) || (null != messageBeans && messageBeans.size() < 20 && messageBeans.size() > 0 && !ActivityUtils.hasNetWorkConection(this))) { List<MessageBean> records = new ArrayList<>(); //判断本地是否存在聊天记录 //如果存在,则补全MessageBean的信息,并将其显示在当前界面 records.addAll(completeMessageBean(messageBeans)); refreshList(records); refreshUnReadCount(); } else if (ActivityUtils.hasNetWorkConection(this)) { getHistoryMsgListFromAPI(); } else { Toast.makeText(this, "没有更早的记录了", Toast.LENGTH_SHORT).show(); mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); } } else { Toast.makeText(this, "没有更早的记录了", Toast.LENGTH_SHORT).show(); mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); } } private void getHistoryMsgListFromAPI() { int index = 0; //循环获取timestamp不为空的记录。 while (index < message_pool.size()) { MessageBean bean = message_pool.get(index++); if (StringUtils.notEmpty(bean.getTimestamp())) { getMessageList(bean); return; } if (index == message_pool.size()) { mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); } } } private void getMessageList(MessageBean bean) { HttpManager.getJsonWithToken(getGetMessageListURL(bean), new StringCallback() { @Override public void onError(Call call, Exception e) { mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); } @Override public void onResponse(String response) throws JSONException { if (StringUtils.notEmpty(response)) { if (StringUtils.notEmpty(new JSONObject(response).get("objValue"))) { try { Map<String, Object> responseMap = JSONConvert.json2MessageBean(new JSONObject(response).getString("objValue"), mContext); IMDBFactory.getInstance(ChatBaseActivity.this).getRecordsManager().insertRecords((List<MessageBean>) responseMap.get("messageBean"), null); refreshList((ArrayList<MessageBean>) responseMap.get("messageBean")); refreshUnReadCount(); } catch (Exception e) { e.printStackTrace(); mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); } } } } }); } public class EnterSessionCallback extends StringCallback { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) throws JSONException { if (StringUtils.notEmpty(response) && StringUtils.notEmpty(new JSONObject(response).get("objValue"))) { try { final Map<String, Object> responsemap = JSONConvert.json2MessageBean(new JSONObject(response).getString("objValue"), mContext); final ArrayList<MessageBean> beans = (ArrayList<MessageBean>) responsemap.get("messageBean"); //保存聊天消息到db中 RecordsManager recordsManager = IMDBFactory.getInstance(mContext).getRecordsManager(); recordsManager.insertRecords(beans, new RecordsManager.RecordsCallback() { @Override public void sendBroadcast() { //向页面发送广播,通知页面刷新数据 Intent intent = new Intent(CommConstants.ACTION_SESSION_MESSAGE_LIST); intent.putExtra("sessionMessageList", beans); intent.putExtra("tipsAtMessage", responsemap.containsKey("atMessageContent") ? (String) responsemap.get("atMessageContent") : ""); intent.setPackage(mContext.getPackageName()); mContext.sendBroadcast(intent); } }); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void onLoadMore() { } protected List<MessageBean> getDBRecords() { //首次进入chat界面,先从数据库中取本地聊天记录 RecordsManager recordsManager = IMDBFactory.getInstance(this).getRecordsManager(); List<MessageBean> dbRecords = null; if (ctype == CommConstants.CHAT_TYPE_SINGLE) { dbRecords = recordsManager.getRecordsByFriendId(sessionObjId, MFSPHelper.getString(CommConstants.EMPADNAME)); } else if (ctype == CommConstants.CHAT_TYPE_GROUP) { dbRecords = recordsManager.getRecordsByRoomId(sessionObjId); } if (null != dbRecords && dbRecords.size() > 0) { //判断本地是否存在聊天记录 //如果存在,则补全MessageBean的信息,并将其显示在当前界面 message_pool.addAll(completeMessageBean(dbRecords)); } return message_pool; } // 与服务器端同步本地聊天记录状态 private void synDbRecords(JSONArray curUnSendRecords) { String url = CommConstants.URL_EOP_IM + "im/logExists"; HttpManager.postJsonWithToken(url, curUnSendRecords.toString(), new StringCallback() { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) throws JSONException { if (StringUtils.notEmpty(response) && StringUtils.notEmpty(new JSONObject(response).get("objValue"))) { //更新数据库中聊天记录状态 RecordsManager imDao = IMDBFactory.getInstance(mContext).getRecordsManager(); //记录需要修改发送状态的聊天记录 Map<String, Integer> recordsMap = new HashMap<>(); JSONArray messageBeans = new JSONObject(response).getJSONArray("objValue"); for (int i = 0; i < messageBeans.length(); i++) { JSONObject messageBean = messageBeans.getJSONObject(i); String timestamp = messageBean.getString("timestamp"); if (null != timestamp && !"".equalsIgnoreCase(timestamp)) { //更新数据库中聊天记录状态 imDao.updateRecord(timestamp, CommConstants.MSG_SEND_SUCCESS, messageBean.getString("msgId")); recordsMap.put(messageBean.getString("msgId"), CommConstants.MSG_SEND_SUCCESS); } else { //更新数据库中聊天记录状态 imDao.updateRecord(timestamp, CommConstants.MSG_SEND_FAIL, messageBean.getString("msgId")); recordsMap.put(messageBean.getString("msgId"), CommConstants.MSG_SEND_FAIL); } } //发送广播,更新当前界面ListView中聊天记录的发送状态 Intent intent = new Intent(CommConstants.MSG_UPDATE_SEND_STATUS_ACTION); SerializableObj obj = new SerializableObj(); obj.setMap(recordsMap); intent.putExtra("recordsMap", obj); mContext.sendBroadcast(intent); } } }); } @Override public void onSendMsgStart(MessageBean obj) { // 开始发送消息 刷新界面 obj.setIsSend(CommConstants.MSG_SEND_PROGRESS); message_pool.add(obj); chatAdapter.refreshChatData(message_pool); mMsgListView.setSelection(message_pool.size() - 1); boolean flag = false; for (int j = 0; j < IMConstants.contactListDatas.size(); j++) { MessageBean bean = IMConstants.contactListDatas.get(j); if (isCurrentSession(bean)) { IMConstants.contactListDatas.remove(j); IMConstants.contactListDatas.add(0, obj); flag = true; break; } } if (!flag) { IMConstants.contactListDatas.add(0, obj); } //保存聊天记录到本地数据库 recordsManager.insertRecord(obj, RecordsManager.MESSAGE_TYPE_SEND, new RecordsManager.RecordsCallback() { @Override public void sendBroadcast() { } }); } @Override public void onSendMsgProcess(int fileSize, int uploadSize) { LogUtils.v("onSendMsgProcess", fileSize + "---" + uploadSize); } @Override public void onSendMsgDone(int responseCode, String message, MessageBean messageDataObj) { //消息发送完,将本次@XX置为空 if (messageDataObj.getMtype().equals(CommConstants.MSG_TYPE_TEXT)) { IMConstants.atMembers.clear(); } if (responseCode == CommConstants.MSG_SEND_SUCCESS && !"".equals(message)) { if (!messageDataObj.getMtype().equals(CommConstants.MSG_TYPE_FILE_1) && !messageDataObj.getMtype().equals(CommConstants.MSG_TYPE_FILE_2)) { File file = new File(message); if (file.exists()) { file.delete(); } } } Message msg = Message.obtain(); msg.what = responseCode; msg.obj = messageDataObj; handler.sendMessage(msg); } protected void refreshUnReadCount() { for (int i = 0; i < IMConstants.contactListDatas.size(); i++) { MessageBean bean = IMConstants.contactListDatas.get(i); if (bean.getCtype() == ctype) { if ((bean.getCtype() == CommConstants.CHAT_TYPE_GROUP && sessionObjId.equalsIgnoreCase(bean.getRoomId())) || (bean.getCtype() == CommConstants.CHAT_TYPE_SINGLE && bean.getFriendId().equalsIgnoreCase(sessionObjId))) { bean.setIsread(CommConstants.MSG_READ); bean.setUnReadCount(0); } } } } private boolean isCurrentSession(MessageBean msgBean) { if (msgBean.getCtype() == ctype) { if (msgBean.getCtype() == CommConstants.CHAT_TYPE_GROUP) { return msgBean.getRoomId().equalsIgnoreCase(sessionObjId); } else if (msgBean.getCtype() == CommConstants.CHAT_TYPE_SINGLE) { return msgBean.getFriendId().equalsIgnoreCase(sessionObjId); } else { return false; } } else { return false; } } //刷新列表 protected void refreshList(List<MessageBean> pullList) { if (pullList != null && !pullList.isEmpty()) { message_pool.addAll(0, pullList); if (!isRefresh) { for (int i = 0; i < IMConstants.failedMsgList.size(); i++) { if (isCurrentSession(IMConstants.failedMsgList.get(i))) { message_pool.add(IMConstants.failedMsgList.get(i)); } } } isRefresh = false; mMsgListView.setEnabled(false); chatAdapter.refreshChatData(message_pool); mMsgListView.setSelection(pullList.size()); mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); handler.postDelayed(new Runnable() { @Override public void run() { mMsgListView.setEnabled(true); } }, 500); } else { ToastUtils.showToast(this, getResources().getString(R.string.pull_to_refresh_footer_nomore)); isRefresh = false; mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); } } protected List<MessageBean> completeMessageBean(List<MessageBean> dbRecords) { //判断本地是否存在聊天记录 if (null != dbRecords && dbRecords.size() > 0) { //如果存在,则补全MessageBean的信息,并将其显示在当前界面 List<MessageBean> records = new ArrayList<>(); //清空unSend数据 curUnSendRecords = new JSONArray(); for (int i = 0; i < dbRecords.size(); i++) { try { MessageBean record = JSONConvert.getMessageBean(dbRecords.get(i)); record.setRoomId(sessionObjId); Group group = IMConstants.groupsMap.get(sessionObjId); record.setSubject(null != group ? group.getDisplayName() : ""); if (hasNewMes && record.isATMessage()) { showAtTips(record, ""); hasNewMes = false; } //记录状态为发送中的聊天记录 if (CommConstants.MSG_SEND_PROGRESS == record.getIsSend()) { /** * 当消息发送中,被中断,再进入聊天页面就需要重新请求查看消息是否发送成功,来更新状态 * 当发送文件时,首先发送给cms,还没上传成功就退出页面,此时就不需要去检查状态了。 */ JSONObject msgObj = new JSONObject(); msgObj.put("msgId", record.getMsgId()); msgObj.put("chatType", record.getCtype()); curUnSendRecords.put(msgObj); } records.add(i, record); } catch (Exception e) { e.printStackTrace(); } } if (curUnSendRecords.length() > 0) { // 与服务器端同步本地聊天记录状态 synDbRecords(curUnSendRecords); } return records; } return null; } private void initView() { mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); mWindowNanagerParams = getWindow().getAttributes(); mTopTitle = (TextView) findViewById(R.id.common_top_title); mTopLeftImage = (ImageView) findViewById(R.id.common_top_img_left); mTopRightImage = (ImageView) findViewById(R.id.common_top_img_right); mMsgListView = (XListView) findViewById(R.id.msg_listView); tv_tips = (TextView) findViewById(R.id.tv_tips); mVoiceBtn = (Button) findViewById(R.id.chat_voice); mFaceSwitchBtn = (Button) findViewById(R.id.chat_face); mAddMoreBtn = (Button) findViewById(R.id.chat_addmore); mSendMsgBtn = (Button) findViewById(R.id.chat_send); mChatEditText = (CurEditText) findViewById(R.id.chat_inputtext); mVoiceSpeakBtn = (Button) findViewById(R.id.chat_voice_speak_btn); chat_voice_popup = findViewById(R.id.chat_voice_popup); voice_rcd_hint_rcding = (LinearLayout) findViewById(R.id.voice_rcd_hint_rcding); voice_rcd_hint_cancle = (LinearLayout) findViewById(R.id.voice_rcd_hint_cancle); voice_rcd_hint_tooshort = (LinearLayout) findViewById(R.id.voice_rcd_hint_tooshort); volume = (ImageView) this.findViewById(R.id.volume); scImage = (ImageView) findViewById(R.id.sc_img1); mFaceRoot = (LinearLayout) findViewById(R.id.face_ll); mMenuRoot = (LinearLayout) findViewById(R.id.menu_ll); mMenuViewPager = (ViewPager) findViewById(R.id.menu_pager); // 触摸ListView隐藏表情和输入法 mMsgListView.setOnTouchListener(this); mMsgListView.setPullLoadEnable(false); mMsgListView.setXListViewListener(this); mChatEditText.setOnTouchListener(this); mVoiceBtn.setOnClickListener(this); mFaceSwitchBtn.setOnClickListener(this); mAddMoreBtn.setOnClickListener(this); mSendMsgBtn.setOnClickListener(this); mVoiceSpeakBtn.setOnTouchListener(this); mTopLeftImage.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); mChatEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (mWindowNanagerParams.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE || mIsFaceShow) { mFaceRoot.setVisibility(View.GONE); mMenuRoot.setVisibility(View.GONE); mIsFaceShow = false; mIsMenuShow = false; return true; } } return false; } }); mChatEditText.addTextChangedListener(new TextChangedListener(this)); } protected void isShowAtTips(boolean isShowTips, final String tipsText) { if (isShowTips && tv_tips.getVisibility() != View.VISIBLE) { tv_tips.setVisibility(View.VISIBLE); tv_tips.setText(tipsText); handler.postDelayed(new Runnable() { @Override public void run() { tv_tips.setVisibility(View.GONE); } }, 3 * 1000); } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.chat_voice) { if (mIsFaceShow) { // 隐藏表情 mIsFaceShow = false; mFaceRoot.setVisibility(View.GONE); mFaceSwitchBtn.setBackgroundResource(R.drawable.chat_emotion_selector); } if (mIsMenuShow) { // 隐藏菜单 mIsMenuShow = false; mMenuRoot.setVisibility(View.GONE); mAddMoreBtn.setBackgroundResource(R.drawable.chat_addmore_selector); } if (!mIsVoiceShow) { // 隐藏键盘,显示语音输入 mVoiceBtn.setBackgroundResource(R.drawable.chat_keyboard_selector); mChatEditText.setVisibility(View.GONE); mVoiceSpeakBtn.setVisibility(View.VISIBLE); mInputMethodManager.hideSoftInputFromWindow( mChatEditText.getWindowToken(), 0); mIsVoiceShow = true; } else { mVoiceBtn.setBackgroundResource(R.drawable.chat_voice_selector); mChatEditText.setVisibility(View.VISIBLE); mVoiceSpeakBtn.setVisibility(View.GONE); mChatEditText.requestFocus(); mInputMethodManager.showSoftInput(mChatEditText, 0); mIsVoiceShow = false; } mMsgListView.setSelection(mMsgListView.getBottom()); } else if (id == R.id.chat_face) { if (mIsVoiceShow) { mIsVoiceShow = false; mVoiceBtn.setBackgroundResource(R.drawable.chat_voice_selector); mChatEditText.setVisibility(View.VISIBLE); mVoiceSpeakBtn.setVisibility(View.GONE); } if (mIsMenuShow) { // 隐藏菜单 mIsMenuShow = false; mMenuRoot.setVisibility(View.GONE); mAddMoreBtn .setBackgroundResource(R.drawable.chat_addmore_selector); } if (!mIsFaceShow) { handler.postDelayed(new Runnable() { // 解决此时界面会变形,有闪烁的现象 @Override public void run() { mFaceSwitchBtn .setBackgroundResource(R.drawable.chat_keyboard_selector); mFaceRoot.setVisibility(View.VISIBLE); mIsFaceShow = true; mChatEditText.requestFocus(); } }, 80); mInputMethodManager.hideSoftInputFromWindow( mChatEditText.getWindowToken(), 0); } else { mFaceRoot.setVisibility(View.GONE); mChatEditText.requestFocus(); mInputMethodManager.showSoftInput(mChatEditText, 0); mFaceSwitchBtn .setBackgroundResource(R.drawable.chat_emotion_selector); mIsFaceShow = false; } mMsgListView.setSelection(mMsgListView.getBottom()); } else if (id == R.id.chat_addmore) { if (mIsVoiceShow) { mIsVoiceShow = false; mVoiceBtn.setBackgroundResource(R.drawable.chat_voice_selector); mChatEditText.setVisibility(View.VISIBLE); mVoiceSpeakBtn.setVisibility(View.GONE); } if (mIsFaceShow) { // 隐藏表情 mIsFaceShow = false; mFaceRoot.setVisibility(View.GONE); mFaceSwitchBtn .setBackgroundResource(R.drawable.chat_emotion_selector); } if (!mIsMenuShow) { handler.postDelayed(new Runnable() { // 解决此时界面会变形,有闪烁的现象 @Override public void run() { mAddMoreBtn .setBackgroundResource(R.drawable.chat_keyboard_selector); mMenuRoot.setVisibility(View.VISIBLE); mIsMenuShow = true; mChatEditText.requestFocus(); } }, 80); mInputMethodManager.hideSoftInputFromWindow( mChatEditText.getWindowToken(), 0); } else { mMenuRoot.setVisibility(View.GONE); mChatEditText.requestFocus(); mInputMethodManager.showSoftInput(mChatEditText, 0); mAddMoreBtn .setBackgroundResource(R.drawable.chat_addmore_selector); mIsMenuShow = false; } mMsgListView.setSelection(mMsgListView.getBottom()); } else if (id == R.id.chat_send) { sendMessageIfNotNull(); } else { } } private void start(String nameraw, String namemp3) { if (_2Mp3util == null) { _2Mp3util = new Audio2Mp3Utils(null, nameraw, namemp3); } boolean result = _2Mp3util.startRecording(); if (result) { handler.postDelayed(mPollTask, POLL_INTERVAL); } } private void stop(boolean cleanMp3) { handler.removeCallbacks(mSleepTask); handler.removeCallbacks(mPollTask); boolean result = _2Mp3util.stopRecordingAndConvertFile(); if (result) { // 获得生成的文件路径 voiceFileNameRaw = _2Mp3util.getFilePath(Audio2Mp3Utils.RAW); voiceFileNameMp3 = _2Mp3util.getFilePath(Audio2Mp3Utils.MP3); // 清理掉源文件 _2Mp3util.cleanFile(Audio2Mp3Utils.RAW); if (cleanMp3) { _2Mp3util.cleanFile(Audio2Mp3Utils.MP3); } } _2Mp3util.close(); volume.setImageResource(R.drawable.amp1); _2Mp3util = null; } private static final int POLL_INTERVAL = 300; private Runnable mSleepTask = new Runnable() { public void run() { stop(false); } }; private Runnable mPollTask = new Runnable() { public void run() { int amp = _2Mp3util.getAmplitude(); updateDisplay(amp); handler.postDelayed(mPollTask, POLL_INTERVAL); } }; private void updateDisplay(int signalEMA) { if (signalEMA >= 0 && signalEMA < 30) { volume.setImageResource(R.drawable.amp1); } else if (signalEMA >= 30 && signalEMA < 60) { volume.setImageResource(R.drawable.amp2); } else if (signalEMA >= 60 && signalEMA < 100) { volume.setImageResource(R.drawable.amp3); } else if (signalEMA >= 100 && signalEMA < 150) { volume.setImageResource(R.drawable.amp4); } else if (signalEMA >= 150 && signalEMA < 200) { volume.setImageResource(R.drawable.amp5); } else if (signalEMA >= 200 && signalEMA < 270) { volume.setImageResource(R.drawable.amp6); } else if (signalEMA >= 270) { volume.setImageResource(R.drawable.amp7); } } @Override public boolean onTouch(View v, MotionEvent event) { int id = v.getId(); if (id == R.id.msg_listView) { mInputMethodManager.hideSoftInputFromWindow( mChatEditText.getWindowToken(), 0); mFaceSwitchBtn .setBackgroundResource(R.drawable.chat_emotion_selector); mFaceRoot.setVisibility(View.GONE); mIsFaceShow = false; mAddMoreBtn.setBackgroundResource(R.drawable.chat_addmore_selector); mMenuRoot.setVisibility(View.GONE); mIsMenuShow = false; } else if (id == R.id.chat_inputtext) { mInputMethodManager.showSoftInput(mChatEditText, 0); mFaceSwitchBtn .setBackgroundResource(R.drawable.chat_emotion_selector); mFaceRoot.setVisibility(View.GONE); mIsFaceShow = false; mAddMoreBtn.setBackgroundResource(R.drawable.chat_addmore_selector); mMenuRoot.setVisibility(View.GONE); mIsMenuShow = false; mMsgListView.setSelection(message_pool.size() - 1); } // 按下语音录制按钮时返回false执行父类OnTouch if (mIsVoiceShow) { int[] location = new int[2]; mVoiceSpeakBtn.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标 int btn_rc_Y = location[1]; int btn_rc_X = location[0]; int[] del_location = new int[2]; voice_rcd_hint_cancle.getLocationInWindow(del_location); int del_Y = del_location[1]; int del_x = del_location[0]; if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) { if (event.getRawY() > btn_rc_Y && event.getRawX() > btn_rc_X) { // 判断手势按下的位置是否是语音录制按钮的范围内 // 如果当前正在播放语音,则停止 chatAdapter.stopVoice(); mVoiceSpeakBtn.setText("松开 发送"); chat_voice_popup.setVisibility(View.VISIBLE); voice_rcd_hint_rcding.setVisibility(View.VISIBLE); voice_rcd_hint_cancle.setVisibility(View.GONE); voice_rcd_hint_tooshort.setVisibility(View.GONE); startVoiceT = System.currentTimeMillis(); File cacheDir = FileUtils.getInstance().getCacheFileDir(); String str = DateUtils.date2Str(new Date(startVoiceT), "yyyyMMddHHmmss"); voiceFileNameRaw = cacheDir.getAbsolutePath() + File.separator + str + ".raw"; voiceFileNameMp3 = cacheDir.getAbsolutePath() + File.separator + str + ".mp3"; start(voiceFileNameRaw, voiceFileNameMp3); flag = 2; } } else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {// 松开手势时执行录制完成 mVoiceSpeakBtn.setText(getString(R.string.clicked_speak)); if (event.getRawY() < btn_rc_Y) { // 在取消发送中 抬起,就取消发送 chat_voice_popup.setVisibility(View.GONE); stop(true); flag = 1; } else { endVoiceT = System.currentTimeMillis(); flag = 1; int time = (int) ((endVoiceT - startVoiceT) / 1000);// 秒 if (time < 1) { stop(true); // 说话时间太短 voice_rcd_hint_rcding.setVisibility(View.GONE); voice_rcd_hint_cancle.setVisibility(View.GONE); voice_rcd_hint_tooshort.setVisibility(View.VISIBLE); handler.postDelayed(new Runnable() { public void run() { voice_rcd_hint_tooshort .setVisibility(View.GONE); chat_voice_popup.setVisibility(View.GONE); } }, 500); return false; } stop(false); // 发送消息 voice_rcd_hint_rcding.setVisibility(View.GONE); chat_voice_popup.setVisibility(View.GONE); JSONObject localVoiceJson = new JSONObject(); try { localVoiceJson.put("url", voiceFileNameMp3); localVoiceJson.put("timeLength", time + ""); } catch (JSONException e) { e.printStackTrace(); } sendVoiceMessage(localVoiceJson.toString()); } } if (event.getRawY() < btn_rc_Y) {// 手势按下的位置不在语音录制按钮的范围内 // 显示 取消发送 Animation mLitteAnimation = AnimationUtils.loadAnimation(this, R.anim.cancel_rc); Animation mBigAnimation = AnimationUtils.loadAnimation(this, R.anim.cancel_rc2); voice_rcd_hint_rcding.setVisibility(View.GONE); voice_rcd_hint_cancle.setVisibility(View.VISIBLE); if (event.getRawY() >= del_Y && event.getRawY() <= del_Y + voice_rcd_hint_cancle.getHeight() && event.getRawX() >= del_x && event.getRawX() <= del_x + voice_rcd_hint_cancle.getWidth()) { scImage.startAnimation(mLitteAnimation); scImage.startAnimation(mBigAnimation); } } else { voice_rcd_hint_rcding.setVisibility(View.VISIBLE); voice_rcd_hint_cancle.setVisibility(View.GONE); } } return false; } private void initFacePage() { mfaceViewPage = new FaceViewPage(mChatEditText, mFaceRoot); mfaceViewPage.initFacePage(); } private void initMenuPage() { List<View> lv = new ArrayList<>(); int count = getMenuGridView(lv); FacePageAdeapter adapter = new FacePageAdeapter(lv); mMenuViewPager.setAdapter(adapter); mMenuViewPager.setCurrentItem(0); if (count > 0) { CirclePageIndicator indicator = (CirclePageIndicator) mMenuRoot .findViewById(R.id.menu_indicator); indicator.setViewPager(mMenuViewPager); indicator.setVisibility(View.VISIBLE); } adapter.notifyDataSetChanged(); mMenuRoot.setVisibility(View.GONE); } private int getMenuGridView(List<View> lv) { boolean meeting = false; boolean recordVideo = false; try { meeting = getPackageManager().getApplicationInfo( getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean( "CHANNEL_MEETING", false); recordVideo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean("CHANNEL_VIDEO", false); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } List<Integer> imgIds = new ArrayList<Integer>(); List<String> titles = new ArrayList<String>(); imgIds.add(R.drawable.chat_menu_pic); titles.add(getResources().getString(R.string.chat_menu_pic)); imgIds.add(R.drawable.chat_menu_camera); titles.add(getResources().getString(R.string.chat_menu_camera)); if (recordVideo) { imgIds.add(R.drawable.chat_menu_vedio); titles.add(getString(R.string.chat_menu_vedio)); } imgIds.add(R.drawable.ico_mail); titles.add(getResources().getString(R.string.chat_menu_mail)); imgIds.add(R.drawable.icon_file); titles.add(getResources().getString(R.string.chat_menu_file)); if (meeting) { imgIds.add(R.drawable.icon_meeting_msg); titles.add(getResources().getString(R.string.chat_menu_metting)); } imgIds.add(R.drawable.icon_map); titles.add(getResources().getString(R.string.chat_menu_send_location)); int count; if (titles.size() <= 4) { count = 0; } else { count = titles.size() / 4; } for (int i = 0; i <= count; i++) { int end = (i + 1) * 4; if (end > titles.size()) { end = titles.size(); } List<Integer> imgIdList = imgIds.subList(i * 4, end); final List<String> titlesList = titles.subList(i * 4, end); GridView gv = new GridView(this); gv.setNumColumns(4); gv.setSelector(new ColorDrawable(Color.TRANSPARENT)); // 屏蔽GridView默认点击效果 gv.setBackgroundColor(Color.TRANSPARENT); gv.setCacheColorHint(Color.TRANSPARENT); gv.setHorizontalSpacing(0); gv.setVerticalSpacing(0); gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); gv.setGravity(Gravity.CENTER | Gravity.BOTTOM); gv.setAdapter(new MenuAdapter(this, imgIdList, titlesList)); gv.setOnTouchListener(forbidenScroll()); gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String txt = titlesList.get(position); if (txt.equals(getResources().getString(R.string.chat_menu_pic))) {// pic Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, REQUEST_CODE_SEND_PIC_ALBUM); } else if (txt.equals(getResources().getString(R.string.chat_menu_camera))) {// camera currentTime = DateUtils.date2Str(new Date(), "yyyyMMddHHmmss"); imageUri = Uri.parse(CommConstants.IMAGE_FILE_LOCATION); // 跳转相机拍照 String sdStatus = Environment.getExternalStorageState(); if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(ChatBaseActivity.this, getString(R.string.can_not_find_sd), Toast.LENGTH_SHORT) .show(); return; } Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent2.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent2, REQUEST_CODE_SEND_PIC_CAMERA); } else if (txt.equals(getResources().getString(R.string.chat_menu_mail))) {// mail if (CommConstants.CHAT_TYPE_GROUP_ANS == groupType) { ToastUtils.showToast(ChatBaseActivity.this, getString(R.string.can_not_send_email)); } else { sendEmail(); } } else if (txt.equals(getResources().getString(R.string.chat_menu_file))) {// send file showPop(); } else if (txt.equals(getResources().getString(R.string.chat_menu_vedio))) {// recorder video Intent intent3 = new Intent(); intent3.setClass(ChatBaseActivity.this, FFmpegRecorderActivity.class); startActivityForResult(intent3, REQUEST_CODE_SEND_VIDEO); } else if (txt.equals(getResources().getString(R.string.chat_menu_metting))) {// metting sendMeeting(); } else if (txt.equals(getResources().getString(R.string.chat_menu_send_location))) {// location Intent intent = new Intent(); intent.setClass(ChatBaseActivity.this, MapViewActivity.class); startActivityForResult(intent, REQUEST_CODE_LOCATION); } } }); lv.add(gv); } return count; } // 防止乱pageview乱滚动 private OnTouchListener forbidenScroll() { return new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE) { return true; } return false; } }; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //返回聊天窗口页面,默认隐藏输入框 mMenuRoot.setVisibility(View.GONE); mIsMenuShow = false; try { if (resultCode == RESULT_OK) { switch (requestCode) { case REQUEST_CODE_VIEWPAGER_PAGE: isRoll = true; mMsgListView.smoothScrollToPosition(data.getIntExtra("BACK_FROM_PAGER",mMsgListView.getCount()-1)); break; case REQUEST_CODE_CHAT_DETAIL_PAGE: finish(); break; // 如果是直接从相册获取 case REQUEST_CODE_SEND_PIC_ALBUM: // 从相册中直接获取文件的真实路径,然后上传 // final String picPath = PicUtils.getPicturePath(data,ChatBaseActivity.this); final String picPath = FileUtils.getPath(ChatBaseActivity.this, data.getData()); startActivityForResult(new Intent(ChatBaseActivity.this, SelectedImageActivity.class).putExtra( "takePicturePath", picPath), REQUEST_CODE_SELECTED_PIC); break; case REQUEST_CODE_SELECTED_PIC: sendPicMessage(data.getStringExtra("takePicturePath")); break; // 如果是调用相机拍照时 case REQUEST_CODE_SEND_PIC_CAMERA: if (imageUri != null) { boolean copy = FileUtils.copyFile(CommConstants.SD_CARD + "/temp.jpg", CommConstants.SD_CARD_IMPICTURES + currentTime + ".jpg"); new File(CommConstants.SD_CARD + "/temp.jpg").delete(); if (copy) { String pathString = CommConstants.SD_CARD_IMPICTURES + currentTime + ".jpg"; PicUtils.scanImages(ChatBaseActivity.this, pathString); String takePicturePath = ""; try { takePicturePath = PicUtils .getSmallImageFromFileAndRotaing(pathString); } catch (Exception e1) { e1.printStackTrace(); } JSONObject localPicJson2 = new JSONObject(); try { localPicJson2.put("url", takePicturePath); localPicJson2.put("size", PicUtils.getPicSizeJson(pathString)); } catch (JSONException e) { e.printStackTrace(); } sendPicMessage(localPicJson2.toString()); } } break; case REQUEST_CODE_SEND_VIDEO: //发送视频 String videoPath = data.getStringExtra("videoPath"); String imagePath = data.getStringExtra("firstImagePath"); if (FFmpegRecorderActivity.useVideo && StringUtils.notEmpty(imagePath) && StringUtils.notEmpty(videoPath)) { FFmpegRecorderActivity.useVideo = false; List<String> filePaths = new ArrayList<>(); filePaths.add(imagePath); filePaths.add(videoPath); HttpManager.multiFileUpload(CommConstants.URL_UPLOAD, filePaths, "fn", new MyListCallback()); } break; case REQUEST_CODE_SEND_FILE: //发送文件 Uri uri = data.getData(); String filePath = FileUtils.getPath(ChatBaseActivity.this, uri); JSONObject localPicJson2 = new JSONObject(); try { File f = new File(filePath); long size = f.length(); if (size > 1024 * 1024 * 20) { ToastUtils.showToast(getApplicationContext(), getString(R.string.can_not_more_than_20m)); return; } int index = filePath.lastIndexOf("."); if (index >= 0) { /* 取得扩展名 */ String fileSuffix = filePath.substring(index, filePath.length()).toLowerCase(); if (fileSuffix.contains("jpg") || fileSuffix.contains("jpeg") || fileSuffix.contains("png") || fileSuffix.contains("gif")) { if (size > 1024 * 1024 * 4) { ToastUtils.showToast(getApplicationContext(), getString(R.string.can_not_more_than_4m)); return; } } } localPicJson2.put("url", filePath); localPicJson2.put("fileSize", size); localPicJson2.put("name", filePath.substring(filePath.lastIndexOf("/") + 1)); } catch (JSONException e) { e.printStackTrace(); } sendFile(localPicJson2.toString(), CommConstants.MSG_TYPE_FILE_1); break; case REQUEST_CODE_SEND_FILE_2: String uuid = data.getStringExtra("uuid"); double size = data.getDoubleExtra("fileSize", 0d); String name = data.getStringExtra("name"); String serverPath = data.getStringExtra("serverPath"); JSONObject localPicJson3 = new JSONObject(); try { localPicJson3.put("uuid", uuid); localPicJson3.put("fileSize", size); localPicJson3.put("name", name); localPicJson3.put("serverPath", serverPath); UserInfo userInfo = CommConstants.loginConfig.getmUserInfo(); String credential = Base64Utils.getBase64(MFSPHelper.getString(CommConstants.USERID) + ":" + userInfo.getEmpAdname()); localPicJson3.put("token", credential); } catch (JSONException e) { e.printStackTrace(); } sendFile(localPicJson3.toString(), CommConstants.MSG_TYPE_FILE_2); break; case REQUEST_CODE_LOCATION://发送位置 String filePath1 = data.getStringExtra("filePath"); String addStr = data.getStringExtra("addStr"); double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); JSONObject localPicJson4 = new JSONObject(); try { localPicJson4.put("url", filePath1); localPicJson4.put("name", addStr); localPicJson4.put("latitude", latitude); localPicJson4.put("longitude", longitude); } catch (JSONException e) { e.printStackTrace(); } sendLocation(localPicJson4.toString()); break; default: break; } }else if (resultCode == 1) { switch (requestCode) { case REQUEST_CODE_SHARE_FILE://share file if (data != null) { UserInfo userInfo = (UserInfo) data.getSerializableExtra("atUserInfos"); if (null != userInfo) { this.finish(); Intent intent = new Intent(ChatBaseActivity.this, ChatActivity.class); intent.putExtra("userInfo", userInfo); intent.putExtra("messageBean", message); startActivity(intent); } } break; case IMConstants.REQUEST_CODE_RESEND_MES: if (data != null) { UserInfo userInfo = (UserInfo) data.getSerializableExtra("atUserInfos"); if (null != userInfo) { this.finish(); Intent intent = new Intent(ChatBaseActivity.this, ChatActivity.class); intent.putExtra("userInfo", userInfo); intent.putExtra("messageBean", message); startActivity(intent); } } break; default: break; } } } catch (Exception e) { e.printStackTrace(); } } class MyListCallback extends StringCallback { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) throws JSONException { if (StringUtils.notEmpty(response)) { JSONArray obj = new JSONObject(response).getJSONObject("response").getJSONArray("message"); JSONObject contentObj = new JSONObject(); for (int i = 0; i < obj.length(); i++) { //获取到服务器端返回的mp4文件地址 if (VIDEO_FILE_EXTENSION.equalsIgnoreCase(obj.getJSONObject(i).getString("suffix"))) { contentObj.put("url", obj.getJSONObject(i).getString("uname")); } else { contentObj.put("imageUrl", obj.getJSONObject(i).getString("uname")); } } //发送video msg sendVideoMessage(contentObj.toString()); } } } @Override public void onAvatarClickListener(MessageBean message, int type) { if (!CommConstants.GROUP_ADMIN.equalsIgnoreCase(message.getFriendId()) && !message.isFromWechatUser()) { // 跳转详情 if (type == CommConstants.MSG_RECEIVE) { // 跳转他人详情 Intent intent = new Intent(); intent.putExtra("userInfo", message.getUserInfo()); ((BaseApplication) this.getApplication()).getUIController().onOwnHeadClickListener(this, intent, 0); } else { // 跳转自己 String userid = MFSPHelper.getString(CommConstants.USERID); UserDao dao = UserDao.getInstance(this); UserInfo me = dao.getUserInfoById(userid); Intent intent = new Intent(); intent.putExtra("userInfo", me); ((BaseApplication) this.getApplication()).getUIController().onOwnHeadClickListener(this, intent, 0); } } } @Override public void onClickedListener(String curText) { if (curText.length() > 0) { mSendMsgBtn.setVisibility(View.VISIBLE); mSendMsgBtn.setEnabled(true); mAddMoreBtn.setVisibility(View.GONE); } else { mSendMsgBtn.setEnabled(false); mSendMsgBtn.setVisibility(View.INVISIBLE); mAddMoreBtn.setVisibility(View.VISIBLE); } } private void showPop() { // 加载popupWindow的布局文件 View contentView = LayoutInflater.from(this).inflate( R.layout.layout_file_chose, null); GridView gv = (GridView) contentView.findViewById(R.id.gv_file); List<Integer> imgIds = new ArrayList<Integer>(); List<String> titles = new ArrayList<String>(); imgIds.add(R.drawable.icon_mobile_file); imgIds.add(R.drawable.icon_wendang); titles.add(getResources().getString(R.string.chat_menu_moblie_file)); titles.add(getResources().getString(R.string.chat_menu_document)); gv.setAdapter(new MenuAdapter(this, imgIds, titles)); gv.setOnTouchListener(forbidenScroll()); final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true); // 为弹出框设定自定义的布局 popupWindow.setContentView(contentView); // 设置点击其他地方 popupWindow消失 popupWindow.setOutsideTouchable(true); /* * 必须设置背景 响应返回键必须的语句。设置 BackgroundDrawable 并不会改变你在配置文件中设置的背景颜色或图像 ,未知原因 */ popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.showAtLocation(mMsgListView, Gravity.CENTER, 0, 0); // 点击自身popupWindow消失 contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0://本地文件 // 打开系统文件浏览功能 Intent intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, REQUEST_CODE_SEND_FILE); break; case 1://文档管理文件 Intent intent2 = new Intent(ChatBaseActivity.this, SkyDriveActivity.class); intent2.putExtra("chat", "chat"); startActivityForResult(intent2, REQUEST_CODE_SEND_FILE_2); break; default: break; } popupWindow.dismiss(); } }); } class CompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // get complete download id long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); String msgId = ChatBaseActivity.downloadMap.get(completeDownloadId); if (ChatBaseActivity.msgIdMap.containsKey(msgId)) { ChatBaseActivity.msgIdMap.remove(msgId); } ChatBaseActivity.downloadMap.remove(completeDownloadId); chatAdapter.notifyDataSetChanged(); } } @Override public void setRedPoint(int point) { } @Override public void updateRecordList(Map<String, Integer> recordMap) { //刷新listview chatAdapter.setRecordMap(recordMap); chatAdapter.refreshChatData(message_pool); } @Override public void receiveNewMessage(MessageBean messageBean) { if ((messageBean.getCtype() == CommConstants.CHAT_TYPE_GROUP && sessionObjId.equalsIgnoreCase(messageBean.getRoomId())) || (messageBean.getCtype() == CommConstants.CHAT_TYPE_SINGLE && messageBean.getFriendId().equalsIgnoreCase(sessionObjId))) { messageBean.setIsread(CommConstants.MSG_READ); message_pool.add(messageBean); chatAdapter.refreshChatData(message_pool); mMsgListView.setSelection(message_pool.size() - 1); showAtTips(messageBean, ""); refreshUnReadCount(); IMDBFactory.getInstance(this).getRecordsManager().updateMsgInsertFlag(messageBean.getMsgId(), 1); } } @Override public void receiveSessionList(List<MessageBean> messageBeans, String atMessage) { showAtTips(null, atMessage); //messageBeans 不为空,说明有新消息返回 if (!messageBeans.isEmpty()) { //警告:又一个坑 //如果enterSession时,增加参数endTime,则去掉message_pool.clear();这一句 message_pool.clear(); message_pool = getDBRecords(); mMsgListView.setEnabled(false); chatAdapter.refreshChatData(message_pool); if(!isRoll){ mMsgListView.setSelection(message_pool.size() - 1); } mMsgListView.stopRefresh(); mMsgListView.setRefreshTime(DateUtils.date2Str(new Date())); handler.postDelayed(new Runnable() { @Override public void run() { mMsgListView.setEnabled(true); } }, 500); } } }
[ "louanna.lu@movit-tech.com" ]
louanna.lu@movit-tech.com
e9d7abd01908b7b34ccc3ba60f6d81a97953422d
c0c8e2b81bae6f92cd26e061e757e2baa76d4bc2
/branch_george/splashScreen/lib/andengine/org/anddev/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java
9befd2827be51901ffee354132246124fd421379
[]
no_license
Fritzendugan/rocket-science
87f22dbcf1fc91718284dd5087c6c0ae67bf56eb
82145989130b01bbd694538e902723b17a409c0c
refs/heads/master
2020-12-25T18:20:12.701833
2011-05-06T21:03:34
2011-05-06T21:03:34
32,224,164
0
0
null
null
null
null
UTF-8
Java
false
false
4,232
java
package org.anddev.andengine.entity.scene.menu.animator; import java.util.ArrayList; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.shape.modifier.AlphaModifier; import org.anddev.andengine.entity.shape.modifier.ease.IEaseFunction; import org.anddev.andengine.util.HorizontalAlign; /** * @author Nicolas Gramlich * @since 11:04:35 - 02.04.2010 */ public class AlphaMenuAnimator extends BaseMenuAnimator { // =========================================================== // Constants // =========================================================== private static final float ALPHA_FROM = 0.0f; private static final float ALPHA_TO = 1.0f; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public AlphaMenuAnimator(){ super(); } public AlphaMenuAnimator(final IEaseFunction pEaseFunction) { super(pEaseFunction); } public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign) { super(pHorizontalAlign); } public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign, final IEaseFunction pEaseFunction) { super(pHorizontalAlign, pEaseFunction); } public AlphaMenuAnimator(final float pMenuItemSpacing) { super(pMenuItemSpacing); } public AlphaMenuAnimator(final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { super(pMenuItemSpacing, pEaseFunction); } public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing) { super(pHorizontalAlign, pMenuItemSpacing); } public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { super(pHorizontalAlign, pMenuItemSpacing, pEaseFunction); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public void buildAnimations(final ArrayList<IMenuItem> pMenuItems, final float pCameraWidth, final float pCameraHeight) { final IEaseFunction easeFunction = this.mEaseFunction; final int menuItemCount = pMenuItems.size(); for(int i = menuItemCount - 1; i >= 0; i--) { final AlphaModifier alphaModifier = new AlphaModifier(DURATION, ALPHA_FROM, ALPHA_TO, easeFunction); alphaModifier.setRemoveWhenFinished(false); pMenuItems.get(i).addShapeModifier(alphaModifier); } } public void prepareAnimations(final ArrayList<IMenuItem> pMenuItems, final float pCameraWidth, final float pCameraHeight) { final float maximumWidth = this.getMaximumWidth(pMenuItems); final float overallHeight = this.getOverallHeight(pMenuItems); final float baseX = (pCameraWidth - maximumWidth) * 0.5f; final float baseY = (pCameraHeight - overallHeight) * 0.5f; final float menuItemSpacing = this.mMenuItemSpacing; float offsetY = 0; final int menuItemCount = pMenuItems.size(); for(int i = 0; i < menuItemCount; i++) { final IMenuItem menuItem = pMenuItems.get(i); final float offsetX; switch(this.mHorizontalAlign) { case LEFT: offsetX = 0; break; case RIGHT: offsetX = maximumWidth - menuItem.getWidthScaled(); break; case CENTER: default: offsetX = (maximumWidth - menuItem.getWidthScaled()) * 0.5f; break; } menuItem.setPosition(baseX + offsetX , baseY + offsetY); menuItem.setAlpha(ALPHA_FROM); offsetY += menuItem.getHeight() + menuItemSpacing; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
[ "george.shirkiv@gmail.com@5b162289-0c3d-0828-5410-29faef4b17c3" ]
george.shirkiv@gmail.com@5b162289-0c3d-0828-5410-29faef4b17c3
59c0a95f4efec493b119f8fd010b16c2ab159c0d
a7b868c8c81984dbcb17c1acc09c0f0ab8e36c59
/src/main/java/com/alipay/api/domain/AlipayEcoEduJzApplyresultSyncModel.java
245e7ca3341687337297137e717a33d7b20b6776
[ "Apache-2.0" ]
permissive
1755616537/alipay-sdk-java-all
a7ebd46213f22b866fa3ab20c738335fc42c4043
3ff52e7212c762f030302493aadf859a78e3ebf7
refs/heads/master
2023-02-26T01:46:16.159565
2021-02-02T01:54:36
2021-02-02T01:54:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,200
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 兼职平台报名同步接口 * * @author auto create * @since 1.0, 2016-09-08 16:00:33 */ public class AlipayEcoEduJzApplyresultSyncModel extends AlipayObject { private static final long serialVersionUID = 3657599694115912117L; /** * 报名编号(通过调用报名信息同步接口返回) */ @ApiField("apply_third_id") private String applyThirdId; /** * 备注 */ @ApiField("audit_remark") private String auditRemark; /** * 报名结果状态 */ @ApiField("listing_status") private String listingStatus; public String getApplyThirdId() { return this.applyThirdId; } public void setApplyThirdId(String applyThirdId) { this.applyThirdId = applyThirdId; } public String getAuditRemark() { return this.auditRemark; } public void setAuditRemark(String auditRemark) { this.auditRemark = auditRemark; } public String getListingStatus() { return this.listingStatus; } public void setListingStatus(String listingStatus) { this.listingStatus = listingStatus; } }
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
9f79e99b8dbe7b632c7d6361b47f50a259bb43a9
559ea64c50ae629202d0a9a55e9a3d87e9ef2072
/com/amap/mapapi/map/bd.java
0fb70ed0c83858e276f18f123fd5e1d567cd3b9b
[]
no_license
CrazyWolf2014/VehicleBus
07872bf3ab60756e956c75a2b9d8f71cd84e2bc9
450150fc3f4c7d5d7230e8012786e426f3ff1149
refs/heads/master
2021-01-03T07:59:26.796624
2016-06-10T22:04:02
2016-06-10T22:04:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
186
java
package com.amap.mapapi.map; import com.amap.mapapi.core.GeoPoint; /* compiled from: TransAnimListener */ public interface bd { void m815a(GeoPoint geoPoint); void m816b(); }
[ "ahhmedd16@hotmail.com" ]
ahhmedd16@hotmail.com
e3bf32787c20961c57af5a9a0ab8992450771ea9
5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1
/Code Snippet Repository/Log4j/Log4j2901.java
a51da535ebd7ffc3d8c58fa8c1a84248e358e8af
[]
no_license
saber13812002/DeepCRM
3336a244d4852a364800af3181e03e868cf6f9f5
be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9
refs/heads/master
2023-03-16T00:08:06.473699
2018-04-18T05:29:50
2018-04-18T05:29:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
752
java
@SuppressWarnings("") private V getObjectValue(final Object k) { if (k == null) { return containsNullKey ? values[arraySize] : defRetValue; } K curr; final K[] key = this.keys; int pos; // The starting point. if ((curr = key[pos = HashCommon.mix(k.hashCode()) & mask]) == null) { return defRetValue; } if (k.equals(curr)) { return values[pos]; } // There's always an unused entry. while (true) { if (((curr = key[pos = (pos + 1) & mask]) == null)) { return defRetValue; } if (k.equals(curr)) { return values[pos]; } } }
[ "Qing.Mi@my.cityu.edu.hk" ]
Qing.Mi@my.cityu.edu.hk
7565d2d927c555c3cc2d147a14af93b04cdfa24d
5a3d1b02c3d15171c78ebe0e91e8b7e429e216c2
/RSFrame/src/main/java/prea/recommender/matrix/BayesianPMF.java
abb49734a941a0ef23ae0342d3c5949068859330
[]
no_license
pangjuntaoer/RSFrame
492741d8916dbd29625cc7c02f7d6b6589159c6f
a8b5ac5514feef971447e8d5f403e3fa6a3cbf23
refs/heads/master
2020-04-11T09:03:36.653953
2014-11-05T07:26:00
2014-11-05T07:26:00
null
0
0
null
null
null
null
GB18030
Java
false
false
10,460
java
package prea.recommender.matrix; import prea.data.structure.SparseMatrix; import prea.data.structure.SparseVector; import prea.util.Distribution; /** * This is a class implementing Bayesian Probabilistic Matrix Factorization. * Technical detail of the algorithm can be found in * Ruslan Salakhutdinov and Andriy Mnih, Bayesian Probabilistic Matrix Factorization using Markov Chain Monte Carlo, * Proceedings of the 25th International Conference on Machine Learning, 2008. * * @author Joonseok Lee * @since 2012. 4. 20 * @version 1.1 */ public class BayesianPMF extends MatrixFactorizationRecommender { private static final long serialVersionUID = 4004; /*======================================== * Constructors *========================================*/ /** * Construct a matrix-factorization model with the given data. * * @param uc The number of users in the dataset. * @param ic The number of items in the dataset. * @param max The maximum rating value in the dataset. * @param min The minimum rating value in the dataset. * @param fc The number of features used for describing user and item profiles. * @param lr Learning rate for gradient-based or iterative optimization. * @param r Controlling factor for the degree of regularization. * @param m Momentum used in gradient-based or iterative optimization. * @param iter The maximum number of iterations. * @param verbose Indicating whether to show iteration steps and train error. */ public BayesianPMF(int uc, int ic, double max, double min, int fc, double lr, double r, double m, int iter, boolean verbose) { super(uc, ic, max, min, fc, lr, r, m, iter, verbose); } /*======================================== * Model Builder *========================================*/ /** * Build a model with given training set. * * @param rateMatrix Training data set. */ @Override public void buildModel(SparseMatrix rateMatrix) { super.buildModel(rateMatrix); double prevErr = 99999999; // Initialize hierarchical priors: int beta = 2; // observation noise (precision) SparseVector mu_u = new SparseVector(featureCount); SparseVector mu_m = new SparseVector(featureCount); SparseMatrix alpha_u = SparseMatrix.makeIdentity(featureCount); SparseMatrix alpha_m = SparseMatrix.makeIdentity(featureCount); // parameters of Inv-Whishart distribution: SparseMatrix WI_u = SparseMatrix.makeIdentity(featureCount); int b0_u = 2; int df_u = featureCount; SparseVector mu0_u = new SparseVector(featureCount); SparseMatrix WI_m = SparseMatrix.makeIdentity(featureCount); int b0_m = 2; int df_m = featureCount; SparseVector mu0_m = new SparseVector(featureCount); double mean_rating = rateMatrix.average(); this.offset = mean_rating; // Initialization using MAP solution found by PMF: for (int f = 0; f < featureCount; f++) { for (int u = 1; u <= userCount; u++) { userFeatures.setValue(u, f, Distribution.normalRandom(0, 1)); } for (int i = 1; i <= itemCount; i++) { itemFeatures.setValue(f, i, Distribution.normalRandom(0, 1)); } } for (int f = 0; f < featureCount; f++) { mu_u.setValue(f, userFeatures.getColRef(f).average()); mu_m.setValue(f, itemFeatures.getRowRef(f).average()); } alpha_u = (userFeatures.covariance()).inverse(); alpha_m = (itemFeatures.transpose().covariance()).inverse(); // Iteration: SparseVector x_bar = new SparseVector(featureCount); SparseVector normalRdn = new SparseVector(featureCount); SparseMatrix S_bar, WI_post, lam; SparseVector mu_temp; double df_upost, df_mpost; for (int round = 1; round <= maxIter; round++) { //------------------------------------------------------------------------------ // Sample from user hyper parameters: int M = userCount; for (int f = 0; f < featureCount; f++) { x_bar.setValue(f, userFeatures.getColRef(f).average()); } S_bar = userFeatures.covariance(); SparseVector mu0_u_x_bar = mu0_u.minus(x_bar); SparseMatrix e1e2 = mu0_u_x_bar.outerProduct(mu0_u_x_bar).scale((double) M * (double) b0_u / (double) (b0_u + M)); WI_post = WI_u.inverse().plus(S_bar.scale(M)).plus(e1e2); WI_post = WI_post.inverse(); WI_post = (WI_post.plus(WI_post.transpose())).scale(0.5); df_upost = df_u + M; SparseMatrix wishrnd_u = Distribution.wishartRandom(WI_post, df_upost); if (wishrnd_u != null) alpha_u = wishrnd_u; mu_temp = ((mu0_u.scale(b0_u)).plus(x_bar.scale(M))).scale(1 / ((double) b0_u + (double) M)); lam = alpha_u.scale(b0_u + M).inverse().cholesky(); if (lam != null) { lam = lam.transpose(); normalRdn = new SparseVector(featureCount); for (int f = 0; f < featureCount; f++) { normalRdn.setValue(f, Distribution.normalRandom(0, 1)); } mu_u = lam.times(normalRdn).plus(mu_temp); } //------------------------------------------------------------------------------ //Sample from item hyper parameters: int N = itemCount; for (int f = 0; f < featureCount; f++) { x_bar.setValue(f, itemFeatures.getRowRef(f).average()); } S_bar = itemFeatures.transpose().covariance(); SparseVector mu0_m_x_bar = mu0_m.minus(x_bar); SparseMatrix e3e4 = mu0_m_x_bar.outerProduct(mu0_m_x_bar).scale((double) N * (double) b0_m / (double) (b0_m + N)); WI_post = WI_m.inverse().plus(S_bar.scale(N)).plus(e3e4); WI_post = WI_post.inverse(); WI_post = (WI_post.plus(WI_post.transpose())).scale(0.5); df_mpost = df_m + N; SparseMatrix wishrnd_m = Distribution.wishartRandom(WI_post, df_mpost); if (wishrnd_m != null) alpha_m = wishrnd_m; mu_temp = ((mu0_m.scale(b0_m)).plus(x_bar.scale(N))).scale(1 / ((double) b0_m + (double) N)); lam = alpha_m.scale(b0_m + N).inverse().cholesky(); if (lam != null) { lam = lam.transpose(); normalRdn = new SparseVector(featureCount); for (int f = 0; f < featureCount; f++) { normalRdn.setValue(f, Distribution.normalRandom(0, 1)); } mu_m = lam.times(normalRdn).plus(mu_temp); } //------------------------------------------------------------------------------ // Gibbs updates over user and item feature vectors given hyper parameters: for (int gibbs = 1; gibbs < 2; gibbs++) { //根据所有用户特征向量推断后验分布 // Infer posterior distribution over all user feature vectors for (int uu = 1; uu <= userCount; uu++) { // list of items rated by user uu: int[] ff = rateMatrix.getRowRef(uu).indexList(); if (ff == null) continue; int ff_idx = 0; for (int t = 0; t < ff.length; t++) { ff[ff_idx] = ff[t]; ff_idx++; } //用户uu评分的item向量 // features of items rated by user uu: SparseMatrix MM = new SparseMatrix(ff_idx, featureCount); SparseVector rr = new SparseVector(ff_idx); int idx = 0; for (int t = 0; t < ff_idx; t++) { int i = ff[t]; rr.setValue(idx, rateMatrix.getValue(uu, i) - mean_rating); for (int f = 0; f < featureCount; f++) { MM.setValue(idx, f, itemFeatures.getValue(f, i)); } idx++; } SparseMatrix covar = (alpha_u.plus((MM.transpose().times(MM)).scale(beta))).inverse(); SparseVector a = MM.transpose().times(rr).scale(beta); SparseVector b = alpha_u.times(mu_u); SparseVector mean_u = covar.times(a.plus(b)); lam = covar.cholesky(); if (lam != null) { lam = lam.transpose(); for (int f = 0; f < featureCount; f++) { normalRdn.setValue(f, Distribution.normalRandom(0, 1)); } SparseVector w1_P1_uu = lam.times(normalRdn).plus(mean_u); for (int f = 0; f < featureCount; f++) { userFeatures.setValue(uu, f, w1_P1_uu.getValue(f)); } } } //------------------------------------------------------------------------------ //根据所有电影特征向量推断后验分布 // Infer posterior distribution over all movie feature vectors for (int ii = 1; ii <= itemCount; ii++) { // list of users who rated item ii: int[] ff = rateMatrix.getColRef(ii).indexList(); if (ff == null) continue; int ff_idx = 0; for (int t = 0; t < ff.length; t++) { ff[ff_idx] = ff[t]; ff_idx++; } // features of users who rated item ii: SparseMatrix MM = new SparseMatrix(ff_idx, featureCount); SparseVector rr = new SparseVector(ff_idx); int idx = 0; for (int t = 0; t < ff_idx; t++) { int u = ff[t]; rr.setValue(idx, rateMatrix.getValue(u, ii) - mean_rating); for (int f = 0; f < featureCount; f++) { MM.setValue(idx, f, userFeatures.getValue(u, f)); } idx++; } SparseMatrix covar = (alpha_m.plus((MM.transpose().times(MM)).scale(beta))).inverse(); SparseVector a = MM.transpose().times(rr).scale(beta); SparseVector b = alpha_m.times(mu_m); SparseVector mean_m = covar.times(a.plus(b)); lam = covar.cholesky(); if (lam != null) { lam = lam.transpose(); for (int f = 0; f < featureCount; f++) { normalRdn.setValue(f, Distribution.normalRandom(0, 1)); } SparseVector w1_M1_ii = lam.times(normalRdn).plus(mean_m); for (int f = 0; f < featureCount; f++) { itemFeatures.setValue(f, ii, w1_M1_ii.getValue(f)); } } } } //---------------------------------------------------------------------------------------- // show progress: double err = 0.0; for (int u = 1; u <= userCount; u++) { int[] itemList = rateMatrix.getRowRef(u).indexList(); if (itemList != null) { for (int i : itemList) { double Aij = rateMatrix.getValue(u, i) - mean_rating; double Bij = userFeatures.getRowRef(u).innerProduct(itemFeatures.getColRef(i)); err += Math.pow(Aij - Bij, 2); } } } if (showProgress) { System.out.println(round + "\t" + (err / rateMatrix.itemCount())); } if (prevErr < err) { break; } else { prevErr = err; } } } }
[ "pangjuntaoer@163.com" ]
pangjuntaoer@163.com
1f5ea4228793e13ee014b6b9d03622b94ea46566
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/ant_cluster/24257/src_2.java
58b5e93c68dc16b6685da9ef919f1f253feadc10
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,254
java
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */ package org.apache.tools.ant.taskdefs.optional.perforce; import java.io.IOException; import org.apache.myrmidon.api.TaskException; import org.apache.oro.text.perl.Perl5Util; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.exec.Execute; import org.apache.tools.ant.types.Commandline; /** * Base class for Perforce (P4) ANT tasks. See individual task for example * usage. * * @author <A HREF="mailto:leslie.hughes@rubus.com">Les Hughes</A> * @see P4Sync * @see P4Have * @see P4Change * @see P4Edit * @see P4Submit * @see P4Label * @see org.apache.tools.ant.taskdefs.Exec */ public abstract class P4Base extends org.apache.tools.ant.Task { /** * Perl5 regexp in Java - cool eh? */ protected Perl5Util util = null; //P4 runtime directives /** * Perforce Server Port (eg KM01:1666) */ protected String P4Port = ""; /** * Perforce Client (eg myclientspec) */ protected String P4Client = ""; /** * Perforce User (eg fbloggs) */ protected String P4User = ""; /** * Perforce view for commands (eg //projects/foobar/main/source/... ) */ protected String P4View = ""; //P4 g-opts and cmd opts (rtfm) /** * Perforce 'global' opts. Forms half of low level API */ protected String P4Opts = ""; /** * Perforce command opts. Forms half of low level API */ protected String P4CmdOpts = ""; /** * The OS shell to use (cmd.exe or /bin/sh) */ protected String shell; public void setClient( String P4Client ) { this.P4Client = "-c" + P4Client; } public void setCmdopts( String P4CmdOpts ) { this.P4CmdOpts = P4CmdOpts; } //Setters called by Ant public void setPort( String P4Port ) { this.P4Port = "-p" + P4Port; } public void setUser( String P4User ) { this.P4User = "-u" + P4User; } public void setView( String P4View ) { this.P4View = P4View; } private void prepare() { util = new Perl5Util(); //Get default P4 settings from environment - Mark would have done something cool with //introspection here.....:-) String tmpprop; if( ( tmpprop = project.getProperty( "p4.port" ) ) != null ) setPort( tmpprop ); if( ( tmpprop = project.getProperty( "p4.client" ) ) != null ) setClient( tmpprop ); if( ( tmpprop = project.getProperty( "p4.user" ) ) != null ) setUser( tmpprop ); } protected void execP4Command( String command ) throws TaskException { execP4Command( command, null ); } public void execute() throws TaskException { //Setup task before executing it prepare(); super.execute(); } /** * Execute P4 command assembled by subclasses. * * @param command The command to run * @param handler A P4Handler to process any input and output * @exception TaskException Description of Exception */ protected void execP4Command( String command, P4Handler handler ) throws TaskException { try { Commandline commandline = new Commandline(); commandline.setExecutable( "p4" ); //Check API for these - it's how CVS does it... if( P4Port != null && P4Port.length() != 0 ) { commandline.createArgument().setValue( P4Port ); } if( P4User != null && P4User.length() != 0 ) { commandline.createArgument().setValue( P4User ); } if( P4Client != null && P4Client.length() != 0 ) { commandline.createArgument().setValue( P4Client ); } commandline.createArgument().setLine( command ); String[] cmdline = commandline.getCommandline(); String cmdl = ""; for( int i = 0; i < cmdline.length; i++ ) { cmdl += cmdline[ i ] + " "; } log( "Execing " + cmdl, Project.MSG_VERBOSE ); if( handler == null ) handler = new SimpleP4OutputHandler( this ); Execute exe = new Execute( handler, null ); exe.setAntRun( project ); exe.setCommandline( commandline.getCommandline() ); try { exe.execute(); } catch( IOException e ) { throw new TaskException( "Error", e ); } finally { try { handler.stop(); } catch( Exception e ) { } } } catch( Exception e ) { throw new TaskException( "Problem exec'ing P4 command: " + e.getMessage() ); } } }
[ "375833274@qq.com" ]
375833274@qq.com
659898fbb856aec0d2c31712a4c09cfe2c59cd28
505033498f0aaaa8c17542c043f131caa2698583
/ListaCustomizeAPI23/app/src/main/java/com/example/bubba/listacustomizeapi23/Adaptador.java
00b8ab9639ad9719cba2a7092382ba304a7b87ec
[]
no_license
Bubba14016/AndroidStudioProjects
7fb61991ca3201712c1b234a5a3db37351b3054d
2cb2f50470b6b1f72507d8d48b1081f3ab9ed38a
refs/heads/master
2021-05-25T11:52:11.899753
2018-08-04T01:30:00
2018-08-04T01:30:00
127,323,207
0
0
null
null
null
null
UTF-8
Java
false
false
1,577
java
package com.example.bubba.listacustomizeapi23; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by Bubba on 07/03/2018. */ public class Adaptador extends ArrayAdapter<Pais> { ArrayList<Pais> items; public Adaptador(Context context, int resource, ArrayList<Pais> objects) { super(context, resource, objects); items=objects; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { Pais pais=getItem(position); if (convertView==null){ convertView= LayoutInflater.from(getContext()).inflate(R.layout.activity_custom,parent,false); } TextView tvPais=(TextView) convertView.findViewById(R.id.tvPais); TextView tvCapital=(TextView) convertView.findViewById(R.id.tvCapital); ImageView bandera=(ImageView) convertView.findViewById(R.id.img); tvPais.setText(pais.nombre); tvCapital.setText(pais.capital); bandera.setImageResource(pais.bandera); return convertView; } @Override public Pais getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } }
[ "cartorres.95@gmail.com" ]
cartorres.95@gmail.com
170818c379241e7269137db53a122cead7559aa1
27c9f96c69f9cf69af5f45b467cef357758aa6c8
/src/com/ssm/util/PagerTag.java
d76b94ce855766db4539e67407ba77e02cf37b8e
[]
no_license
MengJianGui/JAVA-SSM
95e1e7ee86775e196b5f2616047c5b0d49446976
b852301d5951796269fc873a4e5e9177757b6427
refs/heads/master
2020-05-29T15:28:32.648142
2019-05-29T12:37:31
2019-05-29T12:37:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,712
java
package com.ssm.util; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; /** * 分页标签 */ public class PagerTag extends SimpleTagSupport { /** 定义请求URL中的占位符常量 */ private static final String TAG = "{0}"; /** 当前页码 */ private int pageIndex; /** 每页显示的数量 */ private int pageSize; /** 总记录条数 */ private int recordCount; /** 请求URL page.action?pageIndex={0}*/ private String submitUrl; /** 样式 */ private String style = "sabrosus"; /** 定义总页数 */ private int totalPage = 0; /** 在页面上引用自定义标签就会触发一个标签处理类 */ @Override public void doTag() throws JspException, IOException { /** 定义它拼接是终的结果 */ StringBuilder res = new StringBuilder(); /** 定义它拼接中间的页码 */ StringBuilder str = new StringBuilder(); /** 判断总记录条数 */ if (recordCount > 0){ //1499 / 15 = 100 /** 需要显示分页标签,计算出总页数 需要分多少页 */ totalPage = (this.recordCount - 1) / this.pageSize + 1; /** 判断上一页或下一页需不需要加a标签 */ if (this.pageIndex == 1){ // 首页 str.append("<span class='disabled'>上一页</span>"); /** 计算中间的页码 */ this.calcPage(str); /** 下一页需不需要a标签 */ if (this.pageIndex == totalPage){ /** 只有一页 */ str.append("<span class='disabled'>下一页</span>"); }else{ String tempUrl = this.submitUrl.replace(TAG, String.valueOf(pageIndex + 1)); str.append("<a href='"+ tempUrl +"'>下一页</a>"); } }else if (this.pageIndex == totalPage){ // 尾页 String tempUrl = this.submitUrl.replace(TAG, String.valueOf(pageIndex - 1)); str.append("<a href='"+ tempUrl +"'>上一页</a>"); /** 计算中间的页码 */ this.calcPage(str); str.append("<span class='disabled'>下一页</span>"); }else{ // 中间 String tempUrl = this.submitUrl.replace(TAG, String.valueOf(pageIndex - 1)); str.append("<a href='"+ tempUrl +"'>上一页</a>"); /** 计算中间的页码 */ this.calcPage(str); tempUrl = this.submitUrl.replace(TAG, String.valueOf(pageIndex + 1)); str.append("<a href='"+ tempUrl +"'>下一页</a>"); } /** 拼接其它的信息 */ res.append("<table width='100%' align='center' style='font-size:13px;' class='"+ style +"'>"); res.append("<tr><td style='COLOR: #0061de; MARGIN-RIGHT: 3px; PADDING-TOP: 2px; TEXT-DECORATION: none'>" + str.toString()); res.append("&nbsp;跳转到&nbsp;&nbsp;<input style='text-align: center;BORDER-RIGHT: #aaaadd 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #aaaadd 1px solid; PADDING-LEFT: 5px; PADDING-BOTTOM: 2px; MARGIN: 2px; BORDER-LEFT: #aaaadd 1px solid; COLOR: #000099; PADDING-TOP: 2px; BORDER-BOTTOM: #aaaadd 1px solid; TEXT-DECORATION: none' type='text' size='2' id='pager_jump_page_size'/>"); res.append("&nbsp;<input type='button' style='text-align: center;BORDER-RIGHT: #dedfde 1px solid; PADDING-RIGHT: 6px; BACKGROUND-POSITION: 50% bottom; BORDER-TOP: #dedfde 1px solid; PADDING-LEFT: 6px; PADDING-BOTTOM: 2px; BORDER-LEFT: #dedfde 1px solid; COLOR: #0061de; MARGIN-RIGHT: 3px; PADDING-TOP: 2px; BORDER-BOTTOM: #dedfde 1px solid; TEXT-DECORATION: none' value='确定' id='pager_jump_btn'/>"); res.append("</td></tr>"); res.append("<tr align='center'><td style='font-size:13px;'><tr><td style='COLOR: #0061de; MARGIN-RIGHT: 3px; PADDING-TOP: 2px; TEXT-DECORATION: none'>"); /** 开始条数 */ int startNum = (this.pageIndex - 1) * this.pageSize + 1; /** 结束条数 */ int endNum = (this.pageIndex == this.totalPage) ? this.recordCount : this.pageIndex * this.pageSize; res.append("总共<font color='red'>"+ this.recordCount +"</font>条记录,当前显示"+ startNum +"-"+ endNum +"条记录。"); res.append("</td></tr>"); res.append("</table>"); res.append("<script type='text/javascript'>"); res.append(" document.getElementById('pager_jump_btn').onclick = function(){"); res.append(" var page_size = document.getElementById('pager_jump_page_size').value;"); res.append(" if (!/^[1-9]\\d*$/.test(page_size) || page_size < 1 || page_size > "+ this.totalPage +"){"); res.append(" alert('请输入[1-"+ this.totalPage +"]之间的页码!');"); res.append(" }else{"); res.append(" var submit_url = '" + this.submitUrl + "';"); res.append(" window.location = submit_url.replace('"+ TAG +"', page_size);"); res.append(" }"); res.append("}"); res.append("</script>"); }else{ res.append("<table align='center' style='font-size:13px;'><tr><td style='COLOR: #0061de; MARGIN-RIGHT: 3px; PADDING-TOP: 2px; TEXT-DECORATION: none'>总共<font color='red'>0</font>条记录,当前显示0-0条记录。</td></tr></table>"); } this.getJspContext().getOut().print(res.toString()); } /** 计算中间页码的方法 */ private void calcPage(StringBuilder str) { /** 判断总页数 */ if (this.totalPage <= 11){ /** 一次性显示全部的页码 */ for (int i = 1; i <= this.totalPage; i++){ if (this.pageIndex == i){ /** 当前页码 */ str.append("<span class='current'>"+ i +"</span>"); }else{ String tempUrl = this.submitUrl.replace(TAG, String.valueOf(i)); str.append("<a href='"+ tempUrl +"'>"+ i +"</a>"); } } }else{ /** 靠近首页 */ if (this.pageIndex <= 8){ for (int i = 1; i <= 10; i++){ if (this.pageIndex == i){ /** 当前页码 */ str.append("<span class='current'>"+ i +"</span>"); }else{ String tempUrl = this.submitUrl.replace(TAG, String.valueOf(i)); str.append("<a href='"+ tempUrl +"'>"+ i +"</a>"); } } str.append("..."); String tempUrl = this.submitUrl.replace(TAG, String.valueOf(this.totalPage)); str.append("<a href='"+ tempUrl +"'>"+ this.totalPage +"</a>"); } /** 靠近尾页 */ else if (this.pageIndex + 8 >= this.totalPage){ String tempUrl = this.submitUrl.replace(TAG, String.valueOf(1)); str.append("<a href='"+ tempUrl +"'>1</a>"); str.append("..."); for (int i = this.totalPage - 10; i <= this.totalPage; i++){ if (this.pageIndex == i){ /** 当前页码 */ str.append("<span class='current'>"+ i +"</span>"); }else{ tempUrl = this.submitUrl.replace(TAG, String.valueOf(i)); str.append("<a href='"+ tempUrl +"'>"+ i +"</a>"); } } } /** 在中间 */ else{ String tempUrl = this.submitUrl.replace(TAG, String.valueOf(1)); str.append("<a href='"+ tempUrl +"'>1</a>"); str.append("..."); for (int i = this.pageIndex - 4; i <= this.pageIndex + 4; i++){ if (this.pageIndex == i){ /** 当前页码 */ str.append("<span class='current'>"+ i +"</span>"); }else{ tempUrl = this.submitUrl.replace(TAG, String.valueOf(i)); str.append("<a href='"+ tempUrl +"'>"+ i +"</a>"); } } str.append("..."); tempUrl = this.submitUrl.replace(TAG, String.valueOf(this.totalPage)); str.append("<a href='"+ tempUrl +"'>"+ this.totalPage +"</a>"); } } } /** setter 方法 */ public void setPageIndex(int pageIndex) { this.pageIndex = pageIndex; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setRecordCount(int recordCount) { this.recordCount = recordCount; } public void setSubmitUrl(String submitUrl) { this.submitUrl = submitUrl; } public void setStyle(String style) { this.style = style; } }
[ "1249926700@qq.com" ]
1249926700@qq.com
564e5e0d14e1026b6e0189e15d8f4d421d009ac1
740b2ec46604973078cae79115522b9199e5088b
/src/main/java/com/stemsence/paymentapp/services/PaymentReceptor.java
c4c4c883ba5ffbd52c810287d666b779334be4fb
[]
no_license
jokello1/PaymentsApp
1042b0c129002f488a9ee03ead3d5ad298bc6686
498ea7dd75c7a6dc2288b89d8e00cf61e69db8a1
refs/heads/main
2023-06-06T19:03:26.514002
2021-07-23T12:32:24
2021-07-23T12:32:24
388,793,394
0
0
null
null
null
null
UTF-8
Java
false
false
4,438
java
package com.stemsence.paymentapp.services; import com.stemsence.paymentapp.interfaces.DisbursementRepository; import com.stemsence.paymentapp.interfaces.WalletRepository; import com.stemsence.paymentapp.models.Disbursement; import com.stemsence.paymentapp.models.Wallet; import com.stemsence.paymentapp.requests.PurchaseRequest; import com.stemsence.paymentapp.responses.Result; import com.stemsence.paymentapp.utils.DisbursementUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; import java.util.Optional; import static com.stemsence.paymentapp.constants.constants.*; public class PaymentReceptor { static Logger log = LoggerFactory.getLogger(PaymentReceptor.class); @Autowired static DisbursementRepository disbursementRepository; public static List<Wallet> getAllWallets(WalletRepository walletRepository){ return walletRepository.findAll(); } public static List<Disbursement> getAllDisbursements(){ return disbursementRepository.findAll(); } public static void updateWallet(String phone, int amount,WalletRepository walletRepository) { Wallet wallet = new Wallet(); if (walletRepository==null) walletRepository.save(wallet); Optional<Wallet> optionalWallet = walletRepository.findByPhone(phone); if (optionalWallet.isPresent()){ wallet = optionalWallet.get(); int balance = wallet.getBalance()+amount; wallet.setBalance(balance); walletRepository.save(wallet); log.info("Wallet updated successfully."); }else { wallet.setBalance(amount); wallet.setLastUpdated(new Date()); wallet.setPhone(phone); walletRepository.save(wallet); log.info("Wallet created successfully."); } } public static int purchaseContent(PurchaseRequest purchaseRequest,WalletRepository walletRepository){ log.info("Purchase of content.."); Wallet wallet1 = new Wallet(); if (walletRepository==null) walletRepository.save(wallet1); Optional<Wallet> optionalWallet = walletRepository.findByPhone(purchaseRequest.getPhone()); if (optionalWallet.isPresent()){ Wallet wallet = optionalWallet.get(); int balance = wallet.getBalance(); int calculatedAmount = QUESTION_PRICE * purchaseRequest.getQuestions(); if (balance >= calculatedAmount){ balance = balance-calculatedAmount; wallet.setBalance(balance); walletRepository.save(wallet); String teacherAmount = disbursePayment(calculatedAmount, purchaseRequest.getTeacherPhone(), purchaseRequest.getPhone()); return Integer.parseInt(teacherAmount); }else { return -1; } } return -1; } public static String disbursePayment(int amount, String teacherPhone, String studentId){ log.info("Payment disburse.."); DisbursementUtil disbursementObject = new DisbursementUtil(amount); String teacherAmount = String.valueOf(disbursementObject.getTeacherAmount()); Disbursement disbursement = new Disbursement(); disbursement.setDutyAmount(String.valueOf(disbursementObject.getDutyAmount())); disbursement.setDateOfTransaction(new Date()); disbursement.setStemAmount(String.valueOf(disbursementObject.getStemAmount())); disbursement.setTeacherAmount(teacherAmount); disbursement.setStudentId(studentId); disbursement.setTeacherPhone(teacherPhone); disbursement.setTotalAmount(String.valueOf(amount)); disbursement.setTeacherPayStatus("Pending"); disbursementRepository.save(disbursement); return teacherAmount; } public static void confirmTeacherPayment(Result result){ Optional<Disbursement> optionalDisbursement = disbursementRepository.findByOriginatorConversationID(result.getOriginatorConversationID()); if (optionalDisbursement.isPresent()){ log.info("Teacher payment confirmation.."); optionalDisbursement.get().setTeacherPayStatus("Confirmed"); disbursementRepository.save(optionalDisbursement.get()); } } }
[ "joshuajoe12561@gmail.com" ]
joshuajoe12561@gmail.com
e9eef081ab96f12e83fa73fa40d7cf59c9b82418
accc530f612d34429a31ffd3ef1c6beb393b7e93
/src/HockeyTeam.java
c81f3c0740a36d597d1eb7fd8bacd14eeb7985b4
[]
no_license
emirtotic/StrategyDesignPattern
d5e6e7089f425c89f2298f9f4099bc20804fe384
f132ef4278db8838f24df91a791afdd535a0b862
refs/heads/master
2022-12-13T11:49:48.658190
2020-09-09T19:12:59
2020-09-09T19:12:59
294,196,870
0
0
null
null
null
null
UTF-8
Java
false
false
948
java
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class HockeyTeam implements Actions { Scanner scanner = new Scanner(System.in); private String teamName; private List<Player> playersList = new ArrayList<>(); public HockeyTeam() { System.out.print("Enter team name: "); setTeamName(teamName); setPlayersList(playersList); } public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = scanner.nextLine(); } public List<Player> getPlayersList() { return playersList; } public void setPlayersList(List<Player> playersList) { for (int i = 0; i < 3; i++) { System.out.print("Enter " + (i + 1) + ". player of 3: "); playersList.add(new Player(scanner.nextLine())); } } @Override public void getList() { System.out.println("\nTeam - " + teamName + ": " + playersList); } }
[ "Legion@DESKTOP-40T1NOC" ]
Legion@DESKTOP-40T1NOC
5ab7d8ee22936c933b2c6789e2ec5c2cc7f0cd98
3967e05206f8dc21f1f3feae23cc6d9ae32a6bb0
/SpringBank/src/main/java/com/company/bank/service/TestVO.java
89e2d2108e409460775c0b0276ef4218c9a73549
[]
no_license
LEEHYEBIN1702/SpringBank
42719727e0bae8e42cd5d3f7257ba510b0f7e1bb
0af93d456569c0a45960b3e73ac7cd8734e0a72c
refs/heads/master
2023-04-02T00:31:47.862404
2021-03-26T01:39:36
2021-03-26T01:39:36
348,276,531
0
0
null
null
null
null
UTF-8
Java
false
false
161
java
package com.company.bank.service; import lombok.Data; @Data public class TestVO { private String firstName; private String salary; private String hobby; }
[ "qls1702@hanmail.net" ]
qls1702@hanmail.net
fea711f8b88a5ad8a73c378eba6524fbbf76c52f
e0ce3f57d1afcc653008619108fe41310b86e620
/app/src/main/java/com/onenews/base/activity/BaseRlvActivity.java
cb97d314c9151af1305304320b8754f9f02b09e8
[]
no_license
yangweidong/MyNuoMi
bb76d8ace3beafe56ee24effce9cd6ff95b05415
e10124b3548659108eefcb74240a13b04b24e0cf
refs/heads/master
2021-01-21T12:59:09.967507
2016-04-28T06:58:13
2016-04-28T06:58:13
54,644,583
0
0
null
null
null
null
UTF-8
Java
false
false
1,662
java
package com.onenews.base.activity; import android.support.v7.widget.LinearLayoutManager; import com.onenews.R; import com.onenews.base.adapter.BaseRlvAdapter; import com.onenews.remodeling.activity.BaseActivity; import com.onenews.widgets.recyclerview.ProgressStyle; import com.onenews.widgets.recyclerview.XRecyclerView; /** * Created by yangweidong on 16/4/24. */ public abstract class BaseRlvActivity extends BaseActivity { XRecyclerView mXRecyclerView; // ListFragment listFragment; BaseRlvAdapter mBaseRlvAdapter; // ListActivity listActivity; @Override protected int getLayout() { return R.layout.recyclerview; } @Override protected void initView() { mXRecyclerView = (XRecyclerView) findViewById(R.id.recyclerview); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mXRecyclerView.setLayoutManager(layoutManager); mXRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader); mXRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey); mBaseRlvAdapter = getRlvAdater(); mXRecyclerView.setAdapter(mBaseRlvAdapter); } protected abstract BaseRlvAdapter getRlvAdater(); /** * 获取adapter 获取条件为 onCreated 之后 和 覆盖getAdater() 并且返回正确的adapter * @return */ protected BaseRlvAdapter getAdapter(){ if(null == mBaseRlvAdapter){ throw new NullPointerException("adapter not init null Please cover getAdater()"); } return mBaseRlvAdapter; } }
[ "244672111@qq.com" ]
244672111@qq.com
d1331bc8c02d7af4fa6c6d20e0597824bf5578bf
bcf371f91b4be1feb0b24cb632c2fb7285bebdf1
/gen/com/acc/datascript/lang/psi/DsTableDefinition.java
64847e5fae71d33422333b54964db27fab0e8b33
[]
no_license
DemiusAcademius/DataScriptNative
ae101e8c120b5bc16ecbbb328e5cb40abca24cc8
a38b3851d3d36ee1703520e7f20c259d09b0eb0f
refs/heads/master
2021-01-10T18:05:19.005716
2016-01-05T15:15:33
2016-01-05T15:15:33
49,064,914
0
0
null
null
null
null
UTF-8
Java
false
true
393
java
// This is a generated file. Not intended for manual editing. package com.acc.datascript.lang.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface DsTableDefinition extends PsiElement { @NotNull List<DsColumn> getColumnList(); @Nullable DsPrimaryKeyClause getPrimaryKeyClause(); @Nullable PsiElement getId(); }
[ "demius@wks0556.apa-canal.md" ]
demius@wks0556.apa-canal.md
a9b17bd8d84772db37424ac3aae56f5f967832c9
c771ad14eff1cb486d00e47aca4a6aac87f004ac
/src/com/example/Wave.java
3a1be880480fc46524b2f61f6423bc47b4ff9414
[]
no_license
lukaszwek/sound-processing-2
2adec7b473487801c604ac8f65c55215f3a4451e
8170cc054dc28decfb3117f498d10ec227602b24
refs/heads/master
2020-05-26T08:04:17.625685
2015-06-09T19:32:20
2015-06-09T19:32:20
35,620,514
0
0
null
null
null
null
UTF-8
Java
false
false
2,080
java
package com.example; /** * Created by lukaszwieczorek on 12.05.15. */ public class Wave { private String waveType; // { sinusoidal, triangular, sawtooth, rectangular, whiteNoise, redNoise } private double frequency; private double baseFreq; private double amplification; private double percentageFreq=100; private double fCyclePosition=0; private double fCycleInc; public Wave() {} public Wave(String waveType, double frequency, double amplification, double percentageFreq) { this.waveType = waveType; this.percentageFreq = percentageFreq; this.baseFreq = frequency; this.frequency = baseFreq*(percentageFreq/100); this.amplification = amplification; this.fCycleInc = this.frequency/44100; // System.out.println(this.baseFreq + " " + this.frequency + " " + this.fCycleInc); } public double getFrequency() { return frequency; } public double getBaseFreq() { return baseFreq; } public void setFrequency(double frequency) { this.baseFreq = frequency; this.frequency = baseFreq*(percentageFreq/100); this.fCycleInc = this.frequency/44100; // System.out.println(this.baseFreq + " " + this.frequency + " " + this.fCycleInc); } public String getWaveType() { return this.waveType; } public double getPercentageFreq() { return this.percentageFreq; } public void setWaveType(String waveType) { this.waveType = waveType; } public double getAmplification() { return amplification; } public void setAmplification(double amplification) { this.amplification = amplification; } public double getfCycleInc() { return fCycleInc; } //function for getting current point of the wave public double getResult(){ this.fCyclePosition+=fCycleInc; if (this.fCyclePosition > 1) this.fCyclePosition -= 1; return Generator.generateWavSound(this.fCyclePosition, this.waveType); } }
[ "l.wieczorek@binarapps.com" ]
l.wieczorek@binarapps.com
f3a5bc4270e417cb3ec0516ae431d6842b6657ad
d206d67c70ee24c7178d4b7daecc2cce4110c52d
/ADS/LabWork/Lab10/src/com/app/tester/BSTreeApp01.java
380e50596d31caa538a25306e4bb279bd2175b88
[]
no_license
SilverVenom-31/EDAC
7dedcc2b87bfd75c72662f522b4509f03e1090c4
f4218101c389b7de6bbfe58e546ceb7840c044fe
refs/heads/main
2023-04-01T07:52:28.701595
2021-03-30T10:16:42
2021-03-30T10:16:42
327,304,828
0
0
null
null
null
null
UTF-8
Java
false
false
988
java
package com.app.tester; import com.app.core.BSTree; public class BSTreeApp01 { public static void main(String[] args) { BSTree bst = new BSTree(); System.out.println("Print elements - empty tree."); bst.print(); if (bst.find(10)) { System.out.println("Search 10 - Found."); } else { System.out.println("Search 10 - Not Found."); } bst.insert(10); bst.insert(5); bst.insert(1); bst.insert(20); bst.insert(15); System.out.println("Print elements - 1 5 10 15 20."); bst.print(); if (bst.find(10)) { System.out.println("Search 10 - Found."); } else { System.out.println("Search 10 - Not Found."); } if (bst.find(100)) { System.out.println("Search 100 - Found."); } else { System.out.println("Search 100 - Not Found."); } bst.delete(100); // Remove element not preset. System.out.println("Print elements - 1 5 10 15 20."); bst.print(); bst.delete(10); System.out.println("Print elements - 1 5 15 20."); bst.print(); } }
[ "akhil31.ad@gmail.com" ]
akhil31.ad@gmail.com
afe830fab5cfdde4a141f28c2a7a08311e29d6f7
d7452b9df968de07286903ea5f541f9ff680eeb0
/cosmetic-web/src/main/java/com/cyberlink/cosmetic/action/api/product/ListPriceRangAndNameAction.java
e78ff94a557528e007c69ebed921df501e9e2e4a
[ "Apache-2.0" ]
permissive
datree-demo/bcserver_demo
21075c94726932d325b291fb0c26b82cacc26b5b
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
refs/heads/master
2020-04-07T08:28:28.382766
2017-03-14T03:16:35
2017-03-14T03:16:35
158,215,647
0
1
null
null
null
null
UTF-8
Java
false
false
1,626
java
package com.cyberlink.cosmetic.action.api.product; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.cyberlink.core.web.view.page.PageResult; import com.cyberlink.cosmetic.action.api.AbstractAction; import com.cyberlink.cosmetic.modules.product.dao.StorePriceRangeDao; import com.cyberlink.cosmetic.modules.product.model.StorePriceRange; import com.cyberlink.cosmetic.modules.product.model.result.PriceRangeWrapper; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.UrlBinding; import net.sourceforge.stripes.integration.spring.SpringBean; @UrlBinding("/api/store/listPriceRangAndName.action") public class ListPriceRangAndNameAction extends AbstractAction{ private String locale ; @SpringBean("product.StorePriceRangeDao") private StorePriceRangeDao storePriceRangeDao; @DefaultHandler public Resolution route() { final Map<String, Object> results = new HashMap<String, Object>(); List<StorePriceRange> priceRangeResult = new ArrayList<StorePriceRange>(); priceRangeResult = storePriceRangeDao.listAllPriceRangeByLocale(locale); List<PriceRangeWrapper> wrappedPriceRangeList = new ArrayList<PriceRangeWrapper>(); for( StorePriceRange priceRageItem: priceRangeResult ){ wrappedPriceRangeList.add(new PriceRangeWrapper( priceRageItem )); } results.put("results", wrappedPriceRangeList); return json(results); } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } }
[ "wuyongwen@gmail.com" ]
wuyongwen@gmail.com
f541c79e909f836042d64e4d5be22ce49cb4f657
cf729a7079373dc301d83d6b15e2451c1f105a77
/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201509/cm/CustomParameter.java
f828c38fcceee4a2b3bc7e85b7d187f9f359703e
[]
no_license
cvsogor/Google-AdWords
044a5627835b92c6535f807ea1eba60c398e5c38
fe7bfa2ff3104c77757a13b93c1a22f46e98337a
refs/heads/master
2023-03-23T05:49:33.827251
2021-03-17T14:35:13
2021-03-17T14:35:13
348,719,387
0
0
null
null
null
null
UTF-8
Java
false
false
2,651
java
package com.google.api.ads.adwords.jaxws.v201509.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * CustomParameter is used to map a custom parameter key to its value. * * * <p>Java class for CustomParameter complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CustomParameter"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="isRemove" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CustomParameter", propOrder = { "key", "value", "isRemove" }) public class CustomParameter { protected String key; protected String value; protected Boolean isRemove; /** * Gets the value of the key property. * * @return * possible object is * {@link String } * */ public String getKey() { return key; } /** * Sets the value of the key property. * * @param value * allowed object is * {@link String } * */ public void setKey(String value) { this.key = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the isRemove property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsRemove() { return isRemove; } /** * Sets the value of the isRemove property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsRemove(Boolean value) { this.isRemove = value; } }
[ "vacuum13@gmail.com" ]
vacuum13@gmail.com
823f5121cf676c1d84f58add63cbf3999dcb642e
4ac8e7a1c39d91a767d72fadbc33bd803a66a4bf
/app/src/main/java/com/cs/ping/fragment/PingFragment.java
a7897391b3f6f2d55639733596c75ee3b7f76591
[]
no_license
wongkyunban/PingAndTelnetDemo
71957332fdd7331e60e3ec9c03872200547a0470
ffc113ffad85f154376936a0f93ee251cf59683e
refs/heads/master
2020-07-26T17:57:29.393290
2019-09-16T06:29:23
2019-09-16T06:29:23
208,726,244
2
0
null
null
null
null
UTF-8
Java
false
false
12,417
java
package com.cs.ping.fragment; import android.Manifest; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.Group; import androidx.constraintlayout.widget.Placeholder; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.FileUtils; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.cs.ping.PingApplication; import com.cs.ping.R; import com.cs.ping.SharedKey; import com.cs.ping.adapter.PingAdapter; import com.cs.ping.event.CloseFloatingButtonEvent; import com.cs.ping.utils.FileUtil; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A simple {@link Fragment} subclass. */ public class PingFragment extends Fragment { private RecyclerView mRecylerView; private PingAdapter pingAdapter; private PingHandler pingHandler; private EditText mEtInputNewIp; private ExecutorService executorService; private ImageButton mIbMenu; private Placeholder mCopyHolder; private Placeholder mSaveHolder; private Placeholder mClearHolder; private Group mMenuGroup; public PingFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_ping, container, false); init(view); return view; } private void init(View view) { mRecylerView = view.findViewById(R.id.rv_cycler); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); mRecylerView.setLayoutManager(layoutManager); pingAdapter = new PingAdapter(); mRecylerView.setAdapter(pingAdapter); pingHandler = new PingHandler(this); mEtInputNewIp = view.findViewById(R.id.et_input_ip); String defaultAddr = PingApplication.getShared().getString(SharedKey.PING_DEFAULT_ADDRESS, "www.baidu.com"); mEtInputNewIp.setText(defaultAddr); mCopyHolder = view.findViewById(R.id.pl_copy_holder); mSaveHolder = view.findViewById(R.id.pl_save_holder); mClearHolder = view.findViewById(R.id.pl_clear_holder); mMenuGroup = view.findViewById(R.id.g_menu_group); mIbMenu = view.findViewById(R.id.ib_menu); mIbMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mMenuGroup.getVisibility() == View.GONE) { viewVisible(); } else { viewGone(); } } }); view.findViewById(R.id.cl_menu_containter).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { int id = view.getId(); if(R.id.ib_menu != id){ viewGone(); } return false; } }); view.findViewById(R.id.tv_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewGone(); pingAdapter.clear(); } }); view.findViewById(R.id.tv_copy).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getActivity() != null) { // 获取系统剪贴板 ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); // 创建一个剪贴数据集,包含一个普通文本数据条目(需要复制的数据),其他的还有 // newHtmlText、 // newIntent、 // newUri、 // newRawUri String data = pingAdapter.getStringList().toString(); ClipData clipData = ClipData.newPlainText(null, data); // 把数据集设置(复制)到剪贴板 if (clipboard != null) { clipboard.setPrimaryClip(clipData); Toast.makeText(getActivity(), "复制成功!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "复制失败!", Toast.LENGTH_SHORT).show(); } } } }); view.findViewById(R.id.tv_save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { checkStoragePermission(); String data = pingAdapter.getStringList().toString(); String fileName = "ping_" + new Date().getTime() + ".txt"; FileUtil fileUtil = new FileUtil(); File file = fileUtil.append2File(fileUtil.getStoragePath() + "/CS_PING/", fileName, data); if (file.exists()) { Toast.makeText(getActivity(), "保存成功!\n\n保存路径:" + fileUtil.getStoragePath(), Toast.LENGTH_LONG).show(); } viewGone(); } }); view.findViewById(R.id.btn_ping).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pingAdapter.clear(); String ip = mEtInputNewIp.getText().toString(); int count = PingApplication.getShared().getInt(SharedKey.PING_COUNT, 4); int size = PingApplication.getShared().getInt(SharedKey.PING_PACKAGE_SIZE, 64); int interval = PingApplication.getShared().getInt(SharedKey.PING_PACKAGE_INTERVAL, 1); String countCmd = " -c " + count + " "; String sizeCmd = " -s " + size + " "; String timeCmd = " -i " + interval + " "; String ping = "ping" + countCmd + timeCmd + sizeCmd + ip; executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Thread(new PingTask(ping, pingHandler, interval))); } }); } private void checkStoragePermission(){ if(getActivity() != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ if(getActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED || getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){ String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}; requestPermissions(permissions,1000); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == 1000) { for (int per : grantResults) { if (per == PackageManager.PERMISSION_DENIED) { Toast.makeText(getActivity(), "权限申请失败", Toast.LENGTH_LONG).show(); } } } } private void viewGone() { mMenuGroup.setVisibility(View.GONE); mCopyHolder.setContentId(0); mSaveHolder.setContentId(0); mClearHolder.setContentId(0); } private void viewVisible() { mMenuGroup.setVisibility(View.VISIBLE); mCopyHolder.setContentId(R.id.tv_copy); mSaveHolder.setContentId(R.id.tv_save); mClearHolder.setContentId(R.id.tv_clear); } private static class PingHandler extends Handler { private WeakReference<PingFragment> weakReference; public PingHandler(PingFragment fragment) { this.weakReference = new WeakReference<>(fragment); } @Override public void handleMessage(@NonNull Message msg) { switch (msg.what) { case 10: String resultMsg = (String) msg.obj; weakReference.get().pingAdapter.addString(resultMsg); weakReference.get().mRecylerView.scrollToPosition(weakReference.get().pingAdapter.getItemCount() - 1); break; default: break; } } } // 创建ping任务 private class PingTask implements Runnable { private String ping; private PingHandler pingHandler; private long delay; public PingTask(String ping, PingHandler pingHandler, long delay) { this.ping = ping; this.pingHandler = pingHandler; this.delay = delay; } @Override public void run() { Process process = null; BufferedReader successReader = null; BufferedReader errorReader = null; try { process = Runtime.getRuntime().exec(ping); // success successReader = new BufferedReader(new InputStreamReader(process.getInputStream())); // error errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); String lineStr; while ((lineStr = successReader.readLine()) != null) { // receive Message msg = pingHandler.obtainMessage(); msg.obj = lineStr + "\r\n"; msg.what = 10; msg.sendToTarget(); } while ((lineStr = errorReader.readLine()) != null) { // receive Message msg = pingHandler.obtainMessage(); msg.obj = lineStr + "\r\n"; msg.what = 10; msg.sendToTarget(); } Thread.sleep(delay * 1000); } catch (Exception e) { e.printStackTrace(); } finally { try { if (successReader != null) { successReader.close(); } if (errorReader != null) { errorReader.close(); } } catch (IOException e) { e.printStackTrace(); } if (process != null) { process.destroy(); } } } } @Override public void onDestroy() { EventBus.getDefault().unregister(this); if (pingHandler != null) { pingHandler.removeCallbacksAndMessages(null); } if (executorService != null) { executorService.shutdownNow(); } super.onDestroy(); } @Subscribe(threadMode = ThreadMode.MAIN) public void handleData(CloseFloatingButtonEvent event){ viewGone(); } }
[ "wongkyunban" ]
wongkyunban
e42590fcf8335f29e6658ed20e8b9c14a1593579
ef36ad97355550ca4f948f6804dcaba1786e3451
/src/main/java/message/RequestSendFriendList.java
6ac18a7f4a76e1db33a9e595482e91fce2fd1817
[]
no_license
omerucel/bahir-server
7ec83219ea0488422814071952614af56d5f6435
f05948c5b27d9344271bae9321ad28e049a35920
refs/heads/master
2016-09-05T11:34:57.207304
2013-04-30T12:55:25
2013-04-30T12:55:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
279
java
package message; import socket.message.IRequest; public class RequestSendFriendList implements IRequest{ private String token; public RequestSendFriendList(String token) { this.token = token; } public String getToken() { return token; } }
[ "omerucel@gmail.com" ]
omerucel@gmail.com
ffcaa163a7b29d95e694e7e17f62bbff9a207d88
3116cce9a40edb4786c8f784197cae78dcfd4fe2
/app/src/main/java/com/cfish/rvb/adapter/SectionStateChangeListener.java
ae7b2eafae1179590dd5bd14b3134a3bafa5b7f9
[]
no_license
fishho/NKBBS
23640a0028ac0997873d10855c63a6d1495f334a
7f06140d6f10257003bd0a42f078fe53e6b12dbc
refs/heads/master
2020-05-21T12:26:08.963405
2017-01-05T12:56:22
2017-01-05T12:56:22
50,716,931
0
0
null
null
null
null
UTF-8
Java
false
false
224
java
package com.cfish.rvb.adapter; import com.cfish.rvb.bean.Section; /** * Created by dfish on 2016/11/19. */ public interface SectionStateChangeListener { void onSectionStateChanged(Section section, boolean isOpen); }
[ "2012chenjian@gmail.com" ]
2012chenjian@gmail.com
f275ff902679ee25f51c275d12b5569db49b4e34
9882a4f7630677a9c6734b1f65f073ab577bd4d1
/ChatUpperThread-Tugas-Solved/Server.java
5984be972d4fa34df2e06e7d2a0db9d42eb271d7
[]
no_license
yenisaragih/StrukturData-2015
2588aa28b9a44fc179f0199e1a5c502d112365d2
d55a9c72a70596cc0b9207e67a6d3a415599d476
refs/heads/master
2021-01-10T01:12:44.032768
2019-02-26T11:33:09
2019-02-26T11:33:09
45,236,338
0
0
null
null
null
null
UTF-8
Java
false
false
1,002
java
import java.net.Socket; import java.net.ServerSocket; import java.net.BindException; import java.net.InetAddress; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; public class Server { public Server() throws BindException, IOException { serverSocket = new ServerSocket(33333); } public void dengar() { while (true) { try { // Tunggu sampai ada koneksi dari client Socket koneksi = serverSocket.accept(); // Buat thread untuk proses ProcessClientThread satuProcess = new ProcessClientThread(koneksi); Thread satuProcessThread = new Thread(satuProcess); satuProcessThread.start(); } catch(IOException err) { System.out.println(err); } } } private ServerSocket serverSocket = null; }
[ "yeni.hanafiah@gmail.com" ]
yeni.hanafiah@gmail.com
c670e7a175449fb5674d238ba7a14d7c03b15f29
96f48ac6205128b1addf4dc08c9528692e23280f
/ChatConDes/src/Paquetes/Conversor64bits.java
5c0b7f82a8f4ac5e8d9918b27c9c9b6af600bf19
[ "MIT" ]
permissive
RubioHaro/ChatCifrado
e6d7dbcd4fa6c428beba3be84b48add565d34d86
81b683b3a7b247e35f57767feafada0afee99bce
refs/heads/master
2021-09-24T11:03:19.548562
2018-10-08T22:26:51
2018-10-08T22:26:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,413
java
package Paquetes; import java.math.BigInteger; import java.util.Arrays; /* * 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. */ /** * * @author Alumno */ public class Conversor64bits { public Conversor64bits() { } public String ConvertBinToHexa(char[] concatenacionFinal) { String Final = ""; for (int e = 0; e < 64;) { String Hexa = ""; for (int i = 0; i < 4; ++i) { Hexa = Hexa + concatenacionFinal[i + e]; } e = e + 4; Final = Final + new BigInteger(Hexa, 2).toString(16); } return Final; } public String ConvertToBin(String Cadenita) { if (validar(Cadenita)) { String bin = Binarizar(Cadenita); return bin; } else { return "Error"; } } public int StringToBinary(String numeroBinario) { int num = Integer.parseInt(numeroBinario, 2); return num; } public String Binarizar(String Cadenita) { //---------------*******----------------\\ //Desarmamos la cadena en un arreglo: int tamañoCadena = Cadenita.length(); char[] ArregloCadena = new char[tamañoCadena]; for (int i = 0; i < tamañoCadena; ++i) { ArregloCadena[i] = Cadenita.charAt(i); } //---------------*******----------------\\ int num = 0; String[] ArregloBinarios; ArregloBinarios = new String[tamañoCadena]; String BinFinal = ""; for (int i = 0; i < tamañoCadena; ++i) { num = Character.getNumericValue(ArregloCadena[i]); switch (Integer.toBinaryString(num).length()) { case 0: ArregloBinarios[i] = "0000"; break; case 1: ArregloBinarios[i] = "000" + Integer.toBinaryString(num); break; case 2: ArregloBinarios[i] = "00" + Integer.toBinaryString(num); break; case 3: ArregloBinarios[i] = "0" + Integer.toBinaryString(num); break; case 4: ArregloBinarios[i] = "" + Integer.toBinaryString(num); break; default: break; } BinFinal = BinFinal + ArregloBinarios[i]; } return BinFinal; } public String BinarizarCifrasDosDigitos(int numero) { String NumBin = Integer.toBinaryString(numero); String BinFinal = ""; switch (NumBin.length()) { case 1: BinFinal = "000" + NumBin; break; case 2: BinFinal = "00" + NumBin; break; case 3: BinFinal = "0" + NumBin; break; case 4: BinFinal = NumBin; break; default: break; } return BinFinal; } public boolean validar(String cadenita) { return !cadenita.equals(""); } }
[ "noreply@github.com" ]
RubioHaro.noreply@github.com
0c7fdd2232fe7c6201c6240fbeea9cd486a0b647
3c92bc03a7eec96b7eb7a077fbb48e3128434ed6
/CVRP-master/src/ga/core/evaluate/FitnessAndCost.java
c999c13e5427179b19c61013569f786480f5e546
[ "AFL-3.0" ]
permissive
sarja510/CVRP-master_2
98ca694cdb1dacc3783294ca6f173b68df070df1
b1bfffd95124059d116971cbd9349102b94fbb86
refs/heads/master
2020-04-17T23:45:50.038291
2016-08-17T19:02:21
2016-08-17T19:02:21
65,934,323
0
0
null
null
null
null
UTF-8
Java
false
false
326
java
package ga.core.evaluate; /** * @author Debanjan Bhattacharyya <b.debanjan@gmail.com> * This is the interface for computing fitness of a generic chromosome * Copyright 2013 Academic Free License 3.0 */ public interface FitnessAndCost<T> { double computeFitness(T chromosome); double computeActualCost(T chromosome); }
[ "asif.ahmed.sarja@gmail.com" ]
asif.ahmed.sarja@gmail.com
b21fea7d8ea4bc01ef60babbfb17460764d1d08a
dabe717d725be45e5df9c7dac930bb70ea1dbd69
/app/src/androidTest/java/com/mytaxi/android_demo/tests/LoginTest.java
9cc0b47a1e0b1de1891d579f7857029c6d6cbd7f
[]
no_license
kjayachandra2000/AndroidDemo
38d77474442a6cac1aacdcb0934aced7096101ec
629668a055314b69525ccf7a28b7467e9864d5f9
refs/heads/master
2020-03-06T21:45:38.932298
2018-04-06T18:40:36
2018-04-06T18:40:36
127,086,019
1
0
null
null
null
null
UTF-8
Java
false
false
911
java
package com.mytaxi.android_demo.tests; import com.mytaxi.android_demo.data.MemberType; import org.junit.Test; public class LoginTest extends BaseTest { @Test public void validUserTest() { loginSteps .GivenIAmLoggedInAs(MemberType.VALID_MEMBER) .ThenIAbleToLoginSuccessfully(); } @Test public void inValidUserNameTest() { loginSteps .GivenIAmLoggedInAs(MemberType.WRONG_USERNAME) .ThenISeeLoginFailureSnackBar(); } @Test public void inValidPasswordTest() { loginSteps .GivenIAmLoggedInAs(MemberType.WRONG_PASSWORD) .ThenISeeLoginFailureSnackBar(); } @Test public void inValidLoginDetailsTest() { loginSteps .GivenIAmLoggedInAs(MemberType.WRONG_USERNAMEANDPWD) .ThenISeeLoginFailureSnackBar(); } }
[ "jayachandra.kunapareddy@emirates.com" ]
jayachandra.kunapareddy@emirates.com
8ebb73acf7f24bf2d6395f42581d6c161e3def09
42a31fdce5d4f3547179e8fd662fc7c364e02dbd
/src/HW2/Task5.java
f418e6862545d6739555d99f26d9a2d921e67c9f
[]
no_license
YAUHENI1986/HomeWorkLesson2
34bb89d2b63ccd3505303ff3bf8df8b59d4c3510
6ccb1ada8e8bda8b1689c8812723fa2d63206675
refs/heads/master
2020-03-30T10:18:29.200038
2018-10-01T15:51:17
2018-10-01T15:51:17
151,114,714
0
0
null
null
null
null
MacCyrillic
Java
false
false
966
java
package HW2; import java.util.Scanner; // вывести число от 1 до k в виде матрицы NxN слева направо и сверхувниз public class Task5 { public static void main(String[] args) { Scanner scan = new Scanner (System.in); int x; System.out.println("¬ведите целое число от 1 до ..."); x = scan.nextInt(); int M[][]; int K = 0; // количество чисел int N = 1 ; // размер матрицы scan.close(); if (x>1) { for (int i = 0; i<x; i++) { K++; } } int z; do { N++; z = N*N; } while (z<K); M = new int [N][N]; int start = 1; for (int i = 0; i<N; i++) { for (int i2 = 0; i2<N; i2++) { if (start<=K) { M[i][i2] = start++; } } } for (int i = 0; i<N; i++) { for (int i2 = 0; i2<N; i2++) { System.out.print(M[i][i2]); } System.out.println(); } } }
[ "noreply@github.com" ]
YAUHENI1986.noreply@github.com
072d9d3e3c289d1b644b86a9a3d3867f64a65dd8
d85699f49e5ec543822cee3b2b28ae66bff4c702
/app/src/main/java/hr/mars/muzicow/Models/Event.java
3aa4ded962f452ac2d9b591a6daeef4b4f8a682d
[]
no_license
embalint/muzicow
a844c2a404f4eaa4aaf9a5a7606a36c9cb578c8d
da851098d68a562a07e870382a02756e741631c4
refs/heads/master
2021-01-22T08:23:47.253653
2015-12-28T17:02:22
2015-12-28T17:02:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,215
java
package hr.mars.muzicow.Models; /** * Created by mars on 24/12/15. */ public class Event { String _ID; String dj_ID; String name; String longitude; String latitude; String genre; String status; public String get_ID() { return _ID; } public void set_ID(String event_ID) { this._ID = _ID; } public String getDj_ID() { return dj_ID; } public void setDj_ID(String dj_ID) { this.dj_ID = dj_ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
[ "hrvoje.orejas@gmail.com" ]
hrvoje.orejas@gmail.com
0aa914896f77ea786cab52b6ffce5b4e4b93646b
cb1bd19efe1ada618fd508094c6750de11f8295f
/app/src/main/java/com/example/hp/myappmascotas/model/ConstructorMascotasInteractor.java
f4bd1b9d8cd6a19a9fb8ce370a990167266324e9
[]
no_license
liopalacios/MyAppMascotasRetrofit
7b7a8243f7c942e71febfe2f33c601ffb60daaa0
07cfbc0a97f47448b04ecdc795a058d1a9564a17
refs/heads/master
2020-03-08T07:55:20.245880
2018-04-04T04:40:25
2018-04-04T04:40:25
128,007,287
0
0
null
null
null
null
UTF-8
Java
false
false
133
java
package com.example.hp.myappmascotas.model; /** * Created by HP on 25/03/2018. */ public class ConstructorMascotasInteractor { }
[ "leyterpalacios@gmail.com" ]
leyterpalacios@gmail.com
7c8225e15217417399b512b61da84c39482f69c4
24926db34d626118845e2589ae657585f1e86bcd
/myFirstAppArtifactId/src/main/java/com/abolkog/springboot/tut/ErrorDetails.java
aa057dd1d82dc6ab7fcea1e4875f01acda0e0965
[]
no_license
brahim337/TestProject
0ee37a6816f5bebe9b9a6432917c208af24f54fb
30f749a52b030c870591adc95d54822c5766cbab
refs/heads/master
2020-07-15T07:36:58.320477
2019-09-01T12:21:27
2019-09-01T12:21:27
205,513,819
0
0
null
null
null
null
UTF-8
Java
false
false
685
java
package com.abolkog.springboot.tut; import java.util.Date; public class ErrorDetails { private String message; private String url; private Date timeStamp; public ErrorDetails() { timeStamp = new Date(); } public ErrorDetails(String message, String url) { this(); this.message = message; this.url = url; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } }
[ "br@br-Latitude-E5510" ]
br@br-Latitude-E5510
f568410ed2a720632f0a1e87532c78e120057f83
d96fcf7b58a57c4a34a15989481b08f96033484e
/src/main/java/spring/boot/starter/validate/code/properties/SmsCodeProperties.java
2eb05e4df8778ae6b6196aa9bdf02486929652f2
[]
no_license
m666666x/spring-boot-starter-validate-code
bc5d8a11f3796e706a6237d0cde4dabf62ed524b
bd487b38ffa5cb48be871860d27bb84546ad4872
refs/heads/master
2020-09-29T13:21:40.210177
2020-05-17T07:17:13
2020-05-17T07:17:13
227,045,908
0
0
null
null
null
null
UTF-8
Java
false
false
229
java
package spring.boot.starter.validate.code.properties; import lombok.Data; /** * @author zhailiang * */ @Data public class SmsCodeProperties { private int length = 6; private int expireIn = 600; private String url; }
[ "hu@qq.com" ]
hu@qq.com
eef18afeea1def3ba482c1a933a2e3c46973420e
da251beeafd33fcbd68d53474e817b3c1a02ce91
/src/main/java/com/websocket/WebsocketDemoApplication.java
39b8e7ce667d7f17b9342892d47897d24ee454c7
[]
no_license
wangzhuiqiang/websocket-demo
57ecb8e0ad3ecbaf56dc66668f3943da809f52ab
71bc2714b8ffe5e75ac18f5391417b931cef88fc
refs/heads/master
2022-04-18T02:19:54.160846
2020-04-20T17:04:47
2020-04-20T17:04:47
257,348,395
0
0
null
null
null
null
UTF-8
Java
false
false
332
java
package com.websocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebsocketDemoApplication { public static void main(String[] args) { SpringApplication.run(WebsocketDemoApplication.class, args); } }
[ "380540630@qq.com" ]
380540630@qq.com
cc15b1f1baea93aaacac61e1ac223734a153ca27
012a9614620f15cc008c194868c23740ba3587b5
/Youtufy/src/pl/javastart/youtufy/main/Youtube.java
8261210cdaabd6d233c16da96c9fc3179adb0009
[]
no_license
KCisak/YoutubeJavaFX
6a13d905e9f6a93f1818cb39f7450528c8421c95
46260755b1bed9ce3096860d675fdaebc0e515e5
refs/heads/master
2021-09-02T06:04:15.914807
2017-12-30T22:35:05
2017-12-30T22:35:05
115,451,656
0
0
null
null
null
null
UTF-8
Java
false
false
4,825
java
package pl.javastart.youtufy.main; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import pl.javastart.youtufy.data.YoutubeVideo; public class Youtube { private final String YOUTUBE_SEARCH_URL = "http://www.youtube.com/results"; private final String SEARCH_PARAMETER = "search_query"; private final String VIDEO_NODES = "div.yt-lockup-content"; private final String VIDEO_TITLE_URL = "a.yt-uix-tile-link.yt-ui-ellipsis.yt-ui-ellipsis-2.yt-uix-sessionlink.spf-link "; private final String VIDEO_AUTHOR = "a.yt-uix-sessionlink.spf-link.g-hovercard"; private ObservableList<YoutubeVideo> youtubeVideos; private StringProperty searchQuery; public ObservableList<YoutubeVideo> getYoutubeVideos() { return youtubeVideos; } public void setYoutubeVideos(ObservableList<YoutubeVideo> youtubeVideos) { this.youtubeVideos = youtubeVideos; } public StringProperty getSearchQuery() { return searchQuery; } public void setSearchQuery(StringProperty searchQuery) { this.searchQuery = searchQuery; } public Youtube() { youtubeVideos = FXCollections.observableArrayList(); searchQuery = new SimpleStringProperty(); } public void search() throws IOException { try { search(searchQuery.get()); } catch (IOException e) { throw e; } } private void search(String query) throws IOException { // pobieramy źródło strony String pageContent = getPageSource(query); // wyciągamy informacje o filmach Document doc = Jsoup.parse(pageContent); Elements videosNodes = doc.select(VIDEO_NODES); List<YoutubeVideo> videos = new ArrayList<>(); for (Element e : videosNodes) { Element titleUrlElement = e.select(VIDEO_TITLE_URL).first(); Element authorElement = e.select(VIDEO_AUTHOR).first(); String url = titleUrlElement.attr("href").replace("/watch?v=", ""); String title = titleUrlElement.text(); String author = authorElement.text(); if (url.contains("list") || url.contains("channel") || url.contains("user")) { continue; } else { YoutubeVideo yv = new YoutubeVideo(); yv.setId(url); yv.setTitle(title); yv.setAuthor(author); videos.add(yv); } } // usuwamy wszystkie obiekty z Observable List i dodajemy nowe wyniki // wyszukiwania youtubeVideos.clear(); youtubeVideos.addAll(videos); } private String getPageSource(String query) throws IOException { // Tworzymy adres URL zapytania URI searchUri = null; try { searchUri = new URIBuilder(YOUTUBE_SEARCH_URL).addParameter(SEARCH_PARAMETER, query).build(); } catch (URISyntaxException e) { System.err.println("Błąd przy budowaniu adresu URL"); } // tworzymy obiekty do wysłania żądania i odebrania odpowiedzi od // serwera CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet(searchUri); CloseableHttpResponse response = null; HttpEntity httpEntity = null; String pageContent = null; // pobieramy treść strony WWW try { response = httpClient.execute(request); httpEntity = response.getEntity(); pageContent = EntityUtils.toString(httpEntity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { response.close(); httpClient.close(); } // zwracamy źródło strony return pageContent; } }
[ "krzysiek.cisak@gmail.com" ]
krzysiek.cisak@gmail.com
cd9436f838faec1601aa7ff303cc51fd7247df60
62679f849b10e995932ce5b8cb8c36c9261689c1
/org.openntf.xsp.debugtoolbar/src/org/openntf/xsp/debugtoolbar/modules/FileInfo.java
32ab54010006673b05e5c6ff6ef2d51d96e2f85b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "CC-BY-3.0" ]
permissive
bryanchance/OpenNTF-DebugToolbar
300c72031a1997d5099fdc414ec70dfcd2197261
b19913d5afcb00f025a5539683ac25662e7623e8
refs/heads/master
2023-07-12T23:42:43.472495
2016-02-14T20:43:47
2016-02-14T20:43:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
package org.openntf.xsp.debugtoolbar.modules; import java.io.Serializable; //class to hold information about a file public class FileInfo implements Serializable, Comparable<Object> { private static final long serialVersionUID = -120581900512974320L; String name; Long modified; long size; public FileInfo(String name, long modified, long size) { this.name = name; this.modified = new Long(modified); this.size = size; } public String getName() { return name; } public Long getModified() { return modified; } public String getDescription() { return name + " (" + DebugToolbarUtils.getReadableSize(size) + ") "; } public int compareTo(Object argInfo) { return ((FileInfo) argInfo).getModified().compareTo(this.getModified()); } }
[ "m.leusink@gmail.com" ]
m.leusink@gmail.com
eca0dc6d8c91756591a897cdf9b3d0e380e7ffaf
bc4bf51cc41410d6e4483797f606e01cbb16aa38
/Vendor/NCBI eutils/src/gov/nih/nlm/ncbi/www/soap/eutils/efetch_gene/Value_type12.java
3c141f3b754ba150faeba82717b17e72ed1e1ff6
[ "BSD-2-Clause" ]
permissive
milot-mirdita/GeMuDB
088533f38c4093317c5802ed1babd05d5e39c944
336988a7e3baa29a4fcae0807353c12abc54143b
refs/heads/master
2020-05-07T12:25:38.592087
2014-05-12T21:23:28
2014-05-12T21:23:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
21,234
java
/** * Value_type12.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene; /** * Value_type12 bean class */ @SuppressWarnings({"unchecked","unused"}) public class Value_type12 implements org.apache.axis2.databinding.ADBBean{ public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName( "http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "value_type12", "ns1"); /** * field for Value_type12 */ protected java.lang.String localValue_type12 ; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected Value_type12(java.lang.String value, boolean isRegisterValue) { localValue_type12 = value; if (isRegisterValue){ _table_.put(localValue_type12, this); } } public static final java.lang.String _medline = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("medline"); public static final java.lang.String _pubmed = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("pubmed"); public static final java.lang.String _ncbigi = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("ncbigi"); public static final Value_type12 medline = new Value_type12(_medline,true); public static final Value_type12 pubmed = new Value_type12(_pubmed,true); public static final Value_type12 ncbigi = new Value_type12(_ncbigi,true); public java.lang.String getValue() { return localValue_type12;} public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return localValue_type12.toString(); } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME); return factory.createOMElement(dataSource,MY_QNAME); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it java.lang.String namespace = parentQName.getNamespaceURI(); java.lang.String _localName = parentQName.getLocalPart(); writeStartElement(null, namespace, _localName, xmlWriter); // add the type details if this is used in a simple type if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":value_type12", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "value_type12", xmlWriter); } } if (localValue_type12==null){ throw new org.apache.axis2.databinding.ADBException("value_type12 cannot be null !!"); }else{ xmlWriter.writeCharacters(localValue_type12); } xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(MY_QNAME, new java.lang.Object[]{ org.apache.axis2.databinding.utils.reader.ADBXMLStreamReader.ELEMENT_TEXT, org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localValue_type12) }, null); } /** * Factory class that keeps the parse method */ public static class Factory{ public static Value_type12 fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { Value_type12 enumeration = (Value_type12) _table_.get(value); if ((enumeration == null) && !((value == null) || (value.equals("")))) { throw new java.lang.IllegalArgumentException(); } return enumeration; } public static Value_type12 fromString(java.lang.String value,java.lang.String namespaceURI) throws java.lang.IllegalArgumentException { try { return fromValue(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(value)); } catch (java.lang.Exception e) { throw new java.lang.IllegalArgumentException(); } } public static Value_type12 fromString(javax.xml.stream.XMLStreamReader xmlStreamReader, java.lang.String content) { if (content.indexOf(":") > -1){ java.lang.String prefix = content.substring(0,content.indexOf(":")); java.lang.String namespaceUri = xmlStreamReader.getNamespaceContext().getNamespaceURI(prefix); return Value_type12.Factory.fromString(content,namespaceUri); } else { return Value_type12.Factory.fromString(content,""); } } /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static Value_type12 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ Value_type12 object = null; // initialize a hash map to keep values java.util.Map attributeMap = new java.util.HashMap(); java.util.List extraAttributeList = new java.util.ArrayList<org.apache.axiom.om.OMAttribute>(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); while(!reader.isEndElement()) { if (reader.isStartElement() || reader.hasText()){ nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)){ throw new org.apache.axis2.databinding.ADBException("The element: "+"value_type12" +" cannot be null"); } java.lang.String content = reader.getElementText(); if (content.indexOf(":") > 0) { // this seems to be a Qname so find the namespace and send prefix = content.substring(0, content.indexOf(":")); namespaceuri = reader.getNamespaceURI(prefix); object = Value_type12.Factory.fromString(content,namespaceuri); } else { // this seems to be not a qname send and empty namespace incase of it is // check is done in fromString method object = Value_type12.Factory.fromString(content,""); } } else { reader.next(); } } // end of while loop } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
[ "root@proteinsuite.com" ]
root@proteinsuite.com
977555f7a0139d16c52cdb8fb19cfabf372451fc
e8396de27b067a05a2e7571b6551a33f14de7a64
/src/main/java/com/sample/FindLargeNumberApplication.java
3a2ac56b32b122964e3915f847945647bdb816ff
[]
no_license
pnabee/SpringBoot_Projects
dcf6a80ad77bf82ba44d282f4a8ac8bc706280fa
f6d232277a50373a3a90eeeb6b09dd60e71ca37a
refs/heads/master
2023-03-31T21:22:18.892997
2021-04-07T10:35:48
2021-04-07T10:35:48
355,466,608
0
0
null
null
null
null
UTF-8
Java
false
false
321
java
package com.sample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FindLargeNumberApplication { public static void main(String[] args) { SpringApplication.run(FindLargeNumberApplication.class, args); } }
[ "umamaheswari@umas-MacBook-Pro.local" ]
umamaheswari@umas-MacBook-Pro.local
651f4a0e81818db02846a68a2e7b04c3592bd646
7e654327913e8d7b79f685b0632ccca67aaf7b81
/app/src/main/java/com/example/halfchess/Bishop.java
4b0fbabdca68c307ed1cb696cc61a61940d99983
[]
no_license
Yocucuuu/AI_Project
864130a4287f3ad240079fc7b7d6a9057bc7a985
7d1a4ee2b9be59118411cad89b7fce3b991279d8
refs/heads/main
2023-02-27T06:26:49.354327
2021-02-01T12:33:20
2021-02-01T12:33:20
334,943,468
0
0
null
null
null
null
UTF-8
Java
false
false
151
java
package com.example.halfchess; public class Bishop extends Bidak { public Bishop(int value, boolean white) { super(value, white); } }
[ "44639176+Yocucuuu@users.noreply.github.com" ]
44639176+Yocucuuu@users.noreply.github.com
939c4b23b138ac9b1a01fda9f700d79340cc6692
b1b3c1b47ceb5ac9ad4a0621c37b6d92fe75b509
/executor/src/main/java/io/shinto/amaterasu/executor/execution/actions/runners/spark/PySpark/PySparkEntryPoint.java
6531c4d61c75e12d3046365806756c3dd93ef3e5
[]
no_license
roadan/amaterasu
be070fc0aa63a2b7492f1238b00f69d62b3832bf
12cb3587cc6416cf81ae69a72117ec9bbdbdc818
refs/heads/master
2021-01-20T18:40:13.820303
2017-06-27T01:56:30
2017-06-27T01:56:30
46,103,964
0
1
null
2016-03-03T23:25:03
2015-11-13T06:21:24
Scala
UTF-8
Java
false
false
2,624
java
package io.shinto.amaterasu.executor.execution.actions.runners.spark.PySpark; import io.shinto.amaterasu.executor.runtime.AmaContext; import io.shinto.amaterasu.common.runtime.Environment; import org.apache.spark.SparkEnv; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.SQLContext; import org.apache.spark.SparkConf; import org.apache.spark.SparkContext; import org.apache.spark.sql.SparkSession; import py4j.GatewayServer; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.ConcurrentHashMap; public class PySparkEntryPoint { //private static Boolean started = false; private static PySparkExecutionQueue queue = new PySparkExecutionQueue(); private static ConcurrentHashMap<String, ResultQueue> resultQueues = new ConcurrentHashMap<>(); private static int port = 0; private static SparkSession sparkSession = null; private static JavaSparkContext jsc = null; private static SQLContext sqlContext = null; private static SparkEnv sparkEnv = null; public static PySparkExecutionQueue getExecutionQueue() { return queue; } public static ResultQueue getResultQueue(String actionName) { resultQueues.putIfAbsent(actionName, new ResultQueue()); return resultQueues.get(actionName); } public static JavaSparkContext getJavaSparkContext() { SparkEnv.set(sparkEnv); return jsc; } public static SQLContext getSqlContext() { SparkEnv.set(sparkEnv); return sqlContext; } public static SparkSession getSparkSession() { SparkEnv.set(sparkEnv); return sparkSession; } public static SparkConf getSparkConf() { return jsc.getConf(); } private static void generatePort() { try { ServerSocket socket = new ServerSocket(0); port = socket.getLocalPort(); socket.close(); } catch (IOException e) { } } public static int getPort() { return port; } public static void start(SparkSession spark, String jobName, Environment env, SparkEnv sparkEnv) { AmaContext.init(spark, jobName, env); sparkSession = spark; jsc = new JavaSparkContext(spark.sparkContext()); sqlContext = spark.sqlContext(); PySparkEntryPoint.sparkEnv = sparkEnv; generatePort(); GatewayServer gatewayServer = new GatewayServer(new PySparkEntryPoint(), port); gatewayServer.start(); } }
[ "roadan@gmail.com" ]
roadan@gmail.com
3a4792bcae74da26902bad819fb19cb62c362085
6ecf92848504e187bae5b52f25dec0aa8a091492
/showbt_mysql/src/main/java/org/b3log/solo/model/Preference.java
67fc8851f5fe01cc7dbee0a3980673ba30303d8b
[]
no_license
iceelor/showbt_film
343359523e4c90c3dd494611aab78c1aa838b296
9fd83108f011c064bc9045387948907b02f493cc
refs/heads/master
2021-01-04T02:35:04.480518
2013-07-10T09:04:44
2013-07-10T09:04:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,513
java
/* * Copyright (c) 2009, 2010, 2011, 2012, 2013, B3log Team * * 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.b3log.solo.model; import java.util.logging.Level; import java.util.logging.Logger; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.RuntimeEnv; import org.json.JSONArray; import org.json.JSONObject; /** * This class defines all comment model relevant keys. * * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @version 1.1.0.8, Mar 5, 2013 * @since 0.3.1 */ public final class Preference { /** * Preference. */ public static final String PREFERENCE = "preference"; /** * Blog title. */ public static final String BLOG_TITLE = "blogTitle"; /** * Blog subtitle. */ public static final String BLOG_SUBTITLE = "blogSubtitle"; /** * Relevant articles display count. */ public static final String RELEVANT_ARTICLES_DISPLAY_CNT = "relevantArticlesDisplayCount"; /** * Random articles display count. */ public static final String RANDOM_ARTICLES_DISPLAY_CNT = "randomArticlesDisplayCount"; /** * External relevant articles display count. */ public static final String EXTERNAL_RELEVANT_ARTICLES_DISPLAY_CNT = "externalRelevantArticlesDisplayCount"; /** * Recent article display count. */ public static final String RECENT_ARTICLE_DISPLAY_CNT = "recentArticleDisplayCount"; /** * Recent comment display count. */ public static final String RECENT_COMMENT_DISPLAY_CNT = "recentCommentDisplayCount"; /** * Most used tag display count. */ public static final String MOST_USED_TAG_DISPLAY_CNT = "mostUsedTagDisplayCount"; /** * Most comment article display count. */ public static final String MOST_COMMENT_ARTICLE_DISPLAY_CNT = "mostCommentArticleDisplayCount"; /** * Most view article display count. */ public static final String MOST_VIEW_ARTICLE_DISPLAY_CNT = "mostViewArticleDisplayCount"; /** * Article list display count. */ public static final String ARTICLE_LIST_DISPLAY_COUNT = "articleListDisplayCount"; /** * Article list pagination window size. */ public static final String ARTICLE_LIST_PAGINATION_WINDOW_SIZE = "articleListPaginationWindowSize"; /** * Blog host. */ public static final String BLOG_HOST = "blogHost"; /** * Administrator's email. */ public static final String ADMIN_EMAIL = "adminEmail"; /** * Locale string. */ public static final String LOCALE_STRING = "localeString"; /** * Time zone id. */ public static final String TIME_ZONE_ID = "timeZoneId"; /** * Notice board. */ public static final String NOTICE_BOARD = "noticeBoard"; /** * HTML head. */ public static final String HTML_HEAD = "htmlHead"; /** * Key of meta keywords. */ public static final String META_KEYWORDS = "metaKeywords"; /** * Key of meta description. */ public static final String META_DESCRIPTION = "metaDescription"; /** * Key of article update hint flag. */ public static final String ENABLE_ARTICLE_UPDATE_HINT = "enableArticleUpdateHint"; /** * Key of signs. */ public static final String SIGNS = "signs"; /** * Key of key of Solo. */ public static final String KEY_OF_SOLO = "keyOfSolo"; /** * Key of page cache enabled. */ public static final String PAGE_CACHE_ENABLED = "pageCacheEnabled"; /** * Key of allow visit draft via permalink. */ public static final String ALLOW_VISIT_DRAFT_VIA_PERMALINK = "allowVisitDraftViaPermalink"; /** * Key of version. */ public static final String VERSION = "version"; /** * Key of article list display style. * * <p> * Optional values: * <ul> * <li>"titleOnly"</li> * <li>"titleAndContent"</li> * <li>"titleAndAbstract"</li> * </ul> * </p> */ public static final String ARTICLE_LIST_STYLE = "articleListStyle"; /** * Key of reply notification template. */ public static final String REPLY_NOTIFICATION_TEMPLATE = "replyNotificationTemplate"; /** * Key of article/page comment-able. */ public static final String COMMENTABLE = "commentable"; /** * Key of feed (Atom/RSS) output mode. * * <p> * Optional values: * <ul> * <li>"abstract"</li> * <li>"fullContent"</li> * </ul> * </p> */ public static final String FEED_OUTPUT_MODE = "feedOutputMode"; /** * Key of feed (Atom/RSS) output entry count. */ public static final String FEED_OUTPUT_CNT = "feedOutputCnt"; /** * Key of editor type. * * Optional values: * <p> * <ul> * <li>"tinyMCE"</li> * <li>"CodeMirror-Markdown"</li> * </ul> * </p> */ public static final String EDITOR_TYPE = "editorType"; /** * Private default constructor. */ private Preference() {} /** * Default preference. * * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @version 1.1.0.8, Sep 18, 2012 * @since 0.3.1 */ public static final class Default { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Default.class.getName()); /** * Default recent article display count. */ public static final int DEFAULT_RECENT_ARTICLE_DISPLAY_COUNT = 10; /** * Default recent comment display count. */ public static final int DEFAULT_RECENT_COMMENT_DISPLAY_COUNT = 10; /** * Default most used tag display count. */ public static final int DEFAULT_MOST_USED_TAG_DISPLAY_COUNT = 20; /** * Default article list display count. */ public static final int DEFAULT_ARTICLE_LIST_DISPLAY_COUNT = 20; /** * Default article list pagination window size. */ public static final int DEFAULT_ARTICLE_LIST_PAGINATION_WINDOW_SIZE = 15; /** * Default most comment article display count. */ public static final int DEFAULT_MOST_COMMENT_ARTICLE_DISPLAY_COUNT = 5; /** * Default blog title. */ public static final String DEFAULT_BLOG_TITLE = "B3log Solo 示例"; /** * Default blog subtitle. */ public static final String DEFAULT_BLOG_SUBTITLE = "Java 开源博客"; /** * Default skin directory name. */ public static final String DEFAULT_SKIN_DIR_NAME = "ease"; /** * Default language. */ public static final String DEFAULT_LANGUAGE = "zh_CN"; /** * Default time zone. * * @see java.util.TimeZone#getAvailableIDs() */ public static final String DEFAULT_TIME_ZONE = "Asia/Shanghai"; /** * Default enable article update hint. */ public static final boolean DEFAULT_ENABLE_ARTICLE_UPDATE_HINT = true; /** * Default enable post to Tencent microblog. */ public static final boolean DEFAULT_ENABLE_POST_TO_TENCENT_MICROBLOG = false; /** * Default notice board. */ public static final String DEFAULT_NOTICE_BOARD = "Open Source, Open Mind, <br/>Open Sight, Open Future!"; /** * Default meta keywords.. */ public static final String DEFAULT_META_KEYWORDS = "Java 博客,GAE,b3log"; /** * Default meta description.. */ public static final String DEFAULT_META_DESCRIPTION = "An open source blog with Java. Java 开源博客"; /** * Default HTML head to append. */ public static final String DEFAULT_HTML_HEAD = ""; /** * Default relevant articles display count. */ public static final int DEFAULT_RELEVANT_ARTICLES_DISPLAY_COUNT = 5; /** * Default random articles display count. */ public static final int DEFAULT_RANDOM_ARTICLES_DISPLAY_COUNT = 5; /** * Default external relevant articles display count. */ public static final int DEFAULT_EXTERNAL_RELEVANT_ARTICLES_DISPLAY_COUNT = 5; /** * Most view articles display count. */ public static final int DEFAULT_MOST_VIEW_ARTICLES_DISPLAY_COUNT = 5; /** * Default signs. */ public static final String DEFAULT_SIGNS; /** * Default page cache enabled. */ public static final boolean DEFAULT_PAGE_CACHE_ENABLED; /** * Default allow visit draft via permalink. */ public static final boolean DEFAULT_ALLOW_VISIT_DRAFT_VIA_PERMALINK = false; /** * Default allow comment article/page. */ public static final boolean DEFAULT_COMMENTABLE = true; /** * Default administrator's password. */ public static final String DEFAULT_ADMIN_PWD = "111111"; /** * Default article list display style. */ public static final String DEFAULT_ARTICLE_LIST_STYLE = "titleAndAbstract"; /** * Default key of solo. */ public static final String DEFAULT_KEY_OF_SOLO = "Your key"; /** * Default reply notification template. */ public static final String DEFAULT_REPLY_NOTIFICATION_TEMPLATE; /** * Default feed output mode. */ public static final String DEFAULT_FEED_OUTPUT_MODE = "abstract"; /** * Default feed output entry count. */ public static final int DEFAULT_FEED_OUTPUT_CNT = 10; /** * Default editor type. */ public static final String DEFAULT_EDITOR_TYPE = "tinyMCE"; static { final JSONArray signs = new JSONArray(); final int signLength = 4; try { for (int i = 0; i < signLength; i++) { final JSONObject sign = new JSONObject(); sign.put(Keys.OBJECT_ID, i); signs.put(sign); sign.put(Sign.SIGN_HTML, ""); } // Sign(id=0) is the 'empty' sign, used for article user needn't // a sign DEFAULT_SIGNS = signs.toString(); final JSONObject replyNotificationTemplate = new JSONObject(); replyNotificationTemplate.put(Keys.OBJECT_ID, Preference.REPLY_NOTIFICATION_TEMPLATE); replyNotificationTemplate.put("subject", "${blogTitle}: New reply of your comment"); replyNotificationTemplate.put("body", "Your comment on post[<a href='${postLink}'>" + "${postTitle}</a>] received an reply: <p>${replier}" + ": <span><a href='${replyURL}'>${replyContent}</a></span></p>"); DEFAULT_REPLY_NOTIFICATION_TEMPLATE = replyNotificationTemplate.toString(); if (RuntimeEnv.BAE == Latkes.getRuntimeEnv()) { DEFAULT_PAGE_CACHE_ENABLED = false; // https://github.com/b3log/b3log-solo/issues/73 } else { DEFAULT_PAGE_CACHE_ENABLED = true; } } catch (final Exception e) { LOGGER.log(Level.SEVERE, "Creates sign error!", e); throw new IllegalStateException(e); } } /** * Private default constructor. */ private Default() {} } }
[ "Ronny@Ronny-PC" ]
Ronny@Ronny-PC
d00fbefd0d5b4113e4b7a3c34c55bf140d6a6c08
cb17a0b6a97a90fb457e21a63b7b480b8cbc21db
/Demo/BehaviorType/Observer/src/PopularObserver.java
e4dbc19682fe620f382993d0304343437de55b71
[]
no_license
ZJdiem/DesignPattern
9a46309de374d888e297d8bf151f90c8f2e85424
cf46c93413e1c89bb038954d40ed7a50016314b2
refs/heads/master
2022-12-24T21:26:21.267699
2019-11-06T04:53:12
2019-11-06T04:53:12
219,914,628
0
0
null
2022-12-16T03:25:32
2019-11-06T04:52:30
Java
UTF-8
Java
false
false
168
java
public class PopularObserver implements MyObserver { @Override public void update(String str) { System.out.println("他们在说["+str+"]哎"); } }
[ "320647879@qq.com" ]
320647879@qq.com
c6ad5e0baab0eb46f21533a093fa071967ad476a
d06df2555c0b6f1378429332cd05f0bf74d5dedd
/java_summary_base/src/main/java/com/holmes/learn/http/Test.java
ad192f3e573692fc4e1fd50799f0aae06802d5c2
[]
no_license
chenyexin2012/java_summary
96eb476845516328b944d46407497f2b0f13e5f9
82752e002760555351f6d34934b88c9c10bc7447
refs/heads/master
2022-12-24T18:05:34.349698
2020-08-08T07:36:58
2020-08-08T07:36:58
152,171,755
3
1
null
2022-12-16T04:38:18
2018-10-09T01:54:51
Java
UTF-8
Java
false
false
207
java
package com.holmes.learn.http; //import javax.servlet.http.HttpServletRequest; public class Test { public static void main(String[] args) { // HttpServletRequest httpServletRequest = null; } }
[ "chenyexin2012@126.com" ]
chenyexin2012@126.com
d45c14f5c59a5923c4736a440aa7494c0d0466ce
d822c756e33d6caadfc5f5c0112ee16ae833f2ff
/observer-pattern/src/main/java/com/allen/pattern/update/StatisticsDisplay.java
adc4f0c8d95788c4ad5ec4ad99191bb5f705d540
[]
no_license
lgf-Allen/java-design-pattern
3bf60b975766f6c5d490a8ab0544e3b67b9d2762
f30a983d0a9fd761c0d5aa8081db08085c4fb989
refs/heads/master
2020-03-26T23:56:53.811761
2018-11-25T13:38:55
2018-11-25T13:38:55
145,580,276
1
0
null
null
null
null
UTF-8
Java
false
false
823
java
package com.allen.pattern.update; import com.allen.pattern.update.observer.Observer; import com.allen.pattern.update.subject.Subject; /** * Created by meng on 2018/11/21. */ public class StatisticsDisplay implements Observer, DisplayElement { //温度 private float temperature; //湿度 private float humdity; //气压 private float pressure; private Subject weatherData; public StatisticsDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.registryObserver(this); } @Override public void update(float temperature, float humdity, float pressure) { this.temperature = temperature; this.humdity = humdity; this.pressure = pressure; display(); } @Override public void display() { } }
[ "15829927394@163.com" ]
15829927394@163.com
87ef155858231aef0e0e4659ceaed7925bdfca73
9906f4071295e6eb0638df2ebfd357bc1a31d20b
/Lab1/src/Lab1/intTurn.java
e997aaa8ede6f5ba92fadee5b5d79665f2c6f099
[]
no_license
KirillYavorski/TRSPO
1f51c4dec19066ea57f06fd69037aae18ecbb398
4eb55b064443f91bca7d5f59357fdee235da094c
refs/heads/master
2021-08-19T20:15:40.915617
2017-11-27T10:32:51
2017-11-27T10:32:51
105,697,468
0
0
null
null
null
null
UTF-8
Java
false
false
142
java
package Lab1; /** * Created by Dmitry on 22.09.2017. */ public interface intTurn { void place(int el);//место int goOut(); }
[ "32305868+KirillYavorski@users.noreply.github.com" ]
32305868+KirillYavorski@users.noreply.github.com
029b2964e29807162ff7f1fcb5cf8c7e5157fa5d
075a81efe1bc515af7964ce4268446bcc74d82ea
/2주차/WritingNews.java
c118886dc61773e61ec1ff0ccdb10cfc4d43d7bd
[]
no_license
wookoo/Java-Study
c2b0f1ea4d950629c025fafbaab63e0ac1268aa1
47c4f71820ca6bfc0591f12b6dbc789854e03f0c
refs/heads/master
2020-05-05T03:16:09.357825
2019-05-30T12:49:32
2019-05-30T12:49:32
179,666,192
1
0
null
null
null
null
UHC
Java
false
false
2,060
java
import java.util.Scanner; public class WritingNews { //뉴스를 작성하는 클래스 public static void main(String[] args) { Scanner scan = new Scanner(System.in); //Scanner Class 를 가져와서 scan 객체 생성 System.out.print("경기장은 어디입니까 ? : "); String Ground = scan.nextLine(); //scan 객체의 nextLine 메소드를 사용하여 한줄(String)을 입력받는다. //그 값을 Ground 에 저장한다 System.out.print("이긴팀은 어디입니까 ? : "); String Winner = scan.nextLine();//scan 객체의 nextLine 메소드를 사용하여 한줄(String)을 입력받는다. //그 값을 Winner 에 저장한다. System.out.print("진 팀은 어디입니까 ? : "); String Loser = scan.nextLine(); //scan 객체의 nextLine 메소드를 사용하여 한줄(String)을 입력받는다. //그 값을 Loser 에 저장한다. System.out.print("우수선수는 누구입니까 ? : "); String MVP = scan.nextLine();//scan 객체의 nextLine 메소드를 사용하여 한줄(String)을 입력받는다. //그 값을 MVP 에 저장한다. System.out.print("스코어는 몇대몇 입니까? : "); String Score = scan.nextLine(); //scan 객체의 nextLine 메소드를 사용하여 한줄(String)을 입력받는다. //그 값을 Score 에 저장한다. System.out.println("==============================="); System.out.println(String.format("오늘 %s 에서 야구 경기가 열렸습니다", Ground)); //문자열 포맷팅을 사용하여 장소 출력 System.out.println(String.format("%s 과 %s 은 치열한 공방전을 펼쳤습니다.", Winner, Loser)); //문자열 포맷팅을 사용하여 승자 패자 출력 System.out.println(String.format("%s 이 맹활약을 하였습니다", MVP)); //문자열 포맷팅을 사용하여 MVP 출력 System.out.println(String.format("결국 %s 가 %s 를 %s 로 이겼습니다.", Winner, Loser, Score)); //문자열 포맷팅을 사용하여 승자 패자 스코어 출력 System.out.print("==============================="); } }
[ "nanayagoon@daum.net" ]
nanayagoon@daum.net
2f48066f54815c2e13f5053bee46055c782041b4
7ab64dd8a4405031ef5e08d6347cc37d4bf88eed
/rmi-server/src/main/java/com/xiepanpan/rmi/rpc/LBServerDemo.java
4e4ac3d0e85bbc872f747bdf0f64c305e16fb8e7
[]
no_license
xiepanpan/rmi
94c605e20799f5fcdc40748013d3810c25034217
84d02c463fbd3e382cd11e5b9c497b552c203897
refs/heads/master
2022-12-25T03:14:36.115878
2020-07-08T06:25:11
2020-07-08T06:25:11
277,601,542
0
0
null
2020-10-13T23:23:14
2020-07-06T17:05:26
Java
UTF-8
Java
false
false
631
java
package com.xiepanpan.rmi.rpc; import com.xiepanpan.rmi.rpc.zk.IRegisterCenter; import com.xiepanpan.rmi.rpc.zk.RegisterCenterImpl; import java.io.IOException; /** * @author: xiepanpan * @Date: 2020/7/8 * @Description: 模拟负载均衡1 */ public class LBServerDemo { public static void main(String[] args) throws IOException { IXpHello iXpHello = new XpHelloImpl(); IRegisterCenter registerCenter = new RegisterCenterImpl(); RpcServer rpcServer = new RpcServer(registerCenter,"127.0.0.1:8081"); rpcServer.bind(iXpHello); rpcServer.publish(); System.in.read(); } }
[ "xiepanpan@thunisoft.com" ]
xiepanpan@thunisoft.com
136a9296c09e7e7420fc8f212c653bbb78ef7bcd
e19e1cbe07bb8edec6cff72cfce8744593ef91eb
/src/codingBat/ap1/matchUp/Solution.java
ee7586c7b41242f735d7145e131a61e3d6e1cd14
[]
no_license
remaingood/Homework
b7af4f8e15cba704331926a998369b6c3c91c2d0
d40ad11a40b57031448ba1abc56fa102263d77ec
refs/heads/master
2021-03-27T16:35:25.766711
2018-01-26T15:28:55
2018-01-26T15:28:55
112,109,352
0
0
null
null
null
null
UTF-8
Java
false
false
655
java
package codingBat.ap1.matchUp; /* Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty and start with the same char. The strings may be any length, including 0 */ public class Solution { public int matchUp(String[] a, String[] b) { int count = 0; for(int i = 0; i < a.length; i++) { if(a[i].length() > 0 && b[i].length() > 0 && a[i].charAt(0) == b[i].charAt(0)) count++; } return count; } }
[ "john1kramer@mail.ru" ]
john1kramer@mail.ru
b2a37e5513954854c10cccd18630ba32df2d8867
9e623bcc7120e261b2884f5f29eecbd82e276f41
/ly-item/ly-item-service/src/main/java/com/leyou/item/mapper/CategoryMapper.java
a798eda2ef065ee57ceb651ad7db67051e41f7df
[]
no_license
Ninedayssss/leyou
b0e0c15adb296d1be052707e94a818e73f86cdb5
4200383d1966d87415d81304ea495eedd502585b
refs/heads/master
2020-05-23T14:43:47.825479
2019-05-15T11:46:21
2019-05-15T11:46:21
186,810,687
0
0
null
null
null
null
UTF-8
Java
false
false
311
java
package com.leyou.item.mapper; import com.leyou.item.pojo.Category; import tk.mybatis.mapper.additional.idlist.IdListMapper; import tk.mybatis.mapper.common.Mapper; /** * @author itsNine * @create 2019-03-29 9:29 */ public interface CategoryMapper extends Mapper<Category>, IdListMapper<Category,Long> { }
[ "boliviasx@163.com" ]
boliviasx@163.com
6eff806e239adb62c2dac3432361a026475d08f0
755a5432e9b53191a8941591f560e7a4fc28b1a0
/java-project2-server/src19/main/java/com/eomcs/lms/handler/LessonAddCommand.java
6dcf9df1817bbd3fb7182f1be4f203791f046fb3
[]
no_license
SeungWanWoo/bitcamp-java-2018-12
4cff763ddab52721f24ce8abcebcec998dacc9e3
d14a8a935ef7a4d24eb633fedea892378e59168d
refs/heads/master
2021-08-06T22:11:24.954160
2019-08-06T08:17:07
2019-08-06T08:17:07
163,650,664
0
0
null
2020-04-30T03:39:17
2018-12-31T08:00:39
Java
UTF-8
Java
false
false
937
java
package com.eomcs.lms.handler; import com.eomcs.lms.context.Component; import com.eomcs.lms.dao.LessonDao; import com.eomcs.lms.domain.Lesson; @Component("/lesson/add") public class LessonAddCommand extends AbstractCommand { LessonDao lessonDao; public LessonAddCommand(LessonDao lessonDao) { this.lessonDao = lessonDao; } @Override public void execute(Response response) throws Exception { Lesson lesson = new Lesson(); lesson.setTitle(response.requestString("수업명? ")); lesson.setContents(response.requestString("설명? ")); lesson.setStartDate(response.requestDate("시작일? ")); lesson.setEndDate(response.requestDate("종료일? ")); lesson.setTotalHours(response.requestInt("총수업시간? ")); lesson.setDayHours(response.requestInt("일수업시간? ")); lessonDao.insert(lesson); response.println("저장하였습니다."); } }
[ "seungwan.woo94@gmail.com" ]
seungwan.woo94@gmail.com
cb8d93c473bb43fba19c149aa2c281c7153df79e
2a35927da6b9355d5c81b894b752717dd9fb875e
/java/ar/edu/utn/d2s/me/UsuarioTest.java
c8b80dd7c1204a2ad2b98a72ba4f949b3dc6daac
[]
no_license
danielchungara1/gestionDietas
92947984b01f7fa1a88d20c3006a2e3ff6677c7d
49104d0e3c003b42de9b477cd4ac21f6f1b6e921
refs/heads/master
2016-08-11T13:44:30.110480
2015-11-25T16:16:56
2015-11-25T16:16:56
46,883,784
0
0
null
null
null
null
UTF-8
Java
false
false
2,183
java
package ar.edu.utn.d2s.me; import static org.junit.Assert.*; import org.joda.time.LocalDate; import org.junit.Before; import org.junit.Test; import ar.edu.ut.d2s.exceptions.UsuarioInvalidoException; public class UsuarioTest { RepositorioUsuarios repositorioUsuarios = new RepositorioUsuarios(); Usuario usuarioValido = new Usuario(); @Before public void setUp() throws Exception{ usuarioValido.setMail("mailValido@gmail.com"); usuarioValido.setNombre("usuarioValido"); usuarioValido.setFechaNacimiento(new LocalDate(1989, 5, 26)); usuarioValido.agregarPreferencia("preferencia 1"); repositorioUsuarios.agregarUsuario(usuarioValido); } //Que no haya 2 usuarios con el mismo e-mail (vamos a tomar que el nombre de usuario es el e-mail) @Test(expected = UsuarioInvalidoException.class) public void testAgregarUsuarioExistente() throws UsuarioInvalidoException{ Usuario usuarioRepetido = new Usuario(); usuarioRepetido.setMail("mailValido@gmail.com");// 2 usuarios son iguales cuando tienen el mismo mail repositorioUsuarios.agregarUsuario(usuarioRepetido); } //Nombre asumo que debe ser distinto de NULL @Test(expected = UsuarioInvalidoException.class) public void testAgregarUsuarioConNombreNull() throws UsuarioInvalidoException{ Usuario usuarioConNombreInvalido = new Usuario(); usuarioConNombreInvalido.setMail("usuarioConNombreInvalido"); usuarioConNombreInvalido.setNombre(null); repositorioUsuarios.agregarUsuario(usuarioConNombreInvalido); } //Edad (>18) @Test(expected = UsuarioInvalidoException.class) public void testAgregarUsuarioMenorDeEdad() throws UsuarioInvalidoException{ Usuario usuarioMenorDeEdad = new Usuario(); usuarioMenorDeEdad.setMail("usuarioMenorDeEdad"); usuarioMenorDeEdad.setNombre("usuarioMenorDeEdad"); usuarioMenorDeEdad.setFechaNacimiento(new LocalDate(2000, 7, 5)); repositorioUsuarios.agregarUsuario(usuarioMenorDeEdad); } //Si se agrega una preferencia que ya estaba no debe tener efecto @Test public void testAgregarPreferenciaDeUsuario(){ assertFalse (usuarioValido.agregarPreferencia("preferencia 1")); } }
[ "danielchungara89@gmail.com" ]
danielchungara89@gmail.com
ea301993bc4741e656d352267166a4123a35f61c
ad99a913cca71d1e0bb94854ad51cfb206eec86a
/src/main/java/jp/powerbase/xquery/builder/TupleSingle.java
d7fa81c1a36e3dd94213b3e1fcc902457dcc6bb0
[ "Apache-2.0" ]
permissive
powerbase/powerbase-xq
d417f0aca46ff17a9fd8c1722ffcc11fed679f38
6fbb1c187eaf3c2e978ee01c01adee80746cc519
refs/heads/master
2021-01-23T12:22:09.616590
2017-05-29T10:27:47
2017-05-29T10:27:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,566
java
/* * @(#)$Id: TupleSingle.java 1178 2011-07-22 10:16:56Z hirai $ * * Copyright 2005-2011 Infinite Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Toshio HIRAI - initial implementation */ package jp.powerbase.xquery.builder; import jp.powerbase.PowerBaseException; import jp.powerbase.constant.PowerBaseAttribute; import jp.powerbase.precompile.Parser; import jp.powerbase.request.context.RequestContext; import jp.powerbase.xquery.expr.Where; public class TupleSingle extends Tuple { public TupleSingle(RequestContext ctx) { super(ctx); } @Override public void buildXPath() throws PowerBaseException { _xpath = ""; } @Override public void buildOrderBy() throws PowerBaseException { _order = ""; } @Override public void buildWhere() throws PowerBaseException { Where w = new Where(Parser.PREFIX + "/@" + PowerBaseAttribute.ID + " = " + ctx.getNodeID()); // Where w = new Where(Parser.PREFIX + "/@" + PowerBaseAttribute.ID + // " = " + ctx.getTupleID()); _where = w.toString(); } }
[ "toshio.hirai@gmail.com" ]
toshio.hirai@gmail.com
dd083b88eb20a3671733af5ca5826fbd276f8e58
de8115ea16e124352a56da3c4185018affcb6903
/app/src/main/java/com/yousufsohail/ghostcontactbook/dal/DaoMaster.java
58d693b6b174ac69361ef862f5125e4290da0033
[ "MIT" ]
permissive
YousufSohail/GhostContactBook
50a6a744dd268dbbb2eaa20fafdb7095adbaab0d
e48e4e02968f2aa74db577d89872ff862e4ef5d0
refs/heads/master
2021-01-12T02:00:24.803374
2020-01-27T10:43:48
2020-01-27T10:43:48
78,455,371
2
5
null
null
null
null
UTF-8
Java
false
false
3,295
java
package com.yousufsohail.ghostcontactbook.dal; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.util.Log; import org.greenrobot.greendao.AbstractDaoMaster; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseOpenHelper; import org.greenrobot.greendao.database.StandardDatabase; import org.greenrobot.greendao.identityscope.IdentityScopeType; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * Master of DAO (schema version 1): knows all DAOs. */ public class DaoMaster extends AbstractDaoMaster { public static final int SCHEMA_VERSION = 1; public DaoMaster(SQLiteDatabase db) { this(new StandardDatabase(db)); } public DaoMaster(Database db) { super(db, SCHEMA_VERSION); registerDaoClass(UserBeanDao.class); } /** * Creates underlying database table using DAOs. */ public static void createAllTables(Database db, boolean ifNotExists) { UserBeanDao.createTable(db, ifNotExists); } /** * Drops underlying database table using DAOs. */ public static void dropAllTables(Database db, boolean ifExists) { UserBeanDao.dropTable(db, ifExists); } /** * WARNING: Drops all table on Upgrade! Use only during development. * Convenience method using a {@link DevOpenHelper}. */ public static DaoSession newDevSession(Context context, String name) { Database db = new DevOpenHelper(context, name).getWritableDb(); DaoMaster daoMaster = new DaoMaster(db); return daoMaster.newSession(); } public DaoSession newSession() { return new DaoSession(db, IdentityScopeType.Session, daoConfigMap); } public DaoSession newSession(IdentityScopeType type) { return new DaoSession(db, type, daoConfigMap); } /** * Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} - */ public static abstract class OpenHelper extends DatabaseOpenHelper { public OpenHelper(Context context, String name) { super(context, name, SCHEMA_VERSION); } public OpenHelper(Context context, String name, CursorFactory factory) { super(context, name, factory, SCHEMA_VERSION); } @Override public void onCreate(Database db) { Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION); createAllTables(db, false); } } /** * WARNING: Drops all table on Upgrade! Use only during development. */ public static class DevOpenHelper extends OpenHelper { public DevOpenHelper(Context context, String name) { super(context, name); } public DevOpenHelper(Context context, String name, CursorFactory factory) { super(context, name, factory); } @Override public void onUpgrade(Database db, int oldVersion, int newVersion) { Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables"); dropAllTables(db, true); onCreate(db); } } }
[ "ysohail@folio3.com" ]
ysohail@folio3.com
a894efaa754b39e18f8acbc2c0c9acadfc430818
2cd2b48e54081699b6b62380547d08d8e24c403b
/app/src/main/java/br/com/ifbavca/saudemovel/LoginActivity.java
876f31945ac1a952895f34e3a091a1e70f47b2d7
[]
no_license
amorimcltn/saude_movel_app
a13896fcfac1732025a6b3f199fbdadce5abcb77
8e5033974717190af629b7b2b41e3c69d928fcaa
refs/heads/master
2021-01-19T04:26:19.512297
2016-05-29T16:49:40
2016-05-29T16:49:40
59,953,116
0
0
null
null
null
null
UTF-8
Java
false
false
7,355
java
package br.com.ifbavca.saudemovel; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; import br.com.ifbavca.saudemovel.servico.SincronizarDados; public class LoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { protected GoogleApiClient mGoogleApiClient; protected static final int REQUEST_CHECK_SETTINGS = 0x1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(getResources().getColor(R.color.gray_statusbar)); window.setNavigationBarColor(getResources().getColor(R.color.gray_bar)); window.setTitle(""); } android.support.v7.app.ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("Bem-vindo!"); verificaGps(); final EditText editCpf = (EditText) findViewById(R.id.cpf); final EditText editSenha = (EditText) findViewById(R.id.senha); Button btSincronizar = (Button) findViewById(R.id.buttonSinc); btSincronizar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String cpf = editCpf.getText().toString(); String senha = editSenha.getText().toString(); if (!"".equalsIgnoreCase(cpf) && !"".equalsIgnoreCase(senha)){ SincronizarDados sincronizarDados = new SincronizarDados(LoginActivity.this); sincronizarDados.execute(cpf, senha); }else{ Toast.makeText(getApplicationContext(), "Verifique por campos vazios!", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i("API", "User agreed to make required location settings changes."); break; case Activity.RESULT_CANCELED: Log.i("API", "User chose not to make required location settings changes."); Toast.makeText(getApplicationContext(), "Precisamos que ative seu GPS para que a aplicação funcione corretamente.", Toast.LENGTH_SHORT).show(); verificaGps(); break; } break; } } public void verificaGps(){ mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(LoginActivity.this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates n = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult( LoginActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } @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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onConnected(Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } }
[ "amorimcltn@gmail.com" ]
amorimcltn@gmail.com
cf6360c207718de095b86878526cc06be3b435f9
19fb4254821565bc2a6d9dc7dfe77109f4272c65
/AndroidChat/app/src/main/java/edu/galileo/android/androidchat/chat/ChatInteractorImpl.java
7b484d703bc189eea3fa0907d50966068837476b
[]
no_license
miguelf11/DesarrolloAplicacionAndroid
cc8b71fe88d19976326cdd935c325a71ad1a5194
2e1d6df955f5e8e67ea0934b8c2df91684b8d19a
refs/heads/master
2021-01-20T20:48:01.551537
2016-07-04T23:48:04
2016-07-04T23:48:04
60,028,983
0
0
null
null
null
null
UTF-8
Java
false
false
755
java
package edu.galileo.android.androidchat.chat; /** * Created by Alex on 16-06-2016. */ public class ChatInteractorImpl implements ChatInteractor { ChatRepository repository; public ChatInteractorImpl() { this.repository = new ChatRepositoryImpl(); } @Override public void sendMessage(String msg) { repository.sendMessage(msg); } @Override public void setRecipient(String recipient) { repository.setRecipient(recipient); } @Override public void subscribe() { repository.subscribe(); } @Override public void unsubscribe() { repository.unsubscribe(); } @Override public void destroyListener() { repository.destroyListener(); } }
[ "miguelachof11@gmail.com" ]
miguelachof11@gmail.com
1c3e4ad386b85315957ac30197d35564f8c5e3dc
c885ef92397be9d54b87741f01557f61d3f794f3
/results/Cli-38/org.apache.commons.cli.DefaultParser/BBC-F0-opt-90/tests/20/org/apache/commons/cli/DefaultParser_ESTest.java
aff924e6a3ff2f85dbcd42622ea9f2a16119d44c
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
24,292
java
/* * This file was automatically generated by EvoSuite * Wed Oct 20 22:13:17 GMT 2021 */ package org.apache.commons.cli; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import java.util.Properties; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true) public class DefaultParser_ESTest extends DefaultParser_ESTest_scaffolding { @Test(timeout = 4000) public void test00() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); defaultParser0.handleConcatenatedOptions(""); } @Test(timeout = 4000) public void test01() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[1]; stringArray0[0] = "2eO"; Options options1 = options0.addRequiredOption("2eO", "true", true, "2eO"); try { defaultParser0.parse(options1, stringArray0, true); fail("Expecting exception: Exception"); } catch(Exception e) { // // Missing required option: 2eO // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test02() throws Throwable { Options options0 = new Options(); String[] stringArray0 = new String[9]; stringArray0[0] = "-=y{l"; DefaultParser defaultParser0 = new DefaultParser(); // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, true); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } @Test(timeout = 4000) public void test03() throws Throwable { Options options0 = new Options(); Option option0 = new Option((String) null, "---r 7O>7T", false, "--="); Options options1 = options0.addOption((String) null, "has already been selected: '", false, (String) null); Options options2 = options1.addOption(option0); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[4]; stringArray0[0] = "--="; Properties properties0 = new Properties(); try { defaultParser0.parse(options2, stringArray0, properties0, false); fail("Expecting exception: Exception"); } catch(Exception e) { // // Ambiguous option: '--' (could be: 'has already been selected: '', '---r 7O>7T') // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test04() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[9]; stringArray0[0] = "-=y{l"; Properties properties0 = new Properties(); // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, properties0, false); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } @Test(timeout = 4000) public void test05() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[2]; stringArray0[0] = "u;?;)0G6X1Dt"; Properties properties0 = new Properties(); Object object0 = new Object(); properties0.put(object0, "u;?;)0G6X1Dt"); // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, properties0, true); fail("Expecting exception: ClassCastException"); } catch(ClassCastException e) { // // java.lang.Object cannot be cast to java.lang.String // verifyException("java.util.Properties", e); } } @Test(timeout = 4000) public void test06() throws Throwable { Options options0 = new Options(); Option option0 = new Option((String) null, "---r 7O>7T", false, "--="); Options options1 = options0.addOption((String) null, "has already been selected: '", false, (String) null); options1.addOption(option0); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[4]; stringArray0[0] = "--="; try { defaultParser0.parse(options1, stringArray0, (Properties) null); fail("Expecting exception: Exception"); } catch(Exception e) { // // Ambiguous option: '--' (could be: 'has already been selected: '', '---r 7O>7T') // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test07() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[9]; stringArray0[0] = "-=y{l"; // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, (Properties) null); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } @Test(timeout = 4000) public void test08() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[8]; Properties properties0 = new Properties(); // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, properties0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } @Test(timeout = 4000) public void test09() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Properties properties0 = new Properties(); Object object0 = new Object(); properties0.put(options0, object0); // Undeclared exception! try { defaultParser0.parse(options0, (String[]) null, properties0); fail("Expecting exception: ClassCastException"); } catch(ClassCastException e) { // // org.apache.commons.cli.Options cannot be cast to java.lang.String // verifyException("java.util.Properties", e); } } @Test(timeout = 4000) public void test10() throws Throwable { Options options0 = new Options(); Option option0 = new Option((String) null, "---r 7O>7T", false, "--="); Options options1 = options0.addOption((String) null, "has already been selected: '", false, (String) null); options1.addOption(option0); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[4]; stringArray0[0] = "--="; try { defaultParser0.parse(options1, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Ambiguous option: '--' (could be: 'has already been selected: '', '---r 7O>7T') // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test11() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[9]; stringArray0[0] = ";]0%pqLN4L2"; stringArray0[1] = "-=wn.t'e?M+R)jT"; // Undeclared exception! try { defaultParser0.parse(options0, stringArray0); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } @Test(timeout = 4000) public void test12() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[0]; defaultParser0.parse(options0, stringArray0); try { defaultParser0.handleConcatenatedOptions("-Unrecognized option: "); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: -Unrecognized option: // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test13() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); // Undeclared exception! try { defaultParser0.handleConcatenatedOptions("6I6"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test14() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Properties properties0 = new Properties(); CommandLine commandLine0 = defaultParser0.parse(options0, (String[]) null, properties0, true); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test15() throws Throwable { Options options0 = new Options(); Option option0 = new Option((String) null, "---r 7O>7T", false, "--="); DefaultParser defaultParser0 = new DefaultParser(); OptionGroup optionGroup0 = new OptionGroup(); OptionGroup optionGroup1 = optionGroup0.addOption(option0); options0.addOptionGroup(optionGroup1); String[] stringArray0 = new String[4]; Properties properties0 = new Properties(); // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, properties0, false); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } @Test(timeout = 4000) public void test16() throws Throwable { Options options0 = new Options(); OptionGroup optionGroup0 = new OptionGroup(); Option option0 = new Option("L", "L"); OptionGroup optionGroup1 = optionGroup0.addOption(option0); Options options1 = options0.addOptionGroup(optionGroup1); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[7]; stringArray0[0] = "-L2"; optionGroup1.setRequired(true); try { defaultParser0.parse(options1, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: -L2 // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test17() throws Throwable { Options options0 = new Options(); OptionGroup optionGroup0 = new OptionGroup(); Option option0 = new Option("L", "L"); OptionGroup optionGroup1 = optionGroup0.addOption(option0); Options options1 = options0.addOptionGroup(optionGroup1); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[7]; stringArray0[0] = "-L2"; try { defaultParser0.parse(options1, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: -L2 // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test18() throws Throwable { Options options0 = new Options(); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[8]; Options options1 = options0.addOption("L", "L"); stringArray0[0] = "-L2"; Properties properties0 = new Properties(); defaultParser0.parse(options1, stringArray0, properties0, true); defaultParser0.handleConcatenatedOptions("-L2"); } @Test(timeout = 4000) public void test19() throws Throwable { Options options0 = new Options(); DefaultParser defaultParser0 = new DefaultParser(); Options options1 = options0.addRequiredOption("L", "yy.?rZ\"sI", true, "L"); String[] stringArray0 = new String[6]; stringArray0[0] = "yy.?rZ\"sI"; stringArray0[1] = "' contains an illegal "; stringArray0[2] = "yy.?rZ\"sI"; stringArray0[3] = "L"; stringArray0[4] = "L"; stringArray0[5] = "-L2"; CommandLine commandLine0 = defaultParser0.parse(options1, stringArray0); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test20() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Properties properties0 = new Properties(); String[] stringArray0 = new String[6]; stringArray0[0] = ""; stringArray0[1] = ")8=y0d~"; stringArray0[2] = "Missing required option"; stringArray0[3] = ""; stringArray0[4] = ""; stringArray0[5] = "-QQe%zFdTl(O?=oBW"; try { defaultParser0.parse(options0, stringArray0, properties0, false); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: -QQe%zFdTl(O?=oBW // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test21() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Options options1 = options0.addOption("nx", "nx", true, (String) null); String[] stringArray0 = new String[4]; stringArray0[0] = "-nx"; // Undeclared exception! try { defaultParser0.parse(options1, stringArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } @Test(timeout = 4000) public void test22() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[6]; stringArray0[0] = "-8=y{D"; Properties properties0 = new Properties(); CommandLine commandLine0 = defaultParser0.parse(options0, stringArray0, properties0, true); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test23() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[6]; stringArray0[0] = "cMZr}"; stringArray0[1] = "-l"; try { defaultParser0.parse(options0, stringArray0, (Properties) null); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: -l // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test24() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Option option0 = new Option((String) null, "", true, "--="); Options options1 = options0.addOption(option0); String[] stringArray0 = new String[9]; stringArray0[0] = "--="; // Undeclared exception! try { defaultParser0.parse(options1, stringArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } @Test(timeout = 4000) public void test25() throws Throwable { Options options0 = new Options(); Option option0 = new Option((String) null, "---r7O>7T", false, "--="); Options options1 = options0.addOption((String) null, "has already been selected: '", false, (String) null); options1.addOption(option0); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[4]; stringArray0[0] = "--="; try { defaultParser0.parse(options1, stringArray0, false); fail("Expecting exception: Exception"); } catch(Exception e) { // // Ambiguous option: '--' (could be: 'has already been selected: '', '---r7O>7T') // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test26() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Option option0 = new Option((String) null, "", false, "--="); options0.addOption(option0); String[] stringArray0 = new String[9]; stringArray0[0] = "--="; Properties properties0 = new Properties(); try { defaultParser0.parse(options0, stringArray0, properties0, false); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: --= // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test27() throws Throwable { Options options0 = new Options(); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[4]; stringArray0[0] = "-\"4?0*&cM!a?d"; CommandLine commandLine0 = defaultParser0.parse(options0, stringArray0, true); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test28() throws Throwable { Options options0 = new Options(); options0.addOption("L", "L", true, "L"); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[9]; stringArray0[0] = "L"; stringArray0[1] = "--L"; stringArray0[2] = "L"; stringArray0[3] = "L"; stringArray0[4] = "n.T3F_gwGx(Rv%w"; stringArray0[5] = "L"; stringArray0[6] = "L"; stringArray0[7] = "--L"; stringArray0[8] = "-"; CommandLine commandLine0 = defaultParser0.parse(options0, stringArray0); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test29() throws Throwable { Options options0 = new Options(); options0.addOption("L", "L", true, "L"); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[4]; stringArray0[0] = "-L"; stringArray0[1] = "-L"; try { defaultParser0.parse(options0, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Missing argument for option: L // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test30() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[9]; stringArray0[0] = "-"; Properties properties0 = new Properties(); CommandLine commandLine0 = defaultParser0.parse(options0, stringArray0, properties0, true); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test31() throws Throwable { Options options0 = new Options(); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[9]; stringArray0[0] = "L"; stringArray0[1] = "--L"; try { defaultParser0.parse(options0, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Unrecognized option: --L // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test32() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); Properties properties0 = new Properties(); String[] stringArray0 = new String[6]; stringArray0[0] = ""; stringArray0[1] = "I,-tw-y]5n"; stringArray0[2] = "--"; CommandLine commandLine0 = defaultParser0.parse(options0, stringArray0, properties0); assertNotNull(commandLine0); } @Test(timeout = 4000) public void test33() throws Throwable { Options options0 = new Options(); options0.addOption("L", true, "PL"); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[5]; stringArray0[0] = "PL"; stringArray0[1] = "PL"; stringArray0[2] = "L"; stringArray0[3] = "PL"; stringArray0[4] = "PL"; defaultParser0.parse(options0, stringArray0); defaultParser0.handleConcatenatedOptions("xLAQ:G<7<g7kg/n-@"); defaultParser0.handleConcatenatedOptions("PL"); } @Test(timeout = 4000) public void test34() throws Throwable { DefaultParser defaultParser0 = new DefaultParser(); Options options0 = new Options(); String[] stringArray0 = new String[2]; stringArray0[0] = "u;?;)0G6X1Dt"; Properties properties0 = new Properties(); properties0.put(",w", "~;d>wVFX}yK5B9U"); try { defaultParser0.parse(options0, stringArray0, properties0, true); fail("Expecting exception: Exception"); } catch(Exception e) { // // Default option wasn't defined // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test35() throws Throwable { Options options0 = new Options(); options0.addOption("L", true, "-L"); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[8]; stringArray0[0] = "L"; stringArray0[1] = "-L"; stringArray0[2] = "---7=,K4z/"; stringArray0[3] = "-L"; stringArray0[4] = "L"; stringArray0[5] = "-L"; stringArray0[6] = "w%7_aY8P(z(Txg_gx"; stringArray0[7] = "-L"; try { defaultParser0.parse(options0, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Missing argument for option: L // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test36() throws Throwable { Options options0 = new Options(); Options options1 = options0.addOption("L", true, "-L"); DefaultParser defaultParser0 = new DefaultParser(); String[] stringArray0 = new String[3]; stringArray0[0] = "L"; stringArray0[1] = "-L"; stringArray0[2] = "-L"; try { defaultParser0.parse(options1, stringArray0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Missing argument for option: L // verifyException("org.apache.commons.cli.DefaultParser", e); } } @Test(timeout = 4000) public void test37() throws Throwable { Options options0 = new Options(); String[] stringArray0 = new String[3]; DefaultParser defaultParser0 = new DefaultParser(); // Undeclared exception! try { defaultParser0.parse(options0, stringArray0, true); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } }
[ "pderakhshanfar@serg2.ewi.tudelft.nl" ]
pderakhshanfar@serg2.ewi.tudelft.nl
2357c0c56c606ebf02a3c244fd6fc277150b7761
9ef0890781cbb1dd11dfaae988a8e2cafc22647b
/app/src/main/java/jp/kinwork/Common/AES.java
2f63b020085292e6d2e65e028f00003f3eebbde3
[]
no_license
ZD-and/kw_internship
d14a56f6dd2a5be7958f69275da54cc161d6963c
c5d329f8930a6f5a78a98e34f8ad84e144c25648
refs/heads/master
2023-01-23T05:02:42.278674
2020-04-24T08:55:36
2020-04-24T08:55:36
301,904,131
0
0
null
null
null
null
UTF-8
Java
false
false
8,747
java
package jp.kinwork.Common; import android.util.Log; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AES { private final String KEY_GENERATION_ALG = "PBEWITHSHAANDTWOFISH-CBC"; // private final String KEY_GENERATION_ALG = "PBKDF2WithHmacSHA1"; private final int HASH_ITERATIONS = 10000; private final int KEY_LENGTH = 128; // private char[] humanPassphrase = { 'P', 'e', 'r', ' ', 'v', 'a', 'l', 'l', // 'u', 'm', ' ', 'd', 'u', 'c', 'e', 's', ' ', 'L', 'a', 'b', 'a', // 'n', 't' };// per vallum duces labant // private byte[] salt = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, // 0xE, 0xF }; // must save this for next time we want the key // //// private char[] humanPassphrase = null; //// private byte[] salt = null; // private PBEKeySpec myKeyspec = new PBEKeySpec(humanPassphrase, salt, // HASH_ITERATIONS, KEY_LENGTH); private final String CIPHERMODEPADDING = "AES/CBC/PKCS7Padding";// AES/CBC/PKCS7Padding private SecretKeyFactory keyfactory = null; private SecretKey sk = null; private SecretKeySpec skforAES = null; private static String ivParameter = "0000000000000000";// 密钥默认偏移,可更改 private byte[] iv = ivParameter.getBytes(); private IvParameterSpec IV; public AES() { try { keyfactory = SecretKeyFactory.getInstance(KEY_GENERATION_ALG); // sk = keyfactory.generateSecret(myKeyspec); } catch (NoSuchAlgorithmException nsae) { Log.e("AESdemo", "no key factory support for PBEWITHSHAANDTWOFISH-CBC"); // } catch (InvalidKeySpecException ikse) { // Log.e("AESdemo", "invalid key spec for PBEWITHSHAANDTWOFISH-CBC"); } // This is our secret key. We could just save this to a file instead of // regenerating it // each time it is needed. But that file cannot be on the device (too // insecure). It could // be secure if we kept it on a server accessible through https. // byte[] skAsByteArray = sk.getEncoded(); // byte[] skAsByteArray; // try { // skAsByteArray = sKey.getBytes("UTF8"); // skforAES = new SecretKeySpec(skAsByteArray, "AES"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } IV = new IvParameterSpec(iv); } public String encrypt(byte[] plaintext, String key) { byte[] skAsByteArray; try { skAsByteArray = key.getBytes("UTF8"); skforAES = new SecretKeySpec(skAsByteArray, "AES"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] ciphertext = encrypt(CIPHERMODEPADDING, skforAES, IV, plaintext); String base64_ciphertext = Base64Encoder.encode(ciphertext); return base64_ciphertext; } public String decrypt(String ciphertext_base64, String key) { byte[] s = Base64Decoder.decodeToBytes(ciphertext_base64); byte[] skAsByteArray; try { skAsByteArray = key.getBytes("UTF8"); skforAES = new SecretKeySpec(skAsByteArray, "AES"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String decrypted = new String(decrypt(CIPHERMODEPADDING, skforAES, IV, s)); return decrypted; } // Use this method if you want to add the padding manually // AES deals with messages in blocks of 16 bytes. // This method looks at the length of the message, and adds bytes at the end // so that the entire message is a multiple of 16 bytes. // the padding is a series of bytes, each set to the total bytes added (a // number in range 1..16). private byte[] addPadding(byte[] plain) { byte plainpad[] = null; int shortage = 16 - (plain.length % 16); // if already an exact multiple of 16, need to add another block of 16 // bytes if (shortage == 0) shortage = 16; // reallocate array bigger to be exact multiple, adding shortage bits. plainpad = new byte[plain.length + shortage]; for (int i = 0; i < plain.length; i++) { plainpad[i] = plain[i]; } for (int i = plain.length; i < plain.length + shortage; i++) { plainpad[i] = (byte) shortage; } return plainpad; } // Use this method if you want to remove the padding manually // This method removes the padding bytes private byte[] dropPadding(byte[] plainpad) { byte plain[] = null; int drop = plainpad[plainpad.length - 1]; // last byte gives number of // bytes to drop // reallocate array smaller, dropping the pad bytes. plain = new byte[plainpad.length - drop]; for (int i = 0; i < plain.length; i++) { plain[i] = plainpad[i]; plainpad[i] = 0; // don't keep a copy of the decrypt } return plain; } private byte[] encrypt(String cmp, SecretKey sk, IvParameterSpec IV, byte[] msg) { try { Cipher c = Cipher.getInstance(cmp); c.init(Cipher.ENCRYPT_MODE, sk, IV); return c.doFinal(msg); } catch (NoSuchAlgorithmException nsae) { Log.e("AESdemo", "no cipher getinstance support for " + cmp); } catch (NoSuchPaddingException nspe) { Log.e("AESdemo", "no cipher getinstance support for padding " + cmp); } catch (InvalidKeyException e) { Log.e("AESdemo", "invalid key exception"); } catch (InvalidAlgorithmParameterException e) { Log.e("AESdemo", "invalid algorithm parameter exception"); } catch (IllegalBlockSizeException e) { Log.e("AESdemo", "illegal block size exception"); } catch (BadPaddingException e) { Log.e("AESdemo", "bad padding exception"); } return null; } private byte[] encrypt_t2(String cmp, SecretKey sk, IvParameterSpec IV, byte[] msg) { try { Cipher c = Cipher.getInstance(cmp); c.init(Cipher.ENCRYPT_MODE, sk, IV); return c.doFinal(msg); } catch (NoSuchAlgorithmException nsae) { Log.e("AESdemo", "no cipher getinstance support for " + cmp); } catch (NoSuchPaddingException nspe) { Log.e("AESdemo", "no cipher getinstance support for padding " + cmp); } catch (InvalidKeyException e) { Log.e("AESdemo", "invalid key exception"); } catch (InvalidAlgorithmParameterException e) { Log.e("AESdemo", "invalid algorithm parameter exception"); } catch (IllegalBlockSizeException e) { Log.e("AESdemo", "illegal block size exception"); } catch (BadPaddingException e) { Log.e("AESdemo", "bad padding exception"); } return null; } private byte[] decrypt(String cmp, SecretKey sk, IvParameterSpec IV, byte[] ciphertext) { try { Cipher c = Cipher.getInstance(cmp); c.init(Cipher.DECRYPT_MODE, sk, IV); return c.doFinal(ciphertext); } catch (NoSuchAlgorithmException nsae) { Log.e("AESdemo", "no cipher getinstance support for " + cmp); } catch (NoSuchPaddingException nspe) { Log.e("AESdemo", "no cipher getinstance support for padding " + cmp); } catch (InvalidKeyException e) { Log.e("AESdemo", "invalid key exception"); } catch (InvalidAlgorithmParameterException e) { Log.e("AESdemo", "invalid algorithm parameter exception"); } catch (IllegalBlockSizeException e) { Log.e("AESdemo", "illegal block size exception"); } catch (BadPaddingException e) { Log.e("AESdemo", "bad padding exception"); e.printStackTrace(); } return null; } }
[ "zml988721@gmail.com" ]
zml988721@gmail.com
de5223ec3d58115ec613611e166c3b531c255b3d
f9c525f902a1058cf18ebba11637a4630bdd66c8
/generated-different-configs/features-turned-off/src/test/java/db/h2/OneColumnGeneratedIdPostgres.java
d1494e92dc0a14cc91ded7e932cd41aa915024d9
[ "MIT" ]
permissive
plilja/spring-dao-codegen
88aedbb91ec8c81afd5b201e449131f536e41afc
e9ddf578c59eb83cd4ec29dddfd86e387adcfe71
refs/heads/master
2022-08-09T00:42:49.536887
2020-10-17T16:23:06
2020-10-17T16:23:06
164,498,962
0
0
MIT
2022-06-20T22:40:50
2019-01-07T21:28:53
Java
UTF-8
Java
false
false
515
java
package db.h2; public class OneColumnGeneratedIdPostgres implements BaseEntity<Integer> { private Integer id; public OneColumnGeneratedIdPostgres() { } public OneColumnGeneratedIdPostgres(Integer id) { this.id = id; } @Override public Integer getId() { return id; } @Override public void setId(Integer id) { this.id = id; } @Override public String toString() { return "OneColumnGeneratedIdPostgres{id=" + id + "}"; } }
[ "lilja.patrik@gmail.com" ]
lilja.patrik@gmail.com
5d9e54285720c8e0a1ef1bba92572c9297804b98
f050307ffb006645f7e746c2c3289ff6602737d7
/spring-hystrix-school-service/src/main/java/com/cognizant/springhystrixschoolservice/controller/SchoolServiceController.java
13953f628445062d2d76e57359e4464b00b05eaa
[]
no_license
baskarsk/SimpleHystrixOpenshift
3e74d01871532c9c9d1ecd6306966ec4f9ade38c
cef225bf242878a7471c9b9aa0f0862b47fdfd6a
refs/heads/master
2020-04-05T20:11:00.038118
2018-11-12T07:32:42
2018-11-12T07:32:42
157,168,134
0
0
null
null
null
null
UTF-8
Java
false
false
873
java
package com.cognizant.springhystrixschoolservice.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cognizant.springhystrixschoolservice.delegate.StudentServiceDelegate; @RestController public class SchoolServiceController { @Autowired StudentServiceDelegate studentServiceDelegate; @RequestMapping(value = "/getSchoolDetails/{schoolname}", method = RequestMethod.GET) public String getStudents(@PathVariable String schoolname) { System.out.println("Going to call student service to get data!"); return studentServiceDelegate.callStudentServiceAndGetData(schoolname); } }
[ "baskar.saravanan@cognizant.com" ]
baskar.saravanan@cognizant.com
a65341e6710cc0ab00a2a559eda886b555b796cb
f96d2127d45f231d6d515108def0110d707c83a5
/InterestingPictureModel.java
df38698c1b6d3e7f6f52401f10459a22ccdcdb10
[]
no_license
Shayshaylemon/Web_Scraping
61612918f3ba3437f5e025fb90495f8f2496e051
5afded4cb86245c5689ed83b1e51a0e44b255550
refs/heads/master
2020-05-17T22:19:09.530813
2015-02-08T03:33:00
2015-02-08T03:33:00
30,478,650
0
0
null
null
null
null
UTF-8
Java
false
false
2,578
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import javax.net.ssl.HttpsURLConnection; import sun.net.*; public class InterestingPictureModel { private String pictureTag; private String pictureURL; String response; public void doFlickrSearch(String searchTag) { pictureTag = searchTag; response = ""; try { // Create a URL for the desired page URL url = new URL("http://thisisindexed.com/category/"+searchTag); // Create an HttpURLConnection. This is useful for setting headers. URLConnection connection=url.openConnection(); // Read all the text returned by the server //System.out.println(connection.getContent()); BufferedReader in = new BufferedReader (new InputStreamReader(connection.getInputStream(), "UTF-8")); String str; System.out.println(connection.getContentLength()); while ((str = in.readLine()) != null) { // str is one line of text readLine() strips newline characters response += str; } in.close(); } catch (IOException e) { } int random = (int)( Math.random()*10000); int startfarm = response.indexOf("http://thisisindexed.com/wp-content/uploads/201", 5000+random); // only start looking after the quote before http int endfarm = response.indexOf("\"",startfarm + 5); // only start looking after the quote before http // +1 to include the quote pictureURL = "src=\""+ response.substring(startfarm, endfarm+1); } public String getMobileURL() { int start ; int startfrom; int endfrom; int random =(int)(Math.random()*15000); start = response.indexOf("alignnone size-medium wp-image",random); startfrom = response.indexOf("src=\"http://thisisindexed.com/wp-content/uploads/", start+5); endfrom = response.indexOf("\"",startfrom+5); pictureURL = response.substring(startfrom, endfrom+1); return pictureURL; } public String getWebPic(){ return pictureURL; } public String getPictureTag() { return pictureTag; } }
[ "shayguo@gmail.com" ]
shayguo@gmail.com
b8b8e6bfa0cc74d03e44403e2eba3ce6db25790c
c22dd114bacd0cc338eca0bdbdea3f0ab5ba89c9
/spring-boot/jndidatasource/src/main/java/org/springboot/jndidatasource/config/SwaggerConfiguration.java
f767839b5e8bfc31bdfa89d1ec08fd2cac47f575
[ "Apache-2.0" ]
permissive
java-pawar2014/practice
3c3740365366ff78b8bdd8a876c867d291559978
149e482798e1fca2ae870df66aa0f76a54ab39ad
refs/heads/master
2021-04-29T20:27:12.694994
2018-10-08T09:25:42
2018-10-08T09:25:42
121,596,858
0
0
null
null
null
null
UTF-8
Java
false
false
1,697
java
package org.springboot.jndidatasource.config; import static springfox.documentation.builders.PathSelectors.regex; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootConfiguration @EnableSwagger2 public class SwaggerConfiguration extends WebMvcConfigurationSupport { @Bean public Docket swaggerHookup() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("org.springboot.jndidatasource.web.controller")) .paths(regex("/user.*")).build().apiInfo(metaData()); } private ApiInfo metaData() { return new ApiInfoBuilder().title("Spring Boot REST API with Swagger") .description("\"Spring Boot REST API\"").version("1.0.0") .license("Apache License Version 2.0").licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") .build(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
[ "java.pawar2014@gmail.com" ]
java.pawar2014@gmail.com
02e058609f33b96620a68ee8f24ef43def98b8dd
24edaa26e4c78c1d49331bcef8e8df2075ac99b6
/b2b/b2b-activity/activity-dao/src/main/java/com/jumore/b2b/activity/service/impl/GiftCategoryServiceImp.java
62b7fdc4b3821b6dbe63d41263a59dfbfa61cc2a
[]
no_license
73jdjdJDate61hdjd84hdjd52juggwf/activity
7be59b672220e0c07fe48dc5c5a49263229719d0
2ddcbaa25be230ca1b21f8eeb102f86ca94a3b5d
refs/heads/master
2020-03-21T10:18:36.654839
2016-08-19T10:36:53
2016-08-19T10:36:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,066
java
/** * 奖励类别 * GiftCategoryServiceImp.java * Copyright(C) 2015-2015 xxxxxx公司 * All rights reserved. * ----------------------------------------------- * 2016-07-01 Created */ package com.jumore.b2b.activity.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.jumore.b2b.activity.base.service.single.BaseServiceImp; import com.jumore.b2b.activity.comm.Pages; import com.jumore.b2b.activity.mapper.GiftCategoryMapper; import com.jumore.b2b.activity.model.GiftCategory; import com.jumore.b2b.activity.model.GiftCategoryQueryHelper; import com.jumore.b2b.activity.service.IGiftCategoryService; @org.springframework.stereotype.Service public class GiftCategoryServiceImp extends BaseServiceImp<GiftCategory, GiftCategoryQueryHelper> implements IGiftCategoryService { static final Logger log = LogManager.getLogger(GiftCategoryServiceImp.class);; GiftCategoryMapper giftCategoryMapper; @Resource public void setGiftCategoryMapper(GiftCategoryMapper giftCategoryMapper) { this.giftCategoryMapper=giftCategoryMapper; //this.setBaseMapper(giftCategoryMapper); } /** *综合查询 */ public Pages<GiftCategory> browser(GiftCategory giftCategory, int length, int offset) { GiftCategoryQueryHelper example = new GiftCategoryQueryHelper(); /** 查询业务逻辑 **/ // example.createCriteria().andXXXEqualTo(xx.()) /** 查询业务逻辑完 **/ /**######################_我是分隔线######################**/ List<GiftCategory> list = new ArrayList<GiftCategory>(); long total = giftCategoryMapper.countByExample(example); if (total > 0) { /**排序业务逻辑 **/ //example.setOrderByClause(XX) /** 排序业务逻辑完 **/ /**######################_我是分隔线######################**/ //分页插件查询 PageHelper.startPage(offset, length); list = giftCategoryMapper.selectByExample(example); PageInfo<GiftCategory> page = new PageInfo<GiftCategory>(list); list=page.getList(); } return new Pages<com.jumore.b2b.activity.model.GiftCategory>(list, total, offset, length); } /** *添加 */ public long append(GiftCategory giftCategory) { /** 新增业务逻辑 **/ /** 新增业务逻辑完 **/ /**######################_我是分隔线######################**/ return giftCategoryMapper.insert(giftCategory); } /** *添加 */ public long delete(List<GiftCategory> giftCategory) { /** 删除务逻辑 **/ log.info("devlopping"); /** 删除业务逻辑完 **/ /**######################_我是分隔线######################**/ return 0; } /** *添加 */ public long update(GiftCategory giftCategory) { GiftCategoryQueryHelper e = new GiftCategoryQueryHelper(); /** 更新业务逻辑 **/ /** 更新业务逻辑完 **/ /**######################_我是分隔线######################**/ return giftCategoryMapper.updateByExampleSelective(giftCategory,e); } /** *添加 */ public GiftCategory selectUnique(GiftCategory giftCategory) { GiftCategoryQueryHelper e = new GiftCategoryQueryHelper(); /** 查询业务逻辑 **/ /** 查询业务逻辑完 **/ /**######################_我是分隔线######################**/ List<GiftCategory> list = giftCategoryMapper.selectByExample(e); if (list.size() != 1) throw new RuntimeException("对象不存在!"); return list.get(0); } }
[ "fans_2046@126.com" ]
fans_2046@126.com
3f152a45f68236a34427556e3088d84007dd628b
d468cbe15ac0b6a6134e5fed8b34f8d64fbffbc0
/app/src/main/java/com/zhuandian/schoolsocial/adapter/PostListAdapter.java
c8cdb9743a7a1dca92a79d3759a566be8ae70d34
[]
no_license
zhuandian/SchoolSocial
95d9d5adde12cfe98701e647e5f14765ac780e8a
015bfa9a06ab9ea85f3a27d37dddde71158c77b0
refs/heads/master
2020-04-30T22:59:04.099524
2019-05-27T05:06:13
2019-05-27T05:06:13
177,132,973
2
0
null
null
null
null
UTF-8
Java
false
false
5,162
java
package com.zhuandian.schoolsocial.adapter; import android.content.Context; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.zhuandian.schoolsocial.R; import com.zhuandian.schoolsocial.base.BaseAdapter; import com.zhuandian.schoolsocial.base.BaseViewHolder; import com.zhuandian.schoolsocial.business.schoolNews.schoolsocial.MyUtils; import com.zhuandian.schoolsocial.entity.CommentEntity; import com.zhuandian.schoolsocial.entity.PostEntity; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobPointer; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; /** * desc : * author:xiedong * date:2019/4/22 */ public class PostListAdapter extends BaseAdapter<PostEntity, BaseViewHolder> { @BindView(R.id.ll_click_span) LinearLayout llClickSpan; @BindView(R.id.username) TextView username; @BindView(R.id.time) TextView time; @BindView(R.id.content) TextView content; @BindView(R.id.comment) TextView comment; @BindView(R.id.tv_chat) TextView tvChat; private ItemClickListener clickListener; public PostListAdapter(Context context, List<PostEntity> mDatas) { super(context, mDatas); } @Override protected void converData(BaseViewHolder holder, final PostEntity heartShareEntity, final int position) { ButterKnife.bind(this, holder.itemView); username.setText(heartShareEntity.getUsername()); setCommentCount(heartShareEntity.getObjectId(), comment); //评论个数 content.setText(heartShareEntity.getContent()); System.out.println("创建Time----" + heartShareEntity.getCreatedAt() + "系统时间--" + MyUtils.currentTime()); // 创建Time----2016-12-30 10:46:44系统时间--2016-12-30 10:54:03 String createtTime[] = heartShareEntity.getCreatedAt().split(" "); String currentTime[] = MyUtils.currentTime().split(" "); //判断创建时间跟当前时间是否同一天,是,只显示时间,不是,显示创建的日期,不显示时间 if (createtTime[0].equals(currentTime[0])) { String createtTime1[] = createtTime[1].split(":"); time.setText("今天 " + createtTime1[0] + ":" + createtTime1[1]); } else { String createtTime1[] = createtTime[0].split("-"); //正则切割月份 String createtTime2[] = createtTime[1].split(":"); //正则切割时间 time.setText(createtTime1[1] + "/" + createtTime1[2] + " " + createtTime2[0] + ":" + createtTime2[1]); } llClickSpan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (clickListener != null) { clickListener.onItemClick(heartShareEntity); } } }); llClickSpan.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { if (clickListener != null) { clickListener.onItemLongClick(position); } return true; } }); tvChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (clickListener != null) { clickListener.onClicChat(heartShareEntity); } } }); } /** * 得到动态相关的评论个数 * * @param objectId * @return */ private void setCommentCount(String objectId, final TextView countView) { BmobQuery<CommentEntity> query = new BmobQuery<CommentEntity>(); //用此方式可以构造一个BmobPointer对象。只需要设置objectId就行 PostEntity post = new PostEntity(); post.setObjectId(objectId); //得到当前动态的Id号, query.addWhereEqualTo("postEntity", new BmobPointer(post)); //希望同时查询该评论的发布者的信息,以及该帖子的作者的信息,这里用到上面`include`的并列对象查询和内嵌对象的查询 query.include("myuser,postentity.auther"); query.findObjects(new FindListener<CommentEntity>() { @Override public void done(List<CommentEntity> objects, BmobException e) { if (e == null) { countView.setText(objects.size() + ""); } else { System.out.println("查询数据失败"); } } }); } @Override public int getItemLayoutId() { return R.layout.heart_share_item; } public void setClickListener(ItemClickListener clickListener) { this.clickListener = clickListener; } public interface ItemClickListener { void onItemClick(PostEntity heartShareEntity); void onItemLongClick(int pos); void onClicChat(PostEntity heartShareEntity); } }
[ "xiedong11@aliyun.com" ]
xiedong11@aliyun.com
c0eada4a569ff9835c4eabbf062e9d1ed01576e5
d6e1a737062801fd54ff83e7daaf3838cc48191d
/src/main/java/bot/command/Command.java
926a8c7c45ea3d3ab0e86a1e68e49142d044ac87
[]
no_license
Fehzor/tinos
88654b7dc29529639346ce106741797439336e1e
87dae9372024f608564e5770725e858bdb6b4734
refs/heads/master
2020-07-08T13:39:32.503371
2019-08-22T01:39:14
2019-08-22T01:39:14
203,691,490
0
0
null
null
null
null
UTF-8
Java
false
false
933
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 bot.command; import discord4j.core.object.entity.Message; import java.util.HashMap; /** * * @author FF6EB */ public class Command { private static HashMap<String, Command> commands = new HashMap<>(); String [] ident; String description; boolean hidden; public Command(){ ident = new String[]{}; description = ""; hidden = true; } void addCommand(){ for(String id : ident){ commands.put(id, this); } } public static Command get(String s){ return commands.get(s); } public String execute(Message arg){ return "Default command has been called!"; } }
[ "FF6EB4@gmail.com" ]
FF6EB4@gmail.com
6fe19b648dad4548ec5d21bf2a51b66d6a629e0d
ea586a7b7e727bf5b44b0b487dedca9a70c75843
/src/org/vesselonline/ai/learning/NaiveBayesClassifier.java
a66bc2060067d3e7032da651470fcc88de21dafa
[]
no_license
shandy79/vessel-online
1378b403d0fd080e4bddd9d98c755bcfefbb36d5
3cd7157097c79fa3dba64571abbac1487309acf1
refs/heads/master
2022-10-06T20:22:12.535043
2022-09-29T02:26:52
2022-09-29T02:26:52
32,423,031
1
1
null
2022-04-12T01:40:50
2015-03-17T22:06:21
Java
UTF-8
Java
false
false
8,192
java
package org.vesselonline.ai.learning; import java.util.HashMap; import java.util.Map; import org.vesselonline.ai.learning.data.Attribute; import org.vesselonline.ai.learning.data.BasicCSVData; import org.vesselonline.ai.learning.data.CSVData; import org.vesselonline.ai.util.Instrumentable; import org.vesselonline.ai.util.Instrumentation; public class NaiveBayesClassifier implements Instrumentable { private CSVData csvData; private Map<String, Double> classificationPPT; private Map<Integer, Map<String, Map<String, Double>>> attrValueCPTs; private Instrumentation instrumentation; private static final double DIRICHLET_M = 1; private static final double DIRICHLET_P = 0.001; public NaiveBayesClassifier(CSVData csvData, Instrumentation instrumentation) { this.csvData = csvData; this.instrumentation = instrumentation; classificationPPT = new HashMap<String, Double>(getCSVData().getClassification().getDomain().length); attrValueCPTs = new HashMap<Integer, Map<String, Map<String, Double>>>(getCSVData().getAttributeCount()); calculateProbabilities(); } public CSVData getCSVData() { return csvData; } public Map<String, Double> getClassificationPPT() { return classificationPPT; } public Map<Integer, Map<String, Map<String, Double>>> getAttrValueCPTs() { return attrValueCPTs; } @Override public Instrumentation getInstrumentation() { return instrumentation; } @Override public void setInstrumentation(Instrumentation instrumentation) { this.instrumentation = instrumentation; } public String classify(String[] example) { StringBuilder output = new StringBuilder(); double attrClassValue, maxClassValue = 0; String predictedClass = null; for (String classVal : getCSVData().getClassification().getDomain()) { attrClassValue = getClassificationPPT().get(classVal); for (int i = 0; i < getCSVData().getAttributeCount(); i++) { attrClassValue *= getAttrValueCPTs().get(i).get(example[i]).get(classVal); } output.append(classVal + ":" + attrClassValue + " "); if (attrClassValue > maxClassValue) { predictedClass = classVal; maxClassValue = attrClassValue; } } output.append("\tPredicted: " + predictedClass + ", Actual: " + example[getCSVData().getAttributeCount()]); getInstrumentation().print(output.toString()); return predictedClass; } private void calculateProbabilities() { Map<String, Integer> classPPTCount = new HashMap<String, Integer>(getCSVData().getClassification().getDomain().length); Map<Integer, Map<String, Map<String, Integer>>> attrValCPTCount = new HashMap<Integer, Map<String, Map<String, Integer>>>(getCSVData().getAttributeCount()); Attribute attr; // Initialize class PPT and attribute CPTs for (String classVal : getCSVData().getClassification().getDomain()) { classPPTCount.put(classVal, 0); getClassificationPPT().put(classVal, 0.0); } for (int i = 0; i < getCSVData().getAttributeCount(); i++) { attr = getCSVData().getAttributes()[i]; attrValCPTCount.put(i, new HashMap<String, Map<String, Integer>>(attr.getDomain().length)); getAttrValueCPTs().put(i, new HashMap<String, Map<String, Double>>(attr.getDomain().length)); for (String attrVal : attr.getDomain()) { attrValCPTCount.get(i).put(attrVal, new HashMap<String, Integer>(getCSVData().getClassification().getDomain().length)); getAttrValueCPTs().get(i).put(attrVal, new HashMap<String, Double>(getCSVData().getClassification().getDomain().length)); for (String classVal : getCSVData().getClassification().getDomain()) { attrValCPTCount.get(i).get(attrVal).put(classVal, 0); getAttrValueCPTs().get(i).get(attrVal).put(classVal, 0.0); } } } // Count everything in the data set for (String[] ex : getCSVData().getData()) { for (int i = 0; i < ex.length; i++) { if (i == getCSVData().getAttributeCount()) { classPPTCount.put(ex[i], classPPTCount.get(ex[i]).intValue() + 1); } else { attrValCPTCount.get(i).get(ex[i]).put(ex[getCSVData().getAttributeCount()], attrValCPTCount.get(i).get(ex[i]).get(ex[getCSVData().getAttributeCount()]).intValue() + 1); } } } // Calculate the PPT for the classification values based on counts for (String classVal : classPPTCount.keySet()) { getClassificationPPT().put(classVal, (classPPTCount.get(classVal).doubleValue() + DIRICHLET_M * DIRICHLET_P) / (getCSVData().getData().size() + DIRICHLET_M)); } // Calculate the CPTs for the attribute values based on counts for (Integer attrIdx : attrValCPTCount.keySet()) { for (String attrVal : attrValCPTCount.get(attrIdx).keySet()) { for (String classVal : attrValCPTCount.get(attrIdx).get(attrVal).keySet()) { getAttrValueCPTs().get(attrIdx).get(attrVal).put(classVal, (attrValCPTCount.get(attrIdx).get(attrVal).get(classVal).doubleValue() + DIRICHLET_M * DIRICHLET_P) / (classPPTCount.get(classVal).doubleValue() + DIRICHLET_M)); } } } getInstrumentation().print(pptCPTToString(classPPTCount, attrValCPTCount)); } private String pptCPTToString(Map<String, Integer> classPPTCount, Map<Integer, Map<String, Map<String, Integer>>> attrValCPTCount) { StringBuilder output = new StringBuilder("Classification PPT (counts w/Dirichlet Prior probability)\n" + "---------------------------------------------------------\n\t\t" + getCSVData().getClassification().getName() + "\n"); for (String classVal : classPPTCount.keySet()) { output.append(classVal + "\t(" + classPPTCount.get(classVal) + "/" + getCSVData().getData().size() + ") " + getClassificationPPT().get(classVal) + "\n"); } output.append("\nAttribute Value CPTs (counts w/Dirichlet Prior probability)\n-----------------------------------------------------------"); for (Integer attrIdx : attrValCPTCount.keySet()) { output.append("\n\nP(" + getCSVData().getAttributes()[attrIdx].getName() + "|" + getCSVData().getClassification().getName() + ")"); for (String attrVal : attrValCPTCount.get(attrIdx).keySet()) { output.append("\n" + attrVal + "\t"); for (String classVal : attrValCPTCount.get(attrIdx).get(attrVal).keySet()) { output.append(" " + classVal + " - (" + attrValCPTCount.get(attrIdx).get(attrVal).get(classVal) + "/" + classPPTCount.get(classVal) + ") " + getAttrValueCPTs().get(attrIdx).get(attrVal).get(classVal)); } } } return output.toString(); } /** * @param args */ public static void main(String[] args) { try { Instrumentation instrumentation = new Instrumentation(true, System.out); Attribute outlook = new Attribute("Outlook", new String[] {"sunny", "overcast", "rain"}); Attribute temp = new Attribute("Temp.", new String[] {"hot", "mild", "cool"}); Attribute humid = new Attribute("Humidity", new String[] {"normal", "high"}); Attribute windy = new Attribute("Windy", new String[] {"yes", "no"}); Attribute enjoy = new Attribute("Enjoy?", new String[] {"yes", "no"}); CSVData weatherData = new BasicCSVData("weather.data", new Attribute[] {outlook, temp, humid, windy}, enjoy); NaiveBayesClassifier nbc = new NaiveBayesClassifier(weatherData, instrumentation); System.out.println("\nClassification of the Training Items from the Weather Data\n" + "----------------------------------------------------------"); for (String[] ex : weatherData.getData()) { nbc.classify(ex); } } catch (Exception ioe) { ioe.printStackTrace(); } } }
[ "root@eff0a031-7a33-0686-e7e6-ef33ef888833" ]
root@eff0a031-7a33-0686-e7e6-ef33ef888833
8101eeeae3aca15a284eb902b0ae747efc4a0bf7
b49ee04177c483ab7dab6ee2cd3cabb44a159967
/medicineDaChen/src/main/java/com/core/BarcodeScannerView.java
d660e64ccc6709661822a39e9a85c781f66b48f4
[]
no_license
butaotao/MedicineProject
8a22a98a559005bb95fee51b319535b117f93d5d
8e57c1e0ee0dac2167d379edd9d97306b52d3165
refs/heads/master
2020-04-09T17:29:36.570453
2016-09-13T09:17:05
2016-09-13T09:17:05
68,094,294
0
1
null
null
null
null
UTF-8
Java
false
false
6,019
java
package com.core; import android.content.Context; import android.graphics.Color; import android.graphics.Rect; import android.hardware.Camera; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.RelativeLayout; public abstract class BarcodeScannerView extends FrameLayout implements Camera.PreviewCallback { private Camera mCamera; private CameraPreview mPreview; private IViewFinder mViewFinderView; private Rect mFramingRectInPreview; private CameraHandlerThread mCameraHandlerThread; private Boolean mFlashState; private boolean mAutofocusState = true; public BarcodeScannerView(Context context) { super(context); } public BarcodeScannerView(Context context, AttributeSet attributeSet) { super(context, attributeSet); } public final void setupLayout(Camera camera) { removeAllViews(); mPreview = new CameraPreview(getContext(), camera, this); RelativeLayout relativeLayout = new RelativeLayout(getContext()); relativeLayout.setGravity(Gravity.CENTER); relativeLayout.setBackgroundColor(Color.BLACK); relativeLayout.addView(mPreview); addView(relativeLayout); mViewFinderView = createViewFinderView(getContext()); if (mViewFinderView instanceof View) { addView((View) mViewFinderView); } else { throw new IllegalArgumentException("IViewFinder object returned by " + "'createViewFinderView()' should be instance of android.view.View"); } } /** * <p>Method that creates view that represents visual appearance of a barcode scanner</p> * <p>Override it to provide your own view for visual appearance of a barcode scanner</p> * * @param context {@link Context} * @return {@link View} that implements {@link ViewFinderView} */ protected IViewFinder createViewFinderView(Context context) { return new ViewFinderView(context); } public void startCamera(int cameraId) { if(mCameraHandlerThread == null) { mCameraHandlerThread = new CameraHandlerThread(this); } mCameraHandlerThread.startCamera(cameraId); } public void setupCameraPreview(Camera camera) { mCamera = camera; if(mCamera != null) { setupLayout(mCamera); mViewFinderView.setupViewFinder(); if(mFlashState != null) { setFlash(mFlashState); } setAutoFocus(mAutofocusState); } } public void startCamera() { startCamera(-1); } public void stopCamera() { if(mCamera != null) { mPreview.stopCameraPreview(); mPreview.setCamera(null, null); mCamera.release(); mCamera = null; } if(mCameraHandlerThread != null) { mCameraHandlerThread.quit(); mCameraHandlerThread = null; } } public void stopCameraPreview() { if(mPreview != null) { mPreview.stopCameraPreview(); } } protected void resumeCameraPreview() { if(mPreview != null) { mPreview.showCameraPreview(); } } public synchronized Rect getFramingRectInPreview(int previewWidth, int previewHeight) { if (mFramingRectInPreview == null) { Rect framingRect = mViewFinderView.getFramingRect(); int viewFinderViewWidth = mViewFinderView.getWidth(); int viewFinderViewHeight = mViewFinderView.getHeight(); if (framingRect == null || viewFinderViewWidth == 0 || viewFinderViewHeight == 0) { return null; } Rect rect = new Rect(framingRect); rect.left = rect.left * previewWidth / viewFinderViewWidth; rect.right = rect.right * previewWidth / viewFinderViewWidth; rect.top = 100; rect.bottom = rect.bottom * previewHeight / viewFinderViewHeight; mFramingRectInPreview = rect; } return mFramingRectInPreview; } public void setFlash(boolean flag) { mFlashState = flag; if(mCamera != null && CameraUtils.isFlashSupported(mCamera)) { Camera.Parameters parameters = mCamera.getParameters(); if(flag) { if(parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) { return; } parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); } else { if(parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) { return; } parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } mCamera.setParameters(parameters); } } public boolean getFlash() { if(mCamera != null && CameraUtils.isFlashSupported(mCamera)) { Camera.Parameters parameters = mCamera.getParameters(); if(parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) { return true; } else { return false; } } return false; } public void toggleFlash() { if(mCamera != null && CameraUtils.isFlashSupported(mCamera)) { Camera.Parameters parameters = mCamera.getParameters(); if(parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } else { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); } mCamera.setParameters(parameters); } } public void setAutoFocus(boolean state) { mAutofocusState = state; if(mPreview != null) { mPreview.setAutoFocus(state); } } }
[ "1802928215@qq.com" ]
1802928215@qq.com
94b95814cc3b32c6c5f09623bba4ba3f77a1337a
c1c8e67e0f02de1ae9ab2c5d8981f23d07c67079
/app/src/test/java/com/codementor/android/codementortest1/ExampleUnitTest.java
d559f30b6f148df51d134674717d7f4ca3aaa95f
[]
no_license
TonyKazanjian/codementortest1
ca9fb02e8ef1c7966a230c657dfbdb8e55cfcca7
2ab4ac52cbd599c6a2665ed1a65ad7df35692399
refs/heads/master
2021-01-10T15:18:55.353538
2015-12-17T00:49:39
2015-12-17T00:49:39
48,143,598
0
0
null
null
null
null
UTF-8
Java
false
false
331
java
package com.codementor.android.codementortest1; 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); } }
[ "tony.kazanjian@gmail.com" ]
tony.kazanjian@gmail.com
cdc5f65edcbd691e51347115bf8548b11804e0d0
a36f6b1f18fd3694d6b5a160751a31641cda6150
/src/game/interfaces/Resettable.java
aec7b7ef3e48ef27b2a9ebd771d210324b9cf5a3
[]
no_license
isha-k/Java-Rougelike-game-Assignment
901e00bacffca04d2d81d2d2a16442470e349360
67cd0ec3734398e396c952c7678fca6df502e668
refs/heads/main
2023-09-02T15:12:41.128399
2021-11-22T01:37:55
2021-11-22T01:37:55
430,526,633
0
0
null
null
null
null
UTF-8
Java
false
false
862
java
package game.interfaces; import game.ResetManager; public interface Resettable { /** * Allows any classes that use this interface to reset abilities, attributes, and items. * TODO: Use this method in a reset manager to run the soft-reset. */ void resetInstance(); /** * A useful method to clean up the list of instances in the ResetManager class * @return the existence of the instance in the game. * for example, true to keep it permanent, or false if instance needs to be removed from the reset list. */ boolean isExist(); /** * a default interface method that register current instance to the Singleton manager. * TODO: Use this method at the constructor of `this` instance. */ default void registerInstance(){ ResetManager.getInstance().appendResetInstance(this); } }
[ "ikau0006@student.monash.edu" ]
ikau0006@student.monash.edu
329b3099e3bde46ca53143b4bb86fa4b2ad0c4ec
7f31bbbba3749a66bdb97c72e56f7b038625254f
/zftlive/zftlive/apps/zftlive-framework-samples/src/main/java/com/zftlive/android/sample/pulltorefresh/PullToRefreshWebView2Activity.java
dcbf081ace9c77f424a0b28cb2057be6efe26b71
[ "Apache-2.0" ]
permissive
ruanxuexiong/demo
a6aa04825b4f8063258756d56d30a37bc1b3d877
7ca3c71051f85ab6d28e75599e7c38a13bed8d3a
refs/heads/master
2020-05-22T05:27:57.313371
2019-05-12T10:03:41
2019-05-12T10:03:41
186,235,930
0
0
null
null
null
null
UTF-8
Java
false
false
2,832
java
/* * Android基础开发个人积累、沉淀、封装、整理共通 * Copyright (c) 2016. 曾繁添 <zftlive@163.com> * Github:https://github.com/zengfantian || http://git.oschina.net/zftlive * * 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.zftlive.android.sample.pulltorefresh; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import com.zftlive.android.R; import com.zftlive.android.library.widget.pulltorefresh.PullToRefreshBase; import com.zftlive.android.library.widget.pulltorefresh.PullToRefreshBase.OnRefreshListener; import com.zftlive.android.library.widget.pulltorefresh.extras.PullToRefreshWebView2; public final class PullToRefreshWebView2Activity extends Activity implements OnRefreshListener<WebView> { /** Called when the activity is first created. */ @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ptr_webview2); PullToRefreshWebView2 pullRefreshWebView = (PullToRefreshWebView2) findViewById(R.id.pull_refresh_webview2); pullRefreshWebView.setOnRefreshListener(this); WebView webView = pullRefreshWebView.getRefreshableView(); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new SampleWebViewClient()); // We just load a prepared HTML page from the assets folder for this // sample, see that file for the Javascript implementation webView.loadUrl("file:///android_asset/ptr_webview2_sample.html"); //初始化带返回按钮的标题栏 // ActionBarManager.initBackTitle(this, getActionBar(), this.getClass().getSimpleName()); } private static class SampleWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } @Override public void onRefresh(final PullToRefreshBase<WebView> refreshView) { // This is very contrived example, we just wait 2 seconds, then call // onRefreshComplete() refreshView.postDelayed(new Runnable() { @Override public void run() { refreshView.onRefreshComplete(); } }, 2 * 1000); } }
[ "412877174@qq.com" ]
412877174@qq.com
aadb850c0c64f6974c5566546c914cd7bb802f40
995f73d30450a6dce6bc7145d89344b4ad6e0622
/Mate20-9.0/src/main/java/com/huawei/wallet/sdk/common/log/Logger.java
48986d3f11ea53f4ea78c357e343dfe600a17302
[]
no_license
morningblu/HWFramework
0ceb02cbe42585d0169d9b6c4964a41b436039f5
672bb34094b8780806a10ba9b1d21036fd808b8e
refs/heads/master
2023-07-29T05:26:14.603817
2021-09-03T05:23:34
2021-09-03T05:23:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,445
java
package com.huawei.wallet.sdk.common.log; import java.util.Map; public class Logger { private String mTag; public static class Builder { /* access modifiers changed from: private */ public String module; /* access modifiers changed from: private */ public String tag; public Logger build() { return new Logger(this); } public Builder setTag(String tag2) { this.tag = tag2; return this; } public Builder setModule(String module2) { this.module = module2; return this; } public Builder depth(int depth) { return this; } } Logger(Builder builder) { String str; if (builder.module != null) { this.mTag = builder.module + ":"; } if (builder.tag != null) { if (this.mTag == null) { str = builder.tag; } else { str = this.mTag + builder.tag; } this.mTag = str; } } public static Builder tag(String tag) { return new Builder().setTag(tag); } public static Builder module(String module) { return new Builder().setModule(module); } public static boolean isDebugLogEnable() { return LogUtil.isDebugLogEnable(); } public static void d(String tag, String msg, boolean isNeedProguard) { LogUtil.d(tag, msg, isNeedProguard); } public static void i(String tag, String msg, boolean isNeedProguard) { LogUtil.i(tag, msg, isNeedProguard); } public static void i(String tag, String msg, Throwable e, boolean isNeedProguard) { LogUtil.i(tag, msg, e, isNeedProguard); } public static void w(String tag, String msg, boolean isNeedProguard) { LogUtil.e(tag, msg, null, isNeedProguard); } public static void w(String tag, String msg, Throwable e, boolean isNeedProguard) { LogUtil.e(tag, msg, e, isNeedProguard); } public static void e(String tag, String msg, boolean isNeedProguard) { LogUtil.e(tag, msg, null, isNeedProguard); } public static void e(String tag, String msg, Throwable e, boolean isNeedProguard) { LogUtil.e(tag, msg, e, isNeedProguard); } public static void e(String tag, String message, Throwable e, int errorCode, Map<String, String> map, boolean uploadLog, boolean isNeedProguard) { if (message != null) { LogUtil.e(tag, message, e, isNeedProguard); } } public void d(String msg, boolean isNeedProguard) { LogUtil.d(this.mTag, msg, isNeedProguard); } public void i(String msg, boolean isNeedProguard) { LogUtil.i(this.mTag, msg, isNeedProguard); } public void i(String msg, Throwable e, boolean isNeedProguard) { LogUtil.i(this.mTag, msg, e, isNeedProguard); } public void w(String msg, boolean isNeedProguard) { LogUtil.e(this.mTag, msg, null, isNeedProguard); } public void w(String msg, Throwable e, boolean isNeedProguard) { LogUtil.e(this.mTag, msg, e, isNeedProguard); } public void e(String msg, boolean isNeedProguard) { LogUtil.e(this.mTag, msg, null, isNeedProguard); } public void e(String msg, Throwable e, boolean isNeedProguard) { LogUtil.e(this.mTag, msg, e, isNeedProguard); } }
[ "dstmath@163.com" ]
dstmath@163.com
35c2ea22ec0401bce610d1ebf5823ee621493d9b
24d8cf871b092b2d60fc85d5320e1bc761a7cbe2
/JabRef/rev2119-2213/left-trunk-2213/java/net/sf/jabref/imports/EndnoteImporter.java
008c61443db3001f6ef69f11077b08728860afaa
[]
no_license
joliebig/featurehouse_fstmerge_examples
af1b963537839d13e834f829cf51f8ad5e6ffe76
1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad
refs/heads/master
2016-09-05T10:24:50.974902
2013-03-28T16:28:47
2013-03-28T16:28:47
9,080,611
3
2
null
null
null
null
UTF-8
Java
false
false
5,967
java
package net.sf.jabref.imports; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Pattern; import net.sf.jabref.*; public class EndnoteImporter extends ImportFormat { public String getFormatName() { return "Refer/Endnote"; } public String getCLIId() { return "refer"; } public boolean isRecognizedFormat(InputStream stream) throws IOException { BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream)); Pattern pat1 = Pattern.compile("%A .*"), pat2 = Pattern.compile("%E .*"); String str; while ((str = in.readLine()) != null){ if (pat1.matcher(str).matches() || pat2.matcher(str).matches()) return true; } return false; } public List<BibtexEntry> importEntries(InputStream stream) throws IOException { ArrayList<BibtexEntry> bibitems = new ArrayList<BibtexEntry>(); StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream)); String ENDOFRECORD = "__EOREOR__"; String str; boolean first = true; while ((str = in.readLine()) != null){ str = str.trim(); if (str.indexOf("%0") == 0){ if (first){ first = false; }else{ sb.append(ENDOFRECORD); } sb.append(str); }else sb.append(str); sb.append("\n"); } String[] entries = sb.toString().split(ENDOFRECORD); HashMap<String, String> hm = new HashMap<String, String>(); String author = "", Type = "", editor = ""; for (int i = 0; i < entries.length; i++){ hm.clear(); author = ""; Type = ""; editor = ""; boolean IsEditedBook = false; String[] fields = entries[i].trim().substring(1).split("\n%"); for (int j = 0; j < fields.length; j++){ if (fields[j].length() < 3) continue; String prefix = fields[j].substring(0, 1); String val = fields[j].substring(2); if (prefix.equals("A")){ if (author.equals("")) author = val; else author += " and " + val; }else if (prefix.equals("E")){ if (editor.equals("")) editor = val; else editor += " and " + val; }else if (prefix.equals("T")) hm.put("title", val); else if (prefix.equals("0")){ if (val.indexOf("Journal") == 0) Type = "article"; else if ((val.indexOf("Book Section") == 0)) Type = "incollection"; else if ((val.indexOf("Book") == 0)) Type = "book"; else if (val.indexOf("Edited Book") == 0) { Type = "book"; IsEditedBook = true; }else if (val.indexOf("Conference") == 0) Type = "inproceedings"; else if (val.indexOf("Report") == 0) Type = "techreport"; else if (val.indexOf("Review") == 0) Type = "article"; else if (val.indexOf("Thesis") == 0) Type = "phdthesis"; else Type = "misc"; }else if (prefix.equals("7")) hm.put("edition", val); else if (prefix.equals("C")) hm.put("address", val); else if (prefix.equals("D")) hm.put("year", val); else if (prefix.equals("8")) hm.put("date", val); else if (prefix.equals("J")){ if (hm.get("journal") == null) hm.put("journal", val); }else if (prefix.equals("B")){ if (Type.equals("article")) hm.put("journal", val); else if (Type.equals("book") || Type.equals("inbook")) hm.put( "series", val); else hm.put("booktitle", val); }else if (prefix.equals("I")) { if (Type.equals("phdthesis")) hm.put("school", val); else hm.put("publisher", val); } else if (prefix.equals("P")) hm.put("pages", val.replaceAll("([0-9]) *- *([0-9])","$1--$2")); else if (prefix.equals("V")) hm.put("volume", val); else if (prefix.equals("N")) hm.put("number", val); else if (prefix.equals("U")) hm.put("url", val); else if (prefix.equals("O")) hm.put("note", val); else if (prefix.equals("K")) hm.put("keywords", val); else if (prefix.equals("X")) hm.put("abstract", val); else if (prefix.equals("9")){ if (val.indexOf("Ph.D.") == 0) Type = "phdthesis"; if (val.indexOf("Masters") == 0) Type = "mastersthesis"; }else if (prefix.equals("F")) hm.put(BibtexFields.KEY_FIELD, Util .checkLegalKey(val)); } if (IsEditedBook && editor.equals("")) { editor = author; author = ""; } if (!author.equals("")) hm.put("author", fixAuthor(author)); if (!editor.equals("")) hm.put("editor", fixAuthor(editor)); BibtexEntry b = new BibtexEntry(BibtexFields.DEFAULT_BIBTEXENTRY_ID, Globals .getEntryType(Type)); b.setField(hm); if (b.getAllFields().length > 0) bibitems.add(b); } return bibitems; } private String fixAuthor(String s) { int index = s.indexOf(" and "); if (index >= 0) return AuthorList.fixAuthor_lastNameFirst(s); index = s.lastIndexOf(","); if (index == s.length()-1) { String mod = s.substring(0, s.length()-1).replaceAll(", ", " and "); return AuthorList.fixAuthor_lastNameFirst(mod); } else return AuthorList.fixAuthor_lastNameFirst(s); } }
[ "joliebig@fim.uni-passau.de" ]
joliebig@fim.uni-passau.de
1d85979305f8c6627b1477b7ffa66378bf5e5e20
76a1f5162aa33f077aa8ef141bfacd54732fa1dd
/Java/test.java
98787416c55062a903913308aee60d016bc7b735
[]
no_license
kongzx/rsa-service
d269db1f6d5e2ec2fdf0bcc8c1f2191049740e71
ed2f44973a5af50b2f3465ef262046c802e8b8aa
refs/heads/master
2022-10-09T10:06:58.906571
2022-09-30T02:30:11
2022-09-30T02:30:11
250,005,265
11
7
null
null
null
null
UTF-8
Java
false
false
2,093
java
import com.kongzhixiong.Rsa.jsencrypt; public class JavaApplication2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here jsencrypt jsen=new jsencrypt(); String publickey="-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB-----END PUBLIC KEY-----"; String privatekey="-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQABAoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fvxTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeHm7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAFz/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIMV7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATeaTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5AzilpsLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Ozuku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876-----END RSA PRIVATE KEY-----"; System.out.println("----------117位字符加密--------"); String pris=jsen.setEncrypt(publickey,"str12355546655454"); System.out.println(pris); System.out.println("----------117位字符解密--------"); String str=jsen.setDecrypt(privatekey,pris); System.out.println(str); List<String> infoArray=jsen.setLongEncrypt(publickey,pris); out.println("----------长加密--------"); for(String strc:infoArray) { System.out.println(strc); } System.out.println("----------数组解密--------"); String info=jsen.setDecryptArray(privatekey,infoArray); System.out.println(info); } }
[ "1101807353@qq.com" ]
1101807353@qq.com
47419bd9a24b3b350345a59d496e87e4a2b467e2
3fd919f767df07acf0ba6519e87b7a3ca20ccd74
/notification-service/src/main/java/com/skb/notification/push/AndroidNotification.java
8c93445ded4fecbd078a2d5c06f21b173cc6cf62
[]
no_license
yinqiao2017/saikube-parent
bd1f47e8fdfc4cf31a1ff898f82c950cd74b910f
ff6b88fdf3903a8d6bd4b9a3a00eb40fcab177a7
refs/heads/master
2021-01-19T07:16:35.036408
2017-04-08T10:29:22
2017-04-08T10:29:22
87,534,110
0
0
null
null
null
null
UTF-8
Java
false
false
7,296
java
package com.skb.notification.push; import org.json.JSONObject; import java.util.Arrays; import java.util.HashSet; public abstract class AndroidNotification extends UmengNotification { // Keys can be set in the payload level protected static final HashSet<String> PAYLOAD_KEYS = new HashSet<String>(Arrays.asList(new String[]{ "display_type"})); // Keys can be set in the body level protected static final HashSet<String> BODY_KEYS = new HashSet<String>(Arrays.asList(new String[]{ "ticker", "title", "text", "builder_id", "icon", "largeIcon", "img", "play_vibrate", "play_lights", "play_sound", "sound", "after_open", "url", "activity", "custom"})); public enum DisplayType{ NOTIFICATION{public String getValue(){return "notification";}},///通知:消息送达到用户设备后,由友盟SDK接管处理并在通知栏上显示通知内容。 MESSAGE{public String getValue(){return "message";}};///消息:消息送达到用户设备后,消息内容透传给应用自身进行解析处理。 public abstract String getValue(); } public enum AfterOpenAction{ go_app,//打开应用 go_url,//跳转到URL go_activity,//打开特定的activity go_custom//用户自定义内容。 } // Set key/value in the rootJson, for the keys can be set please see ROOT_KEYS, PAYLOAD_KEYS, // BODY_KEYS and POLICY_KEYS. @Override public boolean setPredefinedKeyValue(String key, Object value) throws Exception { if (ROOT_KEYS.contains(key)) { // This key should be in the root level rootJson.put(key, value); } else if (PAYLOAD_KEYS.contains(key)) { // This key should be in the payload level JSONObject payloadJson = null; if (rootJson.has("payload")) { payloadJson = rootJson.getJSONObject("payload"); } else { payloadJson = new JSONObject(); rootJson.put("payload", payloadJson); } payloadJson.put(key, value); } else if (BODY_KEYS.contains(key)) { // This key should be in the body level JSONObject bodyJson = null; JSONObject payloadJson = null; // 'body' is under 'payload', so build a payload if it doesn't exist if (rootJson.has("payload")) { payloadJson = rootJson.getJSONObject("payload"); } else { payloadJson = new JSONObject(); rootJson.put("payload", payloadJson); } // Get body JSONObject, generate one if not existed if (payloadJson.has("body")) { bodyJson = payloadJson.getJSONObject("body"); } else { bodyJson = new JSONObject(); payloadJson.put("body", bodyJson); } bodyJson.put(key, value); } else if (POLICY_KEYS.contains(key)) { // This key should be in the body level JSONObject policyJson = null; if (rootJson.has("policy")) { policyJson = rootJson.getJSONObject("policy"); } else { policyJson = new JSONObject(); rootJson.put("policy", policyJson); } policyJson.put(key, value); } else { if (key == "payload" || key == "body" || key == "policy" || key == "extra") { throw new Exception("You don't need to set value for " + key + " , just set values for the sub keys in it."); } else { throw new Exception("Unknown key: " + key); } } return true; } // Set extra key/value for Android notification public boolean setExtraField(String key, String value) throws Exception { JSONObject payloadJson = null; JSONObject extraJson = null; if (rootJson.has("payload")) { payloadJson = rootJson.getJSONObject("payload"); } else { payloadJson = new JSONObject(); rootJson.put("payload", payloadJson); } if (payloadJson.has("extra")) { extraJson = payloadJson.getJSONObject("extra"); } else { extraJson = new JSONObject(); payloadJson.put("extra", extraJson); } extraJson.put(key, value); return true; } // public void setDisplayType(DisplayType d) throws Exception { setPredefinedKeyValue("display_type", d.getValue()); } ///通知栏提示文字 public void setTicker(String ticker) throws Exception { setPredefinedKeyValue("ticker", ticker); } ///通知标题 public void setTitle(String title) throws Exception { setPredefinedKeyValue("title", title); } ///通知文字描述 public void setText(String text) throws Exception { setPredefinedKeyValue("text", text); } ///用于标识该通知采用的样式。使用该参数时, 必须在SDK里面实现自定义通知栏样式。 public void setBuilderId(Integer builder_id) throws Exception { setPredefinedKeyValue("builder_id", builder_id); } ///状态栏图标ID, R.drawable.[smallIcon],如果没有, 默认使用应用图标。 public void setIcon(String icon) throws Exception { setPredefinedKeyValue("icon", icon); } ///通知栏拉开后左侧图标ID public void setLargeIcon(String largeIcon) throws Exception { setPredefinedKeyValue("largeIcon", largeIcon); } ///通知栏大图标的URL链接。该字段的优先级大于largeIcon。该字段要求以http或者https开头。 public void setImg(String img) throws Exception { setPredefinedKeyValue("img", img); } ///收到通知是否震动,默认为"true" public void setPlayVibrate(Boolean play_vibrate) throws Exception { setPredefinedKeyValue("play_vibrate", play_vibrate.toString()); } ///收到通知是否闪灯,默认为"true" public void setPlayLights(Boolean play_lights) throws Exception { setPredefinedKeyValue("play_lights", play_lights.toString()); } ///收到通知是否发出声音,默认为"true" public void setPlaySound(Boolean play_sound) throws Exception { setPredefinedKeyValue("play_sound", play_sound.toString()); } ///通知声音,R.raw.[sound]. 如果该字段为空,采用SDK默认的声音 public void setSound(String sound) throws Exception { setPredefinedKeyValue("sound", sound); } ///收到通知后播放指定的声音文件 public void setPlaySound(String sound) throws Exception { setPlaySound(true); setSound(sound); } ///点击"通知"的后续行为,默认为打开app。 public void goAppAfterOpen() throws Exception { setAfterOpenAction(AfterOpenAction.go_app); } public void goUrlAfterOpen(String url) throws Exception { setAfterOpenAction(AfterOpenAction.go_url); setUrl(url); } public void goActivityAfterOpen(String activity) throws Exception { setAfterOpenAction(AfterOpenAction.go_activity); setActivity(activity); } public void goCustomAfterOpen(String custom) throws Exception { setAfterOpenAction(AfterOpenAction.go_custom); setCustomField(custom); } public void goCustomAfterOpen(JSONObject custom) throws Exception { setAfterOpenAction(AfterOpenAction.go_custom); setCustomField(custom); } ///点击"通知"的后续行为,默认为打开app。原始接口 public void setAfterOpenAction(AfterOpenAction action) throws Exception { setPredefinedKeyValue("after_open", action.toString()); } public void setUrl(String url) throws Exception { setPredefinedKeyValue("url", url); } public void setActivity(String activity) throws Exception { setPredefinedKeyValue("activity", activity); } ///can be a string of json public void setCustomField(String custom) throws Exception { setPredefinedKeyValue("custom", custom); } public void setCustomField(JSONObject custom) throws Exception { setPredefinedKeyValue("custom", custom); } }
[ "yinqiao@banggood.cn" ]
yinqiao@banggood.cn