blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
156969889ba0ca63b0f80786bc72023ed263de21 | Java | pkhachatrian/voicePlusPlus | /voicePlusPlus-sphinx4/src/main/java/voicePlusPlus/voicePlusPlus_sphinx4/App.java | UTF-8 | 9,118 | 2.96875 | 3 | [] | no_license | package voicePlusPlus.voicePlusPlus_sphinx4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import org.junit.Test;
import static org.junit.Assert.*;
public class App {
public static ArrayList<APICommand> commands = new ArrayList<APICommand>();
public static void main(String[] args) {
FreeswitchClient freeswitch = new FreeswitchClient();
String phoneNumber = "";
processUtterance("invocabot list all of my meetings for today");
freeswitch.ConnectToServer();
freeswitch.AddEventListeners();
while (true) {
System.out.println("Hit Enter To Initiate Call...");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
in.readLine();
} catch (IOException e) {
}
freeswitch.InitiatePhoneCall(phoneNumber);
}
}
public static String processUtterance(String utterance) {
APICommand command = new APICommand();
TaskManager.instantiateHashTable("./src/main/resources/keywords.txt");
utterance = convertNumbersAsTextToDigits(utterance);
System.out.println(utterance);
String commandString = utterance;
// String commandString = SphinxManager.getCommand(utterance);
// if (commandString == null || commandString.equals("")) {
// return;
// }
String determinedAPI;
determinedAPI = TaskManager.determineAPI(commandString);
if (determinedAPI == null)
return null;
command.setAPI(determinedAPI);
if (command.getCommand().equals(APIs.GOOGLE_CALENDAR)) {
commandString = convertNumbersAsTextToDigits(utterance);
}
//System.out.println(command.getCommand());
if (command.getCommand() == null) {
return null;
}
command.setCommand(commandString);
TaskManager.invokeAPICommand(command);
return "SUCCESSFULLY SCHEDULED APPOINTMENT";
}
/**
* Prints all the commands that the user has said throughout the call.
*/
public static void printAllCommands() {
for(int i=0; i<App.commands.size(); i++) {
String command = App.commands.get(i).getCommand();
String API = App.commands.get(i).getAPI();
System.out.println("Command #" + (i + 1) + ": " + API + "\t" + command);
}
}
/**
* Converts a string with numbers as text to a string with numbers as digits.
* For example, "one thirty two" would be "1:32".
*
* @param eventText the string to convert
* @return the string with numbers as digits
*/
public static String convertNumbersAsTextToDigits(String eventText) {
HashSet<String> setOnes = new HashSet<String>();
HashSet<String> setTeens = new HashSet<String>();
HashSet<String> setDecades = new HashSet<String>();
setOnes.add("one");
setOnes.add("two");
setOnes.add("three");
setOnes.add("four");
setOnes.add("five");
setOnes.add("six");
setOnes.add("seven");
setOnes.add("eight");
setOnes.add("nine");
setTeens.add("ten");
setTeens.add("eleven");
setTeens.add("twelve");
setTeens.add("thirteen");
setTeens.add("fourteen");
setTeens.add("fifteen");
setTeens.add("sixteen");
setTeens.add("seventeen");
setTeens.add("eighteen");
setTeens.add("nineteen");
setDecades.add("twenty");
setDecades.add("thirty");
setDecades.add("forty");
setDecades.add("fifty");
String words[] = eventText.split(" ");
StringBuilder sb = new StringBuilder();
boolean notLastWord = true;
boolean colon = false;
for (int i=0; i<words.length; i++) {
colon = false;
if (i == words.length - 1) {
notLastWord = false;
}
if (setTeens.contains(words[i])) {
switch (words[i]) {
case "ten":
sb.append("10");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "eleven":
sb.append("11");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "twelve":
sb.append("12");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "thirteen":
sb.append("13");
break;
case "fourteen":
sb.append("14");
break;
case "fifteen":
sb.append("15");
break;
case "sixteen":
sb.append("16");
break;
case "seventeen":
sb.append("17");
break;
case "eighteen":
sb.append("18");
break;
case "nineteen":
sb.append("19");
break;
}
}
else if (setDecades.contains(words[i])) {
int value = 0;
switch (words[i]) {
case "twenty":
value = 20;
break;
case "thirty":
value = 30;
break;
case "forty":
value = 40;
break;
case "fifty":
value = 50;
break;
}
if (notLastWord && setOnes.contains(words[i+1])) {
switch (words[i+1]) {
case "one":
value += 1;
break;
case "two":
value += 2;
break;
case "three":
value += 3;
break;
case "four":
value += 4;
break;
case "five":
value += 5;
break;
case "six":
value += 6;
break;
case "seven":
value += 7;
break;
case "eight":
value += 8;
break;
case "nine":
value += 9;
break;
}
i++;
if (i == words.length - 1) {
notLastWord = false;
}
}
sb.append(value);
}
else if (setOnes.contains(words[i])) {
switch (words[i]) {
case "one":
sb.append("1");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "two":
sb.append("2");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "three":
sb.append("3");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "four":
sb.append("4");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "five":
sb.append("5");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "six":
sb.append("6");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "seven":
sb.append("7");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "eight":
sb.append("8");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
case "nine":
sb.append("9");
if (notLastWord && (setOnes.contains(words[i+1]) || setTeens.contains(words[i+1]) || setDecades.contains(words[i+1]))) {
sb.append(":");
}
break;
}
colon = true;
}
else {
sb.append(words[i]);
}
if (notLastWord && !colon) {
sb.append(" ");
}
}
return sb.toString();
}
@Test
public static void TestConvertNumbersAsTextToDigits() {
String s1 = "twenty";
String s2 = "forty one";
String s3 = "one forty";
String s4 = "schedule a meeting at one forty pm";
String s5 = "";
String s6 = "one forty five";
String s7 = "two twelve";
assertEquals("20", convertNumbersAsTextToDigits(s1));
assertEquals("41", convertNumbersAsTextToDigits(s2));
assertEquals("1:40", convertNumbersAsTextToDigits(s3));
assertEquals("schedule a meeting at 1:40 pm", convertNumbersAsTextToDigits(s4));
assertEquals("", convertNumbersAsTextToDigits(s5));
assertEquals("1:45", convertNumbersAsTextToDigits(s6));
assertEquals("2:12", convertNumbersAsTextToDigits(s7));
}
} | true |
0a10c0a0b6d495efcddfd23e2768a6590c72634f | Java | klezovics/java-sketchbook | /src/test/java/com/klezovich/demo/unittest/PiSupplierTest.java | UTF-8 | 352 | 2.203125 | 2 | [] | no_license | package com.klezovich.demo.unittest;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;
class PiSupplierTest {
private final PiSupplier supplier = new PiSupplier();
@Test
void get() {
assertThat(supplier.get(), closeTo(3.1415, 0.00001));
}
} | true |
56a4c377da8dc4550a67fd926944973874948f8f | Java | fanshen2010/P2P_lending | /p2p_all/p2p_mgrweb/src/main/java/cn/com/p2p/mgr/action/content/AdvertisingAction.java | UTF-8 | 4,509 | 2.078125 | 2 | [] | no_license | package cn.com.p2p.mgr.action.content;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import cn.com.p2p.contentmanagent.service.AdvertisingService;
import cn.com.p2p.domain.cms.entity.Advertising;
import cn.com.p2p.framework.context.annotation.Validators;
import cn.com.p2p.framework.web.action.BaseAction;
/**
* <p>广告位管理</p>
* @author zhushanyu
* @date 2015-04-23 09:35
*/
@Namespace("/content/advertising")
@Results({
@Result(name = BaseAction.INIT, location = "advertisingindex.ftl", type = "freemarker"),
@Result(name = BaseAction.EDIT, location = "advertisingedit.ftl", type = "freemarker"),
@Result(name = BaseAction.SAVE, location = "index.htm", type = "redirect"),
@Result(name = BaseAction.UPDATE, location = "index.htm", type = "redirect"),
@Result(name = BaseAction.DELETE, location = "index.htm", type = "redirect"),
})
public class AdvertisingAction extends BaseAction{
private static final long serialVersionUID = 1L;
/** 广告位管理服务接口 */
@Autowired
private AdvertisingService advertisingService;
/** 广告栏目实体 */
private Advertising advertising;
/** 广告栏目实体集合 */
private List<Advertising> advertisings;
/**
* <p>列表界面</p>
* @author zhushanyu
* @date 2015-04-23 09:37
* @description 无
*/
@Action(value="index")
public String init() {
advertisings = advertisingService.findAll();
return INIT;
}
/**
* <p>修改界面</p>
* @author zhushanyu
* @date 2015-04-23 10:16
* @description 无
*/
@Action(value="edit")
public String edit() {
advertising = advertisingService.findOne(advertising.getId());
return EDIT;
}
/**
* <p>删除操作</p>
* @author zhushanyu
* @date 2015-04-23 10:23
* @description 无
*/
@Action(value="delete")
public String delete() {
int count = advertisingService.delete(advertising.getId());
if(count == 1){
// 删除成功后的操作
this.delSuccess();
}else{
this.delFailure();
}
return null;
}
/**
* <p>更新操作</p>
* @author zhushanyu
* @date 2015-04-23 10:36
* @description 动态的更新实体,待更新的实体属性为空时,此字段不更新
*/
@Validators(str="advertisingCheck",result = BaseAction.INIT, param = "update")
@Action(value="update")
public String update() {
advertisingService.dynamicUpdate(advertising);
return UPDATE;
}
/**
* <p>保存操作</p>
* @author zhushanyu
* @date 2015-04-23 10:58
* @description 无
*/
@Validators(str="advertisingCheck",result = BaseAction.INIT, param = "save")
@Action(value="save")
public String save() {
advertisingService.save(advertising);
return SAVE;
}
/**
* <p>校验编码的唯一性</p>
* @author zhushanyu
* @date 2015-04-23 10:58
* @description 用户未修改原有编码时,校验通过
*/
@Action(value="checkAdvertisingCode")
public String checkAdvertisingCode() {
try {
String data = this.getAjaxMap().get("advertising.adverCode").toString();
boolean isUsable = advertisingService.checkAdvertisingCode(data, advertising.getId());
if(isUsable){
this.ajaxCheckSuccess();
}else{
this.ajaxCheckFailure();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/* ========================================= getter、setter 方法 ========================================== */
public Advertising getAdvertising() {
return advertising;
}
public void setAdvertising(Advertising advertising) {
this.advertising = advertising;
}
public List<Advertising> getAdvertisings() {
return advertisings;
}
public void setAdvertisings(List<Advertising> advertisings) {
this.advertisings = advertisings;
}
}
| true |
1b015cb40276aa857328bb8361e3159179cfe47c | Java | HemersonGH/sigesdp | /backend/app/serializers/DateSerializer.java | UTF-8 | 897 | 2.328125 | 2 | [] | no_license | package serializers;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import flexjson.transformer.DateTransformer;
import flexjson.transformer.Transformer;
import play.Play;
public class DateSerializer implements JsonSerializer<Date> {
private static final String DATE_FORMAT = Play.configuration.getProperty("date.format");
@Override
public JsonElement serialize(Date date, Type arg1, JsonSerializationContext arg2) {
SimpleDateFormat simpleDateFormatter = new SimpleDateFormat(DATE_FORMAT);
return new JsonPrimitive(simpleDateFormatter.format(date));
}
public static Transformer getTransformer() {
return new DateTransformer(DATE_FORMAT);
}
}
| true |
cc65ac7eec6176437b8a244c79a93700bfe9f04e | Java | dgtyPedro/Appify | /Appify/app/src/main/java/com/spotify_api_example/MainActivity.java | UTF-8 | 2,650 | 2.140625 | 2 | [] | no_license | package com.spotify_api_example;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.spotify.sdk.android.authentication.AuthenticationClient;
import com.spotify.sdk.android.authentication.AuthenticationRequest;
import com.spotify.sdk.android.authentication.AuthenticationResponse;
import com.spotify_api_example.Connectors.SongService;
import com.spotify_api_example.Model.Song;
import com.spotify_api_example.Model.User;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashSet;
import static com.spotify.sdk.android.authentication.LoginActivity.REQUEST_CODE;
public class MainActivity extends AppCompatActivity {
private TextView userView;
private TextView songView;
private Button addBtn;
private Button skipBtn;
private Song song;
private SongService songService;
private ArrayList<Song> recentlyPlayedTracks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songService = new SongService(getApplicationContext());
userView = (TextView) findViewById(R.id.user);
songView = (TextView) findViewById(R.id.song);
addBtn = (Button) findViewById(R.id.add);
skipBtn = (Button) findViewById(R.id.skip);
SharedPreferences sharedPreferences = this.getSharedPreferences("SPOTIFY", 0);
userView.setText(sharedPreferences.getString("userid", "No User"));
getTracks();
addBtn.setOnClickListener(addListener);
skipBtn.setOnClickListener(skipListener);
}
private View.OnClickListener addListener = v -> {
songService.addSongToLibrary(this.song);
if (recentlyPlayedTracks.size() > 0) {
recentlyPlayedTracks.remove(0);
}
updateSong();
};
private void getTracks() {
songService.getRecentlyPlayedTracks(() -> {
recentlyPlayedTracks = songService.getSongs();
updateSong();
});
}
private View.OnClickListener skipListener = v -> {
if (recentlyPlayedTracks.size() > 0) {
recentlyPlayedTracks.remove(0);
}
updateSong();
};
private void updateSong() {
if (recentlyPlayedTracks.size() > 0) {
songView.setText(recentlyPlayedTracks.get(0).getName());
song = recentlyPlayedTracks.get(0);
}
}
}
| true |
5b36efe0c134746133f5bc04405c3cfec9bf54f5 | Java | chunbolin/leetcode | /src/ALi3.java | UTF-8 | 1,150 | 3.28125 | 3 | [] | no_license | import java.util.*;
public class ALi3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] nums = new long[n];
long[] l = new long[n];
long[] r = new long[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextLong();
}
List<Integer> s = new LinkedList<>();
for (int i = 0; i < n; i++) {
while (!s.isEmpty() && nums[s.get(s.size() - 1)] < nums[i]) {
int index = s.get(s.size() - 1);
s.remove(s.size() - 1);
r[index] = i + 1;
}
s.add(i);
}
s.clear();
for (int i = n - 1; i >= 0; i--) {
while (!s.isEmpty() && nums[s.get(s.size() - 1)] < nums[i]) {
int index = s.get(s.size() - 1);
s.remove(s.size() - 1);
l[index] = i + 1;
}
s.add(i);
}
long max = Long.MIN_VALUE;
for (int i = 0; i < n; i++) {
max = Math.max(l[i] * r[i], max);
}
System.out.println(max);
}
}
| true |
87b9aeb1127ad0c15b5d102c740cd40178f38075 | Java | eo339912/yedam2020 | /HelloWorld/src/com/yedam/ljw/classes/PeopleExample.java | UTF-8 | 665 | 3.3125 | 3 | [] | no_license | package com.yedam.ljw.classes;
public class PeopleExample {
public static void main(String[] args) {
People pl2 = new People("Park");
System.out.println(pl2.name);
System.out.println(pl2.age);
People pl = new People("Park", 20, 170);
System.out.println(pl.name);
System.out.println(pl.age);
System.out.println(pl.height);
People pp = new People();
pp.name = "Lee";
pp.age = 15;
pp.height = 180;
System.out.println(pp.name);
System.out.println(pp.age);
System.out.println(pp.height);
//메소드
pp.information();
System.out.println(pp.getAge());
System.out.println(pp.getHeight());
}
}
| true |
c5b405e73987c648c5b5b00378efd66e3a076e3e | Java | onap/vfc-nfvo-driver-vnfm-gvnfm | /juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/onap/vfc/nfvo/vnfm/gvnfm/jujuvnfmadapter/service/rest/VnfResourceRoa.java | UTF-8 | 3,609 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 Huawei Technologies Co., Ltd.
*
* 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.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common.EntityUtils;
import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common.StringUtil;
import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.constant.Constant;
import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.process.VnfResourceMgr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
/**
* Provide interfaces of resource for juju VNFM to call.
* <br/>
*
* @author
* @version NFVO 0.5 Aug 24, 2016
*/
@Path("/v1")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class VnfResourceRoa {
private static final Logger LOG = LoggerFactory.getLogger(VnfResourceRoa.class);
private VnfResourceMgr vnfResourceMgr;
public void setVnfResourceMgr(VnfResourceMgr vnfResourceMgr) {
this.vnfResourceMgr = vnfResourceMgr;
}
/**
* Provide function of grant resource.
* <br/>
*JSONObject compute :
* field:(cpu,mem,disk,action(addResource/removeResource))
* @param context
* @param vnfId
* @return
* @since NFVO 0.5
*/
@PUT
@Path("/instances/{vnfId}/grant")
public String grantVnfRes(@Context HttpServletRequest context, @PathParam("vnfId") String vnfId) {
LOG.info("function=grantVnfRes, msg=enter to grant vnf resource");
JSONObject restJson = new JSONObject();
restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL);
JSONObject compute = StringUtil.getJsonFromContexts(context);
if(null == compute) {
LOG.error("function=grantVnfRes, msg=param request content can't be null!");
restJson.put("data", "param request content can't be null!");
return restJson.toString();
}
JSONObject resultObj = vnfResourceMgr.grantVnfResource(compute, vnfId);
handleResult(resultObj, restJson);
return restJson.toString();
}
private void handleResult(JSONObject resultObj, JSONObject restJson) {
if(resultObj.getInt("retCode") == Constant.REST_SUCCESS) {
restJson.put("retCode", Constant.REST_SUCCESS);
restJson.put("data", resultObj.getJSONObject("data"));
} else {
if(resultObj.containsKey("data")) {
String errorMsg = resultObj.getString("data");
LOG.error("function=handleResult, msg={}", errorMsg);
restJson.put("data", errorMsg);
} else {
LOG.error("function=handleResult, msg=Vnf Resource dispose fail");
restJson.put("data", "Vnf Resource dispose fail");
}
}
}
}
| true |
80c24d780631e5b7955dd864511c48e102eabc6b | Java | tyward/item | /src/main/java/edu/columbia/tjw/item/algo/DoubleVector.java | UTF-8 | 12,311 | 3.296875 | 3 | [
"Apache-2.0"
] | permissive | package edu.columbia.tjw.item.algo;
import org.apache.commons.math3.analysis.BivariateFunction;
import org.apache.commons.math3.analysis.UnivariateFunction;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* A read-only version of a double vector. This is useful where items might need to be passed around quite a lot.
* <p>
* This is also helpful where a large number of vectors are simply manipulations on existing vectors. There is a lot
* of computation of a*b and a+b like objects, and no need to create the whole array for each of them just to tear it
* down right after.
*/
public abstract class DoubleVector implements Serializable
{
private static final long serialVersionUID = 0x5aafcfe25b062dfaL;
private DoubleVector()
{
}
/**
* Get the regressor for observation index_
*
* @param index_ The index of the observation
* @return The value of the regressor for that observation.
*/
public abstract double getEntry(final int index_);
/**
* Returns the number of elements in this Vector.
*
* @return The number of elements in this Vector
*/
public abstract int getSize();
/**
* Collapse this item down to a version with no computations.
* <p>
* For a vector made from a double[], this just returns itself.
*
* @return A version of this vector with all values fully computed.
*/
public abstract DoubleVector collapse();
/**
* Return a copy of the underlying data (as a double[]).
*
* @return
*/
public final double[] copyOfUnderlying()
{
final double[] output = new double[this.getSize()];
for (int i = 0; i < output.length; i++)
{
output[i] = this.getEntry(i);
}
return output;
}
public static DoubleVector of(final DoubleVector.Builder builder_)
{
if (null == builder_)
{
return null;
}
return builder_.build();
}
/**
* Generate a DoubleVector with a defensive copy of the given data.
*
* @param data_
* @return
*/
public static DoubleVector of(final double[] data_)
{
return of(data_, true);
}
public static DoubleVector of(final double[] data_, final boolean doCopy_)
{
if (null == data_)
{
return null;
}
return new DoubleArrayVector(data_, doCopy_);
}
public static DoubleVector of(final float[] data_)
{
if (null == data_)
{
return null;
}
return new FloatArrayVector(data_, true);
}
public static DoubleVector constantVector(final double value_, final int size_)
{
return new ConstantDoubleVector(value_, size_);
}
public static DoubleVector apply(final BivariateFunction function_, final DoubleVector a_, final DoubleVector b_)
{
return new BivariateFunctionDoubleVector(function_, a_, b_);
}
public static DoubleVector apply(final UnivariateFunction function_, final DoubleVector vector_)
{
return new FunctionDoubleVector(function_, vector_);
}
public static DoubleVector.Builder newBuilder(final int size_)
{
return new Builder(size_);
}
/**
* Used to build double vectors without risk of underlying object leakage or excessive copying.
*/
public static final class Builder
{
private double[] _data;
private Builder(final int size_)
{
_data = new double[size_];
}
/**
* Get the regressor for observation index_
*
* @param index_ The index of the observation
* @return The value of the regressor for that observation.
*/
public double getEntry(final int index_)
{
return _data[index_];
}
/**
* Returns the number of elements in this Vector.
*
* @return The number of elements in this Vector
*/
public int getSize()
{
return _data.length;
}
public void setEntry(final int index_, final double value_)
{
_data[index_] = value_;
}
public void addToEntry(final int index_, final double value_)
{
_data[index_] += value_;
}
public void add(final double[] data_)
{
if (data_.length != _data.length)
{
throw new IllegalArgumentException("Length mismatch.");
}
for (int i = 0; i < _data.length; i++)
{
_data[i] += data_[i];
}
}
public void scalarMultiply(final double value_)
{
for (int i = 0; i < _data.length; i++)
{
_data[i] *= value_;
}
}
public DoubleVector build()
{
DoubleVector output = DoubleVector.of(_data, false);
_data = null; // This will prevent any further modifications to the data array.
return output;
}
}
private static final class DoubleArrayVector extends DoubleVector
{
private static final long serialVersionUID = 0x2165692518a8c386L;
private final double[] _underlying;
private DoubleArrayVector(final double[] underlying_, final boolean doCopy_)
{
if (null == underlying_)
{
throw new NullPointerException("Underlying cannot be null.");
}
if (doCopy_)
{
_underlying = underlying_.clone();
}
else
{
_underlying = underlying_;
}
}
@Override
public double getEntry(int index_)
{
return _underlying[index_];
}
@Override
public int getSize()
{
return _underlying.length;
}
@Override
public DoubleVector collapse()
{
return this;
}
}
private static final class FloatArrayVector extends DoubleVector
{
private static final long serialVersionUID = 0x2d399701ea8edac8L;
private final float[] _underlying;
private FloatArrayVector(final float[] underlying_, final boolean doCopy_)
{
if (null == underlying_)
{
throw new NullPointerException("Underlying cannot be null.");
}
if (doCopy_)
{
_underlying = underlying_.clone();
}
else
{
_underlying = underlying_;
}
}
@Override
public double getEntry(int index_)
{
return _underlying[index_];
}
@Override
public int getSize()
{
return _underlying.length;
}
@Override
public DoubleVector collapse()
{
return this;
}
}
private static final class FunctionDoubleVector extends DoubleVector
{
private static final long serialVersionUID = 0x5786e31501ee9960L;
private final UnivariateFunction _function;
private final DoubleVector _underlying;
private transient DoubleVector _collapsed;
public FunctionDoubleVector(final UnivariateFunction function_, final DoubleVector underlying_)
{
if (null == underlying_)
{
throw new NullPointerException("Underlying cannot be null.");
}
if (null == function_)
{
throw new NullPointerException("Function cannot be null.");
}
_function = function_;
_underlying = underlying_;
_collapsed = null;
}
@Override
public double getEntry(int index_)
{
final double underlying = _underlying.getEntry(index_);
return _function.value(underlying);
}
@Override
public int getSize()
{
return _underlying.getSize();
}
@Override
public DoubleVector collapse()
{
if (null == _collapsed)
{
final double[] raw = new double[getSize()];
for (int i = 0; i < raw.length; i++)
{
raw[i] = this.getEntry(i);
}
_collapsed = DoubleVector.of(raw, false);
}
return _collapsed;
}
private Object writeReplace() throws ObjectStreamException
{
if (_function instanceof Serializable)
{
return this;
}
else
{
// Collapse if necessary to preserve serializability.
return this.collapse();
}
}
}
private static final class BivariateFunctionDoubleVector extends DoubleVector
{
private static final long serialVersionUID = 0x77bb1fa9bd592e23L;
private final BivariateFunction _function;
private final DoubleVector _a;
private final DoubleVector _b;
private transient DoubleVector _collapsed;
public BivariateFunctionDoubleVector(final BivariateFunction function_, final DoubleVector a_,
final DoubleVector b_)
{
if (null == a_)
{
throw new NullPointerException("Underlying (A) cannot be null.");
}
if (null == b_)
{
throw new NullPointerException("Underlying (B) cannot be null.");
}
if (null == function_)
{
throw new NullPointerException("Function cannot be null.");
}
if (a_.getSize() != b_.getSize())
{
throw new IllegalArgumentException("Incompatible size: " + a_.getSize() + " != " + b_.getSize());
}
_function = function_;
_a = a_;
_b = b_;
_collapsed = null;
}
@Override
public double getEntry(int index_)
{
final double a = _a.getEntry(index_);
final double b = _b.getEntry(index_);
return _function.value(a, b);
}
@Override
public int getSize()
{
return _a.getSize();
}
@Override
public DoubleVector collapse()
{
if (null == _collapsed)
{
final double[] raw = new double[getSize()];
for (int i = 0; i < raw.length; i++)
{
raw[i] = this.getEntry(i);
}
_collapsed = DoubleVector.of(raw, false);
}
return _collapsed;
}
private Object writeReplace() throws ObjectStreamException
{
// Since this requres two underlying vectors, it's safer to collapse it down to 1 before serialization.
return this.collapse();
}
}
private static final class ConstantDoubleVector extends DoubleVector
{
private static final long serialVersionUID = 0x33d0ef04077b6898L;
private final double _constant;
private final int _size;
private ConstantDoubleVector(final double constant_, final int size_)
{
if (size_ < 0)
{
throw new IllegalArgumentException("Size must be nonnegative.");
}
_constant = constant_;
_size = size_;
}
@Override
public double getEntry(int index_)
{
if (index_ < 0 || index_ >= _size)
{
throw new ArrayIndexOutOfBoundsException("Index out of bounds [0, " + _size + "): " + index_);
}
return _constant;
}
@Override
public int getSize()
{
return _size;
}
@Override
public DoubleVector collapse()
{
return this;
}
}
}
| true |
9727e7719d66e0e569f0739569667829ab5403c3 | Java | biolearning-stadius/rdkit | /Code/JavaWrappers/gmwrapper/src-test/org/RDKit/ScaffoldNetworkTests.java | UTF-8 | 1,433 | 2.171875 | 2 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
*
* Copyright (c) 2019 Greg Landrum and T5 Informatics GmbH
* All rights reserved.
*
* This file is part of the RDKit.
* The contents are covered by the terms of the BSD license
* which is included in the file license.txt, found at the root
* of the RDKit source tree.
*/
package org.RDKit;
import static org.junit.Assert.*;
import org.junit.*;
public class ScaffoldNetworkTests extends GraphMolTest {
@Before public void setUp() {
}
@Test
public void test1Basics() {
ROMol_Vect ms = new ROMol_Vect();
ms.add(RWMol.MolFromSmiles("c1ccccc1CC1NC(=O)CCC1"));
ScaffoldNetworkParams ps = new ScaffoldNetworkParams();
ScaffoldNetwork net = RDKFuncs.createScaffoldNetwork(ms,ps);
assertEquals(net.getNodes().size(),9);
assertEquals(net.getCounts().size(),net.getNodes().size());
assertEquals(net.getEdges().size(),8);
}
@Test
public void test2Basics() {
ROMol_Vect ms = new ROMol_Vect();
ms.add(RWMol.MolFromSmiles("c1ccccc1CC1NC(=O)CCC1"));
ScaffoldNetworkParams ps = new ScaffoldNetworkParams();
ps.setIncludeScaffoldsWithAttachments(false);
ScaffoldNetwork net = RDKFuncs.createScaffoldNetwork(ms,ps);
assertEquals(net.getNodes().size(),5);
assertEquals(net.getCounts().size(),net.getNodes().size());
assertEquals(net.getEdges().size(),4);
}
public static void main(String args[]) {
org.junit.runner.JUnitCore.main("org.RDKit.ScaffoldNetworkTests");
}
}
| true |
df143d876d53745dd0e1b85aa16a4b325981fba3 | Java | ych147142/webManager | /src/main/java/com/neuedu/controller/DoLoginServlet.java | UTF-8 | 1,755 | 2.46875 | 2 | [] | no_license | package com.neuedu.controller;
import com.neuedu.pojo.User;
import com.neuedu.service.IUserService;
import com.neuedu.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/dologin")
public class DoLoginServlet extends HttpServlet {
private IUserService service = new UserServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = service.getOne(username);
if (user == null){
resp.getWriter().write("2");
}else {
if (user.getPassword().equals(password)){
if (user.getLv() == 1){
resp.getWriter().write("1");
}else if (user.getLv() == 2){
resp.getWriter().write("4");
}else if (user.getLv() == 3){
resp.getWriter().write("5");
}
/*添加cookie*/
Cookie cookn =new Cookie("username",username);
Cookie cookp = new Cookie("password",password);
/*设置cookie最大存活时间*/
cookn.setMaxAge(60*60*24*7);
cookp.setMaxAge(60*60*24*7);
resp.addCookie(cookn);
resp.addCookie(cookp);
/*Session*/
HttpSession session = req.getSession();
session.setAttribute("user",user);
}else {
resp.getWriter().write("3");
}
}
}
}
| true |
abe381451186173e89281754bb2aa34cdd8bc8fa | Java | maoyueqiang/neuedu1-project-business-interface | /src/main/java/com/neuedu/controller/portal/ProductController.java | UTF-8 | 2,160 | 2.09375 | 2 | [] | no_license | package com.neuedu.controller.portal;
import com.neuedu.common.ServerResponse;
import com.neuedu.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/product/")
@CrossOrigin
public class ProductController {
@Autowired
IProductService productService;
/**
* 前台-商品详情
*/
@RequestMapping(value = "detail.do")
public ServerResponse detail(Integer productId){
return productService.detail_portal(productId);
}
/**
* 前台-产品搜索,动态排序
*/
@RequestMapping(value = "list.do")
public ServerResponse list(@RequestParam(required = false) Integer categoryId,
@RequestParam(required = false) String keyword,
@RequestParam(required = false,defaultValue = "1") Integer pageNum,
@RequestParam(required = false,defaultValue = "10") Integer pageSize,
@RequestParam(required = false,defaultValue = "") String orderBy){
if(categoryId==null||categoryId.equals("")){
categoryId=null;
}
if(keyword==null||keyword.equals("")){
keyword=null;
}
return productService.list_portal(categoryId,keyword,pageNum,pageSize,orderBy);
}
/**
* 前台-产品搜索 轮播产品
*/
@RequestMapping(value = "bannerlist.do")
public ServerResponse bannerlist(){
return productService.bannerlist();
}
/**
* 前台-产品搜索 热卖产品
*/
@RequestMapping(value = "hotlist.do")
public ServerResponse hotlist(){
return productService.hotlist();
}
/**
* 前台-产品搜索 新品
*/
@RequestMapping(value = "newlist.do")
public ServerResponse newlist(){
return productService.newlist();
}
}
| true |
87457e6898c8d832141b242d43eb2921ef551345 | Java | ch93/baiduMap | /src/com/ch/dbscan/Point.java | UTF-8 | 2,244 | 2.28125 | 2 | [] | no_license | package com.ch.dbscan;
import java.sql.Timestamp;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch.bean.StayPoint;
public class Point extends StayPoint {
private double x;
private double y;
//簇号
private int clusterID;
private boolean isKey;
private boolean isClassed;
/**
* POI类型
*/
private String poiType;
/**
* POI详细说明
*/
private String tag;
public Point(int userid, double lat, double lngt, Timestamp arvT,
Timestamp levT, double iArvT, double iLevT) {
// super(lat, lngt, arvT, levT, iArvT, iLevT);
super(userid, lat, lngt, arvT, levT, iArvT, iLevT);
x = lat;
y = lngt;
}
public boolean isKey() {
return isKey;
}
public void setKey(boolean isKey) {
this.isKey = isKey;
this.isClassed = true;
}
public boolean isClassed() {
return isClassed;
}
public void setClassed(boolean isClassed) {
this.isClassed = isClassed;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public int getClusterID() {
return clusterID;
}
public void setClusterID(int clusterID) {
this.clusterID = clusterID;
}
// public Point(String str) {
// String[] p = str.split(",");
// this.x = Integer.parseInt(p[0]);
// this.y = Integer.parseInt(p[1]);
// }
public String getPoiType() {
return poiType;
}
public void setPoiType(String poiType) {
this.poiType = poiType;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String print() {
return + this.getLat() + " , " + this.getLngt() + " , " + this.getArvT() + " , " + this.getLevT();
}
public JSONObject toJson() {
JSONObject jObject = new JSONObject();
try {
// jObject.put("userid", this.);
jObject.put("lat", this.getLat());
jObject.put("lngt", this.getLngt());
jObject.put("arvT", this.getArvT());
jObject.put("levT", this.getLevT());
jObject.put("iArvT", this.getiArvT());
jObject.put("iLevT", this.getiLevT());
jObject.put("clusterID", clusterID);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObject;
}
}
| true |
134e54428c76f033c2289bf67137641d9317caad | Java | wengyingjian/kylin-archetype-lead | /artic.test-service/src/main/java/com/a/b/c/service/impl/UserServiceImpl.java | UTF-8 | 1,689 | 2.140625 | 2 | [] | no_license | package com.a.b.c.service.impl;
import com.wengyingjian.kylin.common.model.Result;
import com.wengyingjian.kylin.common.utils.ResultUtil;
import com.wengyingjian.kylin.rpc.server.annotation.RemoteService;
import com.wengyingjian.kylin.rpc.server.annotation.ServiceType;
import com.a.b.c.common.enums.UserType;
import com.a.b.c.common.model.User;
import com.a.b.c.common.model.query.UserQuery;
import com.a.b.c.common.service.UserService;
import com.a.b.c.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* Created by wengyingjian on 16/2/1.
*/
@RemoteService(serviceType = ServiceType.HESSIAN, serviceInterface = UserService.class, exportPath = "/userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public Result<List<User>> findUsers(UserQuery userQuery) {
if(userQuery==null){
return ResultUtil.genCommonError("userQuery bean can not be null");
}
return ResultUtil.genSuccessResult(userDao.selectUsers(userQuery));
}
@Override
public Result<Boolean> addUser(User user) {
if (user == null) {
return ResultUtil.genCommonError("target user can not be null");
}
int affectedRows = userDao.insertSelective(user);
boolean result = affectedRows == 0 ? false : true;
return ResultUtil.genSuccessResult(result);
}
@Override
public Result<Boolean> modifyUser(User user) {
int affectedRpws = userDao.updateUser(user);
boolean result = affectedRpws == 0 ? false : true;
return ResultUtil.genSuccessResult(result);
}
}
| true |
fd173f590da4d2bdef7077a84a98e3ed66c9fefa | Java | rosoareslv/SED99 | /java/sonarqube/2018/12/CeWorkerFactoryImpl.java | UTF-8 | 2,780 | 1.789063 | 2 | [] | no_license | /*
* SonarQube
* Copyright (C) 2009-2018 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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 3 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 org.sonar.ce.taskprocessor;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Stream;
import org.sonar.ce.queue.InternalCeQueue;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.stream.MoreCollectors;
public class CeWorkerFactoryImpl implements CeWorkerFactory {
private final UuidFactory uuidFactory;
private final InternalCeQueue queue;
private final CeTaskProcessorRepository taskProcessorRepository;
private final CeWorkerController ceWorkerController;
private final CeWorker.ExecutionListener[] executionListeners;
private Set<CeWorker> ceWorkers = Collections.emptySet();
/**
* Used by Pico when there is no {@link CeWorker.ExecutionListener} in the container.
*/
public CeWorkerFactoryImpl(InternalCeQueue queue, CeTaskProcessorRepository taskProcessorRepository,
UuidFactory uuidFactory, CeWorkerController ceWorkerController) {
this(queue, taskProcessorRepository, uuidFactory, ceWorkerController, new CeWorker.ExecutionListener[0]);
}
public CeWorkerFactoryImpl(InternalCeQueue queue, CeTaskProcessorRepository taskProcessorRepository,
UuidFactory uuidFactory, CeWorkerController ceWorkerController,
CeWorker.ExecutionListener[] executionListeners) {
this.queue = queue;
this.taskProcessorRepository = taskProcessorRepository;
this.uuidFactory = uuidFactory;
this.ceWorkerController = ceWorkerController;
this.executionListeners = executionListeners;
}
@Override
public CeWorker create(int ordinal) {
String uuid = uuidFactory.create();
CeWorkerImpl ceWorker = new CeWorkerImpl(ordinal, uuid, queue, taskProcessorRepository, ceWorkerController, executionListeners);
ceWorkers = Stream.concat(ceWorkers.stream(), Stream.of(ceWorker)).collect(MoreCollectors.toSet(ceWorkers.size() + 1));
return ceWorker;
}
@Override
public Set<CeWorker> getWorkers() {
return ceWorkers;
}
}
| true |
9e91b79de4ff2dda0a9d5dc6b3656a392c934b98 | Java | BJCreslin/WOQ | /src/Objects/WOQCoord.java | UTF-8 | 292 | 2.09375 | 2 | [] | no_license | package Objects;
public class WOQCoord {
long xCoord;
public long getxCoord() {
return xCoord;
}
public long getyCoord() {
return yCoord;
}
long yCoord;
WOQCoord startCoord(){
xCoord=2;
yCoord=2;
return this;
}
}
| true |
04da813695d4220e33b69f095a00f9af973bbb50 | Java | JoinQ/MyBox | /Box/app/src/main/java/com/box/widget/RankViewHolder.java | UTF-8 | 1,971 | 2.21875 | 2 | [] | no_license | package com.box.widget;
import android.graphics.Color;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.box.box.R;
import com.box.mode.QueryInfoThing;
import com.box.mode.RankThing;
public class RankViewHolder extends BaseViewHolder<RankThing, NullPointerException> {
public ImageView rank_ad_iv_grade;
public TextView rank_ad_tv_grade;
public ImageView rank_ad_iv_head;
public TextView rank_ad_tv_name;
public TextView rank_ad_tv_level;
public TextView rank_ad_tv_money;
public RankViewHolder(ViewGroup parent) {
super(parent, R.layout.recyclerview_rank_adapter);
rank_ad_iv_grade = (ImageView) itemView.findViewById(R.id.rank_ad_iv_grade);
rank_ad_tv_grade = (TextView) itemView.findViewById(R.id.rank_ad_tv_grade);
rank_ad_iv_head = (ImageView) itemView.findViewById(R.id.rank_ad_iv_head);
rank_ad_tv_name = (TextView) itemView.findViewById(R.id.rank_ad_tv_name);
rank_ad_tv_level = (TextView) itemView.findViewById(R.id.rank_ad_tv_level);
rank_ad_tv_money = (TextView) itemView.findViewById(R.id.rank_ad_tv_money);
}
@Override
public void setFirstData(RankThing data, boolean isFirst) {
super.setFirstData(data, isFirst);
switch (data.getGrade())
{
case 1:
rank_ad_iv_grade.setImageResource(R.drawable.rank_no1);
break;
case 2:
rank_ad_iv_grade.setImageResource(R.drawable.rank_no2);
break;
default:
rank_ad_iv_grade.setImageResource(R.drawable.rank_no3);
break;
}
rank_ad_tv_grade.setText(data.getGrade()+"");
rank_ad_iv_head.setImageResource(data.getHead());
rank_ad_tv_name.setText(data.getName());
rank_ad_tv_level.setText(data.getLevel()+"");
rank_ad_tv_money.setText(data.getMoney()+"");
}
} | true |
fe22846209f5c885958488e7eda5e81c836d3339 | Java | zed-technology/TagContentExtractor | /src/main/java/Solution.java | UTF-8 | 1,897 | 3.546875 | 4 | [] | no_license | import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Solution assumes we can't have the symbol "<" as text between tags */
public class Solution{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
while(testCases>0){
String line = in.nextLine();
//https://www.hackerrank.com/challenges/tag-content-extractor/forum/comments/253626
// Explain the regular expression: <(.+)>([^<]+)</\1>
// <(.+)> - matches HTML start tags. The parentheses save the contents inside the brackets into Group #1.
// The dot "." matches any single character (except newline). The "+" matches 1 or more of whatever it comes after. Since it comes after the dot ".", we match 1 or more of any character. These characters are inside the brackets "<" and ">", so we can match any number of characters as long as they're within the brackets. That is exactly what an HTML tag is.
// Also, the parentheses save the contents inside the brackets into Group #1.
// ([^<]+) - matches all the text in between the HTML start and end tags. We place a special restriction on the text in that it can't have the "<" symbol. The characters inside the parenthesis are saved into Group #2.
// </\\1> - is to match the HTML end brace that corresponds to our previous start brace. The \1 is here to match all text from Group #1.
boolean matchFound = false;
Pattern r = Pattern.compile("<(.+)>([^<]+)</\\1>");
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println(m.group(2));
matchFound = true;
}
if ( ! matchFound) {
System.out.println("None");
}
testCases--;
}
in.close();
}
}
| true |
41df7051e213ccab28375e68aee06d8a1b33e75b | Java | ilovechai/egeria | /open-metadata-implementation/access-services/analytics-modeling/analytics-modeling-api/src/main/java/org/odpi/openmetadata/accessservices/analyticsmodeling/metadata/MetadataBase.java | UTF-8 | 591 | 2.21875 | 2 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | /* SPDX-License-Identifier: Apache 2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.analyticsmodeling.metadata;
/**
* Base class for metadata beans retrieved from the metadata repository.
*/
public class MetadataBase {
String guid;
/**
* Get repository entity GUID for bean instantiated from that entity.
* @return guid.
*/
public String getGuid() {
return guid;
}
/**
* Set GUID of the bean usually from the entity.
* @param guid to set.
*/
public void setGuid(String guid) {
this.guid = guid;
}
}
| true |
3621a48e05501318e81f5ee8163b3249f719f40a | Java | markeNick/yxx | /yunxiaoxian/src/main/java/com/yxx/websocket/WebSocketConfig.java | UTF-8 | 1,719 | 2.1875 | 2 | [
"MIT"
] | permissive | package com.yxx.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import javax.annotation.Resource;
/**
* 配置文件
*/
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private WebSocketPushHandler webSocketPushHandler;
@Autowired
private MyWebSocketInterceptor myWebSocketInterceptor;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//1.注册websocket
// String websocket_url = "/websocket"; //设置websocket的地址
// String sockjs_url = "/sockjs"; //设置sockjs的地址
registry.addHandler(webSocketPushHandler, "/websocket"). //注册Handler
addInterceptors(myWebSocketInterceptor).setAllowedOrigins("*"); //注册Interceptors
registry.addHandler(webSocketPushHandler, "/sockjs")
.addInterceptors(myWebSocketInterceptor).withSockJS();
}
// @Bean
// public WebSocketHandler WebSocketPushHandler() {
//
// return new WebSocketPushHandler();
// }
}
| true |
6e96d5c67685892d1d4c269ffed0bfe368c761de | Java | DGovi/soen343house | /src/Tests/ModifySimulationParametersTest.java | UTF-8 | 2,379 | 2.71875 | 3 | [] | no_license | package Tests;
import Controller.Simulation;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.time.LocalTime;
import static org.junit.jupiter.api.Assertions.*;
class ModifySimulationParametersTest {
private static final File HOUSE_FILE = new File("./houseinput.json");
private final File USER_FILE = new File("users.json");
@Test
void setHouseLocation() throws IOException, JSONException {
Simulation simulation = Simulation.createInstance("", java.sql.Time.valueOf(LocalTime.now()), HOUSE_FILE, USER_FILE);
String location = "Software Development Hell";
assertEquals("Set house location to " + location + "!", simulation.setHouseLocation(location));
assertEquals(location, simulation.getHouseLocation());
}
@Test
void setOutsideTemperature() throws IOException, JSONException {
Simulation simulation = Simulation.createInstance("", java.sql.Time.valueOf(LocalTime.now()), HOUSE_FILE, USER_FILE);
String temperature = "42069.0";
assertEquals("Setting simulation temperature to " + temperature + "!", simulation.setTemperature(temperature));
assertEquals(temperature, String.valueOf(simulation.getTemperature()));
}
@Test
void turnSimOnOff() throws IOException, JSONException {
Simulation simulation = Simulation.createInstance("", java.sql.Time.valueOf(LocalTime.now()), HOUSE_FILE, USER_FILE);
// turn off then back on
assertEquals("Simulation OFF", simulation.toggleRunning());
assertEquals("Simulation ON", simulation.toggleRunning());
}
@Test
void setTime() throws IOException, JSONException {
Simulation simulation = Simulation.createInstance("", java.sql.Time.valueOf(LocalTime.now()), HOUSE_FILE, USER_FILE);
Time time = java.sql.Time.valueOf(LocalTime.now());
assertEquals("Time set to: " + time + ".", simulation.getSimulationTimes().setTime(time));
}
@Test
void setDate() throws IOException, JSONException {
Simulation simulation = Simulation.createInstance("", java.sql.Time.valueOf(LocalTime.now()), HOUSE_FILE, USER_FILE);
String date = "friday";
assertEquals("Date set to: " + date + ".", simulation.getSimulationTimes().setDate(date));
}
} | true |
b0ad253daccd7f10043f75a6e0b5a77f202c61c9 | Java | SciGaP/seagrid-rich-client | /src/main/java/cct/gaussian/ui/SimpleG03EditorPanel.java | UTF-8 | 18,304 | 1.875 | 2 | [
"Apache-2.0"
] | permissive | /* ***** BEGIN LICENSE BLOCK *****
Version: Apache 2.0/GPL 3.0/LGPL 3.0
CCT - Computational Chemistry Tools
Jamberoo - Java Molecules Editor
Copyright 2008-2015 Dr. Vladislav Vasilyev
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.
Contributor(s):
Dr. Vladislav Vasilyev <vvv900@gmail.com> (original author)
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the Apache 2.0, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the Apache 2.0, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package cct.gaussian.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import cct.gaussian.GJFParserInterface;
import cct.gaussian.Gaussian;
import cct.gaussian.GaussianAtom;
import cct.interfaces.MoleculeInterface;
import cct.modelling.Molecule;
/**
* <p>Title: Gasussian Utility Classes</p>
*
* <p>Description: Computational Chemistry Toolkit</p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: ANU</p>
*
* @author Dr. V. Vasilyev
* @version 1.0
*/
public class SimpleG03EditorPanel
extends JPanel {
Link0Panel link0Panel1 = new Link0Panel();
RouteSectionPanel routeSectionPanel1 = new RouteSectionPanel();
MoleculeSpecsPanel moleculeSpecsPanel1 = new MoleculeSpecsPanel();
JLabel jLabel1 = new JLabel();
JTextField jTextField1 = new JTextField();
JPanel lowerPanel = new JPanel();
JPanel centralPanel = new JPanel();
TitleSectionPanel titleSectionPanel1 = new TitleSectionPanel();
GridBagLayout gridBagLayout2 = new GridBagLayout();
GridBagLayout gridBagLayout3 = new GridBagLayout();
Border border1 = BorderFactory.createLineBorder(Color.gray, 1);
Border border2 = new TitledBorder(border1, "Route section (# lines)");
boolean fieldsEdited = false;
GJFParserInterface gjfParser = null;
//ImageIcon arrowUp = new ImageIcon(cct.gaussian.ui.SimpleG03EditorPanel.class.
// getResource(
// "../../resources/images/icons32x32/arrowUp.gif"));
BorderLayout borderLayout1 = new BorderLayout();
JButton validateGeomButton = new JButton();
//ImageIcon arrowUp = new ImageIcon("../../resources/images/icons32x32/arrowUp.gif");
public boolean isEdited() {
return fieldsEdited;
}
public SimpleG03EditorPanel(GJFParserInterface parser) {
gjfParser = parser;
try {
jbInit();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void setGeometryValidator(GJFParserInterface parser) {
gjfParser = parser;
if (gjfParser != null) {
this.enableValidateGeometry(true);
}
}
private void jbInit() throws Exception {
jLabel1.setToolTipText("");
jLabel1.setText("Charge & Multiplicity");
this.setLayout(borderLayout1);
lowerPanel.setLayout(gridBagLayout2);
centralPanel.setLayout(gridBagLayout3);
moleculeSpecsPanel1.setBorder(new TitledBorder(BorderFactory.
createLineBorder(Color.gray, 1), "Molecule specifications "));
link0Panel1.setBorder(new TitledBorder(BorderFactory.createLineBorder(
Color.
gray, 1), "Link 0 Commands"));
routeSectionPanel1.getViewport().setBackground(Color.black);
routeSectionPanel1.setBorder(new TitledBorder(BorderFactory.
createLineBorder(Color.gray,
1), "Route section (# lines)"));
titleSectionPanel1.setBorder(new TitledBorder(BorderFactory.
createLineBorder(Color.gray,
1), "Title section"));
jTextField1.setToolTipText("Enter Charge and Multiplicity");
validateGeomButton.setMaximumSize(new Dimension(300, 300));
validateGeomButton.setMinimumSize(new Dimension(130, 23));
validateGeomButton.setPreferredSize(new Dimension(160, 23));
validateGeomButton.setToolTipText("Click to Check Molecular Geometry");
validateGeomButton.setBorderPainted(false);
validateGeomButton.setMnemonic('0');
validateGeomButton.setText("Validate Geometry");
validateGeomButton.addActionListener(new
SimpleG03EditorPanel_validateGeomButton_actionAdapter(this));
this.add(centralPanel, BorderLayout.NORTH);
centralPanel.add(link0Panel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
centralPanel.add(routeSectionPanel1,
new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0
, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL,
new Insets(0, 5, 0, 5), 0, 0));
centralPanel.add(titleSectionPanel1,
new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0
, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
this.add(lowerPanel, BorderLayout.CENTER);
lowerPanel.add(validateGeomButton
, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
, GridBagConstraints.CENTER,
GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
lowerPanel.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 5, 5, 5), 0, 0));
lowerPanel.add(jTextField1, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
lowerPanel.add(moleculeSpecsPanel1,
new GridBagConstraints(0, 2, 3, 1, 1.0, 1.0
, GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
new Insets(5, 5, 5, 5), 0, 0));
}
public void setLinkZeroCommands(java.util.List cmd) {
link0Panel1.setText(getText(cmd));
fieldsEdited = true;
}
public void setLinkZeroCommands(String cmd) {
link0Panel1.setText(cmd);
fieldsEdited = true;
}
public String getLinkZeroCommands() {
return link0Panel1.getText();
}
public void setRouteSection(String options) {
routeSectionPanel1.setText(options);
fieldsEdited = true;
}
public String getRouteSection() {
return routeSectionPanel1.getText();
}
public void setTitleSection(String options) {
titleSectionPanel1.setText(options);
fieldsEdited = true;
}
public String getTitleSection() {
return titleSectionPanel1.getText();
}
public void setChargeSection(String options) {
jTextField1.setText(options);
fieldsEdited = true;
}
public String getChargeSection() {
String lines[] = jTextField1.getText().split("\n");
String text = "";
for (int i = 0; i < lines.length; i++) {
String trimmed = lines[i].trim();
if (trimmed.length() != 0) {
text += trimmed + "\n";
}
}
return text;
//return jTextField1.getText();
}
public void setMoleculeSpecsSection(String options) {
moleculeSpecsPanel1.setText(options);
fieldsEdited = true;
}
public String getMoleculeSpecsSection() {
return moleculeSpecsPanel1.getText();
}
public void resetPanel() {
link0Panel1.resetPanel();
routeSectionPanel1.resetPanel();
titleSectionPanel1.resetPanel();
jTextField1.setText("0 1");
moleculeSpecsPanel1.resetPanel();
fieldsEdited = false;
}
public String getStepAsString() {
String step = "";
step = getLinkZeroCommands() + getRouteSection() + "\n" + getTitleSection() +
"\n" + getChargeSection() + getMoleculeSpecsSection();
return step;
}
String getText(java.util.List cmd) {
if (cmd == null || cmd.size() < 1) {
return "";
}
String text = "";
for (int i = 0; i < cmd.size(); i++) {
text += (String) cmd.get(i);
}
return text;
}
public void enableValidateGeometry(boolean enable) {
validateGeomButton.setEnabled(enable);
}
public void validateGeomButton_actionPerformed(ActionEvent e) {
if (gjfParser == null) {
JOptionPane.showMessageDialog(null,
"No geometry validator was specified!",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
moleculeSpecsPanel1.startEditing();
java.util.List<GaussianAtom> atoms = null;
try {
atoms = gjfParser.validateMolecularGeometry(this.getMoleculeSpecsSection());
this.validate();
if (atoms.size() > 0) {
/*
JOptionPane.showMessageDialog(null,
"Found "+atoms.size()+" atoms",
"Success",
JOptionPane.INFORMATION_MESSAGE);
*/
}
else {
JOptionPane.showMessageDialog(null,
"No atoms found",
"No atoms",
JOptionPane.INFORMATION_MESSAGE);
return;
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null,
ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// --- check charge and multiplicity
int ch = 0, multiplicity = 1;
String chargeSection = this.getChargeSection();
StringTokenizer st = new StringTokenizer(chargeSection, " ,\t\n");
if (st.countTokens() < 2) {
ch = 0;
multiplicity = 1;
}
else {
try {
ch = Integer.parseInt(st.nextToken());
multiplicity = Integer.parseInt(st.nextToken());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Wrong value(s) for charge or/and multiplicity " +
chargeSection + " : " + ex.getMessage() +
"\nProgram will try to fix it...",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
if (multiplicity < 1) {
JOptionPane.showMessageDialog(null,
"Multiplicity cannot be less than 1\n" +
"Program will fix it...",
"Error",
JOptionPane.ERROR_MESSAGE);
multiplicity = 1;
}
int[] elements = new int[atoms.size()];
for (int i = 0; i < atoms.size(); i++) {
GaussianAtom atom = atoms.get(i);
elements[i] = atom.getElement();
}
int charge = ch;
try {
Molecule.validateTotalCharge(elements, charge, multiplicity);
}
catch (Exception ex) {
try {
charge = Molecule.guessTotalCharge(elements, multiplicity);
}
catch (Exception exx) {}
JOptionPane.showMessageDialog(this,
"Current values for charge " + ch +
" and multiplicity " +
multiplicity +
" do not make sense\n" +
"Check new values for charge " + charge +
" and multiplicity " + multiplicity +
" suggested by a program"
, "Warning",
JOptionPane.WARNING_MESSAGE);
}
if (st.hasMoreTokens()) {
String newChargeSection = String.valueOf(charge) + " " +
String.valueOf(multiplicity);
while (st.hasMoreTokens()) {
newChargeSection += " " + st.nextToken();
}
setChargeSection(newChargeSection);
}
else {
this.setChargeSection(String.valueOf(charge) + " " +
String.valueOf(multiplicity));
}
// --- Check link0 Section
try {
gjfParser.validateLink0Section(this.getLinkZeroCommands());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error(s) in Link0 Section:\n" +
ex.getMessage(),
"Error(s) in Link0 Section",
JOptionPane.ERROR_MESSAGE);
}
}
public void setupMolecule(MoleculeInterface mol) {
// --- Set link0 section
Object props = mol.getProperty(cct.gaussian.Gaussian.
LINK_ZERO_COMMANDS_KEY);
if (props != null) {
if (props instanceof java.util.List) {
java.util.List link0 = (java.util.List) props;
String text = "";
for (int i = 0; i < link0.size(); i++) {
text += link0.get(i).toString() + "\n";
}
setLinkZeroCommands(text);
}
else {
setLinkZeroCommands(props.toString());
}
}
else {
setLinkZeroCommands("%nproc=1");
}
// --- Set route section
props = mol.getProperty(cct.gaussian.Gaussian.ROUTE_COMMANDS_KEY);
if (props != null) {
setRouteSection(props.toString());
}
else {
setRouteSection("# Opt HF/6-31g");
}
// --- Set title section
setTitleSection(mol.getName());
// --- Set charge section
Integer multiplicity = (Integer) mol.getProperty(MoleculeInterface.MultiplicityProperty);
if (multiplicity == null) {
multiplicity = 1;
System.err.println("Set multiplicity to " + multiplicity);
}
else if (multiplicity < 1) {
JOptionPane.showMessageDialog(null,
"Multiplicity cannot be less than 1\n" +
"Program will fix it...",
"Error",
JOptionPane.ERROR_MESSAGE);
}
Integer ch = (Integer) mol.getProperty(MoleculeInterface.ChargeProperty);
if (ch == null) {
try {
ch = Molecule.guessTotalCharge(mol, multiplicity.intValue());
}
catch (Exception ex) {}
System.err.println("Set total charge to " + ch);
}
int charge = ch;
try {
//charge = Molecule.guessTotalCharge(mol, multiplicity.intValue());
Molecule.validateTotalCharge(mol, ch, multiplicity.intValue());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(this,
"Current combination of total charge " +
ch.intValue() + " and multiplicity " +
multiplicity + " does not make sense" +
"\nCheck values " + charge + " and " +
multiplicity.intValue() +
" suggested by a program"
, "Error",
JOptionPane.ERROR_MESSAGE);
try {
charge = Molecule.guessTotalCharge(mol, multiplicity.intValue());
}
catch (Exception exx) {}
}
setChargeSection(charge + " " + multiplicity);
// --- Set molecule specs
try {
setMoleculeSpecsSection(Gaussian.getMoleculeSpecsAsString(mol));
}
catch (Exception ex) {
JOptionPane.showMessageDialog(this,
"Error generating molecule specifications: " +
ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
public void setFontForText(Font newFont) {
link0Panel1.setFontForText(newFont);
this.routeSectionPanel1.setFontForText(newFont);
this.titleSectionPanel1.setFontForText(newFont);
this.moleculeSpecsPanel1.setFontForText(newFont);
}
public Font getFontForText() {
return link0Panel1.getFontForText();
}
}
class SimpleG03EditorPanel_validateGeomButton_actionAdapter
implements ActionListener {
private SimpleG03EditorPanel adaptee;
SimpleG03EditorPanel_validateGeomButton_actionAdapter(
SimpleG03EditorPanel
adaptee) {
this.adaptee = adaptee;
}
@Override
public void actionPerformed(ActionEvent e) {
adaptee.validateGeomButton_actionPerformed(e);
}
}
| true |
32dad87791a1195158df4229f96008060e24afc3 | Java | viveksharma8506/Java-8-features | /src/main/java/com/java8/stearms/StreamsFeatures.java | UTF-8 | 9,835 | 3.71875 | 4 | [] | no_license | package com.java8.stearms;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamsFeatures {
public static void main(String [] args){
List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("beef", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH) );
//filter method
List<Dish> vegDishes =menu.stream()
.filter(Dish::isVegetarian)
.collect(Collectors.toList());
//filter unique values--give list of dish with unique name {removing duplicate beef}where cal >500
List<String> cal500Dish =menu.stream().filter(dish -> dish.getCalories()>500)
.map(Dish::getName)
.distinct()
.collect(Collectors.toList());
//Limit fix the size of stream
List<String> filteredDish = menu.stream()
.filter(dish -> dish.getCalories()>500 )
.map(Dish::getName)
.limit(3)
.sorted(String::compareTo)
.collect(Collectors.toList());
//filteredDish.sort(Comparator.comparing(String::toString).reversed().)
System.out.println(filteredDish);
//Streams support the skip(n) method to return a stream that discards the first n elements. If the
//stream has fewer elements than n, then an empty stream is returned
// skip first 2 meat dishes
List<Dish> afterSkipFirst2MeatDish= menu.stream()
.filter(dish ->
dish.getType()== Dish.Type.MEAT)
.skip(2)
.collect(Collectors.toList());
//How would you use streams to filter the first two meat dishes?
List<Dish> first2MeatDish= menu.stream()
.filter(dish ->
dish.getType()== Dish.Type.MEAT)
.limit(2)
.collect(Collectors.toList());
//MAP-Given a list of
//words, you’d like to return a list of the number of characters for each word. How would you do it?
List<String> words = Arrays.asList("Java8", "Lambdas", "In", "Action");
List<Integer> lngthList = words.stream()
.map(String::length)
.collect(Collectors.toList());
//FLAT MAP -how could you return a list of all the unique characters for a list of words? For
// example, given the list of words ["Hello", "World"] you’d like to return the list ["H", "e", "l", "o",
// "W", "r", "d"].
List<String> wordList = Arrays.asList("hello", "world");
wordList.stream()
.map(s -> s.split(""))
.flatMap(Arrays::stream )
.distinct()
.collect(Collectors.toList());
// Ex-mapping
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> Squares = numbers.stream()
.map(integer -> integer * integer)
.collect(Collectors.toList());
//Given two lists of numbers, how would you return all pairs of numbers? For example, given a
//list [1, 2, 3] and a list [3, 4] you should return [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]. For
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
List<int[]> array = numbers1.stream()
.flatMap(integer -> numbers2.stream()
.map(integer1 -> new int[]{integer, integer1}))
.collect(Collectors.toList());
array.stream().
forEach(ints -> Arrays.stream(ints).forEach(System.out::println));
// pair divisible by 3
List<int[]> collect = numbers1.stream()
.flatMap(integer -> numbers2.stream()
.filter(i -> i + integer % 3 == 0)
.map(integer1 -> new int[]{integer, integer1}))
.collect(Collectors.toList());
// find , find any , all match none match
menu.stream()
.filter(Dish::isVegetarian)
.findAny() // return optional here
.ifPresent(System.out::println); // evaluation on optional values
//find first
//the code that follows, given a list of numbers,
//finds the first square that’s divisible by 3:
List<Integer> intList= Arrays.asList(1,2,3,4,5,6,7);
Optional<Integer> first = intList.stream()
.map(i -> i *i )
.filter(x -> x % 3 == 0)
.findFirst();
//Reduce Operation folds :
Integer reduce = intList.stream().reduce(0, (a, b) -> a + b);
//OR
Integer sum = intList.stream().reduce(0,Integer::sum);
//Max
Optional<Integer> reduce1 = intList.stream().reduce(Integer::max);
//You could have equally well used the lambda (x,y)->x<y?x:y instead of Integer::min, but the
//latter is easier to read.
Optional<Integer> reduce2 = intList.stream().reduce(Integer::min);
//How would you count the number of dishes in a stream using the map and reduce methods?
menu.stream().map(dish -> 1).reduce(0,Integer::sum);
// Java 8 introduces three primitive specialized stream interfaces to tackle this issue,
// IntStream, DoubleStream, and LongStream, that respectively specialize the elements of a stream to be int, long, and double—and
// thereby avoid hidden boxing costs.
int calories = menu.stream()
.mapToInt(Dish::getCalories)
.sum();
// Numeric Streams and there specilaized optinals
//The sum example was convenient because it has a default value: 0. But if you want to calculate
//the maximum element in an IntStream, you need something different because 0 is a wrong
//result. How can you differentiate that the stream has no element and that the real maximum is 0?
//Earlier we introduced the Optional class, which is a container that indicates the presence or
//absence of a value. Optional can be parameterized with reference types such as Integer, String, and so on. There’s a primitive specialized version of Optional as well for the three primitive
//stream specializations: OptionalInt, OptionalDouble, and OptionalLong.
OptionalInt maxCalories = menu.stream()
.mapToInt(Dish::getCalories)
.max();
//Java 8 introduces two
//static methods available on IntStream and LongStream to help generate such ranges: range and
///rangeClosed. Both methods take the starting value of the range as the first parameter and the
// end value of the range as the second parameter. But range is exclusive, whereas rangeClosed is
//inclusive. Let’s look at an example:
long count = IntStream.rangeClosed(1, 100)
.filter(integer -> integer % 2 == 0)
.count();
//if you were using
//IntStream.range(1, 100) instead, the result would be 49 even numbers because range is
//exclusive.
//t the famous Greek mathematician Pythagoras discovered
//that certain triples of numbers (a, b, c) satisfy the formula a * a + b * b = c * c where a, b, and c
//are integers. For example, (3, 4, 5) is a valid Pythagorean triple because 3 * 3 + 4 * 4 = 5 * 5 or 9
//+ 16 = 25. There are an infinite number of such triples
//generate all such triple in range 1 to 100
IntStream.rangeClosed(1,100).boxed()
.flatMap(a->IntStream.rangeClosed(1,100)
.mapToObj(b->new double [] {a,b, Math.sqrt(a*a+b*b)}))
.filter(t->t[2]%1==0)
.forEach(t-> Arrays.stream(t).forEach(System.out::println)); //Streams from arrays
//TO Do - get result in expected format
//. Streams from values
Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");
stream.map(String::toUpperCase)
.forEach(System.out::println);
Stream<String> emptyStream = Stream.empty();
//Iterate
//Let’s look at a simple example of how to use iterate before we explain it:
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);
//Iterate
// Let’s look at a simple example of how to use iterate before we explain it:
// Fibonacci series
Stream.iterate(new int[]{0, 1},
t -> new int[]{t[1],t[0] + t[1]})
.limit(20)
.map(t -> t[0])
.forEach(System.out::println);
// Fibonacci series -pairs
Stream.iterate(new int[]{0, 1},
t -> new int[]{t[1], t[0]+t[1]})
.limit(20)
.forEach(t -> System.out.println("(" + t[0] + "," + t[1] +")"));
// // Stream genarate - to generate infinite Stream -Must provide Limit
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
}
}
| true |
ce0731dd1fc2c394cc71043446c28d9ebed3e0d8 | Java | servicecatalog/development | /oscm-portal-webtests/javasrc/org/oscm/webtest/setup/ServiceActivationTask.java | UTF-8 | 5,966 | 2.046875 | 2 | [
"Apache-2.0",
"EPL-1.0",
"BSD-3-Clause",
"W3C",
"LGPL-3.0-only",
"CPL-1.0",
"CDDL-1.1",
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-or-later",
"CDDL-1.0",
"Apache-1.1",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"W3C-19980720",
"LGPL-2.1-only",
"... | permissive | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Author: Dirk Bernsau
*
* Creation Date: May 23, 2011
*
* Completion Time: June 8, 2011
*
*******************************************************************************/
package org.oscm.webtest.setup;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.oscm.internal.intf.MarketplaceService;
import org.oscm.internal.intf.ServiceProvisioningService;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.exception.SaaSApplicationException;
import org.oscm.internal.vo.VOCatalogEntry;
import org.oscm.internal.vo.VOCustomerService;
import org.oscm.internal.vo.VOService;
import org.oscm.internal.vo.VOServiceActivation;
/**
* Custom ANT task activating the service specified by service IDs.
*
* @author Dirk Bernsau
*
*/
public class ServiceActivationTask extends IterableTask {
private String serviceIds;
protected boolean active = true; // activate or deactivate?
private boolean failOnMissing = true;
public void setServiceIds(String value) {
serviceIds = value;
}
public void setFailOnMissing(String value) {
failOnMissing = Boolean.parseBoolean(value);
}
@Override
public void executeInternal() throws BuildException,
SaaSApplicationException {
serviceIds = multiply(serviceIds);
if (serviceIds == null || serviceIds.trim().length() == 0) {
throwBuildException("No service IDs specified - use the serviceIds attribute to specify one or more service IDs");
}
String[] split = serviceIds.split(",");
List<String> serviceIds = new ArrayList<String>(split.length);
for (int i = 0; i < split.length; i++) {
if (split[i].trim().length() > 0) {
serviceIds.add(split[i].trim());
}
}
ServiceProvisioningService spsSvc = getServiceInterface(ServiceProvisioningService.class);
MarketplaceService mpSvc = getServiceInterface(MarketplaceService.class);
ArrayList<VOServiceActivation> activations = new ArrayList<VOServiceActivation>();
ArrayList<String> missingIds = new ArrayList<String>(serviceIds);
List<VOCustomerService> csServices = spsSvc
.getAllCustomerSpecificServices();
boolean useAll = split.length == 1 && "*".equals(split[0]);
for (VOService service : spsSvc.getSuppliedServices()) {
if (useAll || serviceIds.contains(service.getServiceId())) {
List<VOCatalogEntry> catEntries = mpSvc
.getMarketplacesForService(service);
VOServiceActivation activation = new VOServiceActivation();
activation.setService(service);
activation.setCatalogEntries(catEntries);
activation.setActive(active);
activations.add(activation);
activations.addAll(getCustomerServicesToDeactivate(service,
csServices));
missingIds.remove(service.getServiceId());
}
}
if (!useAll && missingIds.size() > 0) {
if (failOnMissing) {
throwBuildExceptionForIds(
"The following services were not found: ", missingIds);
} else {
logForIds("The following services were not found: ", missingIds);
}
}
if (activations.size() > 0) {
List<VOService> result = spsSvc.setActivationStates(activations);
if (activations.size() > result.size()) {
throwBuildException("Only " + result.size() + "/"
+ activations.size()
+ " (de-)activations were successful");
}
if (active) {
log("Activated " + activations.size() + " service(s)");
} else {
log("De-activated " + activations.size() + " service(s)");
}
} else {
throwBuildException("Nothing to do");
}
}
/**
* On deactivation, for all active customer specific services belonging to
* the provided service, a {@link VOServiceActivation} to deactivate the
* service will be created that is contained in the result list.
*
* @param service
* the service to get customer specific one for
* @param csServices
* all customer specific services
* @return the {@link VOServiceActivation}s for the customer specific
* services to deactivate
*/
private List<VOServiceActivation> getCustomerServicesToDeactivate(
VOService service, List<VOCustomerService> csServices) {
List<VOServiceActivation> result = new ArrayList<VOServiceActivation>();
if (active) {
return result;
}
for (VOCustomerService cs : csServices) {
if (cs.getStatus() == ServiceStatus.ACTIVE
&& cs.getServiceId().equals(service.getServiceId())) {
VOServiceActivation activation = new VOServiceActivation();
activation.setService(cs);
activation.setCatalogEntries(new ArrayList<VOCatalogEntry>());
activation.setActive(active);
result.add(activation);
}
}
return result;
}
}
| true |
bb50e1c10bc22e0fccaacbede80b4bea93d623a5 | Java | tjniemis/tietokantasovellus | /src/main/java/fi/helsinki/cs/controller/AdminController.java | UTF-8 | 2,763 | 2.640625 | 3 | [] | no_license | package fi.helsinki.cs.controller;
import fi.helsinki.cs.dao.JobDao;
import fi.helsinki.cs.dao.UserDao;
import fi.helsinki.cs.model.Job;
import fi.helsinki.cs.model.User;
import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Controller for various administrator functionalities. Also contains methods for generic errorhandling.
*
*/
@Controller
public class AdminController {
@Autowired
private UserDao userDao;
@Autowired
private JobDao jobDao;
/**
* Controller method for admin call. This method retrieves all possible entitities which administrator can
* maintain and returns call to admin.jsp page.
*
* @param model Model of the page
* @param principal User data
* @return admin.jsp
*/
@RequestMapping(value="/admin", method = RequestMethod.GET)
public String admin(ModelMap model, Principal principal) {
System.out.println("AdminController");
User user = userDao.findByEmail(principal.getName());
List<Job> jobs = jobDao.getJobs();
List<User> persons = userDao.getUsers();
model.addAttribute("jobs", jobs);
model.addAttribute("persons", persons);
model.addAttribute("user", user);
return "admin";
}
/**
* Method for handling unauthorized access attempts. When logged user tries to access page which he/she has no
* access rights, call is forwarded to this method and accessDenied page is displayed instead.
*
* @param model Model of the page
* @return accessDenied.jsp
*/
@RequestMapping(value="/accessDenied", method = RequestMethod.GET)
public String accessDenied(ModelMap model) {
return "accessDenied";
}
/**
* Deletes one job.
*
* @param jobId ID of the job which is to be deleted
* @return Redirection to admin-call in this controller
*/
@RequestMapping(value = "/deleteJobAdmin/{jobId}", method = RequestMethod.GET)
public String deleteJob(@PathVariable Long jobId) {
System.out.println("deleteJobAdmin");
jobDao.delete(jobId);
return "redirect:../admin";
}
}
| true |
34ed7edef423d2cb8c495b0d9bd7cb320ca050a8 | Java | 1005419213zxf/leetcode | /src/main/java/com/litb/bid/component/adw/SearchAdwordsMetricProvider.java | UTF-8 | 5,251 | 2.078125 | 2 | [] | no_license | package com.litb.bid.component.adw;
import com.litb.bid.DirDef;
import com.litb.adw.lib.enums.AdwordsChannel;
import com.litb.adw.lib.enums.AdwordsDevice;
import com.litb.adw.lib.enums.AdwordsReportType;
import com.litb.adw.lib.exception.AdwordsApiException;
import com.litb.adw.lib.exception.AdwordsRemoteException;
import com.litb.adw.lib.exception.AdwordsValidationException;
import com.litb.adw.lib.operation.report.KeywordAttribute;
import com.litb.adw.lib.util.AdwordsCampaignNameHelper;
import com.litb.basic.enums.LanguageType;
import com.litb.basic.enums.SiteType;
import com.litb.basic.io.FileHelper;
import com.litb.basic.util.DateHelper;
import com.litb.bid.object.adwreport.KeywordIntervalReport;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.Scanner;
public class SearchAdwordsMetricProvider extends AdwordsMetricProviderBase implements AdwordsMetricProviderInterface {
// constructor
public SearchAdwordsMetricProvider(Date endDate, int interval) throws SQLException, IOException{
super(endDate, interval);
// initialize
init(endDate, interval, null);
init(endDate, interval, AdwordsDevice.mobile);
System.out.println("after init size(campaign): " + campaignKeyMetricMap.size());
System.out.println("after init size(summary): " + summaryKeyMetricMap.size());
// filter
filter();
System.out.println("after filter size(campaign): " + campaignKeyMetricMap.size());
System.out.println("after filter size(summary): " + summaryKeyMetricMap.size());
}
// initialize
private void init(Date endDate, int interval, AdwordsDevice aDevice) throws IOException{
String InputDir = DirDef.getFormattedReportDir(endDate, AdwordsReportType.keyword_performance, interval
, aDevice);
for(String inputFilePath : FileHelper.getFilePathsInOneDir(InputDir)){
// for one account
BufferedReader br = FileHelper.readFile(inputFilePath);
String line;
while((line = br.readLine()) != null){
KeywordIntervalReport report = KeywordIntervalReport.parseFromLine(line);
KeywordAttribute attribute = (KeywordAttribute) report.getAttribute();
AdwordsChannel thisChannel = AdwordsCampaignNameHelper.getAdwordsChannel(attribute.getCampaignName());
if(!thisChannel.equals(AdwordsChannel.search)){
continue;
}
SiteType siteType = AdwordsCampaignNameHelper.getSiteType(attribute.getCampaignName());
LanguageType languageType = AdwordsCampaignNameHelper.getLanguageTypeFromCampaignName(attribute.getCampaignName());
int cid = attribute.getCategoryId();
Long accountId = attribute.getAccountId();
Long campaignId = attribute.getCampaignId();
mergeDataToMap(report, attribute, aDevice, thisChannel,siteType,languageType, cid, accountId, campaignId);
}
br.close();
}
}
// main for test
public static void main(String[] args) throws IOException, ParseException, AdwordsValidationException, AdwordsApiException, AdwordsRemoteException {
int interval = -1;
Date endDate = null;
try {
interval = Integer.parseInt(args[0]);
if(args.length > 1)
endDate = DateHelper.getShortDate(args[1]);
else {
endDate = DateHelper.getShortDate(DateHelper.getShortDateString(new Date()));
endDate = DateHelper.addDays(-1, endDate);
}
} catch (Exception e) {
System.err.println("Usage : <interval> <end date(optional)>");
System.exit(1);
}
System.out.println();
try {
SearchAdwordsMetricProvider provider = new SearchAdwordsMetricProvider(endDate, interval);
System.out.println("Usage : <accountId> <campaignId> <site type> <channel> <language type> <cid> <minAllConversion> <minPcConversion> <minMobileConversion>");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String line = in.nextLine();
String[] arr = line.split(" ");
int idx = 0;
try {
long accountId = Long.parseLong(arr[idx++]);
long campaignId = Long.parseLong(arr[idx++]);
// site
SiteType siteType = SiteType.valueOf(arr[idx++]);
// channel
String channelStr = arr[idx++];
AdwordsChannel channel = null;
if(channelStr.equals("-1") || channelStr.equals("null"))
channel = null;
else
channel = AdwordsChannel.valueOf(channelStr);
// language
String langStr = arr[idx++];
LanguageType languageType = null;
if(langStr.equals("-1") || langStr.equals("null"))
languageType = null;
else
languageType = LanguageType.valueOf(langStr);
// category
int categoryId = Integer.parseInt(arr[idx++]);
// threshold
int minAllConversion = Integer.parseInt(arr[idx++]);
int minPcConversion = Integer.parseInt(arr[idx++]);
int minMobileConversion = Integer.parseInt(arr[idx++]);
AdwordsDeviceMetricInfo info = provider.getDeviceMetric(accountId, campaignId, siteType, channel, languageType, categoryId,
minAllConversion, minPcConversion, minMobileConversion);
System.out.println(info.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
d08d1ad5049c10d16c8a7678b259bcea4a15486f | Java | greeneley/STI2020 | /3ASTI/Object-oriented programming/Reviser/workspace2/CoffreAndCo/src/valuables/Gemstone.java | UTF-8 | 1,471 | 2.90625 | 3 | [] | no_license | package valuables;
import genericSafes.GenericSafe;
import genericSafes.IGemstore;
import safes.ToSale;
/**
* @author pascal
* @version 1.0
*/
public abstract class Gemstone implements ToSale, IGemstore {
/**
* @uml.property name="value"
*/
protected double value;
/**
* @uml.property name="weight"
*/
protected final double weight;
/**
* @uml.property name="volume"
*/
protected final double volume;
/**
* @param weight
* @param volume
*/
public Gemstone(double weight, double volume) {
this.weight = weight;
this.volume = volume;
mySafe = null;
}
/**
* @return the value
* @uml.property name="value"
*/
public double getValue() {
return value;
}
/**
* @return the weight
* @uml.property name="weight"
*/
public double getWeight() {
return weight;
}
/**
* @return the volume
* @uml.property name="volume"
*/
public double getVolume() {
return volume;
}
public abstract void expertize();
/*
{
value = weight * volume * Math.PI;
}
*/
// Connection with a safe
/**
* @uml.property name="mySafe"
* @uml.associationEnd
*/
private GenericSafe<Integer> mySafe;
/**
* @return the mySafe
* @uml.property name="mySafe"
*/
public GenericSafe<Integer> getMySafe() {
return mySafe;
}
/**
* @param mySafe the mySafe to set
* @uml.property name="mySafe"
*/
public void setMySafe(GenericSafe<Integer> mySafe) {
this.mySafe = mySafe;
}
}
| true |
7a1dc0d2e7841003a2a4a4de1e4cdf8c77e84810 | Java | whatafree/JCoffee | /benchmark/bigclonebenchdata_partial/7087108.java | UTF-8 | 556 | 2.28125 | 2 | [] | no_license |
class c7087108 {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = request.getPathTranslated().substring(0, request.getPathTranslated().length() - request.getPathInfo().length()) + request.getServletPath() + request.getPathInfo();
File file = new File(path);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
IOUtils.copyLarge(in, response.getOutputStream());
in.close();
}
}
}
| true |
3b369840ae7270098d061b8c0f5d022aa3352fa0 | Java | HusseinHroub/ClientUDPRemake | /app/src/main/java/com/example/clientudpremake/commands/senders/WebSocketSenderButton.java | UTF-8 | 696 | 2.234375 | 2 | [] | no_license | package com.example.clientudpremake.commands.senders;
import android.app.Activity;
import com.example.clientudpremake.commands.Command;
import com.example.clientudpremake.utilites.ThreadsUtilty;
import com.example.clientudpremake.workers.websocket.WebSocketManager;
import com.google.gson.Gson;
import lombok.AllArgsConstructor;
public class WebSocketSenderButton implements Command {
private final String message;
public <T> WebSocketSenderButton(T model) {
this.message = new Gson().toJson(model);
}
@Override
public void apply(Activity activity) {
ThreadsUtilty.getExecutorService().execute(() -> WebSocketManager.INSTANCE.sendText(message));
}
}
| true |
095471d09b3f0b9530c33aca629db8dace2c81e1 | Java | RobertBrumbaugh/VendingMachineCapstone1 | /java/src/test/java/com/techelevator/GumTest.java | UTF-8 | 492 | 2.46875 | 2 | [] | no_license | package com.techelevator;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class GumTest {
Gum gumTest;
@Before
public void setup() {
gumTest = new Gum("D1", "U-Chews", "3.05", "Gum", 5);
}
@Test
public void test_01_Checking_Price() {
Assert.assertNotSame("3.50", gumTest.getPriceString());
}
@Test
public void test_02_Checking_Sound() {
Assert.assertEquals("Chew Chew, Yum!", gumTest.getSound());
}
} | true |
e0767dd30d463b7de50c50dd263571764625591c | Java | sonsangjun/java_example | /_20150422_Socket_II/src/_20150422_Socket_II/ServerExample.java | UTF-8 | 548 | 3 | 3 | [] | no_license | package _20150422_Socket_II;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerExample {
public void mainServer()
{
ServerSocket serverSocket = null;
System.out.println("서버시작");
try{
serverSocket = new ServerSocket(9000);
while(true)
{
Socket socket = serverSocket.accept();
Thread thread = new PerClientThread(socket);
thread.start();
}
}catch(Exception e)
{
System.out.println("서버 작동 실패");
}
System.out.println("서버정지");
}
}
| true |
c617998620b9523f624494ea1d4aa632a6d8e9ef | Java | lospejos/xmldemo | /src/main/java/com/example/N1Node.java | UTF-8 | 1,056 | 2.34375 | 2 | [] | no_license | package com.example;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import java.util.List;
/**
* N1Node
*/
@JacksonXmlRootElement(localName = "n1")
public class N1Node {
private String id;
private List<N2Node> n2NodeList;
private String text;
@JacksonXmlProperty(localName = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JacksonXmlElementWrapper(localName = "n2")
public List<N2Node> getN2NodeList() {
return n2NodeList;
}
public void setN2NodeList(List<N2Node> n2NodeList) {
this.n2NodeList = n2NodeList;
}
@JacksonXmlText
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| true |
525ca4e9d777d5ea3c90c359fec13e905dcddbd8 | Java | nagyist/marketcetera | /trunk/util/src/main/java/org/marketcetera/util/unicode/UnicodeOutputStreamWriter.java | UTF-8 | 9,554 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | package org.marketcetera.util.unicode;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import org.marketcetera.util.misc.ClassVersion;
/**
* A variation of {@link OutputStreamWriter} that is BOM-aware. It can
* operate in any of the following modes:
*
* <ul>
*
* <li>As a standard output stream writer that uses the default JVM
* charset.</li>
*
* <li>A writer that uses a specific charset and (optionally) injects
* a specific signature in the header of the output stream.</li>
*
* <li>A writer that uses the signature/charset which a supplied
* reader had used to decode a byte stream. This is useful when a file
* is modified, and the original signature/charset must be
* preserved.</li>
*
* </ul>
*
* @author tlerios@marketcetera.com
* @since 0.6.0
* @version $Id: UnicodeOutputStreamWriter.java 16154 2012-07-14 16:34:05Z colin $
*/
/* $License$ */
@ClassVersion("$Id: UnicodeOutputStreamWriter.java 16154 2012-07-14 16:34:05Z colin $")
public class UnicodeOutputStreamWriter
extends Writer
{
// INSTANCE DATA.
private OutputStream mStream;
private OutputStreamWriter mWriter;
private SignatureCharset mRequestedSignatureCharset;
private SignatureCharset mSignatureCharset;
private boolean mWriteSignature=true;
// CONSTRUCTORS.
/**
* Creates a new writer over the given stream that uses the
* default JVM charset (and no signature is injected).
*
* @param stream The stream.
*/
public UnicodeOutputStreamWriter
(OutputStream stream)
{
super(stream);
mStream=stream;
}
/**
* Creates a new writer over the given stream that normally
* injects the given signature, and uses its associated charset
* for encoding. However, if the charset in the given
* signature/charset pair is not supported by the JVM, the default
* JVM charset is used instead (and no signature is
* injected). Signature injection is also skipped if the given
* flag is set to false (even if the signature/charset pair
* has a signature).
*
* @param stream The stream.
* @param requestedSignatureCharset The signature/charset. It may
* be null to use the default JVM charset.
* @param writeSignature True if a signature (if any) should be
* written.
*/
protected UnicodeOutputStreamWriter
(OutputStream stream,
SignatureCharset requestedSignatureCharset,
boolean writeSignature)
{
this(stream);
mRequestedSignatureCharset=requestedSignatureCharset;
mWriteSignature=writeSignature;
}
/**
* Creates a new writer over the given stream that normally
* injects the given signature, and uses its associated charset
* for encoding. However, if the charset in the given
* signature/charset pair is not supported by the JVM, the default
* JVM charset is used instead (and no signature is injected).
*
* @param stream The stream.
* @param requestedSignatureCharset The signature/charset. It may
* be null to use the default JVM charset.
*/
public UnicodeOutputStreamWriter
(OutputStream stream,
SignatureCharset requestedSignatureCharset)
{
this(stream,requestedSignatureCharset,true);
}
/**
* Creates a new writer over the given stream that uses the actual
* signature/charset of the given reader. If the reader is not a
* valid instance of a {@link UnicodeInputStreamReader}, or if it
* used the default JVM charset, then the writer uses the default
* JVM charset (and no signature is injected). Signature injection
* is also skipped if the given flag is set to false (even if the
* given reader's signature/charset pair has a signature).
*
* @param stream The stream.
* @param reader The reader.
* @param writeSignature True if a signature (if any) should be
* written.
*
* @throws IOException Thrown if an I/O error occurs.
*/
protected UnicodeOutputStreamWriter
(OutputStream stream,
Reader reader,
boolean writeSignature)
throws IOException
{
this(stream);
if (reader instanceof UnicodeInputStreamReader) {
mRequestedSignatureCharset=
((UnicodeInputStreamReader)reader).getSignatureCharset();
mWriteSignature=writeSignature;
}
}
/**
* Creates a new writer over the given stream that uses the actual
* signature/charset of the given reader. If the reader is not a
* valid instance of a {@link UnicodeInputStreamReader}, or if it
* used the default JVM charset, then the writer uses the default
* JVM charset (and no signature is injected).
*
* @param stream The stream.
* @param reader The reader.
*
* @throws IOException Thrown if an I/O error occurs.
*/
public UnicodeOutputStreamWriter
(OutputStream stream,
Reader reader)
throws IOException
{
this(stream,reader,true);
}
// Writer.
@Override
public void write
(int c)
throws IOException
{
synchronized (lock) {
init();
mWriter.write(c);
}
}
@Override
public void write
(char[] cbuf)
throws IOException
{
synchronized (lock) {
init();
mWriter.write(cbuf);
}
}
@Override
public void write
(char cbuf[],
int off,
int len)
throws IOException
{
synchronized (lock) {
init();
mWriter.write(cbuf,off,len);
}
}
@Override
public void write
(String str)
throws IOException
{
synchronized (lock) {
init();
mWriter.write(str);
}
}
@Override
public void write
(String str,
int off,
int len)
throws IOException
{
synchronized (lock) {
init();
mWriter.write(str,off,len);
}
}
@Override
public Writer append
(CharSequence csq)
throws IOException
{
synchronized (lock) {
init();
return mWriter.append(csq);
}
}
@Override
public Writer append
(CharSequence csq,
int start,
int end)
throws IOException
{
synchronized (lock) {
init();
return mWriter.append(csq,start,end);
}
}
@Override
public Writer append
(char c)
throws IOException
{
synchronized (lock) {
init();
return mWriter.append(c);
}
}
@Override
public void flush()
throws IOException
{
synchronized (lock) {
init();
mWriter.flush();
}
}
@Override
public void close()
throws IOException
{
synchronized (lock) {
if (mStream==null) {
return;
}
if (mWriter!=null) {
mWriter.close();
}
mStream.close();
mStream=null;
}
}
// INSTANCE METHODS.
/**
* Returns the receiver's requested signature/charset. This pair
* may have either been requested directly or by requesting that a
* reader's actual signature/charset be matched.
*
* @return The requested signature/charset, which may be null if
* none was requested.
*/
public SignatureCharset getRequestedSignatureCharset()
{
return mRequestedSignatureCharset;
}
/**
* Returns the receiver's actual signature/charset (that is, the
* one in use to encode the stream).
*
* @return The signature/charset, which may be null if the default
* JVM charset is used.
*
* @throws IOException Thrown if an I/O error occurs.
*/
public SignatureCharset getSignatureCharset()
throws IOException
{
synchronized (lock) {
init();
return mSignatureCharset;
}
}
/**
* Initializes the receiver.
*
* @throws IOException Thrown if an I/O error occurs.
*/
private void init()
throws IOException
{
if (mStream==null) {
throw new IOException(Messages.STREAM_CLOSED.getText());
}
if (mWriter!=null) {
return;
}
mSignatureCharset=getRequestedSignatureCharset();
if ((mSignatureCharset!=null) && (!mSignatureCharset.isSupported())) {
mSignatureCharset=null;
}
if (mSignatureCharset!=null) {
if (mWriteSignature) {
mStream.write(mSignatureCharset.getSignature().getMark());
}
mWriter=new OutputStreamWriter
(mStream,mSignatureCharset.getCharset().getCharset());
} else {
mWriter=new OutputStreamWriter(mStream);
}
}
}
| true |
eb7714bd3eee3bdea017b7943e9f1af19ca9f8bb | Java | fangheart/NiuKeTest | /src/SixFive/NK60PrinterTreeLayer/Solution.java | UTF-8 | 1,496 | 3.453125 | 3 | [] | no_license | package SixFive.NK60PrinterTreeLayer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by FangHeart on 2017/3/19.
*/
/*
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
*/
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public static void main(String[] args){
}
/*
*/
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
if (pRoot==null)
return arrayLists;
ArrayList<Integer> arrayList = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
int start=0,end = 1;
while (!queue.isEmpty()){
TreeNode p = queue.poll();
arrayList.add(p.val);
start++;
if (p.left!=null)
queue.add(p.left);
if (p.right!=null)
queue.add(p.right);
if (start==end){
end = queue.size();
start = 0;
arrayLists.add(arrayList);
arrayList = new ArrayList<>();
}
}
return arrayLists;
}
} | true |
244bfb562538fa874dfe01ec391d780d3b72dd9c | Java | simonalford42/Everything | /MENSA/src/Jan16.java | UTF-8 | 2,024 | 3.953125 | 4 | [] | no_license | import java.util.Arrays;
public class Jan16 {
public static final String DESCRIPTION =
"Fill in the blanks with spelled-out numbers to make the"
+ " statement true.";
public final String text;
private final char[] letters;
private int[] numOfLetters;
static final String[] SPELLED_OUT_NUMBERS = {"ZERO", "ONE", "TWO", "THREE",
"FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE",
"THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN",
"NINETEEN", "TWENTY"};
final int MAX_OF_ONE_LETTER;
public Jan16(String text, char[] letters) {
this.text = text;
this.letters = letters;
numOfLetters = new int[letters.length];
MAX_OF_ONE_LETTER = 20;
}
public void solve() {
boolean keepGoing = true;
while(keepGoing == true) {
keepGoing = addOne(numOfLetters);
int[] numOfLetters2 = new int[letters.length];
String fullString = text;
for(int num: numOfLetters)
fullString+=SPELLED_OUT_NUMBERS[num];
for(int i = 0; i < fullString.length(); i++) {
for(int c = 0; c < letters.length; c++) {
if(fullString.charAt(i) == letters[c])
numOfLetters2[c]++;
}
}
// System.out.println(fullString + Arrays.toString(numOfLetters2));
boolean isRight = true;
for(int i = 0; i < numOfLetters.length; i++) {
if(numOfLetters2[i] != numOfLetters[i]) {
isRight = false;
break;
}
}
if(isRight) {
String output = "";
for(int i = 0; i < letters.length; i++)
output+= numOfLetters[i] + " " + Character.toString(letters[i]) + "'S, ";
System.out.println(output);
return;
}
}
}
private boolean addOne(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i]++;
if(array[i] > this.MAX_OF_ONE_LETTER) {
array[i] = 0;
} else {
return true;
}
}
return false;
}
public static void main(String[] args) {
char[] c = {'N', 'S', 'E'};
new Jan16("THIS PICTURE FRAME CONTAINS EXACTLY N'S,S'S, AND E'S", c).solve();
}
}
| true |
5f824e85f6ff8440656efaf2295ba2986316d103 | Java | canavdan/Gagful | /src/main/java/com/gagful/service/impl/CommentServiceImpl.java | UTF-8 | 1,319 | 2.09375 | 2 | [
"MIT"
] | permissive | package com.gagful.service.impl;
import com.gagful.dto.CommentDTO;
import com.gagful.entity.Comment;
import com.gagful.exception.PostNotFoundException;
import com.gagful.mapper.Mapper;
import com.gagful.repository.CommentRepository;
import com.gagful.repository.PostRepository;
import com.gagful.service.CommentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.List;
@RequiredArgsConstructor
@Service
@Validated
@Slf4j
public class CommentServiceImpl implements CommentService {
private final CommentRepository commentRepository;
private final PostRepository postRepository;
private final Mapper mapper;
@Override
public List<CommentDTO> getComments(String postId) {
log.info("Get comments for postId: " + postId);
postRepository.findById(postId).orElseThrow(
() -> new PostNotFoundException("Post not found with postID: " + postId));
List<Comment> comments = commentRepository.findByPost_Id(postId);
return mapper.mapList(comments, CommentDTO.class);
}
@Override
public Long countByPost_Id(String postId) {
return commentRepository.countByPost_Id(postId);
}
}
| true |
a25a13968101d55e25c89b5a8787ed69926d8b93 | Java | JetBrains/intellij-community | /platform/lang-impl/src/com/intellij/internal/DumpScreenConfigurationAction.java | UTF-8 | 8,035 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.JBColor;
import com.intellij.ui.ScreenUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.util.ArrayList;
final class DumpScreenConfigurationAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance(DumpScreenConfigurationAction.class);
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
new ScreenDialog(event).show();
}
private static Rectangle minimize(Rectangle bounds) {
return new Rectangle(bounds.x / 10, bounds.y / 10, bounds.width / 10, bounds.height / 10);
}
private static void append(StringBuilder sb, GraphicsDevice device) {
append(sb, "id", device.getIDstring());
append(sb, "type", getTypeName(device.getType()));
append(sb, device.getDisplayMode());
GraphicsConfiguration configuration = device.getDefaultConfiguration();
append(sb, "outer", configuration.getBounds());
append(sb, "inner", ScreenUtil.getScreenRectangle(configuration));
append(sb, "default image", configuration.getImageCapabilities());
BufferCapabilities capabilities = configuration.getBufferCapabilities();
append(sb, "front buffer image", capabilities.getFrontBufferCapabilities());
append(sb, "back buffer image", capabilities.getBackBufferCapabilities());
sb.append("page flipping: ").append(capabilities.getFlipContents());
if (capabilities.isFullScreenRequired()) {
sb.append("; full-screen exclusive mode is required");
}
if (capabilities.isMultiBufferAvailable()) {
sb.append("; more than two buffers can be used");
}
sb.append("\n");
}
private static void append(StringBuilder sb, String name, String text) {
sb.append(name).append(": ").append(text).append("\n");
}
private static void append(StringBuilder sb, String name, Rectangle bounds) {
sb.append(name);
sb.append(": x=").append(bounds.x);
sb.append(", y=").append(bounds.y);
sb.append(", width=").append(bounds.width);
sb.append(", height=").append(bounds.height);
sb.append("\n");
}
private static void append(StringBuilder sb, DisplayMode mode) {
sb.append("mode: ").append(mode.getWidth()).append("x").append(mode.getHeight());
sb.append("; bit depth=").append(mode.getBitDepth());
sb.append("; refresh rate=").append(mode.getRefreshRate());
sb.append("\n");
}
private static void append(StringBuilder sb, String name, ImageCapabilities capabilities) {
if (capabilities != null) {
sb.append(name).append(": accelerated=").append(capabilities.isAccelerated());
if (capabilities.isTrueVolatile()) {
sb.append("; true volatile");
}
sb.append("\n");
}
}
private static String getTypeName(int type) {
if (type == 0) return "raster screen";
if (type == 1) return "printer";
if (type == 2) return "image buffer";
return "unknown: " + type;
}
private static final class ScreenDialog extends DialogWrapper {
private ScreenDialog(AnActionEvent event) {
super(event.getProject());
init();
setOKButtonText("Dump");
setTitle("Screen Configuration");
}
@Override
protected JComponent createCenterPanel() {
return new ScreenView();
}
@Override
protected Action @NotNull [] createActions() {
return new Action[]{getOKAction(), getCancelAction()};
}
@Override
protected void doOKAction() {
StringBuilder sb = new StringBuilder();
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
append(sb, "number of devices", Integer.toString(devices.length));
for (GraphicsDevice device : devices) {
append(sb.append("\n"), device);
}
LOG.warn(sb.toString());
CopyPasteManager.getInstance().setContents(new StringSelection(sb.toString()));
super.doOKAction();
}
}
private static final class ScreenInfo {
private final Rectangle myOuterBounds = new Rectangle();
private final Rectangle myInnerBounds = new Rectangle();
private boolean update(GraphicsConfiguration configuration) {
boolean updated = false;
Rectangle outer = minimize(configuration.getBounds());
if (!myOuterBounds.equals(outer)) {
myOuterBounds.setBounds(outer);
updated = true;
}
Rectangle inner = minimize(ScreenUtil.getScreenRectangle(configuration));
if (!myInnerBounds.equals(inner)) {
myInnerBounds.setBounds(inner);
updated = true;
}
return updated;
}
}
private static final class ScreenView extends JComponent {
private final ArrayList<ScreenInfo> myScreenList = new ArrayList<>();
private final Rectangle myBounds = new Rectangle();
private boolean update() {
boolean updated = false;
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
while (devices.length > myScreenList.size()) {
myScreenList.add(new ScreenInfo());
updated = true;
}
while (devices.length < myScreenList.size()) {
myScreenList.remove(devices.length);
updated = true;
}
for (int i = 0; i < devices.length; i++) {
if (myScreenList.get(i).update(devices[i].getDefaultConfiguration())) {
updated = true;
}
}
if (updated) {
int minX = 0;
int maxX = 0;
int minY = 0;
int maxY = 0;
for (ScreenInfo info : myScreenList) {
int x = info.myOuterBounds.x;
if (minX > x) {
minX = x;
}
x += info.myOuterBounds.width;
if (maxX < x) {
maxX = x;
}
int y = info.myOuterBounds.y;
if (minY > y) {
minY = y;
}
y += info.myOuterBounds.height;
if (maxY < y) {
maxY = y;
}
}
myBounds.setBounds(minX, minY, maxX - minX, maxY - minY);
}
return updated;
}
@Override
protected void paintComponent(Graphics g) {
if (update()) {
setPreferredSize(myBounds.getSize());
setMinimumSize(myBounds.getSize());
revalidate();
repaint();
}
g = g.create();
if (g instanceof Graphics2D) {
UISettings.setupAntialiasing(g);
}
for (int i = 0; i < myScreenList.size(); i++) {
ScreenInfo info = myScreenList.get(i);
Rectangle bounds = info.myOuterBounds;
int x = bounds.x - myBounds.x + getX();
int y = bounds.y - myBounds.y + getY();
g.setColor(JBColor.BLUE);
g.fillRect(x, y, bounds.width, bounds.height);
bounds = info.myInnerBounds;
x = bounds.x - myBounds.x + getX();
y = bounds.y - myBounds.y + getY();
g.setColor(JBColor.BLACK);
g.fillRect(x, y, bounds.width, bounds.height);
String id = String.valueOf(i + 1);
int size = Math.min(bounds.width << 1, bounds.height);
g.setColor(JBColor.WHITE);
g.setFont(new Font("Monospaced", Font.BOLD, size));
FontMetrics fm = g.getFontMetrics();
x += (bounds.width - fm.stringWidth(id)) / 2;
y += (bounds.height - fm.getHeight()) / 2;
g.drawString(id, x, y + size);
}
g.dispose();
}
}
}
| true |
25fab8b743e3acf6e26de1b6b2778ee50d56daa1 | Java | chives-projects/Java | /src/main/java/LeetCode/RotateRight.java | UTF-8 | 1,175 | 3.390625 | 3 | [] | no_license | package LeetCode;
/**
* @description: 61 旋转链表
* @author: csc
* @create: 2020/1/27 17:27
*/
public class RotateRight {
public static ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) return head;
ListNode pre = head;
int sum = 0;
while (pre != null) {
sum++;
if (pre.next == null) break;
else pre = pre.next;
}
// 减少循环次数
if (sum <= k) k = k % sum;
if (k == 0) return head;
sum = sum - k - 1;
ListNode newHead = head;
for (int i = 0; i < sum; i++) newHead = newHead.next;
pre = newHead;
newHead = newHead.next;
ListNode tail = newHead;
while (tail != null) {
if (tail.next != null) tail = tail.next;
else break;
}
pre.next = tail.next;
tail.next = head;
return newHead;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode newH = rotateRight(head,1);
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
} | true |
5a46b752f78dc35f841859c31df9dbfdd603a69a | Java | yiding-he/sob | /src/main/java/com/hyd/sob/commands/user/UserCommand.java | UTF-8 | 240 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | package com.hyd.sob.commands.user;
import com.hyd.sob.Role;
import com.hyd.sob.commands.Command;
public abstract class UserCommand extends Command {
@Override
public Role forRole() {
return Role.User;
}
}
| true |
d3d9d47720f724e8fdee5dc1d3080a257f93f48e | Java | oubijie/JavaSE | /JavaSE02DataType/src/main/java/com/veryoo/dt/Test04String.java | UTF-8 | 577 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | package com.veryoo.dt;
/**
* String类型演示
* @author obj
* @email oubijie@139.com
* @vserion 2017年12月8日
*
*/
public class Test04String {
public static void main(String[] args) {
System.out.println("Hello");
String name = "obj";
System.out.println("my name is " + name);
String h = "你好," + "obj";
System.out.println(h);
System.out.println("test" + 4 + 5); //任意类型与字符串拼接都是字符串
System.out.println(4 + 5 + "test");
System.out.println(4 + "test" + 5);
// String b = 17;
}
}
| true |
bb8dca4c32b6dd12312edaff96e509682fb2af56 | Java | onexus/intogen-plugins | /src/main/java/org/intogen/decorators/impact/domain/Consequence.java | UTF-8 | 4,244 | 1.921875 | 2 | [] | no_license | package org.intogen.decorators.impact.domain;
import org.onexus.collection.api.IEntity;
import org.onexus.collection.api.IEntityTable;
import org.onexus.resource.api.ORI;
import java.io.Serializable;
public class Consequence implements Serializable {
private String snv;
private String transcript;
private String uniprot;
private String consequenceType;
private String protein;
private String aachange;
private String proteinPosition;
private Object impact;
private String siftClass;
private Double siftScore;
private Double siftTrans;
private String pph2Class;
private Double pph2Score;
private Double pph2Trans;
private String maClass;
private Double maScore;
private Double maTrans;
public Consequence(ORI collectionCT, IEntityTable table) {
super();
IEntity ct = table.getEntity(collectionCT);
boolean old = ct.get("CHROMOSOME") != null;
this.snv = String.valueOf(ct.get(old ? "CHROMOSOME" : "CHR")) + ":" +
String.valueOf(ct.get(old ? "POSITION" : "START")) + ":" +
String.valueOf(ct.get("ALLELE"));
this.transcript = String.valueOf(ct.get("TRANSCRIPT_ID"));
this.uniprot = String.valueOf(ct.get("UNIPROT_ID"));
this.consequenceType = String.valueOf(ct.get("CT"));
this.protein = String.valueOf(ct.get("PROTEIN_ID"));
this.impact = ct.get("IMPACT");
Object protein_pos = ct.get("PROTEIN_POS");
this.aachange = String.valueOf(ct.get("AA_CHANGE"));
if (protein_pos != null) {
this.proteinPosition = String.valueOf(protein_pos);
} else {
this.proteinPosition = "-";
}
// Sift
this.siftClass = String.valueOf(ct.get("SIFT_TRANSFIC_CLASS"));
this.siftScore = (Double) ct.get("SIFT_SCORE");
this.siftTrans = (Double) ct.get("SIFT_TRANSFIC");
// Pph2
this.pph2Class = String.valueOf(ct.get("PPH2_TRANSFIC_CLASS"));
this.pph2Score = (Double) ct.get("PPH2_SCORE");
this.pph2Trans = (Double) ct.get("PPH2_TRANSFIC");
// MA
this.maClass = String.valueOf(ct.get("MA_TRANSFIC_CLASS"));
this.maScore = (Double) ct.get("MA_SCORE");
this.maTrans = (Double) ct.get("MA_TRANSFIC");
}
public Object getImpact() {
return impact;
}
public String getAachange() {
return aachange;
}
public String getProteinPosition() {
return proteinPosition;
}
public String getConsequenceType() {
return consequenceType;
}
public String getPph2Class() {
return pph2Class;
}
public Double getPph2Score() {
return pph2Score;
}
public Double getPph2Trans() {
return pph2Trans;
}
public String getProtein() {
return protein;
}
public String getSiftClass() {
return siftClass;
}
public Double getSiftScore() {
return siftScore;
}
public Double getSiftTrans() {
return siftTrans;
}
public String getMaClass() {
return maClass;
}
public Double getMaScore() {
return maScore;
}
public Double getMaTrans() {
return maTrans;
}
public String getTranscript() {
return transcript;
}
public String getUniprot() {
return uniprot;
}
public String getSnv() {
return snv;
}
public void setSnv(String snv) {
this.snv = snv;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Consequence)) return false;
Consequence that = (Consequence) o;
if (consequenceType != null ? !consequenceType.equals(that.consequenceType) : that.consequenceType != null)
return false;
if (transcript != null ? !transcript.equals(that.transcript) : that.transcript != null) return false;
return true;
}
@Override
public int hashCode() {
int result = transcript != null ? transcript.hashCode() : 0;
result = 31 * result + (consequenceType != null ? consequenceType.hashCode() : 0);
return result;
}
}
| true |
68bf0613595db054ba2dfa81065f91d053cb593a | Java | lizhaowen72/leetcode | /src/main/java/leetcode/editor/cn/ValidPerfectSquare.java | UTF-8 | 2,024 | 3.765625 | 4 | [] | no_license | package leetcode.editor.cn;
//给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
//
// 说明:不要使用任何内置的库函数,如 sqrt。
//
// 示例 1:
//
// 输入:16
//输出:True
//
// 示例 2:
//
// 输入:14
//输出:False
//
// Related Topics 数学 二分查找
public class ValidPerfectSquare {
public static void main(String[] args) {
Solution solution = new ValidPerfectSquare().new Solution();
solution.isPerfectSquare(16);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isPerfectSquare(int num) {
/**
* Newton Method
*/
long x = num;
while (x * x > num) {
x = (x + num / x) >> 1;
}
return x * x == num;
}
/**
* O(log(n))
*
* @param num
* @return
*/
public boolean isPerfectSquare2(int num) {
int low = 1, high = num;
while (low <= high) {
long mid = (low + high) >>> 1;
if (mid * mid == num) {
return true;
} else if (mid * mid < num) {
low = (int) mid + 1;
} else {
high = (int) mid - 1;
}
}
return false;
}
/**
* 1=1
* 4=1+3
* 9=1+3+5
* 16=1+3+5+7
* ...
* so 1+3+5+...+(2n-1)=(1+2n-1)n/2=nn
* time complexity is O(sqrt(n))
*
* @param num
* @return
*/
public boolean isPerfectSquare1(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | true |
067955e04a936d289d06591f9c3b7ac8852fe85d | Java | AnnaKosAlex/Java | /src/leveltwo/lesson2_8/Main.java | UTF-8 | 187 | 1.507813 | 2 | [] | no_license | package leveltwo.lesson2_8;
import leveltwo.lesson2_8.client.OutstandingChat;
public class Main {
public static void main(String[] args) {
new OutstandingChat();
}
}
| true |
7111dccfb208c93731926e0e63aa9e4d99853160 | Java | ZoranLi/thunder | /com/huawei/hms/api/internal/e.java | UTF-8 | 1,001 | 1.695313 | 2 | [] | no_license | package com.huawei.hms.api.internal;
import android.content.Context;
import android.os.Build.VERSION;
import com.huawei.hms.api.HuaweiApiAvailability;
import com.huawei.hms.c.a;
/* compiled from: HuaweiMobileServicesUtil */
public abstract class e {
public static int a(Context context) {
a.a(context, "context must not be null.");
if (VERSION.SDK_INT < 15) {
return 21;
}
com.huawei.hms.c.e eVar = new com.huawei.hms.c.e(context);
context = eVar.a(HuaweiApiAvailability.SERVICES_PACKAGE);
if (com.huawei.hms.c.e.a.NOT_INSTALLED.equals(context)) {
return 1;
}
if (com.huawei.hms.c.e.a.DISABLED.equals(context) != null) {
return 3;
}
if (HuaweiApiAvailability.SERVICES_SIGNATURE.equalsIgnoreCase(eVar.d(HuaweiApiAvailability.SERVICES_PACKAGE)) == null) {
return 9;
}
return eVar.b(HuaweiApiAvailability.SERVICES_PACKAGE) < 20502300 ? 2 : null;
}
}
| true |
19921d3f21ea3466e62e3472731bfabee40c32dc | Java | libt83/DB_PROJECT | /src/EmpReportController.java | UTF-8 | 2,328 | 2.71875 | 3 | [] | no_license | import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.Callback;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by B on 6/3/16.
*/
public class EmpReportController
{
private MYSQL_Connection dbconnect;
private ObservableList<ObservableList> data;
@FXML
private TableView tableView;
/**
* Adds the data from the EMPLOYEE table into the TableView<br>
* in order to be displayed on the GUI.
*
* @throws SQLException
*/
public void generateTable() throws SQLException
{
dbconnect = new MYSQL_Connection();
Connection connection = dbconnect.getConnection();
data = FXCollections.observableArrayList();
String query = "SELECT * from sembab.EMPLOYEE natural join sembab.POSITION";
ResultSet rs = connection.createStatement().executeQuery(query);
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
tableView.getColumns().addAll(col);
System.out.println("Column ["+i+"] ");
}
while(rs.next()){
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
//Iterate Column
row.add(rs.getString(i));
}
System.out.println("Row [1] added "+row );
data.add(row);
}
tableView.setItems(data);
}
}
| true |
6aedd982285ecfb2d00d83e5ac723cc1df1158b3 | Java | wycBig/pms | /src/main/java/com/ujiuye/ExcelUtils/ExcelRead.java | UTF-8 | 1,149 | 2.5625 | 3 | [] | no_license | package com.ujiuye.ExcelUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class ExcelRead {
public static String getExcelContent(Cell cell){
String result = "";
switch (cell.getCellType()){
case HSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_ERROR:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getStringCellValue();
break;
default:
result="";
break;
}
return result;
}
}
| true |
a09f0a4ad451779bf22cc31ebef554eb5f9cca0c | Java | koderka/Servlets | /Exercises_I/src/pl/koderka/collection/Servlet_04.java | UTF-8 | 1,565 | 2.703125 | 3 | [] | no_license | package pl.koderka.collection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet_03
*/
@WebServlet("/Servlet_03")
public class Servlet_03 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Servlet_03() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Integer> random = new ArrayList<>();
Random rand = new Random();
for(int i = 0; i < 10; i++) {
int r = rand.nextInt(100);
while(r == 0) {
r = rand.nextInt(100);
}
random.add(r);
}
response.getWriter().append(random.toString() + "\n");
Collections.sort(random);
response.getWriter().append(random.toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
38ec995f5a7a34321ca06509d5209c0d8d7cbdea | Java | CodeNinja90/Java-Practice | /src/ToggleLetters.java | UTF-8 | 665 | 3.3125 | 3 | [] | no_license |
import java.util.*;
public class ToggleLetters {
public static void main(String[] args) {
String str = "mY nAMe is kHaN";
String togWord ="";
String[] words = str.split("\\s");
for (String w :words){
char []cha = w.toCharArray();
for (char c: cha){
if (Character.isUpperCase(c)){
togWord += Character.toLowerCase(c);
}
else{
togWord += Character.toUpperCase(c);
}
}
togWord += " ";
}
System.out.println(togWord.trim());
}
}
| true |
6216107e7185728b2bcdf694a59a84830fc3a08b | Java | Harrum/piapp | /piApp/src/piApp/PiInputLogger.java | UTF-8 | 490 | 2.828125 | 3 | [] | no_license | package piApp;
import java.util.ArrayList;
import java.util.List;
public class PiInputLogger
{
public interface PiInputListener
{
void inputReceived(Input input);
}
private List<PiInputListener> listeners = new ArrayList<PiInputListener>();
public void addListener(PiInputListener listener)
{
listeners.add(listener);
}
public void inputPressed(Input input)
{
for (PiInputListener pil : listeners)
{
pil.inputReceived(input);
}
}
}
| true |
2e2a1ab82582565cf173860eeeec24f7110c2482 | Java | oONinaOo/Shop-project | /src/bolt/aruk/Sajt.java | UTF-8 | 914 | 2.390625 | 2 | [] | no_license | package bolt.aruk;
import java.util.Date;
public class Sajt extends Elelmiszer {
private double suly;
private double zsirtartalom;
private Long vonalKod;
private String gyarto;
private Date szavatossagiIdo;
public Sajt(Long vonalKod, String gyarto, Date szavatossagiIdo, double zsirtartalom){
super(vonalKod, gyarto, szavatossagiIdo);
this.zsirtartalom = zsirtartalom;
}
public double getSuly() {
return suly;
}
public double getZsirtartalom() {
return zsirtartalom;
}
public String toString (){
return "" + getSuly() + getZsirtartalom() + getSzavatossagiIdo() + getVonalKod() + getGyarto() ;
}
public boolean joMeg() {
Date today = new Date();
return today.before(szavatossagiIdo);
}
public Date getSzavatossagiIdo() {
return szavatossagiIdo;
}
public long getVonalKod() {
return vonalKod;
}
public String getGyarto(){
return gyarto;
}
}
| true |
8af04adc8fdb9303977baf23096146ffbc3189ca | Java | myhtls/nature-platform | /nature-view/src/main/java/org/nature/view/primefaces/model/OrderByHandler.java | UTF-8 | 123 | 1.609375 | 2 | [] | no_license | package org.nature.view.primefaces.model;
public interface OrderByHandler {
public String getOrderBy(String orderBy);
}
| true |
49a7bd79aa9b19b015111256c921584f8f692613 | Java | SAIDProtocol/ICNInteroperability | /src/main/java/edu/rutgers/winlab/icninteroperability/ip/DemultiplexingEntityIPDynamic.java | UTF-8 | 1,448 | 2.484375 | 2 | [] | no_license | /*
* 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 edu.rutgers.winlab.icninteroperability.ip;
import edu.rutgers.winlab.icninteroperability.DemultiplexingEntity;
import java.net.InetSocketAddress;
import java.util.Objects;
/**
*
* @author ubuntu
*/
public class DemultiplexingEntityIPDynamic implements DemultiplexingEntity {
private final InetSocketAddress remoteAddress;
public DemultiplexingEntityIPDynamic(InetSocketAddress remoteAddress) {
this.remoteAddress = remoteAddress;
}
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
@Override
public int hashCode() {
int hash = 7;
hash = 13 * hash + Objects.hashCode(this.remoteAddress);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DemultiplexingEntityIPDynamic other = (DemultiplexingEntityIPDynamic) obj;
return Objects.equals(this.remoteAddress, other.remoteAddress);
}
@Override
public String toString() {
return String.format("Demux(DynamicIP){C=%s}", remoteAddress);
}
} | true |
9bda8c82c18dea3a42145993c7f96503b3626ac0 | Java | CaesarHo/AduroSmratSDK | /app/build/generated/source/apt/aduro/debug/com/adurosmart/activitys/ColourMixingActivity_ViewBinding.java | UTF-8 | 5,206 | 1.796875 | 2 | [] | no_license | // Generated code from Butter Knife. Do not modify!
package com.adurosmart.activitys;
import android.support.annotation.CallSuper;
import android.support.annotation.UiThread;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import butterknife.Unbinder;
import butterknife.internal.DebouncingOnClickListener;
import butterknife.internal.Utils;
import com.adurosmart.sdk.R;
import com.adurosmart.widget.ColorPickerView;
import java.lang.IllegalStateException;
import java.lang.Override;
public class ColourMixingActivity_ViewBinding implements Unbinder {
private ColourMixingActivity target;
private View view2131361957;
private View view2131362034;
private View view2131361942;
private View view2131361839;
private View view2131362195;
private View view2131361943;
private View view2131361842;
@UiThread
public ColourMixingActivity_ViewBinding(ColourMixingActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public ColourMixingActivity_ViewBinding(final ColourMixingActivity target, View source) {
this.target = target;
View view;
view = Utils.findRequiredView(source, R.id.ibtn_left, "field 'imageButton' and method 'onClick'");
target.imageButton = Utils.castView(view, R.id.ibtn_left, "field 'imageButton'", ImageButton.class);
view2131361957 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
target.textView = Utils.findRequiredViewAsType(source, R.id.tv_title, "field 'textView'", TextView.class);
target.seebar_temp = Utils.findRequiredViewAsType(source, R.id.color_seebar, "field 'seebar_temp'", SeekBar.class);
target.color_view = Utils.findRequiredViewAsType(source, R.id.color_view, "field 'color_view'", ColorPickerView.class);
view = Utils.findRequiredView(source, R.id.red, "field 'red_btn' and method 'onClick'");
target.red_btn = Utils.castView(view, R.id.red, "field 'red_btn'", Button.class);
view2131362034 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
view = Utils.findRequiredView(source, R.id.green, "field 'green_btn' and method 'onClick'");
target.green_btn = Utils.castView(view, R.id.green, "field 'green_btn'", Button.class);
view2131361942 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
view = Utils.findRequiredView(source, R.id.blue, "field 'blue_btn' and method 'onClick'");
target.blue_btn = Utils.castView(view, R.id.blue, "field 'blue_btn'", Button.class);
view2131361839 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
view = Utils.findRequiredView(source, R.id.white, "field 'white_btn' and method 'onClick'");
target.white_btn = Utils.castView(view, R.id.white, "field 'white_btn'", Button.class);
view2131362195 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
view = Utils.findRequiredView(source, R.id.grey, "field 'grey_btn' and method 'onClick'");
target.grey_btn = Utils.castView(view, R.id.grey, "field 'grey_btn'", Button.class);
view2131361943 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
view = Utils.findRequiredView(source, R.id.brown, "field 'brown_btn' and method 'onClick'");
target.brown_btn = Utils.castView(view, R.id.brown, "field 'brown_btn'", Button.class);
view2131361842 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.onClick(p0);
}
});
}
@Override
@CallSuper
public void unbind() {
ColourMixingActivity target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.imageButton = null;
target.textView = null;
target.seebar_temp = null;
target.color_view = null;
target.red_btn = null;
target.green_btn = null;
target.blue_btn = null;
target.white_btn = null;
target.grey_btn = null;
target.brown_btn = null;
view2131361957.setOnClickListener(null);
view2131361957 = null;
view2131362034.setOnClickListener(null);
view2131362034 = null;
view2131361942.setOnClickListener(null);
view2131361942 = null;
view2131361839.setOnClickListener(null);
view2131361839 = null;
view2131362195.setOnClickListener(null);
view2131362195 = null;
view2131361943.setOnClickListener(null);
view2131361943 = null;
view2131361842.setOnClickListener(null);
view2131361842 = null;
}
}
| true |
13d5b973159b5f45fcaa0a5aafdb2633e0d4c3d9 | Java | ntngocanh21/apidemo | /src/main/java/com/example/demo/service/UserServiceImpl.java | UTF-8 | 2,154 | 2.40625 | 2 | [] | no_license | package com.example.demo.service;
import com.example.demo.entity.UserEntity;
import com.example.demo.model.LoginResponse;
import com.example.demo.model.MessageResponse;
import com.example.demo.model.UserModel;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public LoginResponse checkLogin(UserModel userLoginModel) {
UserEntity userEntity = userRepository.findUserEntityByUsernameAndPassword(userLoginModel.getUsername(), userLoginModel.getPassword());
MessageResponse messageResponse = new MessageResponse();
if (userEntity == null) {
messageResponse.setCode(302);
messageResponse.setDescription("Failure");
LoginResponse loginResponse = new LoginResponse(messageResponse,null);
return loginResponse;
}
else{
messageResponse.setCode(0);
messageResponse.setDescription("Success");
LoginResponse loginResponse = new LoginResponse(messageResponse,null);
return loginResponse;
}
}
@Override
public MessageResponse register(UserModel userModel) {
UserEntity userEntity = userRepository.findUserEntityByUsername(userModel.getUsername());
MessageResponse messageResponse = new MessageResponse();
if (userEntity == null) {
UserEntity userRegister = new UserEntity();
userRegister.setName(userModel.getName());
userRegister.setUsername(userModel.getUsername());
userRegister.setPassword(userModel.getPassword());
userRepository.save(userRegister);
messageResponse.setCode(0);
messageResponse.setDescription("Success");
return messageResponse;
}
else{
messageResponse.setCode(302);
messageResponse.setDescription("Username existed!!");
return messageResponse;
}
}
} | true |
1952565c8394f79c36803ece901c65f9b2f916be | Java | anmingyu11/AlgorithmsUnion | /LeetCode/src/_java/_0067SqrtX.java | UTF-8 | 2,147 | 3.96875 | 4 | [] | no_license | package _java;
import base.Base;
/**
* Implement int sqrt(int x).
* <p>
* Compute and return the square root of x,
* where x is guaranteed to be a non-negative integer.
* <p>
* Since the return type is an integer,
* the decimal digits are truncated and only the integer part of the result is returned.
* <p>
* Example 1:
* Input: 4
* Output: 2
* <p>
* Example 2:
* Input: 8
* Output: 2
* Explanation: The square root of 8 is 2.82842..., and since
* the decimal part is truncated, 2 is returned.
*/
public class _0067SqrtX extends Base {
private abstract static class Solution {
public abstract int mySqrt(int x);
}
/**
* Runtime: 1 ms, faster than 100.00% of Java online submissions for Sqrt(x).
* Memory Usage: 33.6 MB, less than 5.00% of Java online submissions for Sqrt(x).
*/
private static class Solution1 extends Solution {
@Override
public int mySqrt(int x) {
if (x == 0) {
return 0;
}
int lo = 1, hi = x, ans = 0, mid = 0;
while (lo <= hi) {
mid = (lo + hi) / 2;
if (mid <= x / mid) {
lo = mid + 1;
ans = mid;
} else {
hi = mid - 1;
}
}
return ans;
}
}
/**
* 牛顿法
* Runtime: 1 ms, faster than 100.00% of Java online submissions for Sqrt(x).
* Memory Usage: 33.5 MB, less than 5.00% of Java online submissions for Sqrt(x).
*/
private static class Solution2 extends Solution {
@Override
public int mySqrt(int x) {
double ans = x;
double delta = 1.0E-4;
while (Math.abs((Math.pow(ans, 2) - x)) > delta) {
ans = (ans + x / ans) / 2f;
}
return (int) ans;
}
}
public static void main(String[] args) {
Solution s = new Solution2();
println(s.mySqrt(4));// 2
println(s.mySqrt(8));// 2
}
} | true |
9ad2626f5edcfb261c251a52915f303e4e63ec0b | Java | NishithaSalver/Component-based-model | /src/Nisha_JPA/SaveData.java | UTF-8 | 791 | 2.265625 | 2 | [] | no_license | //Renu Nishitha Salver G00941178
package Nisha_JPA;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
public class SaveData {
@PersistenceContext
public static final EntityManagerFactory emf=Persistence.createEntityManagerFactory("stud");
EntityManager em;
public static EntityManager getEntityManager()
{
EntityManager entityManager = emf.createEntityManager();
return entityManager;
}
public SaveData() {
super();
}
public static void studentsData(Student student) {
EntityManager etm = getEntityManager();
etm.getTransaction().begin();
etm.persist(student);
etm.getTransaction().commit();
etm.close();
}
}
| true |
c6b4e7db755e3f5e202815d7ff37cd5717dd1e59 | Java | eleangel1990/moteles | /app/src/main/java/ua/gov/dp/econtact/activity/BaseActivity.java | UTF-8 | 7,105 | 1.890625 | 2 | [] | no_license | package ua.gov.dp.econtact.activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import java.io.File;
import java.net.HttpURLConnection;
import butterknife.ButterKnife;
import ua.gov.dp.econtact.App;
import ua.gov.dp.econtact.Const;
import ua.gov.dp.econtact.R;
import ua.gov.dp.econtact.event.BaseEvent;
import ua.gov.dp.econtact.event.ErrorApiEvent;
import ua.gov.dp.econtact.interfaces.ChangeTitleListener;
import ua.gov.dp.econtact.util.BackgroundUtil;
import ua.gov.dp.econtact.util.BitmapFileUtil;
import ua.gov.dp.econtact.util.BlurImageUtil;
import ua.gov.dp.econtact.util.DisplayUtil;
import ua.gov.dp.econtact.util.VersionUtils;
/**
* Created by Yalantis
*/
public abstract class BaseActivity extends AppCompatActivity implements ChangeTitleListener {
protected Handler mHandler;
protected Toolbar mToolbar;
private MaterialDialog mMaterialDialog;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
}
@Override
public void setContentView(final int layoutId) {
super.setContentView(layoutId);
ButterKnife.bind(this);
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
// Activity may not have toolbar
if (mToolbar != null) {
setSupportActionBar(mToolbar);
if (VersionUtils.isAtLeastL()) {
mToolbar.setElevation(0.0f);
}
}
}
protected void setGradientLayout(final ViewGroup viewGroup) {
final float firstColorPosition = 0;
final float secondColorPosition = 0.50f;
final float thirdColorPosition = 0.70f;
final float fourthColorPosition = 1;
float[] positions = new float[]{firstColorPosition,
secondColorPosition, thirdColorPosition, fourthColorPosition};
int[] colors = getResources().getIntArray(R.array.gradient_colors);
BackgroundUtil.setLayoutGradient(viewGroup, colors, positions);
}
public void setBlurredLandscape(final ViewGroup viewGroup, @DrawableRes final int bitmapRes) {
if (VersionUtils.isAtJellyBeen()) {
final File file = new File(getCacheDir(), Const.BLURRED_BACKGROUND_FILE_NAME);
Bitmap result;
if (!file.exists()) {
Bitmap source = BitmapFactory.decodeResource(getResources(), bitmapRes);
Point size = DisplayUtil.getDisplaySize();
result = BlurImageUtil.blur(source, size.x, size.y);
final Bitmap finalBitmap = result;
new Thread(new Runnable() {
@Override
public void run() {
BitmapFileUtil.saveBitmapToFile(finalBitmap, file);
}
}).run();
} else {
result = BitmapFactory.decodeFile(file.getPath());
}
if (null != result) {
viewGroup.setBackground(new BitmapDrawable(getResources(), result));
} else {
setGradientLayout(viewGroup);
}
} else {
setGradientLayout(viewGroup);
}
}
@Override
protected void onStart() {
super.onStart();
App.eventBus.registerSticky(this);
}
public void showBackButton() {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow);
}
}
@Override
protected void onStop() {
super.onStop();
App.eventBus.unregister(this);
}
public void showProgress() {
showProgress(false);
}
protected void showProgress(final boolean cancellable) {
if (mMaterialDialog == null) {
mMaterialDialog = new MaterialDialog.Builder(this)
.customView(R.layout.dialog_progress, true)
.cancelable(cancellable).build();
TextView contentView = (TextView) mMaterialDialog.getCustomView().findViewById(R.id.content);
contentView.setText(R.string.loading_message);
}
mMaterialDialog.show();
}
protected boolean isLoading() {
return mMaterialDialog != null && mMaterialDialog.isShowing();
}
public void hideProgress() {
if (mMaterialDialog != null) {
mMaterialDialog.cancel();
}
}
public void removeStickyEvent(final Class<?> eventType) {
final int delayMillis = 100;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
App.eventBus.removeStickyEvent(eventType);
}
}, delayMillis);
}
protected <T extends BaseEvent> void removeStickyEvent(final T event) {
final int delayMillis = 100;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
App.eventBus.removeStickyEvent(event);
}
}, delayMillis);
}
protected void replaceFragment(final Fragment fragment, final boolean addToBackStack,
final int containerId) {
String backStateName = fragment.getClass().getName();
if (getSupportFragmentManager().getFragments() != null) {
Log.d("replaceFragment", getSupportFragmentManager().getFragments().size()
+ " to string: " + getSupportFragmentManager().getFragments().toString());
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(containerId, fragment, fragment.getClass().getSimpleName());
if (addToBackStack) {
transaction.addToBackStack(backStateName);
}
transaction.commit();
invalidateOptionsMenu();
}
public void onEvent(final ErrorApiEvent event) {
removeStickyEvent(event);
if (event != null && event.getErrorResponse() != null && event.getErrorResponse().getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
showProgress();
App.clearSession();
} else {
hideProgress();
}
}
@Override
public void changeTitle(final String title) {
if (!TextUtils.isEmpty(title) && getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
}
}
| true |
bffddd7e4a811a7afa44b6ce42c2ae71677541be | Java | NayLin-H99/ip | /src/main/java/duke/Parser.java | UTF-8 | 9,784 | 3.171875 | 3 | [] | no_license | package duke;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import duke.command.AddCommand;
import duke.command.AddCommandType;
import duke.command.Command;
import duke.command.DeleteCommand;
import duke.command.DoneCommand;
import duke.command.ExitCommand;
import duke.command.FindCommand;
import duke.command.ListCommand;
import duke.command.RescheduleCommand;
import duke.command.UpdateCommand;
import duke.task.TaskList;
/**
* The type Parser that parses user input and returns the appropriate command.
*/
public class Parser {
/** User-inputted string. */
private final String userInput;
/** List of tasks to pass to the commands. */
private final TaskList tasks;
/**
* Instantiates a new Parser.
*
* @param userInput the user-inputted string.
* @param tasks list of tasks to pass to the commands generated.
*/
public Parser(String userInput, TaskList tasks) {
this.userInput = userInput.trim();
this.tasks = tasks;
}
/**
* Checks operation command to be executed.
*
* @return the command to be executed.
* @throws DukeException the duke exception for unrecognised commands.
*/
public final Command checkOperation() throws DukeException {
if (isBye()) {
return new ExitCommand();
} else if (isList()) {
return new ListCommand(tasks);
} else if (isDone()) {
return createDoneCommand();
} else if (isDelete()) {
return createDeleteCommand();
} else if (isFind()) {
return createFindCommand();
} else if (isTodo()) {
return createTodoCommand();
} else if (isEvent()) {
return createEventCommand();
} else if (isDeadline()) {
return createDeadlineCommand();
} else if (isReschedule()) {
return createRescheduleCommand();
} else if (isUpdate()) {
return createUpdateCommand();
} else {
throw new DukeException("☹ OOPS!!! I'm sorry, but I don't know what that means :-(");
}
}
/**
* Checks if the exit command is to be executed.
*
* @return boolean.
*/
private boolean isBye() {
return this.userInput.equals("bye");
}
/**
* Checks if the list command is to be executed.
*
* @return boolean.
*/
private boolean isList() {
return this.userInput.equals("list");
}
/**
* Checks if the done command is to be executed.
*
* @return boolean.
*/
private boolean isDone() {
Pattern donePattern = Pattern.compile("^done\\h\\d+$");
Matcher doneMatcher = donePattern.matcher(userInput);
return doneMatcher.find();
}
/**
* Creates and returns a new instance of DoneCommand to be executed.
*
* @return new instance of DoneCommand.
*/
private Command createDoneCommand() {
String[] inputs = userInput.split(" ");
int idx = Integer.parseInt(inputs[1]) - 1;
return new DoneCommand(idx, tasks);
}
/**
* Checks if the delete command is to be executed.
*
* @return boolean.
*/
private boolean isDelete() {
Pattern deletePattern = Pattern.compile("^delete\\h\\d+$");
Matcher deleteMatcher = deletePattern.matcher(userInput);
return deleteMatcher.find();
}
/**
* Creates and returns a new instance of DeleteCommand to be executed.
*
* @return new instance of DeleteCommand.
*/
private Command createDeleteCommand() {
String[] inputs = userInput.split(" ");
int idx = Integer.parseInt(inputs[1]) - 1;
return new DeleteCommand(idx, tasks);
}
/**
* Checks if the add command is to be executed for a Todo task.
*
* @return boolean.
*/
private boolean isTodo() {
Pattern todoPattern = Pattern.compile("^todo\\h\\w.*");
Matcher todoMatcher = todoPattern.matcher(userInput);
return todoMatcher.find();
}
/**
* Creates and returns a new instance of AddCommand to be executed, for AddCommandType.todo.
*
* @return new AddCommand for creating a Todo.
*/
private Command createTodoCommand() {
String[] inputs = userInput.split(" ", 2);
return new AddCommand(AddCommandType.todo, inputs[1], tasks);
}
/**
* Checks if the add command is to be executed for an Event task.
*
* @return boolean.
*/
private boolean isEvent() {
Pattern eventDateTimePattern =
Pattern.compile("^event\\h\\w.*/at\\h\\d{4}-\\d{2}-\\d{2}\\h\\d{2}:\\d{2}\\h*$");
Matcher eventDateTimeMatcher = eventDateTimePattern.matcher(userInput);
Pattern eventDatePattern =
Pattern.compile("^event\\h\\w.*/at\\h\\d{4}-\\d{2}-\\d{2}\\h*$");
Matcher eventDateMatcher = eventDatePattern.matcher(userInput);
return eventDateTimeMatcher.find() || eventDateMatcher.find();
}
/**
* Creates and returns a new instance of AddCommand to be executed, for AddCommandType.event.
*
* @return new AddCommand for creating an Event.
*/
private Command createEventCommand() {
String[] inputs = userInput.split(" ", 2);
String[] args = inputs[1].split(" /at ", 2);
String[] datetimeArgs = args[1].split(" ", 2);
if (datetimeArgs.length > 1) {
return new AddCommand(AddCommandType.event, args[0], tasks, datetimeArgs[0], datetimeArgs[1]);
}
return new AddCommand(AddCommandType.event, args[0], tasks, datetimeArgs[0]);
}
/**
* Checks if the add command is to be executed for a Deadline task.
*
* @return boolean.
*/
private boolean isDeadline() {
Pattern deadlineDateTimePattern =
Pattern.compile("^deadline\\h\\w.*/by\\h\\d{4}-\\d{2}-\\d{2}\\h\\d{2}:\\d{2}\\h*$");
Matcher deadlineDateTimeMatcher = deadlineDateTimePattern.matcher(userInput);
Pattern deadlineDatePattern =
Pattern.compile("^deadline\\h\\w.*/by\\h\\d{4}-\\d{2}-\\d{2}\\h*$");
Matcher deadlineDateMatcher = deadlineDatePattern.matcher(userInput);
return deadlineDateTimeMatcher.find() || deadlineDateMatcher.find();
}
/**
* Creates and returns a new instance of AddCommand to be executed, for AddCommandType.deadline.
*
* @return new AddCommand for creating a Deadline.
*/
private Command createDeadlineCommand() {
String[] inputs = userInput.split(" ", 2);
String[] args = inputs[1].split(" /by ", 2);
String[] datetimeArgs = args[1].split(" ", 2);
if (datetimeArgs.length > 1) {
return new AddCommand(AddCommandType.deadline, args[0], tasks, datetimeArgs[0], datetimeArgs[1]);
}
return new AddCommand(AddCommandType.deadline, args[0], tasks, datetimeArgs[0]);
}
/**
* Checks if the find command is to be executed for finding tasks with matching substrings.
*
* @return boolean.
*/
private boolean isFind() {
Pattern findPattern = Pattern.compile("^find\\h\\w.*");
Matcher findMatcher = findPattern.matcher(userInput);
return findMatcher.find();
}
/**
* Creates and returns a new instance of FindCommand to be executed.
*
* @return new instance of FindCommand.
*/
private Command createFindCommand() {
String substring = userInput.split(" ", 2)[1];
return new FindCommand(substring, tasks);
}
/**
* Checks if the rescheduling command is to be executed for rescheduling tasks with date and/or time constraints.
*
* @return boolean.
*/
private boolean isReschedule() {
Pattern rescheduleDateTimePattern =
Pattern.compile("^reschedule\\h\\d+\\h/to\\h\\d{4}-\\d{2}-\\d{2}\\h\\d{2}:\\d{2}\\h*$");
Matcher rescheduleDateTimeMatcher = rescheduleDateTimePattern.matcher(userInput);
Pattern rescheduleDatePattern =
Pattern.compile("^reschedule\\h\\d+\\h/to\\h\\d{4}-\\d{2}-\\d{2}\\h*$");
Matcher rescheduleDateMatcher = rescheduleDatePattern.matcher(userInput);
return rescheduleDateTimeMatcher.find() || rescheduleDateMatcher.find();
}
/**
* Creates and returns a new instance of RescheduleCommand to be executed.
*
* @return new instance of RescheduleCommand.
*/
private Command createRescheduleCommand() {
String[] inputs = userInput.split(" ");
int idx = Integer.parseInt(inputs[1]) - 1;
String dateString = inputs[3];
if (inputs.length > 4) {
String timeString = inputs[4];
return new RescheduleCommand(idx, tasks, dateString, timeString);
}
return new RescheduleCommand(idx, tasks, dateString);
}
/**
* Checks if the update command is to be executed to update the description of the task.
*
* @return boolean.
*/
private boolean isUpdate() {
Pattern updatePattern = Pattern.compile("^update\\h\\d+\\h/to\\h.*");
Matcher updateMatcher = updatePattern.matcher(userInput);
return updateMatcher.find();
}
/**
* Creates and returns a new instance of UpdateCommand to be executed.
*
* @return new instance of UpdateCommand.
*/
private Command createUpdateCommand() {
String[] inputs = userInput.split(" ", 2);
String[] args = inputs[1].split(" /to ", 2);
int idx = Integer.parseInt(args[0]) - 1;
String newDescription = args[1];
return new UpdateCommand(idx, tasks, newDescription);
}
}
| true |
b5299d47a97487b62aecd260addfff1739425cfa | Java | linbren/lyt_ssm | /src/main/java/net/test/tools/SQLServerBackup.java | UTF-8 | 3,441 | 2.71875 | 3 | [] | no_license | package net.test.tools;
import java.io.File;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SQLServerBackup {
/**
* 获取数据库连接
*
* @return Connection 对象
*/
public static void main(String argc[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
backup("D:\\work\\db","frm"+sdf.format(new Date()),"frm");
}
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = "jdbc:jtds:sqlserver://192.168.16.14:1433;databaseName=master";
String username = "sa";
String password = "admin";
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 备份数据库
*
* @return backup
* @throws Exception
*/
public static String backup(String toPath, String filename,String dbname) {
System.out.println("backup begin....."+(new Date()).toString());
try {
File file = new File(toPath);
String path = file.getPath() + "\\" + filename + ".bak";
String bakSQL = "backup database " + dbname
+ " to disk=? with init";// SQL语句
PreparedStatement bak = getConnection().prepareStatement(bakSQL);
bak.setString(1, path);// path必须是绝对路径
bak.execute(); // 备份数据库
bak.close();
System.out.println("backup end....."+(new Date()).toString());
} catch (Exception e) {
System.out.println("backup failed....."+(new Date()).toString());
e.printStackTrace();
}
return "backup";
}
/**
* 数据库还原
*
* @return recovery
*/
public static String recovery(String fromPath, String filename, String dbname) {
try {
File file = new File(fromPath);
String path = file.getPath() + "\\" + filename + ".bak";// name文件名
String recoverySql = "ALTER DATABASE " + dbname
+ " SET ONLINE WITH ROLLBACK IMMEDIATE";
PreparedStatement ps = getConnection()
.prepareStatement(recoverySql);
CallableStatement cs = getConnection().prepareCall(
"{call killrestore(?,?)}");
cs.setString(1, dbname); // 数据库名
cs.setString(2, path); // 已备份数据库所在路径
cs.execute(); // 还原数据库
ps.execute(); // 恢复数据库连接
} catch (Exception e) {
e.printStackTrace();
}
return "recovery";
}
/* create proc killrestore (@dbname varchar(20),@dbpath varchar(40))
as
begin
declare @sql nvarchar(500)
declare @spid int
set @sql='declare getspid cursor for select spid from sysprocesses where dbid=db_id('''+@dbname+''')'
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status <> -1
begin
exec('kill '+@spid)
fetch next from getspid into @spid
end
close getspid
deallocate getspid
restore database @dbname from disk= @dbpath with replace
end */
}
| true |
70eda1cac1fd1d345ed2dee66633cd97d2842431 | Java | cckmit/ontap | /app/src/main/java/com/salesforce/dsa/app/ui/dialogs/DownDialog.java | UTF-8 | 13,879 | 2.109375 | 2 | [] | no_license | package com.salesforce.dsa.app.ui.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.abinbev.dsa.R;
import java.lang.reflect.Method;
import butterknife.Bind;
import butterknife.ButterKnife;
public class DownDialog {
@Bind(R.id.alert_title)
TextView alertTitle;
@Bind(R.id.alert_msg)
TextView alertMsg;
@Bind(R.id.precent)
TextView precent;
@Bind(R.id.progress_bar)
ProgressBar progressBar;
@Bind(R.id.progress_layout)
RelativeLayout progressLayout;
@Bind(R.id.alert_left_btn)
Button alertLeftBtn;
@Bind(R.id.btn_line)
View btnLine;
@Bind(R.id.alert_right_btn)
Button alertRightBtn;
@Bind(R.id.btn_layout)
LinearLayout btnLayout;
@Bind(R.id.dialog_alert_layout)
LinearLayout dialogAlertLayout;
private Context context;
private Display display;
private int screenWidth = 0;
private boolean showTitle;
private boolean showMsg;
private boolean showNeBtn;
private boolean showPoBtn;
private Dialog dialog;
public Dialog getDialog() {
return dialog;
}
public DownDialog(Context context) {
this.context = context;
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
this.display = windowManager.getDefaultDisplay();
this.screenWidth = (int) (getScreenRealWidth((Activity) context) / 3 * 2);
}
public LinearLayout getBtnLayout() {
return btnLayout;
}
public RelativeLayout getProgressLayout() {
return progressLayout;
}
public DownDialog builder() {
View view = LayoutInflater.from(context).inflate(R.layout.view_alert_ios_dialog, null);
ButterKnife.bind(this, view);
alertTitle.setVisibility(View.GONE);
alertMsg.setVisibility(View.GONE);
alertRightBtn.setVisibility(View.GONE);
alertLeftBtn.setVisibility(View.GONE);
btnLine.setVisibility(View.GONE);
dialog = new Dialog(context, R.style.AlertDialogStyle);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
if (listener != null) {
listener.onDismiss(dialogInterface);
}
}
});
dialog.setContentView(view);
dialogAlertLayout.setLayoutParams(new FrameLayout.LayoutParams(screenWidth, FrameLayout.LayoutParams.WRAP_CONTENT));
return this;
}
/**
* Set the title
*If the value is null the default setting is null
* @return
*/
public DownDialog setTitle(String title) {
showTitle = true;
alertTitle.setText(TextUtils.isEmpty(title) ? "":title);
return this;
}
/**
* Set message body
*If the value is null the default setting is null
* @return
*/
public DownDialog setMessage(String msg) {
showMsg = true;
alertMsg.setText(TextUtils.isEmpty(msg) ? "":msg);
return this;
}
/**
* The set up button
*If the value is null the default setting is null
* @param poBtnName
* @return
*/
public DownDialog setPoBtn(String poBtnName, final View.OnClickListener listener) {
showPoBtn = true;
if (poBtnName == null) {
//If the button title is empty, it is hidden
alertRightBtn.setVisibility(View.INVISIBLE);
} else {
// set positive Button title
alertRightBtn.setText(poBtnName);
}
if (listener != null) {
alertRightBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onClick(v);
}
});
}
return this;
}
/**
* The set up button
*If the value is null the default setting is null
* @param poBtnName
* @return
*/
public DownDialog setPoBtn(String poBtnName) {
showPoBtn = true;
alertRightBtn.setText(TextUtils.isEmpty(poBtnName) ? "":poBtnName);
return this;
}
/**
* Set the button to listen for events
* @param poBtnName
* @return
*/
public DownDialog setPoBtn(String poBtnName, final View.OnClickListener listener, final boolean noDismiss) {
showPoBtn = true;
if (poBtnName == null) {
//If the button title is empty, it is hidden
alertRightBtn.setVisibility(View.INVISIBLE);
} else {
//set positive Button title
alertRightBtn.setText(poBtnName);
}
if (listener != null) {
alertRightBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onClick(v);
if (noDismiss) {
dialog.dismiss();
}
}
});
}
return this;
}
/**
*Set button color
* @param color
* @return
*/
public DownDialog setPosBtnColor(String color) {
showPoBtn = true;
if (alertRightBtn != null) {
alertRightBtn.setTextColor(Color.parseColor(color));
}
return this;
}
/**Set postive button BackGroundColor
* @param color
* @return
*/
public DownDialog setPosBtnBackGroundColor(String color) {
showPoBtn = true;
if (alertRightBtn != null) {
alertRightBtn.setBackgroundColor(Color.parseColor(color));
}
return this;
}
/**
* set negative button titile
* @param neBtnName
* @return
*/
public DownDialog setNeBtn(String neBtnName, final View.OnClickListener listener) {
showNeBtn = true;
if (neBtnName == null) {
//If the button title is empty, it is hidden
alertLeftBtn.setVisibility(View.INVISIBLE);
} else {
//set negative button titile
alertLeftBtn.setText(neBtnName);
}
//Set listening events
if (listener != null) {
alertLeftBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onClick(v);
dialog.dismiss();
}
});
}
return this;
}
/**
* Set negative the background color of the button
* @param color
* @return
*/
public DownDialog setNeBtnColor(String color) {
showNeBtn = true;
if (alertLeftBtn != null) {
alertLeftBtn.setTextColor(Color.parseColor(color));
}
return this;
}
/**
* Set negative the background color of the button
* @param color
* @return
*/
public DownDialog setNeBtnBackGroundColor(String color) {
showNeBtn = true;
if (alertLeftBtn != null) {
alertLeftBtn.setBackgroundColor(Color.parseColor(color));
}
return this;
}
/**
* Set whether to cancel the dialog box by clicking outside the screen
* @param cancel
* @return
*/
public DownDialog setCancelable(boolean cancel) {
dialog.setCancelable(cancel);
return this;
}
/**
* Set whether to cancel the dialog box by clicking outside the screen
* @return
*/
public DownDialog setCancleAble(boolean cancel) {
dialog.setCancelable(cancel);
return this;
}
/**
* set show Layout
*/
public void setLayout() {
if (!showTitle && !showMsg) {
alertTitle.setVisibility(View.VISIBLE);
alertTitle.setText("");
}
if (showTitle) {
alertTitle.setVisibility(View.VISIBLE);
}
if (showMsg) {
alertMsg.setVisibility(View.VISIBLE);
}
if (!showPoBtn && !showNeBtn) {
alertRightBtn.setText(context.getResources().getString(R.string.yes));
alertRightBtn.setVisibility(View.VISIBLE);
alertRightBtn.setBackgroundResource(R.drawable.alertdialog_single_selector);
alertRightBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (dialog != null) {
dialog.dismiss();
}
}
});
}
if (showPoBtn && !showNeBtn) {
alertRightBtn.setVisibility(View.VISIBLE);
alertRightBtn.setBackgroundResource(R.drawable.alertdialog_single_selector);
}
if (!showPoBtn && showNeBtn) {
alertLeftBtn.setVisibility(View.VISIBLE);
alertLeftBtn.setBackgroundResource(R.drawable.alertdialog_single_selector);
}
if (showNeBtn && showPoBtn) {
alertRightBtn.setVisibility(View.VISIBLE);
alertRightBtn.setBackgroundResource(R.drawable.alertdialog_right_selector);
btnLine.setVisibility(View.VISIBLE);
alertLeftBtn.setVisibility(View.VISIBLE);
alertLeftBtn.setBackgroundResource(R.drawable.alertdialog_right_selector);
}
}
/**
* show Dialog
*/
public void show() {
setLayout();
if (dialog != null) {
dialog.show();
}
}
/**
* Destroy dialog box
*/
public void dismiss() {
if (dialog != null && dialog.isShowing())
dialog.cancel();
dialog = null;
}
/**
* According to the button
* @return
*/
public boolean isShow() {
return (dialog != null && dialog.isShowing());
}
private IOSDismissListener listener;
/**
* Set button Postive visibility
* @param isClick
*/
public void setPoBtnClick(boolean isClick) {
if (alertRightBtn != null) {
alertRightBtn.setClickable(isClick);
}
}
/**
* Dialog box type
*/
public void setType() {
if (dialog != null) {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
}
/**
* Set progress visibility
* @param visibilityProgressBar
*/
public void setVisibilityProgressBar(boolean visibilityProgressBar) {
if (visibilityProgressBar) {
progressLayout.setVisibility(View.VISIBLE);
} else {
progressLayout.setVisibility(View.GONE);
}
}
/**
* Monitor button
* @param activity
*/
public void setOnKeyListener(Activity activity) {
if (dialog != null) {
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (dialog != null)
dialog.dismiss();
if (activity != null)
activity.finish();
}
return false;
}
});
}
}
/**
* Set button and download layout visibility
* true VISIBLE
* false GONE
* @param visibilityBtn
*/
public void setVisibilityBtn(boolean visibilityBtn) {
if (visibilityBtn) {
btnLayout.setVisibility(View.VISIBLE);
} else {
btnLayout.setVisibility(View.GONE);
}
}
/**
* According to progress
* @param total
* @param progress
* @param percent
*/
public void setProgress(float total, float progress, float percent) {
if (progressBar != null) {
progressBar.setProgress((int) percent);
}
if (precent != null) {
int pro = (int) percent;
precent.setText(pro + "%");
}
}
/**
*Button event callback
*/
public interface IOSDismissListener {
public void onDismiss(DialogInterface listener);
}
/**
* Set callback class
* @param listener
*/
public void setOnDismissListener(IOSDismissListener listener) {
this.listener = listener;
}
/**
* Get screen width
* @param activity
* @return
*/
public float getScreenRealWidth(Activity activity) {
float dpi = -1f;
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
dpi = dm.widthPixels;
// dpi = dm.widthPixels + "*" + dm.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return dpi;
}
}
| true |
f6d1a4b5d6e8c92516615e7572b2b2a0303fecdc | Java | rykann/android-twitter-client | /app/src/main/java/org/kannegiesser/twitterclient/clients/TwitterApi.java | UTF-8 | 2,932 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | package org.kannegiesser.twitterclient.clients;
import android.content.Context;
import com.codepath.oauth.OAuthBaseClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.scribe.builder.api.Api;
public class TwitterApi extends OAuthBaseClient {
private static final String TAG = TwitterApi.class.getName();
public static final Class<? extends Api> REST_API_CLASS = org.scribe.builder.api.TwitterApi.class;
public TwitterApi(Context context) {
super(context,
REST_API_CLASS,
TwitterApiConfig.getBaseUrl(),
TwitterApiConfig.getConsumerKey(),
TwitterApiConfig.getConsumerSecret(),
TwitterApiConfig.getCallbackUrl());
}
public void getHomeTimeline(String maxId, AsyncHttpResponseHandler handler) {
String url = getApiUrl("statuses/home_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 25);
if (maxId != null) {
params.put("max_id", maxId);
}
client.get(url, params, handler);
}
public void getMentionsTimeline(String maxId, AsyncHttpResponseHandler handler) {
String url = getApiUrl("statuses/mentions_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 25);
if (maxId != null) {
params.put("max_id", maxId);
}
client.get(url, params, handler);
}
public void getUserTimeline(String maxId, String screenName, AsyncHttpResponseHandler handler) {
String url = getApiUrl("statuses/user_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 25);
params.put("screen_name", screenName);
if (maxId != null) {
params.put("max_id", maxId);
}
client.get(url, params, handler);
}
public void getUserInfo(AsyncHttpResponseHandler handler) {
String url = getApiUrl("account/verify_credentials.json");
RequestParams params = new RequestParams();
params.put("skip_status", "true");
client.get(url, params, handler);
}
public void getUserInfo(String screenName, AsyncHttpResponseHandler handler) {
// if no screen name given, fetch current user's profile
if (screenName == null) {
getUserInfo(handler);
return;
}
String url = getApiUrl("users/show.json");
RequestParams params = new RequestParams();
params.put("screen_name", screenName);
client.get(url, params, handler);
}
public void postTweet(String text, AsyncHttpResponseHandler handler) {
String url = getApiUrl("statuses/update.json");
RequestParams params = new RequestParams();
params.put("status", text);
client.post(url, params, handler);
}
} | true |
fc05cbabbf9bb5bee1b8a3d896069579fa8909cb | Java | yarokhovich/exam | /src/ru/urllink/jjd/exam4/Application.java | UTF-8 | 3,054 | 3.015625 | 3 | [] | no_license | package ru.urllink.jjd.exam4;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.time.LocalDateTime;
import java.util.List;
public class Application {
public static void main(String[] args) {
Climber climber1 = new Climber();
String name = "Иван Григорьев";
int age = 34;
climber1.setFullName(name);
climber1.setAge(age);
climber1.setEmail("ivan@mail.com");
climber1.setUuid();
Climber climber2 = new Climber();
climber2.setAge(19);
climber2.setFullName("Елена Михайлова");
climber2.setEmail("helena@mail.com");
climber2.setUuid();
Mountain everest = new Mountain("Эверест", 8000);
Mountain elbrus = new Mountain("Эльбрус", 6000);
Mountain defaultMountain = new Mountain();
ClimbingGroup climbingGroup = new ClimbingGroup(elbrus, 5);
climbingGroup.addClimber(climber1);
climbingGroup.start();
///////////////////////////////////////////exam4////////////////////////////////
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("exam4");
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
manager.persist(elbrus);
manager.persist(everest);
manager.persist(defaultMountain);
manager.persist(climbingGroup);
manager.persist(climber1);
manager.persist(climber2);
manager.getTransaction().commit();
//2.1 всех гор
manager=factory.createEntityManager();
List list=manager.createQuery("FROM Mountain").getResultList();
list.forEach(o -> System.out.println(o));
//2.2 гор с высотой от min до max/////////////////////////////////
list=manager.createQuery("SELECT m FROM Mountain m ORDER BY m.height").getResultList();
list.forEach(o -> System.out.println(o));
//2.3 групп, которые еще не начали восхождения но горы/////////////////////////////
manager=factory.createEntityManager();
list=manager.createQuery("SELECT cg FROM ClimbingGroup cg WHERE cg.start > :pDate")
.setParameter("pDate", LocalDateTime.now()).getResultList();
list.forEach(o -> System.out.println(o.toString()));
//2.4 альпиниста по имени и email/////////////////////////////////////
Climber findClimber=
(Climber) manager.createQuery("SELECT c FROM Climber c WHERE c.fullName='Елена Михайлова' " +
"OR c.email='helena@mail.com'").getSingleResult();
System.out.println(findClimber.toString());
// 2.5 гору по названию//////////////////////////////////////////////
Mountain findMountain=
(Mountain) manager.createQuery("SELECT m FROM Mountain m WHERE m.name=:mName")
.setParameter("mName","Эльбрус").getSingleResult();
System.out.println(findMountain.toString());
}
}
| true |
6c70fdc7b51fc8561eb795beca6c61cc7c51d284 | Java | pmd/pmd | /pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AccessNode.java | UTF-8 | 8,233 | 2.578125 | 3 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static net.sourceforge.pmd.lang.java.ast.JModifier.STRICTFP;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.NodeStream;
/**
* A node that owns a {@linkplain ASTModifierList modifier list}.
*
* <p>{@link AccessNode} methods take into account the syntactic context of the
* declaration, e.g. {@link #isPublic()} will always return true for a field
* declared inside an interface, regardless of whether the {@code public}
* modifier was specified explicitly or not. If you want to know whether
* the modifier was explicitly stated, use {@link #hasExplicitModifiers(JModifier, JModifier...)}.
*
* TODO make modifiers accessible from XPath
* * Ideally we'd have two attributes, eg @EffectiveModifiers and @ExplicitModifiers,
* which would each return a sequence, eg ("public", "static", "final")
* * Ideally we'd have a way to add attributes that are not necessarily
* getters on the node. It makes no sense in the Java API to expose
* those getters on the node, it's more orthogonal to query getModifiers() directly.
*
* TODO rename to ModifierOwner, kept out from PR to reduce diff
*/
public interface AccessNode extends Annotatable {
@Override
default NodeStream<ASTAnnotation> getDeclaredAnnotations() {
return getModifiers().children(ASTAnnotation.class);
}
/**
* Returns the node representing the modifier list of this node.
*/
default @NonNull ASTModifierList getModifiers() {
return firstChild(ASTModifierList.class);
}
/**
* Returns the visibility corresponding to the {@link ASTModifierList#getEffectiveModifiers() effective modifiers}.
* Eg a public method will have visibility {@link Visibility#V_PUBLIC public},
* a local class will have visibility {@link Visibility#V_LOCAL local}.
* There cannot be any conflict with {@link #hasModifiers(JModifier, JModifier...)}} on
* well-formed code (e.g. for any {@code n}, {@code (n.getVisibility() == V_PROTECTED) ==
* n.hasModifiers(PROTECTED)})
*
* <p>TODO a public method of a private class can be considered to be private
* we could probably add another method later on that takes this into account
*/
default Visibility getVisibility() {
Set<JModifier> effective = getModifiers().getEffectiveModifiers();
if (effective.contains(JModifier.PUBLIC)) {
return Visibility.V_PUBLIC;
} else if (effective.contains(JModifier.PROTECTED)) {
return Visibility.V_PROTECTED;
} else if (effective.contains(JModifier.PRIVATE)) {
return Visibility.V_PRIVATE;
} else {
return Visibility.V_PACKAGE;
}
}
/**
* Returns the "effective" visibility of a member. This is the minimum
* visibility of its enclosing type declarations. For example, a public
* method of a private class is "effectively private".
*
* <p>Local declarations keep local visibility, eg a local variable
* somewhere in an anonymous class doesn't get anonymous visibility.
*/
default Visibility getEffectiveVisibility() {
Visibility minv = getVisibility();
if (minv == Visibility.V_LOCAL) {
return minv;
}
for (ASTAnyTypeDeclaration enclosing : ancestors(ASTAnyTypeDeclaration.class)) {
minv = Visibility.min(minv, enclosing.getVisibility());
if (minv == Visibility.V_LOCAL) {
return minv;
}
}
return minv;
}
/**
* Returns true if this node has <i>all</i> the given modifiers
* either explicitly written or inferred through context.
*/
default boolean hasModifiers(JModifier mod1, JModifier... mod) {
return getModifiers().hasAll(mod1, mod);
}
/**
* Returns true if this node has <i>all</i> the given modifiers
* explicitly written in the source.
*/
default boolean hasExplicitModifiers(JModifier mod1, JModifier... mod) {
return getModifiers().hasAllExplicitly(mod1, mod);
}
// TODO remove all those, kept only for compatibility with rules
// these are about effective modifiers
@Deprecated
default boolean isFinal() {
return hasModifiers(JModifier.FINAL);
}
@Deprecated
default boolean isAbstract() {
return hasModifiers(JModifier.ABSTRACT);
}
@Deprecated
default boolean isStrictfp() {
return hasModifiers(STRICTFP);
}
@Deprecated
default boolean isSynchronized() {
return hasModifiers(JModifier.SYNCHRONIZED);
}
@Deprecated
default boolean isNative() {
return hasModifiers(JModifier.NATIVE);
}
@Deprecated
default boolean isStatic() {
return hasModifiers(JModifier.STATIC);
}
@Deprecated
default boolean isVolatile() {
return hasModifiers(JModifier.VOLATILE);
}
@Deprecated
default boolean isTransient() {
return hasModifiers(JModifier.TRANSIENT);
}
// these are about visibility
@Deprecated
default boolean isPrivate() {
return getVisibility() == Visibility.V_PRIVATE;
}
@Deprecated
default boolean isPublic() {
return getVisibility() == Visibility.V_PUBLIC;
}
@Deprecated
default boolean isProtected() {
return getVisibility() == Visibility.V_PROTECTED;
}
@Deprecated
default boolean isPackagePrivate() {
return getVisibility() == Visibility.V_PACKAGE;
}
// these are about explicit modifiers
@Deprecated
default boolean isSyntacticallyAbstract() {
return hasExplicitModifiers(JModifier.ABSTRACT);
}
@Deprecated
default boolean isSyntacticallyPublic() {
return hasExplicitModifiers(JModifier.PUBLIC);
}
@Deprecated
default boolean isSyntacticallyStatic() {
return hasExplicitModifiers(JModifier.STATIC);
}
@Deprecated
default boolean isSyntacticallyFinal() {
return hasExplicitModifiers(JModifier.FINAL);
}
/**
* Represents the visibility of a declaration.
*
* <p>The ordering of the constants encodes a "contains" relationship,
* ie, given two visibilities {@code v1} and {@code v2}, {@code v1 < v2}
* means that {@code v2} is strictly more permissive than {@code v1}.
*/
enum Visibility {
// Note: constants are prefixed with "V_" to avoid conflicts with JModifier
/** Special visibility of anonymous classes, even more restricted than local. */
V_ANONYMOUS("anonymous"),
/** Confined to a local scope, eg method parameters, local variables, local classes. */
V_LOCAL("local"),
/** File-private. Corresponds to modifier {@link JModifier#PRIVATE}. */
V_PRIVATE("private"),
/** Package-private. */
V_PACKAGE("package"),
/** Package-private + visible to subclasses. Corresponds to modifier {@link JModifier#PROTECTED}. */
V_PROTECTED("protected"),
/** Visible everywhere. Corresponds to modifier {@link JModifier#PUBLIC}. */
V_PUBLIC("public");
private final String myName;
Visibility(String name) {
this.myName = name;
}
@Override
public String toString() {
return myName;
}
/**
* Returns true if this visibility is greater than or equal to
* the parameter.
*/
public boolean isAtLeast(Visibility other) {
return this.compareTo(other) >= 0;
}
/**
* Returns true if this visibility is lower than or equal to the
* parameter.
*/
public boolean isAtMost(Visibility other) {
return this.compareTo(other) <= 0;
}
/**
* The minimum of both visibilities.
*/
static Visibility min(Visibility v1, Visibility v2) {
return v1.compareTo(v2) <= 0 ? v1 : v2;
}
}
}
| true |
b7334d472f59992337b3ab39ced9c2f3e579ad76 | Java | skbadhe/CodeAssignmentPyramed | /src/main/java/com/shubhambadhe/CodeAssignmentPyramed/Repository/ChitRepository.java | UTF-8 | 294 | 1.539063 | 2 | [] | no_license | /**
*
*/
package com.shubhambadhe.CodeAssignmentPyramed.Repository;
import org.springframework.data.repository.CrudRepository;
import com.shubhambadhe.CodeAssignmentPyramed.Chit.Chit;
/**
* @author Shubham
*
*/
public interface ChitRepository extends CrudRepository<Chit, Integer>{
}
| true |
6ccc952da5ad45d18500ec3e8908a967679a8874 | Java | Kevinyulianto0307/ProjectHBC | /org.toba.habco/src/org/toba/habco/callout/HBC_CalloutDemurrage.java | UTF-8 | 1,079 | 1.929688 | 2 | [
"MIT"
] | permissive | package org.toba.habco.callout;
import java.util.Properties;
import org.adempiere.base.IColumnCallout;
import org.compiere.model.CalloutEngine;
import org.compiere.model.GridField;
import org.compiere.model.GridTab;
import org.toba.habco.model.MContract;
import org.toba.habco.model.MDemurrage;
/*
* @author yonk
*/
public class HBC_CalloutDemurrage extends CalloutEngine implements IColumnCallout {
@Override
public String start(Properties ctx, int WindowNo, GridTab mTab,
GridField mField, Object value, Object oldValue) {
if(mField.getColumnName().equals(MDemurrage.COLUMNNAME_IsDefault)){
return Default(ctx, WindowNo, mTab, mField, value);
}
return "";
}
private String Default(Properties ctx, int windowNo, GridTab mTab,
GridField mField, Object value) {
String msg="";
if (value=="N"){
int contractid=(Integer)mTab.getValue("HBC_Contract_ID");
MContract contract = new MContract(ctx,contractid,null);
if(contract.getDemurrages().length<=0){
mTab.setValue("IsDefault", true);
}
}
return msg;
}
}
| true |
69b48c20be86ac1cb61d5ea677f406224755dab0 | Java | oozguc/Bubbleator | /src/main/java/pluginTools/ComputeCurvatureCurrent.java | UTF-8 | 3,183 | 1.882813 | 2 | [] | no_license | package pluginTools;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import costMatrix.PixelratiowDistCostFunction;
import curvatureUtils.DisplaySelected;
import ellipsoidDetector.Intersectionobject;
import ij.ImageStack;
import ij.gui.Line;
import kalmanTracker.ETrackCostFunction;
import kalmanTracker.IntersectionobjectCollection;
import kalmanTracker.KFsearch;
import kalmanTracker.NearestNeighbourSearch;
import kalmanTracker.NearestNeighbourSearch2D;
import kalmanTracker.TrackModel;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.util.Pair;
import net.imglib2.util.ValuePair;
import pluginTools.InteractiveSimpleEllipseFit.ValueChange;
import track.TrackingFunctions;
import utility.CreateTable;
import utility.Curvatureobject;
import utility.Roiobject;
import utility.ThreeDRoiobject;
public class ComputeCurvatureCurrent extends SwingWorker<Void, Void> {
final InteractiveSimpleEllipseFit parent;
final JProgressBar jpb;
public ComputeCurvatureCurrent(final InteractiveSimpleEllipseFit parent, final JProgressBar jpb) {
this.parent = parent;
this.jpb = jpb;
}
@Override
protected Void doInBackground() throws Exception {
EllipseTrack newtrack = new EllipseTrack(parent, jpb);
newtrack.ComputeCurvatureCurrent();
return null;
}
private static HashMap<String, Integer> sortByValues(HashMap<String, Integer> map) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
// Here I am copying the sorted list in HashMap
// using LinkedHashMap to preserve the insertion order
HashMap<String, Integer> sortedHashMap = new LinkedHashMap<String, Integer>();
for (Iterator<Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
@Override
protected void done() {
parent.jpb.setIndeterminate(false);
parent.Cardframe.validate();
try {
get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
} | true |
d5be1984d7e3d50450e4076f3f6bdd3ca7e142aa | Java | alexthaler/OpenSesameDroid | /src/main/java/com/fortysevensixteen/opensesame/activity/SettingsActivity.java | UTF-8 | 997 | 2.34375 | 2 | [] | no_license | package com.fortysevensixteen.opensesame.activity;
import android.app.ActionBar;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
import com.fortysevensixteen.opensesame.fragment.SettingsFragment;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return true;
}
}
}
| true |
2fd03d7282b7164a4bc37891420efc9741443f20 | Java | gregemel/zipinfo | /src/test/java/com/emelgreg/zipinfo/controllers/ZipHttpControllerSpec.java | UTF-8 | 2,823 | 2.28125 | 2 | [] | no_license | package com.emelgreg.zipinfo.controllers;
import com.emelgreg.zipinfo.models.ZipWeather;
import com.emelgreg.zipinfo.ports.ZipWeatherPort;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(ZipWeatherHttpController.class)
public class ZipHttpControllerSpec {
private String zipCode = "98765";
@Autowired
private MockMvc mockMvc;
@MockBean
private ZipWeatherPort zipWeatherPortServiceMock;
@Test
public void shouldGetZipInformationFromLocationService() throws Exception {
when(zipWeatherPortServiceMock.getWeatherByZip(zipCode)).thenReturn(
new ZipWeather("city", "temp", "timezone", "elevation"));
this.mockMvc.perform(get("/api/v1/zipinfo/" + zipCode)).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString(
"At the location city, the temperature is temp, the timezone is timezone, and the elevation is elevation.")));
verify(zipWeatherPortServiceMock, times(1)).getWeatherByZip(anyString());
}
@Test
public void shouldReturnErrorMessageWhenZipCodeIsLessThan5Digits() throws Exception {
when(zipWeatherPortServiceMock.getWeatherByZip(zipCode)).thenReturn(
new ZipWeather("city", "temp", "timezone", "elevation"));
this.mockMvc.perform(get("/api/v1/zipinfo/1234")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString(
"This service requires a valid zip code.")));
verify(zipWeatherPortServiceMock, times(0)).getWeatherByZip(anyString());
}
@Test
public void shouldReturn404WhenZipCodeIsNotProvided() throws Exception {
when(zipWeatherPortServiceMock.getWeatherByZip(zipCode)).thenReturn(
new ZipWeather("city", "temp", "timezone", "elevation"));
this.mockMvc.perform(get("/api/v1/zipinfo/")).andDo(print()).andExpect(status().isNotFound());
}
} | true |
8a3dd6091339876a424f90368030868a4c45acf1 | Java | prag111/Testproject | /February/src/com/pragati/KeyboardUtil.java | UTF-8 | 955 | 2.875 | 3 | [] | no_license | package com.pragati;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class KeyboardUtil {
private KeyboardUtil()
{
}
public static int getInt(String message)
{
System.out.println(message);
Scanner sc=new Scanner(System.in);
return sc.nextInt();
}
public static double getDouble(String message)
{
System.out.println(message);
Scanner sc=new Scanner(System.in);
return sc.nextDouble();
}
public static String getString(String message)
{
System.out.println(message);
Scanner sc=new Scanner(System.in);
return sc.nextLine();
}
public static Date getISODate(String message)
{
String pattern="yyyy-MM-dd";
SimpleDateFormat sdf=new SimpleDateFormat(pattern);
System.out.println(message);
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
try
{
return (Date) sdf.parse(input);
}
catch(Exception e) {
return null;
}
}
}
| true |
c740cc6b1fff7455946a4446f99d4421e882e1be | Java | Wanna-Get-High/Workspace-L-3 | /RSX/MultiCastUdp/src/udp/SendUdp.java | UTF-8 | 1,031 | 3.375 | 3 | [] | no_license | package udp;
import java.io.IOException;
import java.net.*;
public class SendUdp
{
DatagramSocket ds;
DatagramPacket dp;
public SendUdp(String msg,int port,String ad)
{
InetAddress address=null;
// retrieve the InetAdresss from the address passed in argument
try {
address = InetAddress.getByName(ad);
} catch (UnknownHostException e) {
e.printStackTrace();
}
// create a new datagramPacket with the passed message
dp = new DatagramPacket(msg.getBytes(),msg.length(),address,port);
// create a new datagramSocket and send the datagramPacket.
try {
ds = new DatagramSocket(port+1);
} catch (SocketException e) {
e.printStackTrace();
}
try {
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("envoyé : "+msg);
}
public static void main(String[] args)
{
if (args.length < 3)
{
System.out.println("usage : ./SendUdp <msg> <port> <adress>");
}
else
{
new SendUdp(args[0],Integer.parseInt(args[1]),args[2]);
}
}
}
| true |
5cbcd86943cf220c84a5564b5bde7c15e286a5ae | Java | knovakovskaya/color_chooser | /src/main/java/ru/ifmo/thesis/gui/ChooseColorsApplication.java | UTF-8 | 5,122 | 2.703125 | 3 | [
"MIT"
] | permissive | package ru.ifmo.thesis.gui;
import ru.ifmo.thesis.gui.ColorPanel;
import ru.ifmo.thesis.gui.util.ColorChoosenActionListener;
import ru.ifmo.thesis.gui.util.ImagePanel;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.bind.ValidationEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
public class ChooseColorsApplication extends JFrame {
private ImagePanel ImgPane;
private ColorPanel ColorPane;
public JButton Load;
public JButton Save;
private final int DEFAULT_WIDTH = 1024;
private final int DEFAULT_HEIGHT = 600;
private String filename;
ChooseColorsApplication(){
filename = "";
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("Choose colors application");
setContentPane(createContentPane());
setVisible(true);
revalidate();
}
private JPanel createContentPane(){
final JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
ImgPane = new ImagePanel(null, 20);
ImgPane.setBorder(BorderFactory.createLineBorder(Color.black));
ColorPane = new ColorPanel(colorWasChoosenActionListener);
JPanel MenuPane = new JPanel();
Load = new JButton("Open new image");
Load.addActionListener(openImageActionListener);
Save = new JButton("Save colors");
Save.addActionListener(saveImageActionListener);
Save.setEnabled(false);
MenuPane.add(Load, BorderLayout.LINE_START);
MenuPane.add(Save, BorderLayout.LINE_END);
contentPane.add(ImgPane, getYPercentGBC(70,0));
contentPane.add(ColorPane, getYPercentGBC(28,1));
contentPane.add(MenuPane, getYPercentGBC(2,2));
return contentPane;
}
private GridBagConstraints getYPercentGBC(int yperc, int posy){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = posy;
gbc.gridwidth = gbc.gridheight = 1;
gbc.weightx = 1;
gbc.weighty = yperc;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
return gbc;
}
private static BufferedImage loadImage(String filename) {
BufferedImage result = null;
try {
result = ImageIO.read(new File(filename));
} catch (Exception e) {
System.out.println(e.toString() + " Image '" + filename + "' not found.");
}
return result;
}
public ActionListener openImageActionListener = new ActionListener( ) {
public void actionPerformed(ActionEvent event) {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif");
JFileChooser chooser = new JFileChooser(Paths.get(filename).toAbsolutePath().toString());
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
filename = chooser.getSelectedFile().getAbsolutePath();
}
if (filename.length() != 0) {
ImgPane.setImage(loadImage(filename));
} else {
ImgPane.setImage(null);
}
filename = "";
ColorPane.clearAll();
updateChildren();
}
};
public ActionListener saveImageActionListener = new ActionListener( ) {
public void actionPerformed(ActionEvent event) {
if (!ColorPane.validateChoosenColors())
return;
String SaveFilename = "";
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
SaveFilename = chooser.getSelectedFile().getAbsolutePath();
}
try{
PrintWriter writer = new PrintWriter(SaveFilename, "UTF-8");
writer.print(ColorPane.toString());
writer.close();
} catch (IOException e){
System.err.println("Can't save results. Got exception: " + e.toString() );
}
updateChildren();
}
};
private ColorChoosenActionListener colorWasChoosenActionListener = new ColorChoosenActionListener() {
public void actionPerformed(ActionEvent event) {
ColorPane.colorWasChoosen = true;
}
public void buttonCheck(){
Save.setEnabled(ColorPane.validateChoosenColors());
}
};
private void updateChildren(){
revalidate();
repaint();
}
public static void main(String[] args) throws Exception{
ChooseColorsApplication main = new ChooseColorsApplication();
}
}
| true |
36efe9d1b0ed37c9c5aa2e7df3ba3617cc02bd8b | Java | jenkinsci/rocketchatnotifier-plugin | /src/test/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientImplAcceptanceTest.java | UTF-8 | 2,066 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package jenkins.plugins.rocketchatnotifier.rocket;
import jenkins.plugins.rocketchatnotifier.model.Room;
import jenkins.plugins.rocketchatnotifier.rocket.errorhandling.RocketClientException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockserver.integration.ClientAndServer;
import static org.mockserver.model.HttpClassCallback.callback;
import static org.mockserver.model.HttpRequest.request;
public class RocketChatClientImplAcceptanceTest {
private static ClientAndServer mockServer;
@BeforeClass
public static void startServer() {
mockServer = ClientAndServer.startClientAndServer(1080);
mockServer.when(
request().withPath("/api/v1/info")
).callback(
callback().withCallbackClass("jenkins.plugins.rocketchatnotifier.rocket.expectations.InfoExpectationCallback")
);
mockServer.when(
request().withPath("/api/v1/login")
).callback(
callback().withCallbackClass("jenkins.plugins.rocketchatnotifier.rocket.expectations.LoginExpectationCallback")
);
mockServer.when(
request().withPath("/api/v1/chat.postMessage")
).callback(
callback().withCallbackClass("jenkins.plugins.rocketchatnotifier.rocket.expectations.MessageExpectationCallback")
);
}
@AfterClass
public static void stopServer() {
mockServer.stop();
}
@Test(expected = RocketClientException.class)
public void shouldFailWithSSLError() throws Exception {
// given
final RocketChatClientImpl rocketChatClient = new RocketChatClientImpl("127.0.0.1:1080", false, "", "");
final Room room = new Room();
room.setName("room");
// when
rocketChatClient.send(room, "message");
// then no error
}
@Test
public void shouldSendMessageToRoom() throws Exception {
// given
final RocketChatClientImpl rocketChatClient = new RocketChatClientImpl("127.0.0.1:1080", true, "", "");
final Room room = new Room();
room.setName("room");
// when
rocketChatClient.send(room, "message");
// then no error
}
}
| true |
942a91a8e420101482258dedf8ded2351d4a4b06 | Java | jiatianyang/weiDuApp | /app/src/main/java/com/ming/weidushop/adapter/IndexAdapter.java | UTF-8 | 11,698 | 1.828125 | 2 | [] | no_license | package com.ming.weidushop.adapter;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.abner.ming.base.refresh.material.Util;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.postprocessors.IterativeBoxBlurPostProcessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.ming.weidushop.R;
import com.ming.weidushop.activity.CommodityDetailsActivity;
import com.ming.weidushop.activity.SearchActivity;
import com.ming.weidushop.activity.WebViewActivity;
import com.ming.weidushop.bean.BannerBean;
import com.ming.weidushop.bean.BaseBean;
import com.ming.weidushop.bean.IndexListBean;
import com.ming.weidushop.utils.AppUtils;
import com.stx.xhb.xbanner.XBanner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* author:AbnerMing
* date:2019/9/2
* 首页多条目
*/
public class IndexAdapter extends RecyclerView.Adapter {
private Context mContext;
private List<BaseBean> mlist = new ArrayList<>();
public IndexAdapter(Context mContext) {
this.mContext = mContext;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
RecyclerView.ViewHolder viewHolder = null;
switch (i) {//i是返回的类型
case 0://banner
View view_0 = View.inflate(mContext, R.layout.adapter_item_0, null);
viewHolder = new ViewHolder_0(view_0);
break;
case 1://热销新品
case 2://魔力时尚
case 3://品质生活
View viewShop = View.inflate(mContext, R.layout.adapter_item, null);
viewHolder = new ShopViewHolder(viewShop);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
BaseBean baseBean = mlist.get(i);
//第一种类型
if (baseBean instanceof BannerBean) {
final ViewHolder_0 mViewHolder_0 = (ViewHolder_0) viewHolder;
final BannerBean bannerBean = (BannerBean) baseBean;
mViewHolder_0.mXBanner.setBannerData(R.layout.image_fresco, bannerBean.getResult());
mViewHolder_0.mXBanner.loadImage(new XBanner.XBannerAdapter() {
@Override
public void loadBanner(XBanner banner, Object model, View view, int position) {
BannerBean.ResultBean b = (BannerBean.ResultBean) model;
RoundingParams roundingParams = new RoundingParams();
roundingParams.setCornersRadius(Util.dip2px(mContext, 10));
GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(mContext.getResources());
GenericDraweeHierarchy hierarchy = builder.build();
hierarchy.setRoundingParams(roundingParams);
((SimpleDraweeView) view).setHierarchy(hierarchy);
((SimpleDraweeView) view).setImageURI(b.getImageUrl());
}
});
setBannerColor(0, mViewHolder_0, bannerBean);
mViewHolder_0.mXBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int position) {
setBannerColor(position, mViewHolder_0, bannerBean);
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
mViewHolder_0.mXBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
@Override
public void onItemClick(XBanner banner, Object model, View view, int position) {
try {
BannerBean.ResultBean b = (BannerBean.ResultBean) model;
if (b.getJumpUrl().contains("wd://")) {
String s = b.getJumpUrl().split("=")[1];
if (b.getJumpUrl().contains("commodity_list")) {//商品列表
Map<String, String> map = new HashMap<>();
map.put("shop_id", s);
AppUtils.startString(mContext, SearchActivity.class, map);
} else {
Map<String, Integer> map = new HashMap<>();
map.put("id", Integer.parseInt(s));
AppUtils.startInt(mContext, CommodityDetailsActivity.class, map);
}
} else {
Map<String, String> map = new HashMap<>();
map.put("web_url", b.getJumpUrl());
map.put("web_title", b.getTitle());
AppUtils.startString(mContext, WebViewActivity.class, map);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} else if (baseBean instanceof IndexListBean.ResultBean.RxxpBean) {
//第二种;类型
IndexListBean.ResultBean.RxxpBean rxxpBean = (IndexListBean.ResultBean.RxxpBean) baseBean;
ShopViewHolder viewHolder_1 = (ShopViewHolder) viewHolder;
viewHolder_1.mTitle.setText("热销新品");
viewHolder_1.mTitle.setTextColor(mContext.getResources().getColor(R.color.colorFF7F57));
viewHolder_1.mLyout.setBackgroundResource(R.drawable.rxxp_bg);
// viewHolder_1.mIamge.setImageResource(R.drawable.rxxp_more);
RxxpAdapter rxxpAdapter = new RxxpAdapter(mContext, rxxpBean.getCommodityList());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
viewHolder_1.mRecyclerView.setLayoutManager(linearLayoutManager);
viewHolder_1.mRecyclerView.setAdapter(rxxpAdapter);
} else if (baseBean instanceof IndexListBean.ResultBean.MlssBean) {
//第三种;类型
IndexListBean.ResultBean.MlssBean mlssBean = (IndexListBean.ResultBean.MlssBean) baseBean;
ShopViewHolder viewHolder_2 = (ShopViewHolder) viewHolder;
viewHolder_2.mTitle.setText("魔力时尚");
viewHolder_2.mTitle.setTextColor(mContext.getResources().getColor(R.color.color787AF6));
viewHolder_2.mLyout.setBackgroundResource(R.drawable.mlss_bg);
// viewHolder_2.mIamge.setImageResource(R.drawable.mlss_more);
MlssAdapter mlssAdapter = new MlssAdapter(mContext, mlssBean.getCommodityList());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
viewHolder_2.mRecyclerView.setLayoutManager(linearLayoutManager);
viewHolder_2.mRecyclerView.setAdapter(mlssAdapter);
} else if (baseBean instanceof IndexListBean.ResultBean.PzshBean) {
//第四种;类型
IndexListBean.ResultBean.PzshBean pzshBean = (IndexListBean.ResultBean.PzshBean) baseBean;
ShopViewHolder viewHolder_3 = (ShopViewHolder) viewHolder;
viewHolder_3.mTitle.setText("品质生活");
viewHolder_3.mTitle.setTextColor(mContext.getResources().getColor(R.color.colorFEA820));
viewHolder_3.mLyout.setBackgroundResource(R.drawable.pzsh_bg);
// viewHolder_3.mIamge.setImageResource(R.drawable.pzsh_more);
PzshAdapter pzshAdapter = new PzshAdapter(mContext, pzshBean.getCommodityList());
GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
viewHolder_3.mRecyclerView.setLayoutManager(gridLayoutManager);
viewHolder_3.mRecyclerView.setAdapter(pzshAdapter);
}
}
private void setBannerColor(int position, ViewHolder_0 mViewHolder_0, BannerBean bannerBean) {
showUrlBlur(mViewHolder_0.mBannerLayout,
bannerBean.getResult().get(position).getImageUrl(), 20, 20);
}
@Override
public int getItemViewType(int position) {
BaseBean baseBean = mlist.get(position);
if (baseBean instanceof BannerBean) {//banner
return 0;
} else if (baseBean instanceof IndexListBean.ResultBean.RxxpBean) {
return 1;
} else if (baseBean instanceof IndexListBean.ResultBean.MlssBean) {
return 2;
} else {
return 3;//品质生活
}
}
@Override
public int getItemCount() {
return mlist.size();
}
//传递数据
public void setList(List<BaseBean> mlist) {
this.mlist = mlist;
notifyDataSetChanged();
}
//Banner
private class ViewHolder_0 extends RecyclerView.ViewHolder {
XBanner mXBanner;
SimpleDraweeView mBannerLayout;
public ViewHolder_0(@NonNull View itemView) {
super(itemView);
mXBanner = itemView.findViewById(R.id.xbanner);
mBannerLayout = (SimpleDraweeView) itemView.findViewById(R.id.banner_layout);
}
}
//热销新品 魔力时尚 品质生活
private class ShopViewHolder extends RecyclerView.ViewHolder {
TextView mTitle;
RecyclerView mRecyclerView;
RelativeLayout mLyout;
ImageView mIamge;
public ShopViewHolder(@NonNull View itemView) {
super(itemView);
mRecyclerView = (RecyclerView) itemView.findViewById(R.id.recycler);
mTitle = (TextView) itemView.findViewById(R.id.tv_title);
mLyout = (RelativeLayout) itemView.findViewById(R.id.layout);
mIamge = (ImageView) itemView.findViewById(R.id.iv_more);
}
}
//高斯模糊
public static void showUrlBlur(SimpleDraweeView draweeView, String url,
int iterations, int blurRadius) {
try {
Uri uri = Uri.parse(url);
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setPostprocessor(new IterativeBoxBlurPostProcessor(iterations, blurRadius))
.build();
AbstractDraweeController controller = Fresco.newDraweeControllerBuilder()
.setOldController(draweeView.getController())
.setImageRequest(request)
.build();
draweeView.setController(controller);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
3ac058e43bcd3c5c7ed33242c3ab0ebcee3c9ef7 | Java | liusanmu/practice | /test/src/it/ex3/NiMingClass/Demo2_NoNameInnerClass.java | UTF-8 | 971 | 3.84375 | 4 | [] | no_license | package it.ex3.NiMingClass;
class Demo2_NoNameInnerClass {
public static void main(String[] args) {
Outer2 o = new Outer2();
o.method();
}
}
interface Inter2 {
public void show1();
public void show2();
}
//匿名内部类只针对重写一个方法时候使用
class Outer2 {
public void method() {
/*new Inter(){
public void show1() {
System.out.println("show1");
}
public void show2() {
System.out.println("show2");
}
}.show1();
new Inter(){
public void show1() {
System.out.println("show1");
}
public void show2() {
System.out.println("show2");
}
}.show2();*/
Inter2 i = new Inter2(){
public void show1() {
System.out.println("show1");
}
public void show2() {
System.out.println("show2");
}
/*public void show3() {
System.out.println("show3");
}*/
};
i.show1();
i.show2();
//i.show3(); //匿名内部类是不能向下转型的,因为没有子类类名
}
} | true |
a9ffe99d75872710325057efdda540acc2ca64e2 | Java | Left-Behind/study | /redis-distributedlock/src/main/java/work/azhu/redisdistributedlock/controller/RedisLockController.java | UTF-8 | 4,726 | 2.53125 | 3 | [] | no_license | package work.azhu.redisdistributedlock.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Collections;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @Author Azhu
* @Date 2020/1/19 14:06
* @Description
*/
@Api("Redis分布式锁测试")
@Slf4j
@RequestMapping("/redis")
@Controller
public class RedisLockController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final String PRODUCT_KEY = "productKey";
private static final String LOCK_KEY = "redisLock";
@ApiOperation("模拟购买,减库存")
@RequestMapping(value = "/lock",method = RequestMethod.POST)
public void lockTest() throws InterruptedException {
// 用户唯一标识
String lockValue = UUID.randomUUID().toString().replace("-", "");
Random random = new Random();
int sleepTime;
while (true) {
if (tryLock(LOCK_KEY, lockValue)) {
log.info("[{}]成功获取锁", lockValue);
break;
}
sleepTime = random.nextInt(1000);
Thread.sleep(sleepTime);
log.info("[{}]获取锁失败,{}毫秒后重新尝试获取锁", lockValue, sleepTime);
}
// 剩余库存
String products = stringRedisTemplate.opsForValue().get(PRODUCT_KEY);
if (products == null) {
log.info("[{}]获取剩余库存失败,释放锁:{} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", lockValue, unLock(LOCK_KEY, lockValue));
return;
}
int surplus = Integer.parseInt(products);
if (surplus <= 0) {
log.info("[{}]库存不足,释放锁:{} ##########################################", lockValue, unLock(LOCK_KEY, lockValue));
return;
}
log.info("[{}]当前库存[{}],操作:库存-1", lockValue, surplus);
stringRedisTemplate.opsForValue().decrement(PRODUCT_KEY);
log.info("[{}]操作完成,开始释放锁,释放结果:{}", lockValue, unLock(LOCK_KEY, lockValue));
}
@ApiOperation("恢复初始库存,100件")
@RequestMapping(value = "/returnStockTest",method = RequestMethod.POST)
@ResponseBody()
public String returnStockTest(){
stringRedisTemplate.opsForValue().set(PRODUCT_KEY,"100");
return "恢复库存成功";
}
/**
* 加锁
*
* @param key | 指定锁
* @param value | 用户唯一标识,用于释放锁是校验是否是加锁客户端
*/
public boolean tryLock(String key, String value) {
/*
* 如果这个key存在则返回 false,
* 不存在的,设置这个key,设置过期时间,返回true
* 调用 set k v ex 5 nx 命令 (ex表示单位为秒,px表示单位是毫秒)
*/
Boolean isLocked = stringRedisTemplate.opsForValue().setIfAbsent(key, value, 5, TimeUnit.SECONDS);
if (isLocked == null) {
return false;
}
return isLocked;
}
/**
* 解锁
*/
public Boolean unLock(String key, String value) {
// 执行 lua 脚本
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
// 指定 lua 脚本
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis/unLock.lua")));
// 指定返回类型
redisScript.setResultType(Long.class);
// 参数一:redisScript,参数二:key列表,参数三:arg(可多个)
Long result = stringRedisTemplate.execute(redisScript, Collections.singletonList(key), value);
return result != null && result > 0;
}
public Boolean unLockWithoutLua(String key, String value) throws InterruptedException {
if(stringRedisTemplate.opsForValue().get(key).equals(value)){
Thread.sleep(20);
return stringRedisTemplate.delete(key);
}
return false;
}
}
| true |
907a8df953ec982e4cafe0707cae3ca198c44469 | Java | bellmit/is4103-capstone-backend | /src/main/java/capstone/is4103capstone/admin/service/PermissionControllerService.java | UTF-8 | 2,406 | 2.6875 | 3 | [] | no_license | package capstone.is4103capstone.admin.service;
import capstone.is4103capstone.admin.dto.EmployeeDto;
import capstone.is4103capstone.configuration.DBEntityTemplate;
import capstone.is4103capstone.entities.Employee;
import capstone.is4103capstone.entities.SecurityGroup;
import capstone.is4103capstone.util.enums.OperationTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class PermissionControllerService {
public static String GLOBAL_SID_EVERYONE = "S-EVERYONE";
private static boolean CREATOR_ALWAYS_HAS_ACCESS = true;
@Autowired
private EmployeeService employeeService;
public boolean checkUserPermissions(DBEntityTemplate inputObject, Employee employee, OperationTypeEnum operationType) {
// make list to store SIDs
ArrayList<String> sidList = new ArrayList<>();
// store the user's SID into the list
sidList.add(employee.getSecurityId());
// store the user's group's SIDs into the list
for (SecurityGroup sg : employee.getMemberOfSecurityGroups()) {
sidList.add(sg.getSecurityId());
}
// check the operation type against the sidList
for (String currentSid : sidList) {
// if EVERYONE has permissions then return true
if (inputObject.getPermissionMap().get(operationType).contains(GLOBAL_SID_EVERYONE)) return true;
// check if the current permission/user pairing exists
if (inputObject.getPermissionMap().get(operationType).contains(currentSid)) return true;
// if allowed, then the creator always has access to his object
if (CREATOR_ALWAYS_HAS_ACCESS) {
try {
// lookup the creator first
EmployeeDto employeeDto = employeeService.getEmployeeByUuid(inputObject.getCreatedBy());
// check if the creator matches the current presented SID
if (employee.getSecurityId().equalsIgnoreCase(employeeDto.getSecurityId().get())) {
return true;
}
} catch (Exception ex) {
// the user probably doesn't exist anymore, return false.
return false;
}
}
}
return false;
}
}
| true |
98ed75c2d4dba1dbda9f55b50038234619eb44cb | Java | aygeshka10/Credit-Card-Management-System | /src/model/Customer.java | UTF-8 | 2,168 | 2.375 | 2 | [] | no_license | package model;
import java.sql.Timestamp;
public class Customer {
protected String firstName, middleName, lastName, cardNo;
protected String apt, street, city, county, zip, email;
protected int ssn, custPhone;
protected String state;
protected double value;
protected Timestamp lastUpdated;
public Timestamp getlastUpdated() {
return lastUpdated;
}
public void setlastUpdated(Timestamp lastUpdated) {
this.lastUpdated= lastUpdated;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getApt() {
return apt;
}
public void setApt(String apt) {
this.apt = apt;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getSsn() {
return ssn;
}
public void setSsn(int ssn) {
this.ssn = ssn;
}
public int getCustPhone() {
return custPhone;
}
public void setCustPhone(int custPhone) {
this.custPhone = custPhone;
}
}
| true |
eec231aa7515e97a2b7d0835b7b4638ef271be8c | Java | miltonlab/lessons-JPA | /src/main/java/com/mycompany/demo/onetoone/MarcaBi.java | UTF-8 | 2,314 | 2.40625 | 2 | [] | no_license | package com.mycompany.demo.onetoone;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class MarcaBi{
@Id
@GeneratedValue
private Long id;
private Integer anoFundacion;
private String fundador;
private String paisOrigen;
@OneToOne(cascade=CascadeType.ALL)
private DetalleMarcaBi detalleMarcaBi;
public MarcaBi() {
}
public MarcaBi(Integer anoFundacion, String fundador, String paisOrigen,
DetalleMarcaBi detalleMarcaBi) {
super();
this.anoFundacion = anoFundacion;
this.fundador = fundador;
this.paisOrigen = paisOrigen;
this.detalleMarcaBi = detalleMarcaBi;
}
public MarcaBi(Long id, Integer anoFundacion, String fundador,
String paisOrigen, DetalleMarcaBi detalleMarcaBi) {
super();
this.id = id;
this.anoFundacion = anoFundacion;
this.fundador = fundador;
this.paisOrigen = paisOrigen;
this.detalleMarcaBi = detalleMarcaBi;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public DetalleMarcaBi getDetalleMarcaBi() {
return detalleMarcaBi;
}
public void setDetalleMarcaBi(DetalleMarcaBi detalleMarcaBi) {
this.detalleMarcaBi = detalleMarcaBi;
}
public Integer getAnoFundacion() {
return anoFundacion;
}
public void setAnoFundacion(Integer anoFundacion) {
this.anoFundacion = anoFundacion;
}
public String getFundador() {
return fundador;
}
public void setFundador(String fundador) {
this.fundador = fundador;
}
public String getPaisOrigen() {
return paisOrigen;
}
public void setPaisOrigen(String paisOrigen) {
this.paisOrigen = paisOrigen;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof MarcaBi))
return false;
MarcaBi other = (MarcaBi) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Marca [id=" + id + "]";
}
}
| true |
99be4d4eebdd42e4775137d6dda49a0a336802f0 | Java | sanjay-mishra1/SNJDeveloper | /app/src/main/java/com/example/snjdeveloper/RecyclerUI/UserListAdapter.java | UTF-8 | 5,492 | 2.03125 | 2 | [] | no_license | package com.example.snjdeveloper.RecyclerUI;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.snjdeveloper.R;
import com.example.snjdeveloper.ViewHolder;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class UserListAdapter extends RecyclerView.Adapter<ViewHolder.FoodViewHolder> {
private ArrayList<HashMap<String, Object>> data;
Context context;
private ArrayList<String> registrationIDs;
private ArrayList<String> displayList;
TextView textView1;
TextView textView2;
int layout;
public UserListAdapter(Context context, ArrayList<String> registrationIDs, ArrayList<String> displayList) {
this.context = context;
this.registrationIDs = registrationIDs;
this.displayList = displayList;
this.layout = R.layout.listview_layout;
}
public UserListAdapter(Context context, ArrayList<String> registrationIDs, ArrayList<String> displayList, TextView textView1, TextView textView2) {
this.context = context;
this.registrationIDs = registrationIDs;
this.displayList = displayList;
this.textView1 = textView1;
this.textView2 = textView2;
this.layout = R.layout.list_with_delete;
}
public UserListAdapter(Context context, ArrayList<HashMap<String, Object>> data) {
this.context = context;
this.data = data;
layout = R.layout.notification_item;
}
@NonNull
@Override
public com.example.snjdeveloper.ViewHolder.FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new com.example.snjdeveloper.ViewHolder.FoodViewHolder(LayoutInflater.from(context)
.inflate(layout, parent, false));
}
// @Override
// public int getItemViewType(int position) {
// HashMap<String, Object> map = data.get(position);
// if (layout==R.layout.notification_item){
// if (map.containsKey("have_img"))
// return R.layout.notification_item_with_img;
// else return layout;
// }else return layout;
//
// }
@Override
public void onBindViewHolder(@NonNull com.example.snjdeveloper.ViewHolder.FoodViewHolder holder, int position) {
if (layout == R.layout.notification_item) {
HashMap<String, Object> map = data.get(position);
holder.setName((String) map.get("message"));
holder.setBackground(map.get("status"), context);
Date time = (Date) map.get("time");
holder.setTime(time.toString().replace("GMT+05:30 ", ""));
if (map.containsKey("have_img"))
{
Log.e("Adapter","Pos->"+position+"\n"+"->"+map);
if (map.get("img")==null)
holder.getUserData((boolean)map.containsKey("have_img"),context,map,(String) map.get("uid"),(String) map.get("key"),position);
else holder.setData(context,(String) map.get("img"),(String) map.get("name"),(String)map.get("uid"),(String)map.get("mobile"));
}
} else {
String[] data = displayList.get(position).split(",");
holder.setImg(data[0], data[2], position);
holder.setName(data[2]);
holder.setMobile(data[3]);
if (layout == R.layout.list_with_delete) {
holder.itemView.findViewById(R.id.delBt).setOnClickListener(v -> {
holder.itemView.findViewById(R.id.delProgress).setVisibility(View.VISIBLE);
FirebaseDatabase.getInstance().getReference("Customers").child(data[0]).child("RECEIVE_MONTHLY_PAYMENT").setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
holder.itemView.findViewById(R.id.delProgress).setVisibility(View.GONE);
if (task.isSuccessful()) {
displayList.remove(position);
registrationIDs.remove(data[0]);
notifyDataSetChanged();
} else {
Toast.makeText(context, "Failed to delete " + data[2] + ". Error: " + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
});
}
}
}
private void showMessageTextView() {
textView1.setVisibility(View.VISIBLE);
textView2.setVisibility(View.VISIBLE);
}
private void hideMessageTextView() {
textView1.setVisibility(View.GONE);
textView2.setVisibility(View.GONE);
}
@Override
public int getItemCount() {
if (textView1 != null) {
if (displayList.isEmpty())
hideMessageTextView();
else showMessageTextView();
}
if (data == null)
return displayList.size();
else return data.size();
}
}
| true |
8b07e959a3ddc08931816f946bc2b081cde75ee1 | Java | zhenglu1989/demo | /src/main/java/zbuer/com/cluster/processor/ClusterSupportWithRedis.java | UTF-8 | 3,061 | 2.3125 | 2 | [] | no_license | package zbuer.com.cluster.processor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import zbuer.com.jedis.RedisUtil;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zbuer.com.jedis.RunWithJedis;
import com.alibaba.fastjson.JSON;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @author buer
* @since 16/8/2
*/
@Component
public class ClusterSupportWithRedis extends JedisPubSub implements Runnable, ClusterSupport {
private static final Logger logger = LoggerFactory.getLogger(ClusterSupportWithRedis.class);
private final ExecutorService listenerThread = Executors.newSingleThreadExecutor();
private Map<ClusterNotifyType, ClusterMessageProcessor<?>> processors = new ConcurrentHashMap<ClusterNotifyType, ClusterMessageProcessor<?>>();
public void register(ClusterNotifyType type, ClusterMessageProcessor<?> processor) {
processors.put(type, processor);
}
@Autowired
private RedisUtil redisUtil;
@Override
public void onMessage(String channel, String message) {
super.onMessage(channel, message);
logger.info("recieve msg channel : " + channel + " detail : " + message);
ClusterNotifyType type = ClusterNotifyType.parse(channel);
if (type == null) {
logger.error("can not find channel type for channel : " + String.valueOf(channel));
} else {
ClusterMessageProcessor<?> proc = processors.get(ClusterNotifyType.parse(channel));
if (proc == null) {
logger.error("can not find channel processor for channel:" + String.valueOf(channel));
} else {
proc.onMessage(channel, message);
}
}
}
public String notifyCluster(final ClusterNotifyType channel, final Object body) {
try {
logger.info("notify cluster app :");
Long result = redisUtil.execute(this.getClass().getSimpleName(), new RunWithJedis<Long>() {
public Long run(Jedis jedis) {
Long result = jedis.publish(channel.name(), JSON.toJSONString(body));
return result;
}
});
logger.info("notify cluster app : " + String.valueOf(result));
return String.valueOf(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@PostConstruct
public void monitor() {
listenerThread.execute(this);
}
public void run() {
logger.info("listen start.....");
try {
redisUtil.execute(this.getClass().getSimpleName(), new RunWithJedis<String>() {
public String run(Jedis jedis) {
Client client = jedis.getClient();
client.setTimeoutInfinite();
proceed(client, ClusterNotifyType.all());
return null;
}
});
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
@PreDestroy
public void destroy() {
listenerThread.shutdown();
}
}
| true |
eb196c1a03c520dd7a1dd74da8d0b38a1cb92a6b | Java | LangtechKHMin/java_practice | /ChapterThreePractice/src/ArrayRandomPrint.java | UTF-8 | 713 | 3.1875 | 3 | [] | no_license | import java.util.Random;
public class ArrayRandomPrint {
public static void main(String[] args) {
Random r = new Random();
int intArray[][] = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
int a, b, c;
for (int i = 0; i<8;i++) {
while (true) {
a = r.nextInt(4);
b = r.nextInt(4);
if (intArray[a][b] != 0)
continue;
else
break;
}
while (true) {
c = r.nextInt(10);
if (c!=0)
{
intArray[a][b] = c;
break;
}
else
continue;
}
}
for (int i = 0; i < intArray.length; i++) {
System.out.print("[ ");
for (int j = 0; j < intArray[0].length; j++) {
System.out.print(intArray[i][j]+" ");
}
System.out.print("]\n");
}
}
} | true |
a175e6130984fc41e91b8967816e4b48a0691c37 | Java | benchdoos/Specs | /src/main/java/com/mmz/specs/service/MaterialService.java | UTF-8 | 1,308 | 1.882813 | 2 | [] | no_license | /*
* (C) Copyright 2018. Eugene Zrazhevsky and others.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Contributors:
* Eugene Zrazhevsky <eugene.zrazhevsky@gmail.com>
*/
package com.mmz.specs.service;
import com.mmz.specs.dao.MaterialDao;
import com.mmz.specs.model.MaterialEntity;
import java.util.List;
public interface MaterialService {
int addMaterial(MaterialEntity materialEntity);
MaterialEntity getMaterialById(int id);
MaterialEntity getMaterialByShortMarkAndProfile(String shortMark, String shortProfile);
MaterialDao getMaterialDao();
void setMaterialDao(MaterialDao materialDao);
List<MaterialEntity> listMaterials();
MaterialEntity migrate(MaterialEntity oldMaterial, MaterialEntity newMaterial);
void removeMaterial(int id);
void updateMaterial(MaterialEntity materialEntity);
}
| true |
bbaf4f3fb00c2a638c4939466b88bc7e3415b4c5 | Java | rhotin/ReveraProjectV3 | /app/src/main/java/com/ideaone/tabletapp1/HomeFragment.java | UTF-8 | 28,559 | 1.585938 | 2 | [] | no_license | package com.ideaone.tabletapp1;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class HomeFragment extends Fragment implements HomeDownload.Communicator {
View V;
public static String promoType = "Announcement";
ArrayList<PromoObject> promosArrayList = new ArrayList<>();
HomeDBAdapter db;
int tempMonth = 1;
HomeDownload downloadHome;
public static String companySelected;
public static String locationSelected;
//00000.1.71368 = waterloo, ontario / kitchener
//00000.76.71622 = london, ontario
//00000.11.71639 = richmond hill, ontario
//00000.1.71265 = toronto, ontario
//00000.1.71892 = Vancouver, BC
//00000.6.71775 = Langley, BC
//00000.12.71639 = vaughan, ontario
//00000.3.71629 = Lindsay, Ontario - william place
//00000.28.WCYOO = Port Perry, Ontario
//00000.74.71368 = strasburg, Ontario or Cambridge Ontatio
//00000.162.71624 = Mississauga, ontario
//00000.42.71697 = Oshawa, ontario
//00000.160.71624 = etobecoke
public static String weatherLocation = "ontario/toronto";
/**
* Weather API KEYS
* 421f30eef552c298 = Leaside
* 421f30eef552c298 = Revera
*/
public static String APIKEY = "421f30eef552c298"; // leaside
public static String URL = "http://api.wunderground.com/api/" + APIKEY + "/conditions/q/zmw:" + weatherLocation + ".json";
// TextView clock;
// long yourmilliseconds;
// Date resultdate;
// SimpleDateFormat sdf_clock;
HttpGetTask httpGetTask;
TextView msg1_view;
TextView msg1_view_authur;
MsgObjectHome mObj = new MsgObjectHome("Connection Issue", "Loading...");
//weather
Bitmap icon;
ImageView weather_icon;
TextView weather_condition, temperature, feels_like;
HttpGetTaskWeather httpGetTaskWeather;
ImageView mImageViewChoice;
ImageView mImageViewLogo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
V = inflater.inflate(R.layout.home_fragment, container, false);
final SharedPreferences prefs = getActivity().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
locationSelected = prefs.getString("location", getString(R.string.RetirementLocation));
companySelected = prefs.getString("company", getString(R.string.RetirementCompany));
if (locationSelected.equals("leaside-14")) {
locationSelected = "leaside";
}
switch (locationSelected) {
case "beechwood_court":
weatherLocation = "ontario/mississauga";
break;
case "beechwood_place":
weatherLocation = "ontario/mississauga";
break;
case "bough_beeches":
weatherLocation = "ontario/mississauga";
break;
case "bradgate":
weatherLocation = "ontario/toronto";
break;
case "briarfield_gardens":
weatherLocation = "ontario/kitchener";
break;
case "cedarcroft_place":
weatherLocation = "ontario/Oshawa";
break;
case "demo":
weatherLocation = "ontario/toronto";
break;
case "demo_2":
weatherLocation = "ontario/toronto";
break;
case "demo4":
weatherLocation = "ontario/toronto";
break;
case "donmills_apartments":
weatherLocation = "ontario/toronto";
break;
case "donway_place":
weatherLocation = "ontario/toronto";
break;
case "fergus_place":
weatherLocation = "ontario/kitchener";
break;
case "forest_hill":
weatherLocation = "ontario/toronto";
break;
case "glynnwood":
weatherLocation = "ontario/thornhill";
break;
case "granite_landing":
weatherLocation = "ontario/cambridge";
break;
case "highland_place":
weatherLocation = "ontario/kitchener";
break;
case "kingsway":
weatherLocation = "ontario/etobicoke";
break;
case "leaside":
weatherLocation = "ontario/toronto";
break;
case "pinevilla":
weatherLocation = "ontario/toronto";
break;
case "port_perry_villa":
weatherLocation = "ontario/Port%20Perry";
break;
case "rayoak":
weatherLocation = "ontario/North%20York";
break;
case "terrace":
weatherLocation = "ontario/North%20York";
break;
case "annex":
weatherLocation = "ontario/toronto";
break;
case "the_renoir":
weatherLocation = "ontario/newmarket";
break;
case "william_place":
weatherLocation = "ontario/lindsay";
break;
case "windermere":
weatherLocation = "ontario/london";
break;
default:
weatherLocation = "ontario/toronto";
break;
}
// URL = "http://api.wunderground.com/api/" + APIKEY + "/conditions/q/zmw:" + weatherLocation + ".json";
URL = "http://api.wunderground.com/api/" + APIKEY + "/conditions/q/" + weatherLocation + ".json";
Log.e("Home Weather", "" + URL);
msg1_view_authur = (TextView) V.findViewById(R.id.msgAuthur);
msg1_view = (TextView) V.findViewById(R.id.msgText);
mImageViewChoice = (ImageView) V.findViewById(R.id.imageViewChoice);
mImageViewLogo = (ImageView) V.findViewById(R.id.imageViewLogo);
db = new HomeDBAdapter(getActivity().getApplicationContext());
getAllItems();
if (isNetworkAvailable()) {
httpGetTask = new HttpGetTask();
httpGetTask.execute();
} else {
msg1_view.setText(mObj.msgText);
msg1_view_authur.setText("..." + mObj.msgAuthor);
}
weather_icon = (ImageView) V.findViewById(R.id.weatherIcon);
weather_condition = (TextView) V.findViewById(R.id.weatherCondText);
temperature = (TextView) V.findViewById(R.id.tempText);
feels_like = (TextView) V.findViewById(R.id.feelText);
if (isNetworkAvailable()) {
feels_like.setText("Getting Weather");
weather_condition.setText("");
httpGetTaskWeather = new HttpGetTaskWeather();
httpGetTaskWeather.execute();
} else {
feels_like.setText(R.string.loading);
weather_condition.setText("weather");
}
mImageViewChoice.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
try {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View promptView = layoutInflater.inflate(R.layout.dialog_password, null);
// ArrayList selectLocationList = new ArrayList<String>();
// DownloadLocations downloadTask = new DownloadLocations();
// try {
// selectLocationList = downloadTask.execute().get();
// } catch (ExecutionException | InterruptedException e) {
// e.printStackTrace();
// }
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Settings");
builder.setMessage("Password needed to change location");
builder.setView(promptView);
final EditText input = (EditText) promptView.findViewById(R.id.userInput);
builder.setCancelable(false);
// final ArrayList<String> finalSelectLocationList = selectLocationList;
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("Idea12345")) {
Intent intent = new Intent(getActivity().getApplicationContext(), SettingsActivity.class);
startActivity(intent);
dialog.dismiss();
/*
final String[] selectLocation = new String[finalSelectLocationList.size()];
for (int i = 0; i < finalSelectLocationList.size(); i++) {
selectLocation[i] = finalSelectLocationList.get(i);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Location");
builder.setItems(selectLocation, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editor.putString("location", selectLocation[which]);
editor.commit();
locationSelected = selectLocation[which];
Toast.makeText(getActivity(), selectLocation[which] + " Selected",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity().getApplicationContext(), SettingsActivity.class);
startActivity(intent);
dialog.dismiss();
}
});
builder.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
*/
} else {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Wrong Password");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
} catch (NullPointerException e) {
e.printStackTrace();
}
return false;
}
});
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
if (isNetworkAvailable()) {
Log.e("Announce PIC", " network ");
if (month != tempMonth) {
tempMonth = month;
db.open();
db.resetDB();
db.close();
}
// messageText.setText("");
downloadHome = new HomeDownload(this);
downloadHome.execute();
// }
}else{
getAllItems();
}
return V;
}
@Override
public void updateUI(ArrayList<PromoObject> photosArrayList) {
getAllItems();
}
public void getAllItems() {
promosArrayList.clear();
String creatorID;
String created;
String name;
String zone;
String displayID;
int length;
int priority;
String dateStart;
String dateEnd;
String web;
String display;
String calendar;
String bulletin;
String kiosk;
String type;
String promoType;
String modified;
int showMonday;
int showTuesday;
int showWednesday;
int showThursday;
int showFriday;
int showSaturday;
int showSunday;
String url;
String text;
byte[] Image;
byte[] ImageBack;
Bitmap photo = null;
Bitmap backPhoto = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = true;
options.inSampleSize = calculateInSampleSize(options, 300, 300);
options.inPreferredConfig = Bitmap.Config.RGB_565;
BitmapFactory.Options optionsBack = new BitmapFactory.Options();
optionsBack.inScaled = true;
optionsBack.inSampleSize = calculateInSampleSize(options, 200, 200);
optionsBack.inPreferredConfig = Bitmap.Config.RGB_565;
db.open();
Cursor c = db.getAllItems();
if (c.moveToFirst()) {
do {
creatorID = c.getString(1);
created = c.getString(2);
name = c.getString(3);
zone = c.getString(4);
displayID = c.getString(5);
length = c.getInt(6);
priority = c.getInt(7);
dateStart = c.getString(8);
dateEnd = c.getString(9);
web = c.getString(10);
display = c.getString(11);
calendar = c.getString(12);
bulletin = c.getString(13);
kiosk = c.getString(14);
type = c.getString(15);
promoType = c.getString(16);
modified = c.getString(17);
showMonday = c.getInt(18);
showTuesday = c.getInt(19);
showWednesday = c.getInt(20);
showThursday = c.getInt(21);
showFriday = c.getInt(22);
showSaturday = c.getInt(23);
showSunday = c.getInt(24);
url = c.getString(25);
text = c.getString(26);
Image = c.getBlob(27);
ImageBack = c.getBlob(28);
if (Image != null) {
try {
photo = BitmapFactory.decodeByteArray(Image, 0, Image.length, options);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
if (ImageBack != null) {
try {
backPhoto = BitmapFactory.decodeByteArray(ImageBack, 0, ImageBack.length, optionsBack);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
/*creatorID, created, name,
zone, displayID, length, priority, dateStart, dateEnd, web,
display, calendar, messages, type, promoType, modified, showMonday,
showTuesday, showWednesday, showThursday, showFriday, showSaturday,
showSunday, url, text, bmp
*/
PromoObject obj = new PromoObject(creatorID, created, name, zone,
displayID, length, priority, dateStart, dateEnd, web, display, calendar, bulletin,
kiosk, type, promoType, modified, showMonday, showTuesday, showWednesday,
showThursday, showFriday, showSaturday, showSunday, url, text, photo, backPhoto);
promosArrayList.add(obj);
photo = null;
setLogoImage(obj);
} while (c.moveToNext());
PromoObject ob = promosArrayList.get(0);
//backgroundImageView.setImageBitmap(ob.backPhoto);
}
db.close();
}
private void setLogoImage(final PromoObject obj) {
mImageViewLogo.setImageBitmap(obj.photo);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private class HttpGetTask extends AsyncTask<Void, Void, List<String>> {
/* ******** This is for Quote of the day (don't change) ******** */
private final String URL = "http://revera.mxs-s.com/displays/demo/promos.json?nohtml=1";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
@Override
protected List<String> doInBackground(Void... params) {
URL theUrl;
try {
theUrl = new URL(URL);
BufferedReader reader = new BufferedReader
(new InputStreamReader(theUrl.openConnection().getInputStream(), "UTF-8"));
String instagram_json = reader.readLine();
JSONObject instagram_object = new JSONObject(instagram_json);
JSONArray data_arr = instagram_object.getJSONArray("promos");
int totalMsgs = data_arr.length();
for (int i = 0; i < totalMsgs; i++) {
if (data_arr.getJSONObject(i).getString("name").equals("TodaysQuote") &&
data_arr.getJSONObject(i).getString("displayID").equals("537cd48cc0af978a0b000007")) {
String msgText = data_arr.getJSONObject(i).getString("text");
String[] parts = msgText.split("!!!"); // escape .
mObj.msgText = parts[0];
mObj.msgAuthor = parts[1];
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<String> strings) {
//super.onPostExecute(strings);
msg1_view.setText(Html.fromHtml(mObj.msgText));
msg1_view_authur.setText(Html.fromHtml("..." + mObj.msgAuthor));
mClient.close();
}
}
@Override
public void onDetach() {
super.onDetach();
if (httpGetTask != null)
httpGetTask.cancel(true);
if (httpGetTaskWeather != null)
httpGetTaskWeather.cancel(true);
}
@Override
public void onPause() {
super.onPause();
if (httpGetTask != null)
httpGetTask.cancel(true);
if (httpGetTaskWeather != null)
httpGetTaskWeather.cancel(true);
}
//weather
private class ICON_download extends AsyncTask<String, Void, Boolean> {
//int ViewID;
@Override
protected Boolean doInBackground(String... param) {
icon = downloadBitmap(param[0]);
finishedTask();
return true;
}
@Override
protected void onPostExecute(Boolean df) {
weather_icon.setImageBitmap(icon);
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + " " + e.toString());
}
return null;
}
public boolean finishedTask() {
return true;
}
}
private class HttpGetTaskWeather extends AsyncTask<Void, Void, List<String>> {
//private final String URL = WeatherFragment.URL;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
@Override
protected List<String> doInBackground(Void... params) {
HttpGet request = new HttpGet(URL);
JSONResponseHandler responseHandler = new JSONResponseHandler();
try {
return mClient.execute(request, responseHandler);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(final List<String> result) {
if (mClient != null)
mClient.close();
if (result != null && result.size() > 3) {
try {
new ICON_download().execute(result.get(4));
weather_condition.setText(" " + result.get(1) + " ");
temperature.setText(Html.fromHtml("<b>" + result.get(2) + "</b>" + " " + "<b>°</b>C"));
feels_like.setText(Html.fromHtml("Feels like " + "<b>" + result.get(3) + "</b>" + " " + "<b>°</b>C"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class JSONResponseHandler implements ResponseHandler<List<String>> {
private static final String CURRENT_OBS_TAG = "current_observation";
private static final String LOCATION_TAG = "display_location";
private static final String CITY_TAG = "city";
private static final String STATE_TAG = "state";
private static final String TEMP_TAG = "temp_c";
private static final String WEATHER_TAG = "weather";
private static final String FEELS_LIKE_TAG = "feelslike_c";
private static final String ICON_URL_TAG = "icon_url";
@Override
public List<String> handleResponse(HttpResponse response)
throws IOException {
List<String> result = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
// Get top-level JSON Object - a Map
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue();
// Extract value of "messages" key -- a List
JSONObject current = responseObject
.getJSONObject(CURRENT_OBS_TAG);
JSONObject locationJSON = current.getJSONObject(LOCATION_TAG);
String city = (String) locationJSON.get(CITY_TAG);
String state = (String) locationJSON.get(STATE_TAG);
String temperature1 = Integer.toString(((Number) current.get(TEMP_TAG)).intValue());
String weather = ((String) current.get(WEATHER_TAG));
String feelsLike = ((String) current.get(FEELS_LIKE_TAG));
String Url = ((String) current.get(ICON_URL_TAG));
result.add(city + "," + state);
result.add(weather);
result.add(temperature1);
result.add(feelsLike);
result.add(Url);
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
public boolean isNetworkAvailable() {
getActivity().getApplicationContext();
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
} | true |
43502730b7820d6914b76ca3aa5640fc63dce4e5 | Java | themodernway/themodernway-server-core | /src/main/groovy/com/themodernway/server/core/support/spring/ServletFactoryContextCustomizer.java | UTF-8 | 7,002 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2018, The Modern Way. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.themodernway.server.core.support.spring;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration.Dynamic;
import org.slf4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import com.themodernway.common.api.java.util.CommonOps;
import com.themodernway.common.api.java.util.StringOps;
import com.themodernway.server.core.ICoreCommon;
import com.themodernway.server.core.logging.LoggingOps;
import com.themodernway.server.core.servlet.IServletExceptionHandler;
import com.themodernway.server.core.servlet.IServletResponseErrorCodeManager;
import com.themodernway.server.core.servlet.ISessionIDFromRequestExtractor;
public class ServletFactoryContextCustomizer implements IServletContextCustomizer, ICoreCommon, IServletFactoryContextCustomizer
{
private final Logger m_logs = LoggingOps.getLogger(getClass());
private final String m_name;
private final String[] m_maps;
private int m_load = 1;
private double m_rate = 0.0;
private List<String> m_role = arrayList();
private IServletFactory m_fact;
private ISessionIDFromRequestExtractor m_extr;
private IServletResponseErrorCodeManager m_code;
private IServletExceptionHandler m_hand;
public ServletFactoryContextCustomizer(final String name, final String maps)
{
this(name, StringOps.toUniqueTokenStringList(maps));
}
public ServletFactoryContextCustomizer(final String name, final Collection<String> maps)
{
m_name = requireTrimOrNull(name);
m_maps = StringOps.toUniqueArray(maps);
}
@Override
public void setServletFactory(final IServletFactory fact)
{
m_fact = CommonOps.requireNonNull(fact);
}
@Override
public void setRateLimit(final double rate)
{
m_rate = rate;
}
@Override
public double getRateLimit()
{
return m_rate;
}
@Override
public Logger logger()
{
return m_logs;
}
@Override
public void setLoadOnStartup(final int load)
{
m_load = load;
}
@Override
public int getLoadOnStartup()
{
return m_load;
}
@Override
public String getServletName()
{
return m_name;
}
@Override
public String[] getMappings()
{
return StringOps.toUniqueArray(m_maps);
}
@Override
public List<String> getRequiredRoles()
{
return toUnmodifiableList(m_role);
}
@Override
public void setRequiredRoles(String roles)
{
if (null == (roles = toTrimOrNull(roles)))
{
setRequiredRoles(arrayList());
}
else
{
setRequiredRoles(toUniqueTokenStringList(roles));
}
}
@Override
public void setRequiredRoles(final List<String> roles)
{
m_role = (roles == null ? arrayList() : roles);
}
@Override
public void close() throws IOException
{
if (logger().isInfoEnabled())
{
logger().info(LoggingOps.THE_MODERN_WAY_MARKER, "close().");
}
}
@Override
public ISessionIDFromRequestExtractor getSessionIDFromRequestExtractor()
{
return m_extr;
}
@Override
public void setSessionIDFromRequestExtractor(final ISessionIDFromRequestExtractor extractor)
{
m_extr = extractor;
}
@Override
public void setServletResponseErrorCodeManager(final IServletResponseErrorCodeManager manager)
{
m_code = requireNonNull(manager);
}
@Override
public IServletResponseErrorCodeManager getServletResponseErrorCodeManager()
{
return m_code;
}
@Override
public IServletExceptionHandler getServletExceptionHandler()
{
return m_hand;
}
@Override
public void setServletExceptionHandler(final IServletExceptionHandler handler)
{
m_hand = handler;
}
@Override
public void customize(final ServletContext sc, final WebApplicationContext context)
{
final String name = toTrimOrNull(getServletName());
if (null != name)
{
final String[] maps = getMappings();
if ((null != maps) && (maps.length > 0))
{
final Servlet servlet = m_fact.make(this, sc, context);
if (null != servlet)
{
final Dynamic dispatcher = sc.addServlet(name, servlet);
if (null != dispatcher)
{
final Collection<String> done = dispatcher.addMapping(maps);
if ((false == done.isEmpty()) && (logger().isWarnEnabled()))
{
logger().warn(LoggingOps.THE_MODERN_WAY_MARKER, format("customize (%s) already mapped (%s).", name, StringOps.toCommaSeparated(done)));
}
dispatcher.setLoadOnStartup(getLoadOnStartup());
if (logger().isInfoEnabled())
{
logger().info(LoggingOps.THE_MODERN_WAY_MARKER, format("customize (%s) mapped to (%s).", name, StringOps.toCommaSeparated(maps)));
}
}
else if (logger().isErrorEnabled())
{
logger().error(LoggingOps.THE_MODERN_WAY_MARKER, format("customize (%s) already registered.", name));
}
}
else if (logger().isErrorEnabled())
{
logger().error(LoggingOps.THE_MODERN_WAY_MARKER, format("customize (%s) null servlet.", name));
}
}
else if (logger().isErrorEnabled())
{
logger().error(LoggingOps.THE_MODERN_WAY_MARKER, format("customize (%s) empty mappings.", name));
}
}
else if (logger().isErrorEnabled())
{
logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "customize() no servlet name.");
}
}
}
| true |
609bdfdff03b77f408bafb424c6a8efd80e24391 | Java | tanseda/hackerrank | /src/main/java/leetcode/PowerofANum.java | UTF-8 | 1,020 | 3.671875 | 4 | [] | no_license | /**
* Created by stan on 07/04/2021.
*/
package leetcode;
public class PowerofANum {
public boolean isPowerOfFour(int n) {
if(n == 0)
return false;
double temp = Math.log(n) / Math.log(4);
System.out.println("return : " + temp);
System.out.println("return : " + Math.floor(temp));
return (temp == Math.floor(temp));
}
public boolean isPowerOfThree(int n) {
if ( n == 0 )
return false;
double epsilon = 0.00000001;
return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
}
public boolean isPowerOfTwo(int n) {
return (n > 0) && (n & (n - 1)) == 0;
}
public static void main(String[] args) {
PowerofANum powerofANum = new PowerofANum();
boolean retVal = powerofANum.isPowerOfFour(-4);
System.out.println("return : " + retVal);
boolean retVal1 = powerofANum.isPowerOfThree(14348906);
System.out.println("return : " + retVal1);
}
}
| true |
358b771e2806b02788c6bec44132ff74e0f780af | Java | iamshijun/spring_demo | /spring_demo_module/spring_sample_demo/src/test/java/cjava/walker/common/service/impl/AServiceImpl.java | GB18030 | 1,190 | 2.40625 | 2 | [] | no_license | package cjava.walker.common.service.impl;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cjava.walker.common.service.AService;
import cjava.walker.common.service.BService;
import cjava.walker.support.BeanSelfAware;
//@Service
public class AServiceImpl implements AService, BeanSelfAware {// ˴ʡAserviceӿڶ
@Autowired
private BService bService; // ͨ@AutowiredʽעBService
private AService self; // עԼAOP
public void setSelf(Object proxyBean) {
this.self = (AService) proxyBean; //
// ͨInjectBeanSelfProcessorעԼĿAOP
System.out.println("AService==" + AopUtils.isAopProxy(this.self)); // trueʶAOPעɹ
}
@Transactional(propagation = Propagation.REQUIRED)
public void a() {
self.b();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void b() {
}
}
| true |
dd1689270d82bc1ddba33ef3c8a60b73f5a4859c | Java | eisen1990/PayDoctorApp | /app/src/main/java/com/linepayroll/paydoctor/Utils/RestAPITask.java | UTF-8 | 3,315 | 2.921875 | 3 | [] | no_license | package com.linepayroll.paydoctor.Utils;
import android.os.AsyncTask;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by eisen on 2017-11-13.
*
* FIXME : 해당 클래스는 RestAPI 호출을 위한 Sample Source Code이므로,
* FIXME: 각각의 Activity들에서 Rest API 호출이 필요할 경우 아래 코드를 참고하여
* FIXME : Parameter들에 맞게 작성할 것.
* Rest API는 모두 JSON 방식으로 Return 하므로, AsyncTask<String, Void, JSONObject>의 JSONObject는 기본적으로 동일하다.
* String 인자는 execute()의 Parameter로, 다수의 String type veriable이 올 수 있다. 그리고 execute()의 Parameter는
* doInBackground(String... params)에 전달되며, execute(첫 번째, 두 번째, n번 째) Argument는 doInBackground의 params에서 params[0], params[1], params[n-1]
*
* Sample Code:
* ... source code ...
*
* JSONObject ResultObject = new RestAPITask().execute(SOME_URL_STRING_VALUE).get();
*
* ... source code ...
*/
public class RestAPITask extends AsyncTask<String, Void, JSONObject> {
public RestAPITask() {
super();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(JSONObject aJSONObject) {
super.onPostExecute(aJSONObject);
}
@Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
String url = params[0];
String Body = "KEY1=VALUE1&KEY2=VALUE2...";
URL URLObj = new URL(url);
HttpURLConnection Conn = (HttpURLConnection) URLObj.openConnection();
Conn.setReadTimeout(100000);
Conn.setConnectTimeout(15000);
/**
* 1. Todo:POST Method 설정
* 2. Todo:Accept-Charset 설정
* 3. Todo:Content-Type 설정
*/
Conn.setRequestMethod("POST");
Conn.setRequestProperty("Accept-Charset", "UTF-8"); // Accept-Charset 설정.
Conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Conn.setDoInput(true);
Conn.setDoOutput(true);
OutputStream OutStream = Conn.getOutputStream();
OutStream.write(Body.getBytes("utf-8"));
InputStreamReader InputStream = new InputStreamReader(Conn.getInputStream(), "UTF-8");
BufferedReader Reader = new BufferedReader(InputStream);
StringBuilder Builder = new StringBuilder();
String ResultStr;
while ((ResultStr = Reader.readLine()) != null) {
Builder.append(ResultStr + "\n");
}
result = new JSONObject(Builder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
result = null;
} catch (Exception e) {
e.printStackTrace();
result = null;
} finally {
//Todo finally..
}
return result;
}
}
| true |
5b715ed5741a3e194364fdd3d1f2889a1c191aea | Java | iwsrh/cinema-server | /src/main/java/ru/megagrinn/model/Action.java | UTF-8 | 481 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | package ru.megagrinn.model;
public class Action {
private int id;
private String imgUrl;
private String description;
public Action(int id, String imgUrl, String description) {
this.id = id;
this.imgUrl = imgUrl;
this.description = description;
}
public int getId() {
return id;
}
public String getImgUrl() {
return imgUrl;
}
public String getDescription() {
return description;
}
}
| true |
f0de2c36f41ed6469b9ba2f3298bc7368034527e | Java | syafiqabdillah/TA_6_6 | /src/main/java/com/apap/farmasi/service/PermintaanService.java | UTF-8 | 362 | 1.921875 | 2 | [] | no_license | package com.apap.farmasi.service;
import java.util.List;
import java.util.Optional;
import com.apap.farmasi.model.PermintaanModel;
public interface PermintaanService {
List<PermintaanModel> getAll();
PermintaanModel findById(long id);
PermintaanModel save(PermintaanModel permintaan);
void updateStatusPermintaan(PermintaanModel newPermintaanModel);
}
| true |
0a23a9dde94463380bd1fd7e12a8502540d6f074 | Java | sharco-code/2DAM | /data-acces/UD3/examenUD3/src/pojos/CicloFormativo.java | UTF-8 | 933 | 2.6875 | 3 | [] | no_license | package pojos;
public class CicloFormativo {
private String nom;
private String familia;
private int grau;
private int hores;
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getFamilia() {
return familia;
}
public void setFamilia(String familia) {
this.familia = familia;
}
public int getGrau() {
return grau;
}
public void setGrau(int grau) {
this.grau = grau;
}
public int getHores() {
return hores;
}
public void setHores(int hores) {
this.hores = hores;
}
public CicloFormativo(String nom, String familia, int grau, int hores) {
super();
this.nom = nom;
this.familia = familia;
this.grau = grau;
this.hores = hores;
}
public CicloFormativo() {
super();
}
@Override
public String toString() {
return "CicloFormativo [nom=" + nom + ", familia=" + familia + ", grau=" + grau + ", hores=" + hores + "]";
}
}
| true |
544fa0e5cce36b7bf2506336e500d8851b182966 | Java | Open-source-sharing/REST-doc | /smartdoc-oas/src/main/java/io/swagger/v3/core/util/EncodingPropertyStyleEnumDeserializer.java | UTF-8 | 1,565 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | package io.swagger.v3.core.util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.v3.oas.models.media.EncodingProperty;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
public class EncodingPropertyStyleEnumDeserializer
extends JsonDeserializer<EncodingProperty.StyleEnum> {
@Override
public EncodingProperty.StyleEnum deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
if (node != null) {
String value = node.asText();
return getStyleEnum(value);
}
return null;
}
private EncodingProperty.StyleEnum getStyleEnum(String value) {
return Arrays.stream(EncodingProperty.StyleEnum.values())
.filter(i -> i.toString().equals(value))
.findFirst()
.orElseThrow(
() ->
new RuntimeException(
String.format(
"Can not deserialize value of type EncodingProperty.StyleEnum from String"
+ " \"%s\": value not one of declared Enum instance names: %s",
value,
Arrays.stream(EncodingProperty.StyleEnum.values())
.map(EncodingProperty.StyleEnum::toString)
.collect(Collectors.joining(", ", "[", "]")))));
}
}
| true |
80f90f93a03c1bfd530e306ffa7a564a59f37807 | Java | gstamatakis/ANAC-agents | /src/Core/ThrashAgent.java | UTF-8 | 8,592 | 2 | 2 | [] | no_license | package Core;
import Utils.SearchMethodEnum;
import Utils.StrategyEnum;
import Utils.ValFreqEnum;
import negotiator.AgentID;
import negotiator.Bid;
import negotiator.Deadline;
import negotiator.actions.*;
import negotiator.parties.AbstractNegotiationParty;
import negotiator.persistent.PersistentDataContainer;
import negotiator.timeline.TimeLineInfo;
import negotiator.utility.AbstractUtilitySpace;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public abstract class ThrashAgent extends AbstractNegotiationParty implements AgentAPI {
private StrategyEnum AgentStrat;
public static BidHistory bidHistory;
static boolean useHistory;
public static SearchMethodEnum SearchingMethod;
public static ValFreqEnum ValueFrequencySel;
static double CutoffVal;
private static double VetoVal;
static String myDescription;
static double concessionThreshold;
private AbstractUtilitySpace utilitySpace;
private NegotiationStatistics Information;
private BidStrategy bidStrategy;
private int supporter_num = 0;
private Bid offeredBid = null;
private Random RNG;
static PrintWriter gLog;
static String filename;
static int MemoryDepth;
static double softConcessionThreshold;
@Override
public void init(AbstractUtilitySpace utilSpace, Deadline dl, TimeLineInfo tl, long randomSeed, AgentID agentId, PersistentDataContainer data) {
super.init(utilSpace, dl, tl, randomSeed, agentId, data);
this.RNG = getRand();
utilitySpace = utilSpace;
MemoryDepth = getMemoryDepth();
concessionThreshold = getConcessionThreshold();
softConcessionThreshold = getSoftConcessionThreshold();
myDescription = getDescription();
VetoVal = getVetoVal();
SearchingMethod = getSearchingMethod();
ValueFrequencySel = getFrequencyValueSelection();
CutoffVal = getCutoffValue();
AgentStrat = getAgentStrategy();
filename = "C:/Users/gstamatakis/IdeaProjects/ANAC-agents/logs/" + AgentStrat + "_logs.txt";
try {
gLog = new PrintWriter(new FileWriter(filename, true));
} catch (Exception e) {
gLog = new PrintWriter(System.out);
}
gLog.println("*********\n" + Instant.now());
useHistory = useHistory();
if (useHistory) {
try {
bidHistory = new BidHistory(RNG, getData());
} catch (Exception e) {
gLog.println(e.toString());
useHistory = false;
}
} else {
gLog.println("Not using history.");
}
Information = new NegotiationStatistics(utilitySpace, RNG);
bidStrategy = new BidStrategy(utilitySpace, Information, RNG, getBidUtilThreshold(), getSimulatedAnnealingParams(), getTimeScalingFactor());
if (useHistory) {
try {
bidHistory.logHistory();
} catch (Exception e) {
gLog.println(e.toString());
}
}
}
/**
* Each round this method gets called and ask you to accept or offer. The
* first party in the first round is a bit different, it can only propose an
* offer.
*
* @param validActions Either a list containing both accept and offer or only offer.
* @return The chosen action.
*/
@Override
public Action chooseAction(List<Class<? extends Action>> validActions) {
Information.incrementRound();
double time = getTimeLine().getTime();
Double targetTime;
Bid bidToOffer;
if (Information.getRound() < 2) {
try {
return new Offer(getPartyId(), Information.updateMyBidHistory(utilitySpace.getMaxUtilityBid()));
} catch (Exception e) {
gLog.println(e.toString());
}
}
switch (AgentStrat) {
case Time:
targetTime = bidStrategy.targetTime(time);
bidToOffer = bidStrategy.SimulatedAnnealingUop(utilitySpace.getDomain().getRandomBid(RNG), targetTime, time);
if (validActions.contains(Offer.class) && Information.getRound() <= 1) {
return new Offer(getPartyId(), Information.updateMyBidHistory(bidStrategy.getMaxBid()));
} else if (validActions.contains(Accept.class) && utilitySpace.getUtility(bidToOffer) > VetoVal) {
if (utilitySpace.getUtilityWithDiscount(offeredBid, time) >= targetTime) {
return new Accept(getPartyId(), offeredBid);
}
} else if (validActions.contains(EndNegotiation.class) && bidStrategy.selectEndNegotiation(time)) {
return new EndNegotiation(getPartyId());
}
return new Offer(getPartyId(), Information.updateMyBidHistory(bidToOffer));
case Threshold:
if (utilitySpace.getUtility(offeredBid) >= bidStrategy.getThreshold(time)) {
return new Accept(getPartyId(), offeredBid);
} else if (validActions.contains(EndNegotiation.class) && bidStrategy.selectEndNegotiation(time)) {
return new EndNegotiation(getPartyId());
}
bidToOffer = bidStrategy.AppropriateSearch(generateRandomBid(), time);
return new Offer(getPartyId(), Information.updateMyBidHistory(bidToOffer));
case Mixed:
if (utilitySpace.isDiscounted()) {
targetTime = bidStrategy.targetTime(time);
bidToOffer = bidStrategy.SimulatedAnnealingUop(utilitySpace.getDomain().getRandomBid(RNG), targetTime, time);
if (utilitySpace.getUtilityWithDiscount(offeredBid, time) >= targetTime) {
return new Accept(getPartyId(), offeredBid);
}
} else {
bidToOffer = bidStrategy.AppropriateSearch(generateRandomBid(), time);
if (utilitySpace.getUtility(offeredBid) >= bidStrategy.getThreshold(time)) {
return new Accept(getPartyId(), offeredBid);
} else if (validActions.contains(EndNegotiation.class) && bidStrategy.selectEndNegotiation(time)) {
return new EndNegotiation(getPartyId());
}
}
return new Offer(getPartyId(), Information.updateMyBidHistory(bidToOffer));
default:
return new Offer(getPartyId(), generateRandomBid());
}
}
/**
* All offers proposed by the other parties will be received as a message.
* You can use this information to your advantage, for example to predict
* their utility.
*
* @param sender The party that did the action. Can be null.
* @param action The action that party did.
*/
@Override
public void receiveMessage(AgentID sender, Action action) {
super.receiveMessage(sender, action);
double time = getTimeLine().getTime();
if (action != null) {
if (action instanceof Inform) {
Integer opponentsNum = (Integer) ((Inform) action).getValue();
Information.updateOpponentsNum(opponentsNum);
} else if (action instanceof Offer) {
if (!Information.getOpponents().containsKey(sender)) {
Information.initOpponent(sender);
}
supporter_num = 1;
offeredBid = ((Offer) action).getBid();
Information.updateInfo(sender, offeredBid, time);
} else if (action instanceof Accept) {
if (!Information.getOpponents().containsKey(sender)) {
Information.initOpponent(sender);
}
Information.updateAcceptanceHistory(sender, offeredBid);
supporter_num++;
} else if (action instanceof EndNegotiation) {
gLog.println("Someone left..");
}
if (offeredBid != null && supporter_num == (Information.getNegotiatorNum() - 1)) {
Information.updatePopularBidList(offeredBid);
}
}
}
@Override
public HashMap<String, String> negotiationEnded(Bid acceptedBid) {
gLog.println("\nnegotiationEnded");
gLog.close();
return super.negotiationEnded(acceptedBid);
}
} | true |
96d6c72a0f3728d5398d0c1052ba87d1682b5af9 | Java | gspandy/xss-spring | /src/main/java/com/ryanperrizo/spring/sample/cont/AdminController.java | UTF-8 | 3,155 | 2.21875 | 2 | [] | no_license | package com.ryanperrizo.spring.sample.cont;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ryanperrizo.spring.sample.dto.InsecureSearchForm;
import com.ryanperrizo.spring.sample.dto.SearchForm;
import com.ryanperrizo.spring.sample.dto.SecureSearchForm;
import com.ryanperrizo.spring.sample.entities.Applicant;
import com.ryanperrizo.spring.sample.repositories.ApplicantRepository;
import com.ryanperrizo.spring.sample.services.AdminService;
import com.ryanperrizo.spring.sample.services.UserServiceImpl;
@Controller
public class AdminController {
private ApplicantRepository applicantRepository;
private AdminService adminService;
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
public AdminController(ApplicantRepository applicantRepository, AdminService adminService){
this.applicantRepository = applicantRepository;
this.adminService = adminService;
}
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(@RequestParam(required=false, value = "toggle") String toggle, Model model){
if(toggle != null && toggle.equals("Secure")){
model.addAttribute("secure", "Insecure");
model.addAttribute("searchForm", new InsecureSearchForm());
return "search";
}
model.addAttribute("searchForm", new SecureSearchForm());
model.addAttribute("secure", "Secure");
return "search";
}
@RequestMapping(value = "/search", params = "Secure", method = RequestMethod.POST)
public String search(@RequestParam(required=false, value="Secure") String secure,
@ModelAttribute("searchForm") @Valid SecureSearchForm searchForm, BindingResult result,
Model model){
if (!result.hasErrors()){
model.addAttribute("searchText", searchForm.getSearch());
List<Applicant> applicants = applicantRepository.searchApplicants(searchForm.getSearch());
model.addAttribute("applicants", applicants);
}
model.addAttribute("secure", "Secure");
return "search";
}
@RequestMapping(value = "/search", params = "Insecure", method = RequestMethod.POST)
public String InsecureSearch(@ModelAttribute("searchForm") InsecureSearchForm searchForm, Model model){
model.addAttribute("searchText", searchForm.getSearch());
List<Applicant> applicants = applicantRepository.searchApplicants(searchForm.getSearch());
model.addAttribute("applicants", applicants);
model.addAttribute("secure", "Insecure");
return "search";
}
}
| true |
77b7d42711bb52e9d7f157d17d67474155359163 | Java | isriram/train-ticket | /src/main/java/net/sriramiyer/train/Main.java | UTF-8 | 490 | 1.992188 | 2 | [] | no_license | package net.sriramiyer.train;
public class Main {
public static void main(String[] args){
Loader loader = new Loader();
loader.readFromFile();
loader.readInputsForTesting();
loader.writeCostsToFile();
/*try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("output.txt"))) {
bufferedWriter.write("This is a sample sentence");
} catch (IOException e) {
e.printStackTrace();
} */
}
}
| true |
ee418db6ab7008ea371b2026cc7dcc90c6fdfad5 | Java | filipebastos/taskmanager | /taskmanager/taskmanager-core/src/main/java/com/taskmanager/repository/UserRepository.java | UTF-8 | 668 | 2.625 | 3 | [
"MIT"
] | permissive | package com.taskmanager.repository;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.taskmanager.domain.User;
public class UserRepository {
private static final UserRepository INSTANCE = new UserRepository();
private List<User> list = new ArrayList<>();
private UserRepository() {
}
public static UserRepository getInstance() {
return INSTANCE;
}
public void add(User user) {
list.add(user);
}
public void remove(User user) {
list.remove(user);
}
public User get(User user) {
int index = list.indexOf(user);
return list.get(index);
}
public Collection<User> listAll() {
return list;
}
}
| true |
b9b28b63f8af472ab37f88f67ca9eff03f87b59b | Java | TergBug/hw9 | /src/main/java/org/mycode/behavioral/mediator/Demo.java | UTF-8 | 542 | 2.3125 | 2 | [] | no_license | package org.mycode.behavioral.mediator;
public class Demo {
public static void main(String[] args) {
CircleDock dock = new CircleDock();
Spaceship bigSpaceship = new BigSpaceship(dock);
Spaceship smallSpaceship = new SmallSpaceship(dock);
dock.setSpaceship1(bigSpaceship);
dock.setSpaceship2(smallSpaceship);
bigSpaceship.sendRequestToConnect();
bigSpaceship.sendRequestToConnect();
bigSpaceship.sendRequestToConnect();
bigSpaceship.sendRequestToConnect();
}
}
| true |
0d4687aeb99007538aa0e1db888ca4180aaca6cd | Java | pftx/niolex-network-nio | /network-name/src/test/java/org/apache/niolex/network/name/demo/NameServerDemo.java | UTF-8 | 1,261 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | /**
* NameServerDemo.java
*
* Copyright 2012 Niolex, Inc.
*
* Niolex licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.apache.niolex.network.name.demo;
import java.io.IOException;
import org.apache.niolex.network.name.server.MasterNameServer;
/**
* @author <a href="mailto:xiejiyun@gmail.com">Xie, Jiyun</a>
* @version 1.0.0
* @since 2012-6-27
*/
public class NameServerDemo {
private static MasterNameServer name;
/**
* The Server Demo
* @param args
*/
public static void main(String[] args) throws IOException {
name = new MasterNameServer();
name.setPort(8181);
name.setDeleteTime(10000);
name.start();
}
public static void stop() {
name.stop();
}
}
| true |
ac416fe84cc2548c628b22a3e615dd54bc79977c | Java | spartalex/geekweb | /src/test/java/ru/geekbrains/lesson6/PageObjectTest.java | UTF-8 | 1,881 | 2 | 2 | [] | no_license | package ru.geekbrains.lesson6;
import io.qameta.allure.Description;
import io.qameta.allure.Story;
import io.qameta.allure.TmsLink;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import static org.hamcrest.MatcherAssert.assertThat;
import static ru.geekbrains.lesson8.CreateExpenseTestDataElements.baseCreateExpenseData;
import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.isDisplayed;
@Story("Заявки на расходы")
public class PageObjectTest extends BaseTest {
@Test
@Description("Тест логина и создания заявки на расход")
@TmsLink("234")
void loginInCrmWithPageObjTest() throws InterruptedException {
driver.get("https://crm.geekbrains.space/");
new LoginPage(driver)
.fillInputLogin("Applanatest1")
.fillInputPassword("Student2020!")
.clickLoginButton()
.navigationMenu.openNavigationMenuItem("Расходы");
new ExpensesSubMenu(driver).goToExpensesRequestsPage();
new ExpensesRequestsPage(driver)
.createExpense()
.fillName("test")
.selectBusinessUnit("Research & Development")
.selectExpenditure("01101 - ОС: вычислительная техника инфраструктуры")
.selectCurrency("Доллар США")
.fillSumPlan("1000")
.selectDatePlan(baseCreateExpenseData.getDate())
.saveAndCloseButton.click();
webDriverWait.until(
ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[contains(text(),'Загрузка')]")));
assertThat(new CreateExpensePage(driver).requestSavedSuccessfullyElement, isDisplayed());
}
}
| true |
72cb54ef463c501ffe02ea340603e1d3a92ecbc8 | Java | akanshamehta17/Gumball-Machine | /Part 1/Main.java | UTF-8 | 1,155 | 3.359375 | 3 | [] | no_license | import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(25);
list.add(5);
list.add(10);
GumballMachine gumballMachine1 = new GumballMachine(5,25,list);
GumballMachine gumballMachine2 = new GumballMachine(5,50,list);
GumballMachine gumballMachine3 = new GumballMachine(5,50,list);
System.out.println(gumballMachine1);
gumballMachine1.insertMoney( 25 );
gumballMachine1.turnCrank();
System.out.println(gumballMachine2);
gumballMachine2.insertMoney( 25 );
gumballMachine2.turnCrank();
gumballMachine2.insertMoney( 25 );
gumballMachine2.turnCrank();
System.out.println(gumballMachine3);
gumballMachine3.insertMoney( 10 );
gumballMachine3.turnCrank();
gumballMachine3.insertMoney( 25 );
gumballMachine3.turnCrank();
gumballMachine3.insertMoney( 10 );
gumballMachine3.turnCrank();
gumballMachine3.insertMoney( 5 );
gumballMachine3.turnCrank();
}
}
| true |
a197023312931844b8fa4797d248c2f576ecbe74 | Java | sureshakella/crack-code | /src/main/java/fornow/linkedlist/GetNthNodeFromLast.java | UTF-8 | 1,354 | 3.640625 | 4 | [] | no_license | package fornow.linkedlist;
import java.util.Random;
import static java.util.Objects.nonNull;
public class GetNthNodeFromLast {
static class Node<T> {
T item;
Node<T> next;
Node(T item) {
this.item = item;
}
}
public static void main(String[] args) {
Node<Integer> root = new Node<>(1);
Node<Integer> tail = root;
Random rand = new Random();
for(int i=0; i<10; i++) {
tail.next = new Node<>(rand.nextInt(20) + 1);
tail = tail.next;
}
printList(root);
System.out.println();
System.out.println(getNthNodeFromLast(root, 1).item);
System.out.println(getNthNodeFromLast(root, 2).item);
System.out.println(getNthNodeFromLast(root, 3).item);
}
private static <T> Node<T> getNthNodeFromLast(Node<T> root, int position) {
Node<T> fast = root;
Node<T> slow = root;
int cnt = 1;
while (nonNull(fast )) {
fast = fast.next;
if(cnt > position) {
slow = slow.next;
}
cnt++;
}
return slow;
}
private static void printList(Node<Integer> root) {
while(nonNull(root)) {
System.out.print(root.item + "==>");
root = root.next;
}
}
}
| true |