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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
86b392cda96a35c456855bbf9fb8da519e01cce6
|
Java
|
zcc888/Java9Source
|
/jdk.javadoc/com/sun/tools/doclets/internal/toolkit/taglets/BaseInlineTaglet.java
|
UTF-8
| 845
| 2.0625
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.tools.doclets.internal.toolkit.taglets;
/**
* An abstract inline taglet that outputs HTML.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @author Jamie Ho
* @since 1.4
*/
@Deprecated
public abstract class BaseInlineTaglet extends BaseTaglet {
/**
* Will return true since this is an inline tag.
* @return true since this is an inline tag.
*/
public boolean isInlineTag() {
return true;
}
}
| true
|
18ea8a24d91e6f4b2bc5c4501f6d8b24a75e3f2a
|
Java
|
jainamgala321/EnglishErudition-master
|
/app/src/main/java/com/example/alienware/englisherudition/LeaderboardAdapter.java
|
UTF-8
| 1,904
| 2.40625
| 2
|
[] |
no_license
|
package com.example.alienware.englisherudition;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Vector;
/**
* Created by Alienware on 28-02-2017.
*/
public class LeaderboardAdapter extends RecyclerView.Adapter<LeaderboardAdapter.TheViewHolder>{
private List<JSONObject> userList;
public LeaderboardAdapter(List<JSONObject> userList) {
this.userList = userList;
}
public class TheViewHolder extends RecyclerView.ViewHolder {
public TextView name, user_name,score;
public TheViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.Leaderboard_name);
user_name = (TextView) view.findViewById(R.id.Leaderboard_username);
score = (TextView)view.findViewById(R.id.Leaderboard_score);
}
}
@Override
public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.leader_card, parent, false);
return new TheViewHolder(view);
}
@Override
public void onBindViewHolder(TheViewHolder holder, int position) {
JSONObject jsonObject = userList.get(position);
try {
holder.name.setText(jsonObject.getString("nameOfUser"));
holder.user_name.setText(jsonObject.getString("user_name"));
holder.score.setText(jsonObject.getString("score"));
}catch (JSONException je){je.printStackTrace();}
}
@Override
public int getItemCount() {
return userList.size();
}
}
| true
|
e14dd99a84592a61e8d1fcf682ef70d76c37f954
|
Java
|
chrisstrive/eoms
|
/eoms-shecc-deploy/com-shecc-eoms-web/src/main/java/com/shecc/eoms/web/common/ValTemplate.java
|
UTF-8
| 2,923
| 2
| 2
|
[] |
no_license
|
package com.shecc.eoms.web.common;
/**
*
* USER ray ray1192@163.com
* DATE 2014-2-11 下午03:35:52
* INFO com.shecc.eoms.web.common ValTemplate.java
* REMARK 值模板
*
*/
public class ValTemplate {
public static final String V_T_USER_NAME="userName";
public static final String V_T_USER_PWD="userPwd";
public static final String V_T_KEY_MSG_CODE="kmc";
public static final String V_T_KEY_MSG_RMK="kmr";
public static final String V_T_VAL_MSG_CODE_0000="0000";
public static final String V_T_VAL_MSG_CODE_0001="0001";
public static final String V_T_VAL_MSG_CODE_0002="0002";
public static final String V_T_VAL_MSG_CODE_0003="0003";
public static final String V_T_VAL_MSG_CODE_0004="0004";
public static final String V_T_VAL_MSG_CODE_0005="0005";
public static final String V_T_VAL_MSG_CODE_0006="0006";
public static final String V_T_VAL_MSG_CODE_0007="0007";
public static final String V_T_VAL_MSG_CODE_0008="0008";
public static final String V_T_VAL_MSG_CODE_0009="0009";
public static final String V_T_VAL_MSG_CODE_0010="0010";
public static final String V_T_VAL_MSG_CODE_0011="0011";
public static final String V_T_VAL_MSG_CODE_0012="0012";
public static final String V_T_VAL_MSG_CODE_0013="0013";
public static final String V_T_VAL_MSG_CODE_0014="0014";
public static final String V_T_VAL_MSG_CODE_0015="0015";
public static final String V_T_VAL_MSG_CODE_ERROR = "ERROR";
public static final String V_T_VAL_MSG_RMK_0000="完成";
public static final String V_T_VAL_MSG_RMK_0001="未完成";
public static final String V_T_VAL_MSG_RMK_0002="创建失败,当前用户已存在。";
public static final String V_T_VAL_MSG_RMK_0003="创建失败,用户已有绑定角色。";
public static final String V_T_VAL_MSG_RMK_0004="系统中存在一条未完成的修改记录。";
public static final String V_T_VAL_MSG_RMK_0005="该分类存在子分类信息,不允许删除。";
public static final String V_T_VAL_MSG_RMK_0006="该分类存在关联合作机构,不允许删除。";
public static final String V_T_VAL_MSG_RMK_0007="该区域存在下级区域,不允许删除。";
public static final String V_T_VAL_MSG_RMK_0008="该区域有商圈存在,不允许删除。";
public static final String V_T_VAL_MSG_RMK_0009="该区域有关联合作机构,不允许删除。";
public static final String V_T_VAL_MSG_RMK_0010="更新密码失败,系统中不存在该用户!";
public static final String V_T_VAL_MSG_RMK_0011="更新密码失败,原始密码输入错误!";
public static final String V_T_VAL_MSG_RMK_0012="添加错误,系统存在该关联关系!";
public static final String V_T_VAL_MSG_RMK_0013="订单创建失败!";
public static final String V_T_VAL_MSG_RMK_0014="获取订单号失败!";
public static final String V_T_VAL_MSG_RMK_0015="发送订单失败!";
public static final String V_T_VAL_MSG_RMK_ERROR = "操作错误";
}
| true
|
516582b7a53645867f758e2d6e2b509a8bf045bc
|
Java
|
countd/bus-query
|
/uk/ac/bradford/pisoc/UnableToContactServerException.java
|
UTF-8
| 221
| 2.234375
| 2
|
[] |
no_license
|
package uk.ac.bradford.pisoc;
public class UnableToContactServerException extends Exception {
public UnableToContactServerException() {
super();
}
public UnableToContactServerException(String s) {
super(s);
}
}
| true
|
420e8be5b2756ec0fdd94abf99f0395349c4ee0b
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/12/12_97257b9aae7116da7ecc144c249b3841801742a2/MonteCarloModel/12_97257b9aae7116da7ecc144c249b3841801742a2_MonteCarloModel_t.java
|
UTF-8
| 3,260
| 2.671875
| 3
|
[] |
no_license
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cz.paulrz.montecarlo;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.exception.ConvergenceException;
import org.apache.commons.math.random.NormalizedRandomGenerator;
/**
* This class implements Monte Carlo model. It provides constructs paths,
* evaluate them and collect statistics.
*
*/
public class MonteCarloModel<TValue> {
private final Accumulator<TValue> summary;
private final PathGenerator pathGenerator;
private final PathValuation<TValue> pathValuation;
/**
* Constructor of Monte Carlo model
*
* @param random Underlying random number generator
* @param process Underlying stochastic process
* @param duration Duration of paths in time units
* @param timeSteps Path discretization time step
* @param valuation Path valuation function
* @param statistics Statistics summary
*/
public MonteCarloModel(NormalizedRandomGenerator random,
GenericProcess process, double duration, int timeSteps,
PathValuation<TValue> valuation, Accumulator<TValue> statistics) {
this.summary = statistics;
this.pathGenerator = new PathGenerator(process, timeSteps, duration,
random);
this.pathValuation = valuation;
}
/**
* Adds path samples to statistics
*
* @param samples Number of paths to add
*/
public int addSamples(int samples) throws FunctionEvaluationException {
for (int i = 0; i < samples; ++i) {
Path path = pathGenerator.next();
TValue pathValue = pathValuation.value(path);
summary.addValue(pathValue);
}
return samples;
}
public int addSamples(int minSamples, double eps, int maxSteps) throws FunctionEvaluationException {
addSamples(minSamples);
Accumulator<TValue> prev = summary.clone();
int steps = 1;
while(steps==1 || summary.norm(prev) > eps) {
addSamples(minSamples);
prev = summary.clone();
steps++;
if (steps>maxSteps)
throw new ConvergenceException();
}
return steps*minSamples;
}
/**
* Gets statistics summary
*
* @return Statistics summary
*/
public Accumulator<TValue> getStats() {
return summary;
}
}
| true
|
df0ef706066ceb9a3bec7e724a9bc498d0db9af6
|
Java
|
al4fun/CountdownView
|
/app/src/main/java/cn/szx/countdownviewsample/MainActivity.java
|
UTF-8
| 1,011
| 2.390625
| 2
|
[] |
no_license
|
package cn.szx.countdownviewsample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
FrameLayout fl_container = findViewById(R.id.fl_container);
CountdownView.Listener listener = new CountdownView.Listener() {
@Override
public void onFinished() {
Toast.makeText(MainActivity.this, "计时结束", Toast.LENGTH_SHORT).show();
}
};
CountdownView countdownView = new CountdownView(this, 10, listener)
.setSize(400, 400)
.setStrokeWidth(20)
.setTextsize(200);
fl_container.addView(countdownView);
}
}
| true
|
7582f6481aa49d696bb4a5c2bc57c0fbfeb83874
|
Java
|
johnmwai/Joomla-Extension-Factory
|
/src/html/html32TreeConstants.java
|
UTF-8
| 3,222
| 1.507813
| 2
|
[] |
no_license
|
/* Generated By:JavaCC: Do not edit this line. html32TreeConstants.java Version 5.0 */
package html;
public interface html32TreeConstants
{
public int JJTERROR_SKIPTO = 0;
public int JJTPCDATA = 1;
public int JJTATTRIBUTE = 2;
public int JJTATTLIST = 3;
public int JJTVOID = 4;
public int JJTTT = 5;
public int JJTI = 6;
public int JJTB = 7;
public int JJTU = 8;
public int JJTSTRIKE = 9;
public int JJTBIG = 10;
public int JJTSMALL = 11;
public int JJTSUB = 12;
public int JJTSUP = 13;
public int JJTEM = 14;
public int JJTSTRONG = 15;
public int JJTDFN = 16;
public int JJTCODE = 17;
public int JJTSAMP = 18;
public int JJTKBD = 19;
public int JJT_VAR = 20;
public int JJTCITE = 21;
public int JJTFONT = 22;
public int JJTBASEFONT = 23;
public int JJTBR = 24;
public int JJTBODY = 25;
public int JJTADDRESS = 26;
public int JJTDIV = 27;
public int JJTCENTER = 28;
public int JJTA = 29;
public int JJTMAP = 30;
public int JJTAREA = 31;
public int JJTLINK = 32;
public int JJTIMG = 33;
public int JJTAPPLET = 34;
public int JJTPARAM = 35;
public int JJTHR = 36;
public int JJTP = 37;
public int JJTH1 = 38;
public int JJTH2 = 39;
public int JJTH3 = 40;
public int JJTH4 = 41;
public int JJTH5 = 42;
public int JJTH6 = 43;
public int JJTPRE = 44;
public int JJTBLOCKQUOTE = 45;
public int JJTDL = 46;
public int JJTDT = 47;
public int JJTDD = 48;
public int JJTOL = 49;
public int JJTUL = 50;
public int JJTDIR = 51;
public int JJTMENU = 52;
public int JJTLI = 53;
public int JJTFORM = 54;
public int JJTINPUT = 55;
public int JJTSELECT = 56;
public int JJTOPTION = 57;
public int JJTTEXTAREA = 58;
public int JJTTABLE = 59;
public int JJTTR = 60;
public int JJTTH = 61;
public int JJTTD = 62;
public int JJTCAPTION = 63;
public int JJTHEAD = 64;
public int JJTTITLE = 65;
public int JJTISINDEX = 66;
public int JJTBASE = 67;
public int JJTMETA = 68;
public int JJTSTYLE = 69;
public int JJTSCRIPT = 70;
public int JJTHTML = 71;
public String[] jjtNodeName = {
"error_skipto",
"pcdata",
"attribute",
"attlist",
"void",
"tt",
"i",
"b",
"u",
"strike",
"big",
"small",
"sub",
"sup",
"em",
"strong",
"dfn",
"code",
"samp",
"kbd",
"_var",
"cite",
"font",
"basefont",
"br",
"body",
"address",
"div",
"center",
"a",
"map",
"area",
"link",
"img",
"applet",
"param",
"hr",
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"pre",
"blockquote",
"dl",
"dt",
"dd",
"ol",
"ul",
"dir",
"menu",
"li",
"form",
"input",
"select",
"option",
"textarea",
"table",
"tr",
"th",
"td",
"caption",
"head",
"title",
"isindex",
"base",
"meta",
"style",
"script",
"html",
};
}
/* JavaCC - OriginalChecksum=9b5bc6c81c50a73573d06640eec2652f (do not edit this line) */
| true
|
dd72bdfab063f7eaf3c26eac099a8b173eeb9c25
|
Java
|
expodecay/Introduction_to_Java_Programming
|
/src/chapter_2/ComputeLoan.java
|
UTF-8
| 1,590
| 4.53125
| 5
|
[] |
no_license
|
package chapter_2;
/**
* pg. 61
* Created by Rick on 6/27/2015.
* This program computes loan payments. The user enters the interest rate, loan amount, and the number of years for
* which the payments will be made. It will then compute and display the monthly payment and total payment amounts.
*/
import java.util.Scanner;
public class ComputeLoan
{
public static void main(String[] args)
{
// create a scanner
Scanner input = new Scanner(System.in);
// Enter annual interest rate
System.out.print("Enter annual interest rate, e.g., 7.25: ");
double annualInterestRate = input.nextDouble();
// Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
// Enter number of years
System.out.print("Enter the number of years as an integet, e.g., 5: ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print("Enter loan amount, e.g., 120000.95: ");
double loanAmount = input.nextDouble();
// Calculate payment (Given in the textbook)
double monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1/ Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;
// Display results using "casting" to produce two decimal places
System.out.println("The monthly payment is $" + (int)(monthlyPayment * 100) / 100.0);
System.out.println("The total payment is $" + (int)(totalPayment * 100) / 100.0);
}
}
| true
|
17de597ec29097db220b94089c06b3adb9b28d3e
|
Java
|
amith2233/java-programming-1
|
/q5.java
|
UTF-8
| 941
| 3.375
| 3
|
[] |
no_license
|
class Complex
{
double real;
double img;
void set(double real,double img)
{
this.real=real;
this.img=img;
}
void display(Complex c6)
{
if(c6.img>0)
{
System.out.println(c6.real+"+"+c6.img+"i");
}
else
{
System.out.print(c6.real);
System.out.print(c6.img+"i"+"\n");
}
}
void add(Complex c)
{
Complex temp=new Complex();
temp.real=real+c.real;
temp.img=img+c.img;
this.display(temp);
}
void subtract(Complex c1)
{
Complex temp1=new Complex();
temp1.real=real-c1.real;
temp1.img=img-c1.img;
this.display(temp1);
}
void multiply(Complex c3)
{
Complex temp2=new Complex();
temp2.real=real*c3.real-img*c3.img;
temp2.img=img*c3.real+real*c3.img;
this.display(temp2);
}
}
public class TestComplex
{
public static void main (String[] args) {
Complex c1=new Complex();
Complex c2=new Complex();
c1.set(-1,2);
c2.set(3,4);
c1.add(c2);
c1.subtract(c2);
c1.multiply(c2);
}
}
| true
|
01d0324a0d47384b0fd0e240abda33bd220db3ce
|
Java
|
MarinaShaposhnikova/Barcode
|
/app/src/main/java/com/google/android/gms/samples/vision/barcodereader/splash/Splash.java
|
UTF-8
| 970
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) Marina Meier, The Bachelor Degree
*/
package com.google.android.gms.samples.vision.barcodereader.splash;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.samples.vision.barcodereader.MainActivity;
import com.google.android.gms.samples.vision.barcodereader.R;
public class Splash extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread t = new Thread() {
public void run() {
try {
sleep(2000);
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
| true
|
423b70201ed2a3d2f1f730086d51bb19cb7c71e3
|
Java
|
Frayo44/SmartPijam
|
/PijamaSan/app/src/main/java/pijama/com/pijamasan/Server/PijamServerr.java
|
UTF-8
| 2,034
| 2.25
| 2
|
[] |
no_license
|
package pijama.com.pijamasan.Server;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Yoav on 8/23/2015.
*/
public class PijamServerr {
public void sendTemprature(String temprature)
{
JSONObject jsonObject = null;
try {
new Request("/sendtemp", temprature).execute();
} catch (Exception e) {}
}
public void sendConnected()
{
JSONObject jsonObject = null;
try {
new Request("/connected", null).execute();
} catch (Exception e) {}
}
private static class Request extends AsyncTask<String, String, JSONObject> {
String request;
String temp;
public Request(String request, String temp) {
this.request = request;
this.temp = temp;
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser json = new JSONParser();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("Loggggggggg", Consts.REQUEST_PREFIX + "" + request);
if(temp != null)
params.add(new BasicNameValuePair("temp", temp));
JSONObject jObj = json.getJSONFromUrl(Consts.REQUEST_PREFIX + "" + request, params);
return jObj;
}
@Override
protected void onPostExecute(JSONObject json) {
}
}
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
}
| true
|
f9c80d6a7daf0566a8a0277c7a528c6443636ca8
|
Java
|
kashish97/Test_App-master-master
|
/app/src/main/java/in/codecorp/myapplication/Response/TestSubjectResponse.java
|
UTF-8
| 678
| 1.960938
| 2
|
[] |
no_license
|
package in.codecorp.myapplication.Response;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import in.codecorp.myapplication.Utils.TestSubjects;
public class TestSubjectResponse extends BaseResponse {
@SerializedName("data")
private List<Object> data;
@SerializedName("records")
private List<TestSubjects> records;
public List<Object> getData() {
return data;
}
public void setData(List<Object> data) {
this.data = data;
}
public List<TestSubjects> getRecords() {
return records;
}
public void setRecords(List<TestSubjects> records) {
this.records = records;
}
}
| true
|
1d8f15d2dce2d10561d37a3cc4a65f189e8e85a5
|
Java
|
MaxRobinson/Starcraft-AI
|
/src/unitTests/ProductionManagerTest.java
|
UTF-8
| 572
| 1.835938
| 2
|
[] |
no_license
|
package unitTests;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Hashtable;
import org.junit.Test;
import StarcraftAI.ProductionManager;
import bwapi.*;
import bwapi.UnitType;
public class ProductionManagerTest {
@Test
public void testExaminePath() {
fail("Not yet implemented");
}
@Test
public void testInitTechPaths() {
// Hashtable<UnitType, ArrayList<UnitType>> results = ProductionManager.initTechPaths();
assertEquals(true, true);
}
@Test
public void testBuildDependecies() {
fail("Not yet implemented");
}
}
| true
|
0880340964cf657e5e8f0262132d463f16c28226
|
Java
|
GustavDahlman/shopDatabase
|
/src/db_connect/PgTest3.java
|
UTF-8
| 661
| 2.375
| 2
|
[] |
no_license
|
package db_connect;
import java.sql.*;
import java.util.*;
public class PgTest3 {
private static String adress = "jdbc:postgresql://localhost/postgres";
private static String username = "postgres";
private static String password = "123";
//"jdbc:postgresql://localhost/postgres?user=postgres&password=123&ssl=false"
public static void main(String[] args) throws Exception {
Class.forName("org.postgresql.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres?user=postgres&password=123&ssl=false");
System.out.println("connected");
conn.close();
}
}
| true
|
40ca3ecc89b362a064dc821fb1983a8f17b6b2d8
|
Java
|
mzzdxt/ViewPager-RecyclerView
|
/lib.homepage/src/main/java/com/coderwjq/lib/homepage/fragment/HomePageFragment.java
|
UTF-8
| 11,128
| 1.992188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.coderwjq.lib.homepage.fragment;
import android.graphics.Rect;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.coderwjq.lib.homepage.R;
import com.coderwjq.lib.homepage.base.BaseFragment;
import com.coderwjq.lib.homepage.common.Constant;
import com.coderwjq.lib.homepage.manager.HomePageManager;
import com.coderwjq.lib.homepage.manager.SmoothScrollLayoutManager;
import com.coderwjq.lib.homepage.view.EmptySearchBar;
import com.coderwjq.lib.homepage.view.HomeRecyclerView;
import com.coderwjq.lib.homepage.view.NewsViewPager;
import java.util.ArrayList;
import java.util.List;
/**
* @author: wangjiaqi
* @data: 2018/1/12
*/
public class HomePageFragment extends BaseFragment {
private static final String TAG = "HomePageFragment";
private HomeRecyclerView mRvHomePage;
private TabLayout mTlNewsTitle;
private SmoothScrollLayoutManager mLayoutManager;
private HomePageAdapter mHomePageAdapter;
private int mBottomViewPagerHeight;
public HomeRecyclerView getRvHomePage() {
return mRvHomePage;
}
@Override
protected int getLayoutId() {
return R.layout.fragment_home_page;
}
@Override
protected void initView(View rootView) {
mTlNewsTitle = rootView.findViewById(R.id.tl_news_title);
mRvHomePage = rootView.findViewById(R.id.rv_home_page);
mHomePageAdapter = new HomePageAdapter();
mLayoutManager = new SmoothScrollLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
mRvHomePage.setLayoutManager(mLayoutManager);
mRvHomePage.setAdapter(mHomePageAdapter);
mRvHomePage.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
mRvHomePage.addOnScrollListener(mOnScrollListener);
}
private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE && mTlNewsTitle.getVisibility() == View.VISIBLE) {
View view = mLayoutManager.findViewByPosition(mHomePageAdapter.getItemCount() - 1);
if (view != null) {
if (view.getY() <= Constant.TITLE_SHOW_RANGE) {
Log.i(TAG, "onScrollStateChanged: 自动吸顶");
mLayoutManager.smoothScrollToPosition(mRvHomePage, null, mHomePageAdapter.getItemCount() - 1);
// mRvHomePage.scrollBy(0, (int) (Constant.TITLE_SHOW_RANGE - view.getY()));
}
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
View view = mLayoutManager.findViewByPosition(mHomePageAdapter.getItemCount() - 1);
if (view != null) {
if (view.getY() <= Constant.TITLE_SHOW_RANGE) {
mTlNewsTitle.setVisibility(View.VISIBLE);
mTlNewsTitle.setAlpha((Constant.TITLE_SHOW_RANGE - view.getY()) / (Constant.TITLE_SHOW_RANGE - mTlNewsTitle.getHeight()));
} else {
mTlNewsTitle.setVisibility(View.GONE);
mTlNewsTitle.setAlpha(0);
}
}
}
};
class HomePageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HOME_PAGE_ITEM_COUNT = 10;
private NewsPagerAdapter mNewsPagerAdapter;
private NewsViewHolder mNewsViewHolder;
private EmptySearchBar mEmptySearchBar;
public EmptySearchBar getEmptySearchBar() {
return mEmptySearchBar;
}
public NewsViewHolder getNewsViewHolder() {
return mNewsViewHolder;
}
public HomePageAdapter() {
mEmptySearchBar = new EmptySearchBar(mContext);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
// 普通item
return new NormalViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_home_page_normal, null));
} else if (viewType == 2) {
return new SearchBarViewHolder(mEmptySearchBar);
} else {
Log.i(TAG, "onCreateViewHolder: 创建新闻ViewHolder");
return new NewsViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_home_page_news, null));
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof NormalViewHolder) {
NormalViewHolder holder = (NormalViewHolder) viewHolder;
holder.mTvContent.setText("item: " + position);
} else if (viewHolder instanceof NewsViewHolder) {
Log.i(TAG, "onBindViewHolder: 绑定新闻ViewHolder");
NewsViewHolder holder = (NewsViewHolder) viewHolder;
mNewsViewHolder = holder;
if (mNewsPagerAdapter == null) {
mNewsPagerAdapter = new NewsPagerAdapter(getChildFragmentManager());
}
holder.mVpContainer.setAdapter(mNewsPagerAdapter);
mTlNewsTitle.setupWithViewPager(holder.mVpContainer);
mTlNewsTitle.getTabAt(0).setText("文本新闻");
mTlNewsTitle.getTabAt(1).setText("视频新闻");
// 设置ViewPager滚动监听
holder.mVpContainer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
HomePageManager.getInstance().setCurrentChannel(mNewsPagerAdapter.getItem(position));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
calcNewsViewHolder(false);
}
}
@Override
public int getItemCount() {
return HOME_PAGE_ITEM_COUNT;
}
@Override
public int getItemViewType(int position) {
if (position < HOME_PAGE_ITEM_COUNT - 1 && position != 1) {
return 0;
} else if (position == 1) {
return 2;
} else {
return 1;
}
}
class SearchBarViewHolder extends RecyclerView.ViewHolder {
public SearchBarViewHolder(View itemView) {
super(itemView);
}
}
class NormalViewHolder extends RecyclerView.ViewHolder {
private final TextView mTvContent;
private final LinearLayout mLlContainer;
public NormalViewHolder(View itemView) {
super(itemView);
mTvContent = itemView.findViewById(R.id.tv_content);
mLlContainer = itemView.findViewById(R.id.ll_container);
mLlContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, mTvContent.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
class NewsViewHolder extends RecyclerView.ViewHolder {
private final NewsViewPager mVpContainer;
public NewsViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "NewsViewHolder: 创建新闻的ViewHolder");
mVpContainer = itemView.findViewById(R.id.vp_container);
}
}
class NewsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
public NewsPagerAdapter(FragmentManager fm) {
super(fm);
Log.d(TAG, "NewsPagerAdapter() called with: fm = [" + fm + "]");
mFragments.add(new TextNewsFragment());
mFragments.add(new VideoNewsFragment());
HomePageManager.getInstance().setCurrentChannel(mFragments.get(0));
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
}
public void calcNewsViewHolder(boolean isOritationChanged) {
HomePageAdapter.NewsViewHolder holder = mHomePageAdapter.getNewsViewHolder();
if (holder == null) {
Log.i(TAG, "calcNewsViewHolder: NewsViewHolder...null");
return;
}
DisplayMetrics dm = new DisplayMetrics();
mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
Log.e(TAG, "屏幕高度: " + dm.heightPixels);
int menuBarHeight = HomePageManager.getInstance().getMenuBarHeight();
Log.e(TAG, "菜单栏高度: " + menuBarHeight);
Log.e(TAG, "TabLayout高度: " + mTlNewsTitle.getMeasuredHeight());
//应用区域
Rect outRect1 = new Rect();
mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
// 状态栏高度 = 屏幕高度 - 应用区域高度
int statusBar = dm.heightPixels - outRect1.height();
Log.e(TAG, "状态栏高度: " + statusBar);
mBottomViewPagerHeight = dm.heightPixels - menuBarHeight - mTlNewsTitle.getMeasuredHeight() - statusBar;
// 设置ViewPager高度
ViewGroup.LayoutParams layoutParams = holder.mVpContainer.getLayoutParams();
layoutParams.height = mBottomViewPagerHeight;
Log.e(TAG, "ViewPager高度: " + mBottomViewPagerHeight);
holder.mVpContainer.setLayoutParams(layoutParams);
}
public void backToNormalState() {
HomePageManager.getInstance().setNormalMode();
if (mLayoutManager.findFirstCompletelyVisibleItemPosition() != 0) {
mRvHomePage.smoothScrollToPosition(0);
}
}
}
| true
|
a748de17e18d041e756f5bcfab868b6a166ca561
|
Java
|
davidsamueljones/LoRaSimulator
|
/src/main/java/ecs/soton/dsj1n15/smesh/model/lora/LoRaCfg.java
|
UTF-8
| 9,364
| 2.4375
| 2
|
[] |
no_license
|
package ecs.soton.dsj1n15.smesh.model.lora;
/**
* A full configuration for a LoRa radio with methods available for determining airtime using LoRa
* modulation consistent across all LoRa radios.
*
* @author David Jones (dsj1n15)
*/
public class LoRaCfg {
/*
* Coding rates
*/
public static final int CR_4_5 = 5;
public static final int CR_4_6 = 6;
public static final int CR_4_7 = 7;
public static final int CR_4_8 = 8;
/*
* Spreading factor limits
*/
public static final int MIN_SF = 6;
public static final int MAX_SF = 12;
/*
* 125kHz or 250kHz (1% duty cycle) - 14dBm
*/
public static final double BAND_G1_C0_MHZ = 868.1;
public static final double BAND_G1_C1_MHZ = 868.3;
public static final double BAND_G1_C2_MHZ = 868.5;
public static final double BAND_G_C3_MHZ = 867.1;
public static final double BAND_G_C4_MHZ = 867.3;
public static final double BAND_G_C5_MHZ = 867.5;
public static final double BAND_G_C6_MHZ = 867.7;
public static final double BAND_G_C7_MHZ = 867.9;
/*
* 125kHz or 250kHz (10% duty cycle) - 27dBm
*/
public static final double BAND_G3_MID_MHZ = 869.525;
private double freq;
private int sf;
private double txPow;
private int bw;
private int cr;
private int preambleSymbols;
private boolean crc;
private boolean explicitHeader;
/**
* @return The current centre frequency in MHz
*/
public double getFreq() {
return freq;
}
/**
* @param freq The new centre frequency in MHz
*/
public void setFreq(double freq) {
this.freq = freq;
}
/**
* @return The current LoRa spreading factor (chips = 2 ^ sf)
*/
public int getSF() {
return sf;
}
/**
* @param sf The new LoRa spreading factor (chips = 2 ^ sf)
*/
public void setSF(int sf) {
this.sf = sf;
}
/**
* @return The current transmission power in dBm
*/
public double getTxPow() {
return txPow;
}
/**
* @param txPow The new transmission power in dBm
*/
public void setTxPow(double txPow) {
this.txPow = txPow;
}
/**
* @param bw The new bandwidth in Hz
*/
public int getBW() {
return bw;
}
/**
* @param bw The new bandwidth in Hz
*/
public void setBW(int bw) {
this.bw = bw;
}
/**
* @return The current denominator for the coding rate. Actual CR = 4 / cr.
*/
public int getCR() {
return cr;
}
/**
* @param cr The new denominator for the coding rate. Actual CR = 4 / cr.
*/
public void setCR(int cr) {
this.cr = cr;
}
/**
* @return The current number of user programmable preamble symbols to send (actual -4.25)
*/
public int getPreambleSymbols() {
return preambleSymbols;
}
/**
* @param preambleSymbols The new number of user programmable preamble symbols to send (actual
* -4.25)
*/
public void setPreambleSymbols(int preambleSymbols) {
this.preambleSymbols = preambleSymbols;
}
/**
* @return Whether the CRC is enabled
*/
public boolean isCRC() {
return crc;
}
/**
* @param crc Whether the CRC should be enabled
*/
public void setCrc(boolean crc) {
this.crc = crc;
}
/**
* @return Whether the explicit header is enabled
*/
public boolean isExplicitHeader() {
return explicitHeader;
}
/**
* @param explicitHeader Whether the explicit header should be enabled
*/
public void setExplicitHeader(boolean explicitHeader) {
this.explicitHeader = explicitHeader;
}
/**
* Calculate packet airtime for this instance. <br>
* See {@link #calculatePacketAirtime(LoRaCfg cfg, int packetLen)}.
*
* @param packetLen Length of packet to send
* @return Total send time for packet in ms
*/
public int calculatePacketAirtime(int packetLen) {
return calculatePacketAirtime(this, packetLen);
}
/**
* Calculate preamble airtime for this instance. <br>
* See {@link #calculatePreambleTime(LoRaCfg cfg)}.
*
* @return Total send time for packet in ms
*/
public int calculatePreambleTime() {
return calculatePreambleTime(this);
}
/**
* Calculate the airtime for a full packet transmission for a given LoRa configuration and packet
* length. <br>
* All equations (modified for our formats) from: <a
* href=https://www.semtech.com/uploads/documents/LoraDesignGuide_STD.pdf>LoRa Design Guide</a>
*
* @param cfg LoRa configuration
* @param packetLen Length of packet to send
* @return Total send time for packet in ms
*/
public static int calculatePacketAirtime(LoRaCfg cfg, int packetLen) {
double symbolTime = getSymbolTime(cfg); // ms
double preambleTime = (cfg.preambleSymbols + 4.25) * symbolTime;
boolean ldr = isLDRRequired(cfg);
int pscTop = 8 * packetLen - 4 * cfg.sf + 28 + 16 - 20 * (cfg.explicitHeader ? 1 : 0);
int pscBot = 4 * (cfg.sf - 2 * (ldr ? 1 : 0));
int pscLHS = (int) Math.ceil(pscTop / pscBot);
int payloadSymbolCount = 8 + (Math.max(pscLHS * (cfg.cr), 0));
double payloadTime = payloadSymbolCount * symbolTime;
double totalTime = preambleTime + payloadTime;
return (int) Math.ceil(totalTime);
}
/**
* Calculate the preamble airtime for a given LoRa configuration. See
* {@link #calculatePacketAirtime(LoRaCfg cfg, int packetLen)} for full packet airtime calculation
* and equation reference.
*
* @param cfg LoRa configuration
* @return Send time for preamble in ms
*/
public static int calculatePreambleTime(LoRaCfg cfg) {
return (int) Math.ceil((cfg.preambleSymbols + 4.25) * getSymbolTime(cfg));
}
/**
* Sync requires 5 preamble symbols before sync and margin. Determine how long this is in ms.
* https://www.semtech.com/uploads/documents/an1200.23.pdf
*
* @param cfg LoRa configuration for determining timing
* @return Preamble time in ms
*/
public static int requiredPreambleTime(LoRaCfg cfg) {
return (int) Math.ceil((5 + 4.25) * getSymbolTime(cfg));
}
/**
* The symbol airtime for a given LoRa configuration.
*
* @param cfg LoRa configuration
* @return Send time for symbol in ms
*/
public static double getSymbolTime(LoRaCfg cfg) {
return 1000.0 * Math.pow(2, cfg.sf) / cfg.bw; // ms
}
/**
* Check if low data rate is required for this instance.<br>
* See {@link #sLDRRequired(LoRaCfg cfg)}.
*
* @return Whether LDR is required
*/
public boolean isLDRRequired() {
return isLDRRequired(this);
}
/**
* Check if low data rate is required. Value of 16.0 for symbol time required for enabling low
* data rate is copied from RadioHead library. No source provided but keep the same for
* consistency.
*
* @param cfg LoRa configuration to check.
* @return Whether LDR is required
*/
public static boolean isLDRRequired(LoRaCfg cfg) {
double symbol_time = 1000.0 * Math.pow(2, cfg.sf) / cfg.bw; // ms
return symbol_time > 16.0;
}
/**
* @return Profile configured for LoRaWAN D0
*/
public static LoRaCfg getDataRate0() {
LoRaCfg cfg = getDefault();
cfg.setSF(12);
return cfg;
}
/**
* @return Profile configured for LoRaWAN D1
*/
public static LoRaCfg getDataRate1() {
LoRaCfg cfg = getDefault();
cfg.setSF(11);
return cfg;
}
/**
* @return Profile configured for LoRaWAN D2
*/
public static LoRaCfg getDataRate2() {
LoRaCfg cfg = getDefault();
cfg.setSF(10);
return cfg;
}
/**
* @return Profile configured for LoRaWAN D3
*/
public static LoRaCfg getDataRate3() {
LoRaCfg cfg = getDefault();
cfg.setSF(9);
return cfg;
}
/**
* @return Profile configured for LoRaWAN D4
*/
public static LoRaCfg getDataRate4() {
LoRaCfg cfg = getDefault();
cfg.setSF(8);
return cfg;
}
/**
* @return Profile configured for LoRaWAN D5
*/
public static LoRaCfg getDataRate5() {
LoRaCfg cfg = getDefault();
cfg.setSF(7);
return cfg;
}
/**
* @return Profile configured for LoRaWAN D6
*/
public static LoRaCfg getDataRate6() {
LoRaCfg cfg = getDefault();
cfg.setSF(7);
cfg.setBW(250000);
return cfg;
}
/**
* Get LoRaWAN datarate via index (0-6).
*
* @param dr Datarate index.
* @return Created configuration for datarate
*/
public static LoRaCfg getDatarate(int dr) {
switch (dr) {
case 0:
return LoRaCfg.getDataRate0();
case 1:
return LoRaCfg.getDataRate1();
case 2:
return LoRaCfg.getDataRate2();
case 3:
return LoRaCfg.getDataRate3();
case 4:
return LoRaCfg.getDataRate4();
case 5:
return LoRaCfg.getDataRate5();
case 6:
return LoRaCfg.getDataRate6();
}
return null;
}
/**
* Default parameters, by default uses G3 ETSI band.
*
* @return Profile with default LoRaWAN configuration
*/
public static LoRaCfg getDefault() {
LoRaCfg cfg = new LoRaCfg();
cfg.setFreq(BAND_G3_MID_MHZ);
cfg.setPreambleSymbols(8);
cfg.setSF(MAX_SF);
cfg.setTxPow(14);
cfg.setBW(125000);
cfg.setCrc(true);
cfg.setExplicitHeader(true);
cfg.setCR(CR_4_5);
return cfg;
}
/**
* @return Get the LoRa chirp rate
*/
public double getChirpRate() {
double bw = this.bw / 1e6;
return (bw * bw) / Math.pow(2, sf);
}
}
| true
|
26233a5ff5e81b9f1dfc3c1f10b3e95c54d67b2f
|
Java
|
suifeng3051/myproject
|
/src/main/java/com/zitech/gateway/param/ObjectValidator.java
|
UTF-8
| 765
| 2.359375
| 2
|
[] |
no_license
|
package com.zitech.gateway.param;
import com.alibaba.fastjson.JSONObject;
import com.zitech.gateway.common.ParamException;
public class ObjectValidator implements IValidator {
@Override
public boolean v(Object object, Param param) {
if (!param.getRequired()) {
if (!(object == null || (object instanceof JSONObject)))
throw new ParamException(Constants.Code.PARAM_ERROR,
param.getName() + " should be an object or null");
} else {
if (object == null || !(object instanceof JSONObject))
throw new ParamException(Constants.Code.PARAM_ERROR,
param.getName() + " should be an object and not null");
}
return true;
}
}
| true
|
46327b7b4b640653cf67a96ddee19c588b9e84ac
|
Java
|
OpenConext/OpenConext-manage
|
/manage-server/src/test/java/manage/validations/BasicAuthenticationUsernameFormatValidatorTest.java
|
UTF-8
| 765
| 2.359375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package manage.validations;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BasicAuthenticationUsernameFormatValidatorTest {
private BasicAuthenticationUsernameFormatValidator subject = new BasicAuthenticationUsernameFormatValidator();
@Test
public void validate() throws Exception {
Optional<String> result = subject.validate(null);
assertTrue(result.isPresent());
result = subject.validate(" ");
assertTrue(result.isPresent());
result = subject.validate("http://test");
assertTrue(result.isPresent());
result = subject.validate("user");
assertFalse(result.isPresent());
}
}
| true
|
e92aa107b4e1e9efa7be0145564a303a70194c17
|
Java
|
RoOmuloO/Trabalho-Java-RM
|
/TrabalhoDaves_RM-e/src/java/model/dao/ReceitaDAO.java
|
UTF-8
| 1,200
| 2.390625
| 2
|
[] |
no_license
|
package model.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import model.Receita;
public class ReceitaDAO {
private EntityManager em;
private EntityManagerFactory emf;
public ReceitaDAO() {
emf = Persistence.createEntityManagerFactory("TrabalhoDavesPU");
em = emf.createEntityManager();
}
public EntityManager getEntityManager() {
return em;
}
public EntityManagerFactory getEntityManagerFactory() {
return emf;
}
public void salvar(Receita receita) {
em.getTransaction().begin();
em.persist(receita);
em.getTransaction().commit();
}
public List<Receita> findAll() {
Query q = em.createNamedQuery("Receita.findAll");
return q.getResultList();
}
public Receita findById(int id) {
Query q = em.createNamedQuery("Receita.findByIdreceita");
q.setParameter("idreceita", id);
try {
return (Receita) q.getSingleResult();
} catch (Exception e) {
return null;
}
}
}
| true
|
4d2658096f46875f8056c3f0a96f94e7524b2acc
|
Java
|
vijendra880/github-profile
|
/src/main/java/com/github/controller/ProfileController.java
|
UTF-8
| 1,569
| 2.0625
| 2
|
[] |
no_license
|
package com.github.controller;
import com.github.dto.ErrorResponse;
import com.github.dto.ProfileSearchHistoryDto;
import com.github.dto.ProfileRequestDto;
import com.github.dto.ProfileSearchResponseDto;
import com.github.service.ProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/v1/profile")
public class ProfileController {
@Autowired private ProfileService profileService;
@PostMapping
public ResponseEntity<ProfileSearchResponseDto> searchProfile(
@ModelAttribute ProfileRequestDto profileRequestDto) {
return new ResponseEntity<ProfileSearchResponseDto>(
profileService.searchProfile(profileRequestDto), HttpStatus.OK);
}
@GetMapping
public ResponseEntity<ProfileSearchHistoryDto> getSearchHistory(
@ModelAttribute ProfileRequestDto profileRequestDto) {
return new ResponseEntity<ProfileSearchHistoryDto>(
profileService.getSearchHistory(profileRequestDto.getUserId()), HttpStatus.OK);
}
// TODO- change it to @DeleteMapping
@GetMapping("/delete")
public ResponseEntity<ErrorResponse> deleteSearchHistory(
@ModelAttribute ProfileRequestDto profileRequestDto) {
profileService.deleteSearchHistory(
profileRequestDto.getUserId(), profileRequestDto.getHandle());
return new ResponseEntity(new ErrorResponse(), HttpStatus.OK);
}
}
| true
|
3d162fb7a7b5e31c79ccbc000c96514b2af646e0
|
Java
|
mynewworldyyl/jmicro
|
/api/src/main/java/cn/jmicro/api/net/RpcRequestJRso.java
|
UTF-8
| 5,737
| 1.640625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.jmicro.api.net;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import cn.jmicro.api.monitor.MC;
import cn.jmicro.api.registry.ServiceMethodJRso;
import lombok.Serial;
/**
*
* @author Yulei Ye
* @date 2018年10月4日-下午12:07:03
*/
@Serial
public final class RpcRequestJRso implements IRequest/*,ISerializeObject*/ {
protected Map<String, Object> params = new HashMap<String, Object>();
private Object[] args;
private int impl;
private String transport;
protected long reqId = -1L;
protected long reqParentId = -1L;
/*
* private transient String serviceName;
*
* private transient String method;
*
* private transient String namespace;
*
* private transient String version;
*/
private transient ISession session;
private transient boolean isMonitorEnable = false;
private transient Message msg;
private transient ServiceMethodJRso sm;
private transient boolean success = false;
private transient boolean finish = false;
public RpcRequestJRso() {
}
@SuppressWarnings("unchecked")
public <T> T getParam(String key, T defautl) {
T v = (T) this.params.get(key);
if (v == null) {
return defautl;
}
return v;
}
public int getLogLevel() {
if (msg != null) {
return msg.getLogLevel();
}
return MC.LOG_NO;
}
public Long getMsgId() {
if (this.msg != null) {
return this.msg.getMsgId();
}
// super.getFloat("", 33F);
return -1l;
}
public boolean isFinish() {
return finish;
}
public boolean needResponse() {
return this.msg.isNeedResponse();
}
public String getTransport() {
return transport;
}
public long getReqParentId() {
return reqParentId;
}
public void setReqParentId(long reqParentId) {
this.reqParentId = reqParentId;
}
public void setTransport(String transport) {
this.transport = transport;
}
public ServiceMethodJRso getSm() {
return sm;
}
public void setSm(ServiceMethodJRso sm) {
this.sm = sm;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean isSuccess) {
this.success = isSuccess;
}
public Message getMsg() {
return msg;
}
public void setMsg(Message msg) {
this.msg = msg;
}
public ISession getSession() {
return session;
}
public void setSession(ISession session) {
this.session = session;
}
@Override
public void setRequestId(long reqId) {
this.reqId = reqId;
}
@Override
public long getRequestId() {
return this.msg != null ? this.msg.getMsgId() : 0;
}
@Override
public int hashCode() {
return (int) reqId;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof RpcRequestJRso)) {
return false;
}
return reqId == ((RpcRequestJRso) obj).reqId;
}
public boolean isMonitorEnable() {
return isMonitorEnable;
}
public void setMonitorEnable(boolean isMonitorEnable) {
this.isMonitorEnable = isMonitorEnable;
}
public boolean containsParam(String key) {
if(this.params == null || this.params.isEmpty()) {
return false;
}
return this.params.containsKey(key);
}
@Override
public Map<String, Object> getRequestParams() {
return this.getParams();
}
public int getSvnHash() {
return impl;
}
public void setSnvHash(int impl) {
this.impl = impl;
}
public String getServiceName() {
return this.sm.getKey().getServiceName();
}
public String getNamespace() {
return this.sm.getKey().getNamespace();
}
public String getVersion() {
return this.sm.getKey().getVersion();
}
public String getMethod() {
return this.sm.getKey().getMethod();
}
public Object[] getArgs() {
return args;
}
public void setArgs(Object[] args) {
this.args = args;
}
public Map<String, Object> getParams() {
return this.params;
}
// public abstract ByteBuffer newBuffer();
public Integer getInt(String key, int defautl) {
return this.getParam(key, defautl);
}
public String getString(String key, String defautl) {
return this.getParam(key, defautl);
}
public Boolean getBoolean(String key, boolean defautl) {
return this.getParam(key, defautl);
}
public Float getFloat(String key, Float defautl) {
return this.getParam(key, defautl);
}
public Double getDouble(String key, Double defautl) {
return this.getParam(key, defautl);
}
public Object getObject(String key, Object defautl) {
return this.getParam(key, defautl);
}
public void putObject(String key, Object value) {
this.params.put(key, value);
}
@Override
public byte getProtocol() {
return this.msg.getUpProtocol();
}
@Override
public String toString() {
return "RpcRequest [params=" + params + ", args=" + Arrays.toString(args) + ", impl=" + impl + ", transport="
+ transport + ", reqId=" + reqId + ", reqParentId=" + reqParentId + "]";
}
@Override
public int getPacketSize() {
return msg != null ? msg.getLen() : 0;
}
}
| true
|
75aa058039562233d8882ad2b77d771ff971c753
|
Java
|
jvluso/VotingSimulator
|
/src/main/java/voting/systems/ElectionFactory.java
|
UTF-8
| 2,130
| 2.53125
| 3
|
[] |
no_license
|
package voting.systems;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import com.google.gson.Gson;
import voting.systems.ranked.Plurality;
import voting.systems.ranked.SingleTransferable;
import voting.systems.score.AtLarge;
import voting.systems.score.SequentialScore;
public class ElectionFactory {
public static List<Election> getElections() throws FileNotFoundException{
Gson gson = new Gson();
Reader reader = new FileReader("src/main/resources/Elections.json");
List<ElectionConfiguration> electionConfigs = Arrays.asList(gson.fromJson(reader, ElectionConfiguration[].class));
Reader defreader = new FileReader("src/main/resources/ElectionDefaults.json");
ElectionConfiguration def = gson.fromJson(defreader, ElectionConfiguration.class);
List<Election> elections = new LinkedList<Election>();
for(ElectionConfiguration ec:electionConfigs){
elections.add(getInstance(ec,def));
}
return elections;
}
public static Election getInstance(ElectionConfiguration config,ElectionConfiguration def){
config.withDefaults(def);
switch(config.type){
case AtLarge:
return new AtLarge(config.size);
case HypotheticalBestRunningCandidate:
return new HypotheticalBestRunningCandidate();
case HypotheticalDirectDemocracy:
return new HypotheticalDirectDemocracy();
case HypotheticalPerfectSingleWinner:
return new HypotheticalPerfectSingleWinner();
case Jury:
return new Jury(config.size);
case Plurality:
return new Plurality();
case SequentialScore:
return new SequentialScore(config.size);
case SingleTransferable:
return new SingleTransferable(config.size);
case WithCandidates:
return new WithCandidates(config.candidatePool,ElectionFactory.getInstance(config.system,def));
case WithDistricts:
return new WithDistricts(config.districts,ElectionFactory.getInstance(config.system,def));
default:
return null;
}
}
}
| true
|
76e1a1e1ecc47a54ed494f9d9c7620156151bd3d
|
Java
|
topfontes/FinanceSoluction
|
/i9Finance/src/java/br/com/i9/finance/client/i9finance/easyfin/v_conta_pagar_pago/V_conta_pagar_pagoUpdateDeleteGWT.java
|
UTF-8
| 6,167
| 1.632813
| 2
|
[] |
no_license
|
package br.com.i9.finance.client.i9finance.easyfin.v_conta_pagar_pago;
import br.com.i9.finance.client.Constantes;
import br.com.easynet.gwt.client.EasyAccessURL;
import br.com.easynet.gwt.client.EasyContainer;
import br.com.easynet.gwt.client.IListenetResponse;
import br.com.easynet.gwt.client.component.EasyTextField;
import br.com.i9.finance.client.i9finance.easyfin.transfer.*;
import br.com.easynet.gwt.client.AlterarExcluirBaseGWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.Widget;
import java.util.HashMap;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.user.client.Timer;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.widget.Dialog;
import br.com.i9.finance.client.i9finance.easyfin.service.*;
/**
*
* @author geoleite
*/
public class V_conta_pagar_pagoUpdateDeleteGWT extends V_conta_pagar_pagoInsertGWT {
private V_conta_pagar_pagoT v_conta_pagar_pagoT;
public V_conta_pagar_pagoUpdateDeleteGWT() {
getBtnClear().setVisible(false);
getBtnInsert().setVisible(false);
getBtnUpdate().setVisible(true);
getBtnDelete().setVisible(true);
setHeading("Alterar V_conta_pagar_pago");
}
public void load(V_conta_pagar_pagoT v_conta_pagar_pagoT) {
this.v_conta_pagar_pagoT = v_conta_pagar_pagoT;
dt_pagamento.setValue(v_conta_pagar_pagoT.getDt_pagamento());
valor.setValue(v_conta_pagar_pagoT.getValor() + "");
id_cli_fab.setValue(v_conta_pagar_pagoT.getId_cli_fab() + "");
nome.setValue(v_conta_pagar_pagoT.getNome());
fop_nr_id.setValue(v_conta_pagar_pagoT.getFop_nr_id() + "");
forma.setValue(v_conta_pagar_pagoT.getForma());
ban_nr_id.setValue(v_conta_pagar_pagoT.getBan_nr_id() + "");
banco.setValue(v_conta_pagar_pagoT.getBanco());
pago.setValue(v_conta_pagar_pagoT.getPago());
parcela.setValue(v_conta_pagar_pagoT.getParcela());
documento.setValue(v_conta_pagar_pagoT.getDocumento() + "");
dt_emissao.setValue(v_conta_pagar_pagoT.getDt_emissao());
vencimento.setValue(v_conta_pagar_pagoT.getVencimento());
obs.setValue(v_conta_pagar_pagoT.getObs());
car_nr_id.setValue(v_conta_pagar_pagoT.getCar_nr_id() + "");
cartao.setValue(v_conta_pagar_pagoT.getCartao());
loj_nr_id.setValue(v_conta_pagar_pagoT.getLoj_nr_id() + "");
}
public void btnUpdateAction(ButtonEvent ce) {
if (valide()) {
v_conta_pagar_pagoT.setDt_pagamento(dt_pagamento.getValue());
v_conta_pagar_pagoT.setValor( Double.parseDouble(valor.getValue()));
v_conta_pagar_pagoT.setId_cli_fab( Integer.parseInt(id_cli_fab.getValue()));
v_conta_pagar_pagoT.setNome(nome.getValue());
v_conta_pagar_pagoT.setFop_nr_id( Integer.parseInt(fop_nr_id.getValue()));
v_conta_pagar_pagoT.setForma(forma.getValue());
v_conta_pagar_pagoT.setBan_nr_id( Integer.parseInt(ban_nr_id.getValue()));
v_conta_pagar_pagoT.setBanco(banco.getValue());
v_conta_pagar_pagoT.setPago(pago.getValue());
v_conta_pagar_pagoT.setParcela(parcela.getValue());
v_conta_pagar_pagoT.setDocumento( Integer.parseInt(documento.getValue()));
v_conta_pagar_pagoT.setDt_emissao(dt_emissao.getValue());
v_conta_pagar_pagoT.setVencimento(vencimento.getValue());
v_conta_pagar_pagoT.setObs(obs.getValue());
v_conta_pagar_pagoT.setCar_nr_id( Integer.parseInt(car_nr_id.getValue()));
v_conta_pagar_pagoT.setCartao(cartao.getValue());
v_conta_pagar_pagoT.setLoj_nr_id( Integer.parseInt(loj_nr_id.getValue()));
AsyncCallback<Void> callback = new AsyncCallback<Void>() {
public void onFailure(Throwable caught) {
MessageBox.alert("ATENÇÃO", caught.getMessage(), null);
}
public void onSuccess(Void result) {
Info.display(EASY_LABELS.confirmation(), "Operação realizada com sucesso!");
if (v_conta_pagar_pagoConsult != null) {
v_conta_pagar_pagoConsult.load();
}
setVisible(false);
}
};
V_conta_pagar_pagoServiceAsync v_conta_pagar_pagoAsync = GWT.create(V_conta_pagar_pagoService.class);
v_conta_pagar_pagoAsync.update(v_conta_pagar_pagoT, callback);
}
}
public void btnDeletetAction(ButtonEvent ce) {
MessageBox.confirm(EASY_LABELS.warning(), EASY_LABELS.messageDeleteConfirm(), new Listener<MessageBoxEvent>() {
public void handleEvent(MessageBoxEvent be) {
if (new Dialog().yesText.equalsIgnoreCase(be.getButtonClicked().getText())) {
AsyncCallback<Void> callback = new AsyncCallback<Void>() {
public void onFailure(Throwable caught) {
MessageBox.alert("ATENÇÃO", caught.getMessage(), null);
}
public void onSuccess(Void result) {
Info.display(EASY_LABELS.confirmation(), "Operação realizada com sucesso!");
if (v_conta_pagar_pagoConsult != null) {
v_conta_pagar_pagoConsult.load();
}
setVisible(false);
}
};
V_conta_pagar_pagoServiceAsync v_conta_pagar_pagoAsync = GWT.create(V_conta_pagar_pagoService.class);
v_conta_pagar_pagoAsync.delete(v_conta_pagar_pagoT, callback);
}
}
});
}
/**
* @return the v_conta_pagar_pagoConsult
*/
public V_conta_pagar_pagoConsultGWT getV_conta_pagar_pagoConsult() {
return v_conta_pagar_pagoConsult;
}
/**
* @param v_conta_pagar_pagoConsult the v_conta_pagar_pagoConsult to set
*/
public void setV_conta_pagar_pagoConsult(V_conta_pagar_pagoConsultGWT v_conta_pagar_pagoConsult) {
this.v_conta_pagar_pagoConsult = v_conta_pagar_pagoConsult;
}
}
| true
|
07fbff78637343540745e43e93febbb5163f04e5
|
Java
|
cmigayi/zapiMini
|
/app/src/main/java/com/example/zapimini/daoDatabases/BankTransactionDaoDatabase.java
|
UTF-8
| 995
| 2.25
| 2
|
[] |
no_license
|
package com.example.zapimini.daoDatabases;
import android.content.Context;
import com.example.zapimini.daos.BankTransactionDao;
import com.example.zapimini.data.BankTransaction;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = BankTransaction.class, exportSchema = false, version = 1)
public abstract class BankTransactionDaoDatabase extends RoomDatabase {
private static final String DB_NAME = "bank_transaction_db";
private static BankTransactionDaoDatabase instance;
public static synchronized BankTransactionDaoDatabase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(),
BankTransactionDaoDatabase.class, DB_NAME)
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
public abstract BankTransactionDao bankTransactionDao();
}
| true
|
e64ca0d73edf2ed30a043baed38cb178422f2a3c
|
Java
|
1196216842/wlzy
|
/wlzy/src/cn/wlzy/chat/Message.java
|
UTF-8
| 762
| 2.359375
| 2
|
[] |
no_license
|
package cn.wlzy.chat;
import java.util.Set;
public class Message {
private String come;//加入聊天发送的消息
private String leave;//离开后发送的消息
private Set<String> usernames;//用户列表
private String content;//正式聊天发送的消息的内容
public String getCome() {
return come;
}
public void setCome(String come) {
this.come = come;
}
public String getLeave() {
return leave;
}
public void setLeave(String leave) {
this.leave = leave;
}
public Set<String> getUsernames() {
return usernames;
}
public void setUsernames(Set<String> usernames) {
this.usernames = usernames;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| true
|
2641ed23ec8f347881f005ebe8ded86bb421015e
|
Java
|
Lee-Jung-Hoon/Edu-MIS
|
/AdvanceEduMIS/src/main/java/kr/co/edumis/admin/attendance/controller/AdminAttController.java
|
UTF-8
| 2,328
| 2.046875
| 2
|
[] |
no_license
|
package kr.co.edumis.admin.attendance.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import kr.co.edumis.admin.attendance.service.AdminAttService;
import kr.co.edumis.admin.attendance.service.AdminAttServiceImpl;
import kr.co.edumis.admin.attendance.vo.AdminAttVO;
import kr.co.edumis.user.member.vo.MemberVO;
@Controller
@RequestMapping("/attendance")
public class AdminAttController extends HttpServlet{
@Autowired
private AdminAttService service;
// 학생 리스트 불러오기
@RequestMapping("/memAttList.do")
private void memAttList(HttpServletRequest req, HttpServletResponse res) throws Exception{
res.setContentType("text/html; charset=UTF-8");
PrintWriter out = res.getWriter();
List<MemberVO> memList = service.selectMemList();
System.out.println("콘트롤러 memList사이즈 : "+memList.size());
List<AdminAttVO> attList = service.selectAttList2();
String json = "";
json += "[";
for(int i = 0; i < memList.size(); i++){
MemberVO mem = memList.get(i);
json += " {";
json += " 'no': '" + mem.getNo() + "', ";
json += " 'mName': "+"'"+mem.getName() + "', ";
json += " 'grade': "+"'"+mem.getGrade() + "'";
List<AdminAttVO> attMemList = service.selectAttMemList(mem.getNo());
for(int j = 0; j < attMemList.size(); j++) {
if (j == 0) {
json += ", ";
json += "'attInfo': [";
}
AdminAttVO attMem = attMemList.get(j);
json += "'" + attMem.getAttType()+ ":" + attMem.getAttDate()+"' ";
if(j != attMemList.size() -1){
json += ", ";
}
}
if (attMemList.size() != 0) {
json += "]";
}
json += " } ";
if(i != memList.size() - 1){
json += ", ";
}
}
System.out.println(json);
json += "]";
out.println(json);
out.close();
}
}
| true
|
09bb694f60e42842c928ee7f1aa54c1415ab7cb8
|
Java
|
Aleksefo/PopularMovies
|
/app/src/main/java/com/example/alex/nanopopularmovies/model/MovieResponse.java
|
UTF-8
| 272
| 2.0625
| 2
|
[] |
no_license
|
package com.example.alex.nanopopularmovies.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class MovieResponse {
@SerializedName("results")
private List<Movie> results;
public List<Movie> getResults() {
return results;
}
}
| true
|
922b7a6717d417ba84564d8ba91511b33ae9d8ff
|
Java
|
JPDSousa/spotify-web-api-java
|
/src/main/java/com/wrapper/spotify/exceptions/BadRequestException.java
|
UTF-8
| 251
| 1.859375
| 2
|
[
"MIT"
] |
permissive
|
package com.wrapper.spotify.exceptions;
@SuppressWarnings("javadoc")
public class BadRequestException extends WebApiException {
private static final long serialVersionUID = 1L;
public BadRequestException(String message) {
super(message);
}
}
| true
|
aaff52aeb4ef83b250258f0f8c6b3561c0dee1a9
|
Java
|
Alex-Golub/restful-web-services
|
/src/test/java/edu/mrdrprof/app/ws/ui/controller/UserControllerTest.java
|
UTF-8
| 2,364
| 2.21875
| 2
|
[] |
no_license
|
package edu.mrdrprof.app.ws.ui.controller;
import edu.mrdrprof.app.ws.service.UserService;
import edu.mrdrprof.app.ws.shared.dto.AddressDto;
import edu.mrdrprof.app.ws.shared.dto.UserDto;
import edu.mrdrprof.app.ws.ui.model.response.UserRest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;
class UserControllerTest {
@Mock
UserService userService;
@InjectMocks
UserController userController;
UserDto userDto;
final String USER_ID = "1gdsfgkjnlkntg1ku3rt3";
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this); // init mocks
userDto = UserDto.builder()
.firstName("Alex")
.lastName("Go")
.email("text@test.com")
.userId(USER_ID)
.addresses(getAddressDtoList())
.build();
}
@Test
void testGetUser() {
when(userService.getUserByUserId(anyString())).thenReturn(userDto);
UserRest userRest = userController.getUser(USER_ID);
assertNotNull(userRest);
assertEquals(userDto.getFirstName(), userRest.getFirstName());
assertEquals(userDto.getLastName(), userRest.getLastName());
assertEquals(userDto.getEmail(), userRest.getEmail());
assertEquals(userDto.getUserId(), userRest.getUserId());
assertEquals(userDto.getAddresses().size(), userRest.getAddresses().size());
}
private List<AddressDto> getAddressDtoList() {
AddressDto addressDto1 = new AddressDto();
addressDto1.setAddressId("51knh5lkj1h124313");
addressDto1.setCity("Israel");
addressDto1.setStreetName("5th Shit hole Ave.");
addressDto1.setType("Shipping");
AddressDto addressDto2 = new AddressDto();
addressDto2.setAddressId("531k5;3lm52jtiprjtg34");
addressDto2.setCity("USA");
addressDto2.setStreetName("1st Hole in the Ground Main");
addressDto2.setType("Billing");
List<AddressDto> addressDtoList = new ArrayList<>();
addressDtoList.add(addressDto1);
addressDtoList.add(addressDto2);
return addressDtoList;
}
}
| true
|
ab4d1a8d08c97368f5ea968207a05f5103d4e9c2
|
Java
|
BigHAKA/alibabacloud-vodupload-sdk
|
/android/VodUploadSdk/vod-upload-android-sdk/src/main/java/com/alibaba/sdk/android/vod/upload/VODSVideoUploadClient.java
|
UTF-8
| 1,696
| 1.984375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2020 Alibaba Group Holding Limited
*/
package com.alibaba.sdk.android.vod.upload;
import com.alibaba.sdk.android.vod.upload.session.VodSessionCreateInfo;
/**
* Created by Mulberry on 2017/11/2.
*/
public interface VODSVideoUploadClient {
/**
* 初始化短视频上传
*/
void init();
/**
* @param vodSessionCreateInfo 短视频点播上传配置,需要构造一个
* @param callback 回调
* {@link VodSessionCreateInfo}
* {@link VODSVideoUploadCallback}
*/
void uploadWithVideoAndImg(VodSessionCreateInfo vodSessionCreateInfo, VODSVideoUploadCallback callback);
/**
* STSToken 过期刷新
*
* @param accessKeyId
* @param accessKeySecret
* @param securityToken 安全token
* @param expriedTime 过期时间
*/
void refreshSTSToken(String accessKeyId, String accessKeySecret, String securityToken, String expriedTime);
/**
* 取消上传
*/
void cancel();
/**
* 恢复上传
*/
void resume();
/**
* 暂停上传
*/
void pause();
/**
* 释放资源
*/
void release();
/**
* 为打通log数据传递appversion
*
* @param appVersion
*/
void setAppVersion(String appVersion);
/**
* 配置上传地址region,默认为 cn-shanghai,不传则使用默认
*
* @param region
*/
void setRegion(String region);
/**
* 是否开启断点续传,默认为开启
*
* @param enabled
*/
void setRecordUploadProgressEnabled(boolean enabled);
}
| true
|
73b26c1d193e172f2c857d40d11717b3cbe5b661
|
Java
|
selimfirat/man-of-war
|
/src/main/java/com/manofwar/logic/mob/MobInputComponent.java
|
UTF-8
| 2,222
| 3.078125
| 3
|
[] |
no_license
|
package com.manofwar.logic.mob;
import com.manofwar.logic.Config;
import com.manofwar.logic.Direction;
import com.manofwar.logic.GameStateManager;
import com.manofwar.logic.bullet.Bullet;
import com.manofwar.logic.character.Character;
import java.awt.*;
import java.awt.event.KeyEvent;
/**
* MobInputComponent includes a simple AI for the mobs.
*/
public class MobInputComponent {
private Mob mob;
/**
* Simply, constructor
* @param mob the mob to be composited with this component
*/
public MobInputComponent(Mob mob) {
this.mob = mob;
mob.getVelocity().setX(Config.MOB_SPEED * (Math.random() > 0.5 ? -1 : 1));
}
private int bulletUpdateCounter = 0;
/**
* The method that is executed each iteration of game loop.
* Manages the fire AI for the mobs.
* @param gameStateManager The Game State Manager instance that is in control.
*/
public void update(GameStateManager gameStateManager) {
Character character = gameStateManager.getCharacter();
boolean isFIRE = false;
// for readability
if (Math.abs(mob.getBoundingBox().y - character.getBoundingBox().y) < character.getBoundingBox().height &&
((mob.getVelocity().getDirection() == Direction.LEFT && character.getBoundingBox().x < mob.getBoundingBox().x) ||
(mob.getVelocity().getDirection() == Direction.RIGHT && character.getBoundingBox().x > mob.getBoundingBox().x)
))
isFIRE = true;
if (isFIRE && bulletUpdateCounter <= 0) {
Rectangle bb = (Rectangle) mob.getBoundingBox().clone();
bb.height *= 0.25;
bb.width *= 0.25;
bb.x += bb.width * 2;
bb.y += bb.height * 2;
Bullet bullet = new Bullet(bb, mob.getVelocity().getDirection(), mob.getPower(), true);
gameStateManager.getBullets().add(bullet);
bulletUpdateCounter = Config.MOB_BULLET_UPDATE_LIMIT;
mob.getVelocity().setX(0);
} else if (!isFIRE && mob.getVelocity().getX() == 0)
mob.getVelocity().setX(Config.MOB_SPEED * (Math.random() > 0.5 ? -1 : 1));
bulletUpdateCounter--;
}
}
| true
|
960d9ba625923dcf87c1d57aad58ede2f1003bb3
|
Java
|
tskyline/Summer2019_Java
|
/src/day44_accessModifiers/test45.java
|
UTF-8
| 466
| 3.09375
| 3
|
[] |
no_license
|
package day44_accessModifiers;
import day45_inheritance.protected_vs_default;
public class test45 extends protected_vs_default
{
public static void main(String[] args)
{
printHello();
hola(); //protected
System.out.println(name); //only public and protected can be inheritad outside the package
//System.out.println(obj.ID);
//default: not visible outside the package
testData obj=new testData();
System.out.println(obj.year);
}
}
| true
|
277da3c326c1120e1f44a6fd5d2313e36c008c33
|
Java
|
aa12501/subang
|
/subang_9003_lost/src/main/java/com/subang/lost/dao/CommentDao.java
|
UTF-8
| 309
| 1.601563
| 2
|
[] |
no_license
|
package com.subang.lost.dao;
import com.subang.lost.pojo.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface CommentDao extends JpaRepository<Comment, String>, JpaSpecificationExecutor<Comment> {
}
| true
|
68ad6b1c7db18f46013bdec1eae7fd0306ae06f8
|
Java
|
520ZH1314/ZhiXings
|
/employlib/src/main/java/com/zhixing/employlib/model/gardenplot/EmployeeFlie.java
|
UTF-8
| 2,362
| 1.898438
| 2
|
[] |
no_license
|
package com.zhixing.employlib.model.gardenplot;
import java.io.Serializable;
public class EmployeeFlie implements Serializable {
/**
* FileID : 图片ID
* FileTitle : 图片名称
* FilePath : 图片地址
* FileType : 图片类型
* FileSize : 图片大小
* FileDesc : 图片描述
* LinkedTable : 图片链接表
* LinkedTableId : 图片链接表ID
* UploadDate : 上传时间
* TenantId : 租号
*/
private String FileID;
private String FileTitle;
private String FilePath;
private String FileType;
private String FileSize;
private String FileDesc;
private String LinkedTable;
private String LinkedTableId;
private String UploadDate;
private String TenantId;
public String getFileID() {
return FileID;
}
public void setFileID(String FileID) {
this.FileID = FileID;
}
public String getFileTitle() {
return FileTitle;
}
public void setFileTitle(String FileTitle) {
this.FileTitle = FileTitle;
}
public String getFilePath() {
return FilePath;
}
public void setFilePath(String FilePath) {
this.FilePath = FilePath;
}
public String getFileType() {
return FileType;
}
public void setFileType(String FileType) {
this.FileType = FileType;
}
public String getFileSize() {
return FileSize;
}
public void setFileSize(String FileSize) {
this.FileSize = FileSize;
}
public String getFileDesc() {
return FileDesc;
}
public void setFileDesc(String FileDesc) {
this.FileDesc = FileDesc;
}
public String getLinkedTable() {
return LinkedTable;
}
public void setLinkedTable(String LinkedTable) {
this.LinkedTable = LinkedTable;
}
public String getLinkedTableId() {
return LinkedTableId;
}
public void setLinkedTableId(String LinkedTableId) {
this.LinkedTableId = LinkedTableId;
}
public String getUploadDate() {
return UploadDate;
}
public void setUploadDate(String UploadDate) {
this.UploadDate = UploadDate;
}
public String getTenantId() {
return TenantId;
}
public void setTenantId(String TenantId) {
this.TenantId = TenantId;
}
}
| true
|
33ce948f6a6273da6089bd7187f482e606ed4c8f
|
Java
|
jinsedeyuzhou/component
|
/CusLib/webviewlib/src/main/java/com/ebrightmoon/webviewlib/utils/WebUtil.java
|
UTF-8
| 10,947
| 1.875
| 2
|
[] |
no_license
|
package com.ebrightmoon.webviewlib.utils;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.TypedValue;
import android.view.Display;
import android.webkit.WebSettings;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
/**
* Time: 2020-04-13
* Author:wyy
* Description:
*/
public class WebUtil {
/**
* 检查 URL 是否合法
* @param url
* @return true 合法,false 非法
*/
public static boolean isNetworkUrl(String url) {
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern patt = Pattern.compile(regex);
Matcher matcher = patt.matcher(url);
return matcher.matches();
}
public static void initWebViewSettings(WebSettings wSet) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
wSet.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
// 是否显示缩放按钮
wSet.setBuiltInZoomControls(false);
// 支持缩放
wSet.setSupportZoom(false);
wSet.setTextZoom(100);
// 默认字体大小
wSet.setDefaultFontSize(12);
wSet.setAllowFileAccess(false);
// 设置可以访问文件
// 设置支持webView JavaScript
wSet.setJavaScriptEnabled(true);
// 设置缓冲的模式
wSet.setCacheMode(WebSettings.LOAD_NO_CACHE);
// 设置字符编码
wSet.setDefaultTextEncodingName("utf-8");
//优先使用缓存
// wSet.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wSet.setAppCacheEnabled(false);
wSet.setDomStorageEnabled(true);
wSet.setDatabaseEnabled(true);
}
/**
* dp转px
*
* @param context
* @param dpVal
* @return
*/
public static int dp2px(Context context, float dpVal)
{
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
//跳转到打电话的界面
public static Intent getCallIntent(String telNumber) {
Uri uri = Uri.parse("tel:"+telNumber);
Intent it = new Intent(Intent.ACTION_DIAL, uri);
return it;
}
//获取跳转到权限列表的intent
public static Intent getAppDetailSettingIntent(Context mContext) {
Intent localIntent = new Intent();
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 9) {
localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
} else if (Build.VERSION.SDK_INT <= 8) {
localIntent.setAction(Intent.ACTION_VIEW);
localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
localIntent.putExtra("com.android.settings.ApplicationPkgName", mContext.getPackageName());
}
return localIntent;
}
/**
* 获取拍照的图片
*
* @param context
* @param data
* @return
*/
public static String getCameraUriCompress(Activity context, Intent data) {
Display display = context.getWindowManager().getDefaultDisplay();
float ScreenW = display.getWidth();
float ScreenH = display.getHeight();
String sdState = Environment.getExternalStorageState();
if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
new DateFormat();
String photoName = DateFormat.format("yyyyMMdd_hhmmss",
Calendar.getInstance(Locale.CHINA))
+ ".jpg";
// Bundle bundle = data.getExtras();
// 获取相机返回的数据,并转换为图片格式
// data.getParcelableExtra("data");
Bitmap bitmap=null;
if (data.hasExtra("data")) {
bitmap = (Bitmap) data.getParcelableExtra("data");
}else
{
return null;
}
FileOutputStream fout = null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path + "/vm");
file.mkdirs();
String filename = file.getPath() + "/" + photoName;
try {
fout = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG
, 100, fout);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return filename;
}
public static Bitmap getGalleryPicture(Activity context, Intent data) throws Exception {
Display display = context.getWindowManager().getDefaultDisplay();
float ScreenW = display.getWidth();
float ScreenH = display.getHeight();
ContentResolver resolver = context.getContentResolver();
// 照片的原始资源地址
Uri originalUri = data.getData();
System.out.println("uri=" + originalUri);
String photoName = DateFormat.format("yyyyMMdd_hhmmss",
Calendar.getInstance(Locale.CHINA))
+ ".jpg";
File file = new File("/sdcard/pintu/");
file.mkdirs();
String filename = file.getPath() + "/" + photoName;
FileOutputStream fout = null;
try {
fout = new FileOutputStream(filename);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, originalUri);
try {
// 使用ContentProvider通过URI获取原始图片
float oldBitW = bitmap.getWidth();
float oldBitH = bitmap.getHeight();
float x = ((ScreenH * oldBitW) / oldBitH) / oldBitW;
float y = ScreenH / oldBitH;
Matrix matrix = new Matrix();
matrix.postScale(x, y);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, (int) oldBitW,
(int) oldBitH, matrix, true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 1, fout);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fout.flush();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
public static CookieManager cookieManager=new CookieManager();
public static Map<String, Object> request(String method, String url, String param, JSONObject headers) throws Exception {
URL uri = new URL(url);
method = method.toUpperCase();
HttpURLConnection urlCon = (HttpURLConnection) uri.openConnection();
urlCon.setRequestMethod(method);
urlCon.setConnectTimeout(10000);
handleRequestHeaders(urlCon,headers);
if (urlCon instanceof HttpsURLConnection) {
addCertVerifier((HttpsURLConnection) urlCon);
}
if (method.equals("POST")) {
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
if (!param.trim().isEmpty()) {
PrintWriter pw = new PrintWriter(urlCon.getOutputStream());
pw.print(param);
pw.flush();
pw.close();
}
}
Map<String, Object> response=new HashMap<>();
response.put("responseText",inputStream2String(urlCon.getInputStream()));
response.put("statusCode",urlCon.getResponseCode());
Map<String, List<String>> responseHeaders= new HashMap<>(urlCon.getHeaderFields());
responseHeaders.remove(null);
responseHeaders=handleResponseHeaders(urlCon,responseHeaders);
response.put("headers",responseHeaders);
return response;
}
//对于https请求,进行证书校验
private static void addCertVerifier(HttpsURLConnection urlCon) throws Exception {
// 在此做证书校验
// urlCon.setSSLSocketFactory(getSSLSocketFactory());
urlCon.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
//return "api.dtworkroom.com".equals(hostname);
HostnameVerifier hv=HttpsURLConnection.getDefaultHostnameVerifier();
return hv.verify("*.dtworkroom.com",session);
}
});
}
//预处理请求头
private static void handleRequestHeaders(HttpURLConnection connection,JSONObject headers) throws Exception {
Iterator iterator = headers.keys();
while(iterator.hasNext()){
String key = (String) iterator.next();
String value = headers.getString(key);
if(!key.toLowerCase().equals("cookie")){
//请求cookie
connection.setRequestProperty(key, value);
}
}
List<HttpCookie> cookies= cookieManager.getCookieStore().get(connection.getURL().toURI());
cookies.toString();
}
private static Map<String, List<String>> handleResponseHeaders(HttpURLConnection connection, Map<String, List<String>> responseHeaders) throws Exception {
//获取响应头中的cookies,端上统一管理cookie
cookieManager.put(connection.getURL().toURI(),responseHeaders);
responseHeaders.remove("set-cookie");
return responseHeaders;
}
private static String inputStream2String(InputStream is) {
String result = "";
String line;
InputStreamReader inputReader = new InputStreamReader(is);
BufferedReader bufReader = new BufferedReader(inputReader);
try {
while ((line = bufReader.readLine()) != null)
result += line + "\r\n";
bufReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
| true
|
0eaea23a1eb33f50b6314c5a41821d5e6a6c7dbf
|
Java
|
aquinovale/sondaNASA
|
/src/main/java/br/aquino/Cartesiano.java
|
UTF-8
| 512
| 3.328125
| 3
|
[] |
no_license
|
package br.aquino;
public class Cartesiano{
private int x;
private int y;
public Cartesiano(int x, int y){
this.x = x;
this.y = y;
}
public void move(RosaVentos rosaVentos){
switch (rosaVentos) {
case N:
this.y = this.y + 1;
break;
case S:
this.y = this.y - 1;
break;
case W:
this.x = this.x - 1;
break;
case E:
this.x = this.x + 1;
break;
default:
break;
}
}
@Override
public String toString(){
return String.format("(%s, %s)", this.x, this.y);
}
}
| true
|
bdc909089d34ccba26ff1725f70af9e203b7c0b7
|
Java
|
VivekMadarapu/Compression
|
/src/CompressionHandler.java
|
UTF-8
| 3,323
| 2.875
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CompressionHandler {
private HashMap<Character, Integer> freq = new HashMap<>();
public HuffmanTree tree;
public File input;
public File output;
private int compressSize;
public CompressionHandler(String file) throws FileNotFoundException {
input = new File(file);
compressSize = 0;
initFreq(file);
tree = new HuffmanTree(freq);
}
public void initFreq(String file) throws FileNotFoundException {
Scanner reader = new Scanner(new File(file));
reader.useDelimiter("");
while(reader.hasNext()){
Character c = reader.next().charAt(0);
if(!freq.containsKey(c)){
freq.put(c, 1);
}
else {
freq.put(c, freq.get(c)+1);
}
}
freq.put(null, 1);
}
public void compress() throws IOException {
output = new File(input.getName() + ".viv");
int version = 0;
while (output.exists()) {
version++;
output = new File(input.getName() + "(" + version + ")" + ".viv");
}
//noinspection ResultOfMethodCallIgnored
output.createNewFile();
BitOutputStream bitOut = new BitOutputStream(output.getName());
Scanner file = new Scanner(input);
file.useDelimiter("");
while(file.hasNext()){
char nextChar = file.next().charAt(0);
compressSize += tree.codes.get(nextChar).length();
bitOut.writeBits(tree.codes.get(nextChar).length(), Integer.parseInt(tree.codes.get(nextChar), 2));
}
bitOut.writeBits(tree.codes.get(null).length(), Integer.parseInt(tree.codes.get(null), 2));
bitOut.flush();
}
public void decompress() throws IOException {
File out = new File(output.getName() + ".txt");
int version = 0;
while (out.exists()) {
version++;
out = new File(output.getName() + "(" + version + ")" + ".txt");
}
//noinspection ResultOfMethodCallIgnored
out.createNewFile();
BitInputStream bitIn = new BitInputStream(output);
BufferedWriter writer = new BufferedWriter(new FileWriter(out));
String curCode = "";
for (int i = 0; i < compressSize; i++){
curCode += bitIn.readBits(1);
if(tree.codes.containsValue(curCode)){
if(tree.swappedCodes.get(curCode) == null){
break;
}
writer.write(tree.swappedCodes.get(curCode));
curCode = "";
}
}
writer.flush();
}
public static void main(String[] args) throws IOException {
File[] files = new File("C:\\Users\\228800\\IdeaProjects\\Compression\\").listFiles();
for (File file : files) {
if(!file.getName().equals("Compression.iml") && !file.getName().equals(".git") && !file.getName().equals(".idea") && !file.getName().equals("out") && !file.getName().equals("src")){
CompressionHandler brick = new CompressionHandler(file.getName());
brick.compress();
brick.decompress();
}
}
}
}
| true
|
894bf392391a2a34e326c8af9d439d2b8c2b6383
|
Java
|
Straianaidas/MHFC
|
/src/main/java/mhfc/net/common/ai/entity/boss/kirin/KirinIdle.java
|
UTF-8
| 817
| 2.390625
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
package mhfc.net.common.ai.entity.boss.kirin;
import mhfc.net.common.ai.ActionAdapter;
import mhfc.net.common.entity.monster.EntityKirin;
public class KirinIdle extends ActionAdapter<EntityKirin> {
private static final int LAST_FRAME = 160;
public KirinIdle() {
setLastFrame(LAST_FRAME);
setAnimation("mhfc:models/Kirin/KirinIdle.mcanm");
}
@Override
public float getWeight() {
EntityKirin entity = this.getEntity();
if (entity.isDead) {
return DONT_SELECT;
}
target = entity.getAttackTarget();
// if (target == null)
// return DONT_SELECT;
return rng().nextFloat() * 3;
}
@Override
public void update() {
EntityKirin entity = this.getEntity();
if (this.getCurrentFrame() == 10) {
entity.playLivingSound();
}
// just a copy from roar the update method. nothing else
}
}
| true
|
d879237858899d073ca3e1ad730919fd4ba0785e
|
Java
|
DisSsha/Social
|
/Soc/src/item/lib/Fer.java
|
UTF-8
| 146
| 1.5625
| 2
|
[] |
no_license
|
package item.lib;
import environment.api.Ressources;
public class Fer extends Ressources {
public int getProduction(int i) {
return 3;
}
}
| true
|
8371da469c2bdde2aa562a00f28c846a561d5a08
|
Java
|
Giordano26/Java-Introduction
|
/Prog32/Prog32.java
|
UTF-8
| 1,211
| 4.1875
| 4
|
[] |
no_license
|
//Prog32 - verificação de produto
//Stefano Giordano
//Entrar com 3 numeros inteiros e dizer se o maior é produto dos outros dois
//Caso contrario informar: nada a declarar
//Usar o Scanner
import java.util.*;
public class Prog32
{
public static void main(String[] args)
{
int a,b,c;
System.out.println("Digite o primeiro número");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
System.out.println("Digite o segundo número");
sc = new Scanner(System.in);
b = sc.nextInt();
System.out.println("Digite o terceiro número");
sc = new Scanner(System.in);
c = sc.nextInt();
if((a>=b) && (a>=c) && (b*c == a)){
System.out.println(a + " é o maior numero e "+b+"*"+c+" resultam em "+a);
}else if((b>=a) && (b>=c) && (a*c == b)){
System.out.println(b + " é o maior numero e "+a+"*"+c+" resultam em "+b);
}else if ((c>=a) && (c>=b) && (b*a == c)){
System.out.println(c + " é o maior numero e "+b+"*"+a+" resultam em "+c);
}else{
System.out.println("Nada a declarar");
}
}
}
| true
|
a3a467471afc7a2e267c975e09cd8aa1506d0c06
|
Java
|
slanger/RPG
|
/rpg-desktop/src/com/me/rpg/Main.java
|
UTF-8
| 448
| 2.0625
| 2
|
[] |
no_license
|
package com.me.rpg;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class Main
{
public static void main(String[] args)
{
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "The Legend of the Diforce";
cfg.useGL20 = true;
cfg.width = 640;
cfg.height = 640;
new LwjglApplication(new ScreenHandler(), cfg);
}
}
| true
|
2c3aae529e118304ca5920ba031b278e6865f250
|
Java
|
SSVerma/EspressoLab
|
/app/src/main/java/com/ssverma/espressolab/custommatcher/CofferPreparationActivity.java
|
UTF-8
| 1,929
| 2.328125
| 2
|
[] |
no_license
|
package com.ssverma.espressolab.custommatcher;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.ssverma.espressolab.R;
import java.util.Arrays;
import java.util.List;
public class CofferPreparationActivity extends AppCompatActivity {
@VisibleForTesting
public static final List<String> COFFEE_PREPARATIONS =
Arrays.asList("Espresso", "Latte", "Mocha", "Café con leche", "Cold brew");
@VisibleForTesting
public static final String VALID_ENDING = "coffee";
private TextView tvSuccess;
private TextView tvFail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coffer_preparation);
final EditText etChoice = findViewById(R.id.et_coffee);
Button btnValidate = findViewById(R.id.btn_validate);
tvSuccess = findViewById(R.id.tv_success);
tvFail = findViewById(R.id.tv_fail);
btnValidate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayResult(isValid(etChoice.getText().toString()));
}
});
}
private void displayResult(boolean isValid) {
tvSuccess.setVisibility(isValid ? View.VISIBLE : View.GONE);
tvFail.setVisibility(isValid ? View.GONE : View.VISIBLE);
}
private boolean isValid(String choice) {
if (choice.toLowerCase().endsWith(VALID_ENDING)) {
return true;
}
for (String preparation : COFFEE_PREPARATIONS) {
if (preparation.equalsIgnoreCase(choice)) {
return true;
}
}
return false;
}
}
| true
|
f8ac99b73b4c296afb8265a6376bc57a030fc6f2
|
Java
|
HamzaSonic/Hamza-Atypon
|
/Employee.java
|
UTF-8
| 4,668
| 3.765625
| 4
|
[] |
no_license
|
public class Employee implements Cloneable{
private String name,jobDescreption,dept ;
long sin;int salary ,age ;
public Employee(int sin,String name,int age){
/**basic attributes for an employee */
this.sin=sin;
this.name=name;
this.age=age;
}
public Employee(int sin,String name,int age ,String dept,String jobDescreption,int salary){
/**full information about employee constructor*/
this.sin=sin;
this.name=name;
this.age=age;
this.dept=dept;
this.jobDescreption=jobDescreption;
this.salary=salary;
}
/**setters and getters methods for attributes except the name and sin because sin and name does not change*/
public void setAge(int age) {
this.age = age;
}
public void setDept(String dept) {
this.dept = dept;
}
public void setJobDescreption(String jobDescreption) {
this.jobDescreption = jobDescreption;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public int getSalary() {
return salary;
}
public long getSin() {
return sin;
}
public String getDept() {
return dept;
}
public String getJobDescreption() {
return jobDescreption;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object obj)
{
/**if the object is compared to itself*/
if(this == obj)
return true;
/**the 2 objects must be from the same class */
if(obj == null || obj.getClass()!= this.getClass())
return false;
/**if they have the same sin then it's the same employee*/
Employee emp = (Employee) obj;
return (emp.name.equals(this.name) && emp.sin == this.sin);
}
@Override
public int hashCode()
{
return (int) this.sin;
}
@Override
public String toString() {
String s= "I'm an employee my name is "+name+" and i work in the "+dept+" department and my social security number is "+sin;
return s;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Employee e1=null;
try{
e1=(Employee)super.clone();
}
catch (CloneNotSupportedException e){}
return e1;
}
/**the tax calculator in assignment 4*/
public double taxCalculator() throws Exception1 {
/**the limit i set was 130 $ so if the tax is greater than 130 it will throw an exception*/
double tax;
tax= 0.05*salary;
if (tax<=130)return tax;
else throw new Exception1();
}
/**the function that validate the SIN number*/
private boolean isValid () throws Exception2{
/**based on Canada SIN */
long v=121212121;
long v2=sin;
int s=0;
while (v2!=0){
s+=v%10 *v2%10;
v/=10;
v2/=10;
}
if (s%10==0) return true;else throw new Exception2();
}
public int insurance() throws Exception2 {
/**if the sin is valid return the last 3 digits of the salary*/
if (isValid()) return salary%1000;
return 0;
}
public static void main(String[] args) throws Exception2 {
/**2 employees to test the functionality of the code*/
Employee e1=new Employee(131192544,"Hamza",25);
e1.setDept("IT department ");
e1.setJobDescreption("Java Developer ");
e1.setSalary(2800);
System.out.println(e1.toString());
Employee e2=new Employee(231231423,"malik",30,"Marketing","call center",1400);
/**the equals method*/
if (e1.equals(e2)) System.out.println("same Employee"); else System.out.println("different employee ");
System.out.println();
/**now the tax and exceptions task*/
Double tax;
try {
tax=e1.taxCalculator();
}catch (Exception1 e){
System.out.println("the tax is more than 130 $");
tax=130.0;
}
System.out.println("the tax is "+tax);
/**the sin validate*/
int in;
try{
in=e1.insurance();
}catch (Exception2 e){
System.out.println("the SIN is not valid");
in=0;
}
System.out.println("the insurance is "+in);
/**this function to check if the valid function works so it will throw an exception*/
Employee e3=new Employee(965942103,"ahmad",20);
e3.setSalary(2000);
int z=e3.insurance();
}
}
| true
|
33552c0e6ce52e688cc412efbd3966a300b99729
|
Java
|
gauravsingh1983/BillingApp
|
/src/java/test/ChangePwd.java
|
UTF-8
| 3,107
| 2.296875
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author Gaurav
*/
public class ChangePwd extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession sess = request.getSession();
Service scv = new Service();
Connection con = (Connection)sess.getAttribute("con");
scv.theConnection = con;
RequestDispatcher rd = request.getRequestDispatcher("pwdsettings.jsp");
String errmsg="";
try {
String usrnm =request.getParameter("user");
String pword = scv.getPwd(usrnm);
String opwd = request.getParameter("opwd");
String npwd = request.getParameter("npwd");
String cnpwd = request.getParameter("cnpwd");
if(npwd.equals(cnpwd)&&opwd.equals(pword)){
String uqry = "UPDATE LOGIN SET PASSWORD = ? WHERE USERNAME = ?";
PreparedStatement ups = con.prepareStatement(uqry);
ups.setString(1, npwd);
ups.setString(2, usrnm);
//ups.executeUpdate();
if(ups.executeUpdate()==1){
errmsg="Password has been changed successfully!!Please logout and re-login";
}
}else{
errmsg="Password not matched!! Please retype password.";
}
request.setAttribute("emsg", errmsg);
rd.forward(request, response);
} catch(SQLException ex ){ex.getMessage();}finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
| true
|
95aeae8cb5193deb9c564f849eb5416fb38e6031
|
Java
|
zhuzilyy/NewbigFitnessMember
|
/BigFitness/src/main/java/com/member/gufei/bigfitness/util/NgCommon/MyViewHolder.java
|
UTF-8
| 3,764
| 2.28125
| 2
|
[] |
no_license
|
package com.member.gufei.bigfitness.util.NgCommon;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.member.gufei.bigfitness.R;
import com.member.gufei.bigfitness.util.NgCommon.view.SlidingButtonView;
import static com.member.gufei.bigfitness.Constants.BASEURL;
/**
* Created by jiangzn on 17/1/1.
*/
public class MyViewHolder extends RecyclerView.ViewHolder {
private SparseArray<View> views; // 控件集合
private View currentView; // 当前视图
private Context context; // 上下文
public TextView textView;
public ViewGroup layout_content;
public SlidingButtonView slidingButtonView;
public RelativeLayout rl_left;
public RadioButton rbtn;
/**
* 构造函数,初始化属性
*/
public MyViewHolder(View itemView, Context context) {
super(itemView);
this.currentView = itemView;
this.context = context;
this.views = new SparseArray<>();
textView = (TextView) itemView.findViewById(R.id.text);
layout_content = (ViewGroup) itemView.findViewById(R.id.layout_content);
slidingButtonView = (SlidingButtonView) itemView;
rl_left = (RelativeLayout) itemView.findViewById(R.id.rl_left);
slidingButtonView = (SlidingButtonView) itemView;
rbtn = (RadioButton) itemView.findViewById(R.id.rbtn);
}
/**
* 实例方法
* @param layoutId 布局ID
* @param context 上下文
* @param parent 父容器
*/
public static MyViewHolder getInstants(int layoutId, Context context, ViewGroup parent) {
return new MyViewHolder(LayoutInflater.from(context).inflate(layoutId, parent, false),context);
}
/**
* 通过控件ID 获取控件
* @param viewId 控件ID
* @param <V> 控件
*/
public <V extends View> V getView(int viewId) {
View view = views.get(viewId);
if (view == null) {
view = currentView.findViewById(viewId);
views.put(viewId, view);
}
return (V) view;
}
/**
* 设置 TextView 内容
* @param viewId 控件ID
* @param text 内容
*/
public MyViewHolder setText(int viewId, String text) {
TextView textView = getView(viewId);
textView.setText(text);
return this;
}
/**
* 设置图片
* 以下 setXXX 方法可随时添加,方便调用者处理绑定控件.
*/
public MyViewHolder setImage(int viewId, int resId) {
ImageView imageView = getView(viewId);
imageView.setImageResource(resId);
return this;
}
/**
* 设置图片
* 使用 Glide 请求网络图片
*/
public MyViewHolder setImage(int viewId, String url) {
ImageView imageView = getView(viewId);
RequestOptions options = new RequestOptions();
options.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL);
Glide.with(context)
.load(url)
.apply(options)
.into(imageView);
return this;
}
/**
* 设置控件点击事件
*/
public MyViewHolder setOnClickListener(int viewId, View.OnClickListener listener) {
View view = getView(viewId);
view.setOnClickListener(listener);
return this;
}
}
| true
|
32ee36d582fc17af48ab5262aff7e5c80eb69276
|
Java
|
samadhanugale/JavaLabSessionTasks
|
/JavaLabSessionTasks/src/lab10/TryCatchFinallyTest.java
|
UTF-8
| 623
| 3.515625
| 4
|
[] |
no_license
|
//Write a program to illustrate usage of try/catch with finally clause.
package lab10;
import java.util.Scanner;
public class TryCatchFinallyTest {
public static void main(String[] args) {
//create scanner obj
Scanner sc=new Scanner(System.in);
System.out.println("Enter a numbr :- ");
int a=sc.nextInt();
//load jdbc driver
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}//try
catch (ClassNotFoundException cnf) {
System.out.println("From Catch block ");
cnf.printStackTrace();
} finally {
sc.close();
System.out.println("From finally block ");
}//finally
}//main
}//class
| true
|
159f21cb577de74a520450f4c07a8ec1e3020271
|
Java
|
fengfengfeng1234/AvoidMistakePlugin
|
/buildSrc/src/main/java/com/java/pluginExtends/AvoidMistakeField.java
|
UTF-8
| 554
| 2.1875
| 2
|
[] |
no_license
|
package com.java.pluginExtends;
/**
* 根据ClassName 为 key
* 对应多个规则
*/
public class AvoidMistakeField {
public boolean isEnd = false;
public String fieldName;
public String fieldValue;
public String className;
@Override
public String toString() {
return "AvoidMistakeField{" +
"isEnd=" + isEnd +
", fieldName='" + fieldName + '\'' +
", fieldValue='" + fieldValue + '\'' +
", className='" + className + '\'' +
'}';
}
}
| true
|
74ad54a53bf20d48b7d1091a6da59294714c0c72
|
Java
|
1111chengtong/LeetCode
|
/src/Algorithms/SearchInRotatedSortedArrayII.java
|
UTF-8
| 2,577
| 3.875
| 4
|
[] |
no_license
|
package Algorithms;
/**
* There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
*
* Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].
*
* Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.
*
*
*
* Example 1:
*
* Input: nums = [2,5,6,0,0,1,2], target = 0
* Output: true
* Example 2:
*
* Input: nums = [2,5,6,0,0,1,2], target = 3
* Output: false
*
*
* Constraints:
*
* 1 <= nums.length <= 5000
* -104 <= nums[i] <= 104
* nums is guaranteed to be rotated at some pivot.
* -104 <= target <= 104
*
*
* Follow up: This problem is the same as Search in Rotated Sorted Array, where nums may contain duplicates. Would this affect the runtime complexity? How and why?
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class SearchInRotatedSortedArrayII {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return false;
}
int start = 0;
int end = nums.length - 1;
int mid;
while (start <= end) {
mid = start + (end - start) / 2;
if (nums[mid] == target) {
return true;
}
if (nums[start] == nums[mid]) {
start++;
continue;
}
//前半部分有序
if (nums[start] < nums[mid]) {
//target在前半部分
if (nums[mid] > target && nums[start] <= target) {
end = mid - 1;
} else { //否则,去后半部分找
start = mid + 1;
}
} else {
//后半部分有序
//target在后半部分
if (nums[mid] < target && nums[end] >= target) {
start = mid + 1;
} else { //否则,去后半部分找
end = mid - 1;
}
}
}
//一直没找到,返回false
return false;
}
}
| true
|
23f3e8943755b990599c70f2bbb5c614a5a107f0
|
Java
|
PanagiotisVek/Store
|
/src/main/java/gr/codehub/store/Store.java
|
UTF-8
| 142
| 2.25
| 2
|
[] |
no_license
|
package gr.codehub.store;
public interface Store {
void buy(Product product);
void sell(Product product);
double getRevenue();
}
| true
|
09b37bf46ea612ab6798e7a274923da6392ad177
|
Java
|
JarvisJim/HSSM
|
/src/main/java/com/li/service/impl/DepartmentServiceImpl.java
|
UTF-8
| 930
| 2.09375
| 2
|
[] |
no_license
|
package com.li.service.impl;
import com.li.dao.DepartmentMapper;
import com.li.pojo.Department;
import com.li.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
public List<Department> list() {
return departmentMapper.selectByExample(null);
}
public void add(Department department) {
departmentMapper.insertSelective(department);
}
public void update(Department department) {
departmentMapper.updateByExampleSelective(department,null);
}
public void delete(int id) {
departmentMapper.deleteByPrimaryKey(id);
}
public Department get(int id) {
return departmentMapper.selectByPrimaryKey(id);
}
}
| true
|
eecbd86247a71c5fd3d402cceacbe68c836a35dc
|
Java
|
gn01868184/BOTEN
|
/src/main/java/ntou/cs/sose/model/rule/SwaggerValidator.java
|
UTF-8
| 2,077
| 2.1875
| 2
|
[] |
no_license
|
package ntou.cs.sose.model.rule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.stream.Collectors;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import ntou.cs.sose.entity.BotenSwagger;
public class SwaggerValidator implements BotenRule {
@Override
public ArrayList<String> checkRules(BotenSwagger botenSwagger) {
String swaggerUrl = botenSwagger.getUrl();
ArrayList<String> chatbotEnabledSwaggerErrors = new ArrayList<String>();
try {
StringBuilder stringBuilder = new StringBuilder("https://validator.swagger.io/validator/debug");
stringBuilder.append("?url=");
stringBuilder.append(URLEncoder.encode(swaggerUrl, "UTF-8"));
URL url = new URL(stringBuilder.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
BufferedReader br = null;
if (200 <= con.getResponseCode() && con.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String responseBody = br.lines().collect(Collectors.joining());
JsonObject convertedObject = new Gson().fromJson(responseBody, JsonObject.class);
try {
JsonArray messages = convertedObject.get("schemaValidationMessages").getAsJsonArray();
for (int i = 0; i < messages.size(); i++) {
chatbotEnabledSwaggerErrors.add(((JsonObject) messages.get(i)).get("message").toString());
}
} catch (NullPointerException e) {
System.out.println("SwaggerValidator:" + e.getMessage());
}
} else {
chatbotEnabledSwaggerErrors.add("Response error: " + con.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return chatbotEnabledSwaggerErrors;
}
}
| true
|
c6ec4b321381febc5e0b98b272b5b71a68da45df
|
Java
|
09rmaini/Java-EE
|
/src/main/java/peristance/repository/AccountRepository.java
|
UTF-8
| 401
| 1.90625
| 2
|
[] |
no_license
|
package peristance.repository;
import java.util.List;
import persistance.domain.Account;
public interface AccountRepository {
//List<Account> findAllAccounts();
//Account findAccount(Long id);
Account createAccount(Long id, Account createAccount);
Account updateAccount(Account updateAccount, long id);
Account deleteAccount(Account deleteAccount, long id);
}
| true
|
c94c05cd00fbfee2546598caca0228df2eafcb18
|
Java
|
hanseul777/delinori01
|
/src/main/java/com/noriteo/delinori/board/dto/BoardDTO.java
|
UTF-8
| 1,473
| 2.203125
| 2
|
[] |
no_license
|
package com.noriteo.delinori.board.dto;
import com.noriteo.delinori.board.domain.Board;
import com.noriteo.delinori.board.domain.BoardAttach;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class BoardDTO {
// private int replyCnt;
private Long bno;
private String title;
private String writer;
private String content;
private LocalDateTime regDate;
private LocalDateTime modDate;
private String show;
private List<UploadResponseDTO> files = new ArrayList<>();
public Board getDomain() {
Board board = Board.builder()
.bno(bno)
.title(title)
.content(content)
.writer(writer)
.regDate(regDate)
.modDate(modDate)
.show(show)
.build();
files.forEach(uploadResponseDTO -> {
BoardAttach attach = BoardAttach.builder()
.fileName(uploadResponseDTO.getFileName())
.uuid(uploadResponseDTO.getUuid())
.image(uploadResponseDTO.isImage())
.path(uploadResponseDTO.getUploadPath())
.build();
board.addAttach(attach);
});
return board;
}
}
| true
|
2a1855cd2e3676daccb7b208d3755b20a049f7b1
|
Java
|
geraldo1993/Spring-2016
|
/codes/Assignment02/Question2.java
|
UTF-8
| 294
| 2.875
| 3
|
[] |
no_license
|
class Question2
{
public static void main(String[] arg)
{
try
{
int number = 1/0;
System.out.println("to be");
}
catch(Exception exception)
{
System.out.println("or not to be");
}
finally
{
System.out.println("that is the question");
}
}
}
| true
|
f1768048ea5883e0ee5afa529bc987f5507a88df
|
Java
|
aerdy/Java-Fundamental
|
/Contoh/Perulangan/src/perulangan/Perulangan.java
|
UTF-8
| 539
| 2.28125
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package perulangan;
/**
*
* @author root
*/
public class Perulangan {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// byte nilai = 1;
// System.out.println("NIlai");
for(int i=1;i<11;i++){
// nilai = 0+1;
//nilai *= 2;
System.out.println("NIlai"+i);
}
}
}
| true
|
fe4302c62c0cc9eae43dd00e39c1ff8b2b14600d
|
Java
|
dowsam/rebirth-search-core
|
/src/main/java/cn/com/rebirth/search/core/index/engine/CreateFailedEngineException.java
|
UTF-8
| 1,201
| 2.4375
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2005-2012 www.china-cti.com All rights reserved
* Info:rebirth-search-core CreateFailedEngineException.java 2012-7-6 14:28:46 l.xue.nong$$
*/
package cn.com.rebirth.search.core.index.engine;
import cn.com.rebirth.search.core.index.shard.ShardId;
/**
* The Class CreateFailedEngineException.
*
* @author l.xue.nong
*/
public class CreateFailedEngineException extends EngineException {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 2544428849521582153L;
/** The type. */
private final String type;
/** The id. */
private final String id;
/**
* Instantiates a new creates the failed engine exception.
*
* @param shardId the shard id
* @param create the create
* @param cause the cause
*/
public CreateFailedEngineException(ShardId shardId, Engine.Create create, Throwable cause) {
super(shardId, "Create failed for [" + create.type() + "#" + create.id() + "]", cause);
this.type = create.type();
this.id = create.id();
}
/**
* Type.
*
* @return the string
*/
public String type() {
return this.type;
}
/**
* Id.
*
* @return the string
*/
public String id() {
return this.id;
}
}
| true
|
6f822a00f193b365b3ecdbe8cccbc4566ff81761
|
Java
|
souzamarques/tecnicasDeProgramacao
|
/ManipulacaodeArquivos/src/Arquivos/LendoArquivoTexto.java
|
UTF-8
| 822
| 2.90625
| 3
|
[] |
no_license
|
package Arquivos;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LendoArquivoTexto {
public static void main(String[] args) {
try {
String pathDir = "/home/lucas/NetBeansProjects/ManipulacaodeArquivos/POO/LendoArquivoTexto";
String pathArquivo = pathDir + "/" + "ArquivoTexto.txt";
FileReader arquivo = new FileReader(pathArquivo);
BufferedReader leitor = new BufferedReader(arquivo);
String conteudo = leitor.readLine();
while(conteudo != null) {
System.out.println(conteudo);
conteudo = leitor.readLine();
}
leitor.close();
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
| true
|
8523514641bfe7da9318e81135ab2c354e25abdb
|
Java
|
liwenhui19941115/JavaTestPro
|
/src/main/java/com/gavin/basicTest/MutiThreadLearning/ThreadContainerTest/ConcurrentHashMapTest.java
|
UTF-8
| 2,278
| 3.375
| 3
|
[] |
no_license
|
package com.gavin.basicTest.MutiThreadLearning.ThreadContainerTest;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 插数据的效率比较低,读的效率高
*/
public class ConcurrentHashMapTest {
static Map<UUID,UUID> map = new ConcurrentHashMap<>();
static int count = Constants.COUNT;
static UUID[] keys = new UUID[count];
static UUID[] values = new UUID[count];
static final int THREAD_COUNT =Constants.THREAD_COUNT;
static {
for(int i=0;i<count;i++){
keys[i] = UUID.randomUUID();
values[i] = UUID.randomUUID();
}
}
static class MyThread extends Thread{
int start;
int gap = count/THREAD_COUNT;
public MyThread(int start){
this.start=start;
}
@Override
public void run() {
for(int i=start;i<start+gap;i++){
map.put(keys[i],values[i]);
}
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
Thread[] threads =new Thread[THREAD_COUNT];
for(int i=0;i<threads.length;i++){
threads[i] =
new MyThread(i*(count/THREAD_COUNT));
}
for(Thread t:threads){
t.start();
}
for(Thread t:threads){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long end =System.currentTimeMillis();
System.out.println("插入耗时"+(end-start)+"ms");
System.out.println(map.size());
start=System.currentTimeMillis();
for(int i=0;i<threads.length;i++){
threads[i] = new Thread(()->{
for(int j=0;j<10000000;j++){
map.get(keys[10]);
}
});
}
for(Thread t:threads){
t.start();
}
for(Thread t:threads){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
end=System.currentTimeMillis();
System.out.println("获取耗时"+(end-start)+"ms");
}
}
| true
|
9e7987772493ecff542693d0539131b9c0498072
|
Java
|
gautamp8/PMJDY-App
|
/app/src/main/java/org/bom/india_hackaton/activities/TransactionHistoryActivity.java
|
UTF-8
| 2,181
| 2.265625
| 2
|
[] |
no_license
|
package org.bom.india_hackaton.activities;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.bom.android.container.models.banking.Transaction;
import org.bom.india_hackaton.App;
import org.bom.india_hackaton.R;
import org.bom.india_hackaton.activities.base.BaseBankingActivity;
import org.bom.india_hackaton.utils.RxUtils;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;
public class TransactionHistoryActivity extends BaseBankingActivity {
@BindView(R.id.transaction_history_textview)
TextView mTransactionHistoryTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions_history);
ButterKnife.bind(this);
initializeToolbar("Transactions History", true);
fetchTransactionsHistory();
}
private void fetchTransactionsHistory() {
showProgressDialog();
App.getClientContainer().getBankingClient().getTransactionsHistoryObservable()
.compose(RxUtils.<List<Transaction>>applyDefaultSchedulers(this))
.subscribe(new Action1<List<Transaction>>() {
@Override
public void call(List<Transaction> transactions) {
hideProgressDialog();
showTransactions(transactions);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable error) {
hideProgressDialog();
showError(error);
}
});
}
private void showTransactions(List<Transaction> transactions) {
StringBuilder sb = new StringBuilder();
for (Transaction transaction : transactions) {
sb.append(App.getSharedGson().toJson(transaction)).append("\n\n");
System.out.println("Txn History: " + App.getSharedGson().toJson(transaction));
}
mTransactionHistoryTextView.setText(sb.toString());
}
}
| true
|
c6a5b1007712cb57083f7aea6d6ac9f9d29085ea
|
Java
|
yy4r/Myproject
|
/jack/src/main/java/com/example/jack/controller/TestController.java
|
UTF-8
| 401
| 1.984375
| 2
|
[] |
no_license
|
package com.example.jack.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Jack
* @version 1.0
* @date 2020/4/14 16:21
*/
@RestController
public class TestController {
@RequestMapping("/hello")
public String test(){
System.out.println("hello");
return "hello";
}
}
| true
|
e4db11f926d046a428bdc9ef6541b1443c979603
|
Java
|
sondo65/BaseMVP
|
/app/src/main/java/com/sondo65/basemvp/ui/main/MainMvpView.java
|
UTF-8
| 252
| 1.585938
| 2
|
[] |
no_license
|
package com.sondo65.basemvp.ui.main;
import com.sondo65.basemvp.ui.base.MvpView;
public interface MainMvpView extends MvpView {
void showCategoryFragment();
void onRadioButtonCategoryClick();
void lockDrawer();
void unlockDrawer();
}
| true
|
5e54866bc26a12111d41eea10a3a24c63b6aaf3a
|
Java
|
foxcats/LPS
|
/Desktop/myproject/src/Data/TargetPredicate.java
|
UTF-8
| 404
| 2.53125
| 3
|
[] |
no_license
|
package Data;
import java.util.ArrayList;
public class TargetPredicate {
private ArrayList<String> targetList;
public TargetPredicate()
{
this.targetList=new ArrayList<String>();
}
public void addTargetPredicate(String targetPredicate)
{
targetList.add(targetPredicate);
}
public ArrayList<String> getTargetList()
{
return this.targetList;
}
}
| true
|
3dc57d8ec677a2d80bf2286b0e56a616026707d9
|
Java
|
cpt22/WebServer
|
/src/main/java/com/cptingle/WebServer/server/AbstractServlet.java
|
UTF-8
| 2,374
| 2.390625
| 2
|
[] |
no_license
|
package com.cptingle.WebServer.server;
import com.cptingle.WebServer.messaging.Request;
import com.cptingle.WebServer.messaging.Response;
import com.cptingle.WebServer.response.Status;
import jdk.net.SocketFlow;
import java.io.IOException;
public abstract class AbstractServlet implements HTTPServlet {
protected String[] uris;
protected HTTPServer server;
public AbstractServlet(HTTPServer server, String[] uris) {
this.server = server;
this.uris = uris;
}
public String[] getURIs() {
return uris;
}
public void get(ClientConnection conn, Request req) {
System.err.println("superpoop");
Response resp = new Response(conn, Status.METHOD_NOT_ALLOWED);
resp.buildErrorPage();
try {
conn.sendResponse(resp);
} catch (IOException e) {
e.printStackTrace();
}
}
public void head(ClientConnection conn, Request req) {
Response resp = new Response(conn, Status.METHOD_NOT_ALLOWED);
resp.buildErrorPage();
try {
conn.sendResponse(resp);
} catch (IOException e) {
e.printStackTrace();
}
}
public void post(ClientConnection conn, Request req) {
Response resp = new Response(conn, Status.METHOD_NOT_ALLOWED);
resp.buildErrorPage();
try {
conn.sendResponse(resp);
} catch (IOException e) {
e.printStackTrace();
}
}
public void put(ClientConnection conn, Request req) {
Response resp = new Response(conn, Status.METHOD_NOT_ALLOWED);
resp.buildErrorPage();
try {
conn.sendResponse(resp);
} catch (IOException e) {
e.printStackTrace();
}
}
public void patch(ClientConnection conn, Request req) {
Response resp = new Response(conn, Status.METHOD_NOT_ALLOWED);
resp.buildErrorPage();
try {
conn.sendResponse(resp);
} catch (IOException e) {
e.printStackTrace();
}
}
public void delete(ClientConnection conn, Request req) {
Response resp = new Response(conn, Status.METHOD_NOT_ALLOWED);
resp.buildErrorPage();
try {
conn.sendResponse(resp);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
66c0cda7970a9c3e19ef7d298a0fc2eef8812737
|
Java
|
UsenkoKonstantinVL/multithreading
|
/src/main/java/NumberTranslator/NumberTranslater.java
|
UTF-8
| 3,179
| 3.71875
| 4
|
[] |
no_license
|
package NumberTranslator;
import java.util.HashMap;
/**
* Класс перевода из буквенного представления числа в цифровое
*/
public class NumberTranslater {
private HashMap<String, Integer> numberMap;
private HashMap<String, Integer> degreeMap;
public NumberTranslater(){
numberMap = new HashMap<>();
degreeMap = new HashMap<>();
initializeNumberMap();
initializeDegreeMap();
}
/***
* Функция, возвращающая цифровое представление буквенной записи
* @param number Строковое представление числа
* @return Цифровое представление строки
* @throws Exception
*/
public int getNumber(String number) throws Exception{
int res = 0;
String strArr[] = number.split(" ");
res = convertStrintToNumber(strArr);
return res;
}
/***
* Конвертер из строки в число
* @param strMass массив из слов
* @return число
* @throws Exception
*/
private int convertStrintToNumber(String[] strMass) throws Exception{
int res = 0;
for(int i = strMass.length - 1; i != -1; i--){
if(degreeMap.containsKey(strMass[i].toLowerCase())){
if(i != -1 && numberMap.containsKey(strMass[i - 1].toLowerCase())){
res += degreeMap.get(strMass[i]) * numberMap.get(strMass[i - 1]);
i--;
}
}
else if(numberMap.containsKey(strMass[i].toLowerCase())){
res += numberMap.get(strMass[i]);
}
else {
throw new NumberException(strMass[i]);
}
}
return res ;
}
public class NumberException extends Exception{
public NumberException(String res){
super("Error in word: " + res);
}
}
private void initializeNumberMap(){
numberMap.put("one", 1);
numberMap.put("two", 2);
numberMap.put("three", 3);
numberMap.put("four", 4);
numberMap.put("five", 5);
numberMap.put("six", 6);
numberMap.put("seven", 7);
numberMap.put("eight", 8);
numberMap.put("nine", 9);
numberMap.put("ten", 10);
numberMap.put("eleven", 11);
numberMap.put("twelve", 12);
numberMap.put("thirteen", 13);
numberMap.put("fourteen", 14);
numberMap.put("fifteen", 15);
numberMap.put("sixteen", 16);
numberMap.put("seventeen", 17);
numberMap.put("eighteen", 18);
numberMap.put("nineteen", 19);
numberMap.put("twenty", 20);
numberMap.put("thirty", 30);
numberMap.put("forty", 40);
numberMap.put("fifty", 50);
numberMap.put("sixty", 60);
numberMap.put("seventy", 70);
numberMap.put("eighty", 80);
numberMap.put("ninety", 90);
}
private void initializeDegreeMap(){
degreeMap.put("hundred", 100);
degreeMap.put("thousand", 1000);
}
}
| true
|
4bb19d7cdfbb70bd98336f82566200f1a7bc8282
|
Java
|
yashu183/Coda-java-tarining
|
/LabManual/CommandLineArg.java
|
UTF-8
| 349
| 3.03125
| 3
|
[] |
no_license
|
package labAssignment;
public class CommandLineArg {
public static void main(String[] args) {
System.out.println("printing command line arguements.....");
if(args.length == 0)
System.out.println("No command line arguements given");
else
for(int i = 0; i <args.length; i++)
{
System.out.println(args[i]);
}
}
}
| true
|
c752b6da5a58e4f0fd81673e912e2528df0bd196
|
Java
|
rasm586m/AndroidProjects
|
/src/main/java/com/example/recyclerviewdemo/storage/NoteStorage.java
|
UTF-8
| 662
| 2.875
| 3
|
[] |
no_license
|
package com.example.recyclerviewdemo.storage;
import com.example.recyclerviewdemo.model.Note;
import java.util.ArrayList;
import java.util.List;
public class NoteStorage {
public static List<Note> list;
static {
list = new ArrayList<>();
Note n1 = new Note("1", "Jens");
Note n2 = new Note("2", "Er en mand...");
list.add(n1);
list.add(n2);
}
public static Note getNote(int index) {
return list.get(index);
}
public static int getLength() {
return list.size();
}
public static List<Note> getList() {
return list;
}
}
| true
|
130afa86944c7547f2158e491f5f52cc177c6b79
|
Java
|
YoshikiHigo/MPAnalyzer
|
/src/main/java/yoshikihigo/cpanalyzer/lexer/token/IMPORT.java
|
UTF-8
| 129
| 1.765625
| 2
|
[
"MIT"
] |
permissive
|
package yoshikihigo.cpanalyzer.lexer.token;
public class IMPORT extends Token {
public IMPORT() {
super("import");
}
}
| true
|
52f2ec52bd9be17ce11f597151a1c71d1e567da3
|
Java
|
wmateer/Animawl-Brawl
|
/Swing_GUI_TEST/Animawls_SWING/src/Networking/chatWindowClient.java
|
UTF-8
| 2,942
| 2.921875
| 3
|
[] |
no_license
|
package Networking;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import GameEngine.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.Scanner;
public class chatWindowClient extends JFrame {
private JTextArea chatWindow;
private JScrollPane chatCase;
private JTextField userInput;
private JButton submit;
private User uZero;
private User uOne;
private JPanel content;
private Socket mySocket;
private PrintWriter outWriter;
private BufferedReader in;
private BufferedReader stdIn;
public chatWindowClient(User inZero, User inOne) {
this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
this.setBounds(500, 200, 500, 600);
this.setTitle("Client");
getContentPane().setLayout(null);
uZero=inZero;
uOne=inOne;
//initialize variables
//chat window
chatWindow=new JTextArea(100,100);
chatWindow.setBackground(Color.white);
chatWindow.setBounds(50, 50,400, 400);
chatWindow.setLineWrap(true);
chatWindow.setVisible(true);
//scroll pane for chat area
/*chatCase=new JScrollPane();
chatCase.setVisible(true);
chatCase.setBackground(Color.white);
chatCase.setViewportView(chatWindow);
*/
//user input text feild
userInput=new JTextField();
userInput.setBounds(150, 500, 300, 50);
userInput.setVisible(true);
submit= new JButton("Submit");
submit.addActionListener(new submitListner());
submit.setBounds(50, 500, 100, 50);
submit.setVisible(true);
this.add(submit);
this.add(chatWindow);
//this.add(chatCase);
this.add(userInput);
this.setVisible(true);
try {
mySocket= new Socket("localhost", 4444);
outWriter= new PrintWriter(mySocket.getOutputStream(),true);
in= new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
stdIn= new BufferedReader(new InputStreamReader(System.in));
int i=0;
while(i==0){
if (in.ready()) {
chatWindow.append((in.readLine())); // Read one line and output it
}
}
/*
int i=0;
while(i==1){
try {
System.out.println(in.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("it didnt work");
}
/*
String serverInput;
try {
while((serverInput= stdIn.readLine()) !=null){
out.println(userInput);
System.out.println("server: " + in.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
public class submitListner implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String userIn= userInput.getText();
String toAdd= "\n"+uZero.getName()+": "+ userIn+"\n";
userInput.setText("");
chatWindow.append(toAdd);
outWriter.println(toAdd);
}
}
}
| true
|
5ada5efed6817d0263e998499c8f3d1fef08c033
|
Java
|
nestaale/UML2JavaTest1
|
/dst/socketwordcountdataflow/datatypes/WordCount.java
|
UTF-8
| 975
| 2.671875
| 3
|
[] |
no_license
|
package socketwordcountdataflow.datatypes;
public class WordCount {
private String word;
// org.eclipse.uml2.uml.internal.impl.PrimitiveTypeImpl@61e3a1fd (name: String, visibility: <unset>) (isLeaf: false, isAbstract: false, isFinalSpecialization: false)
private Integer count;
// org.eclipse.uml2.uml.internal.impl.PrimitiveTypeImpl@7e8e8651 (name: Integer, visibility: <unset>) (isLeaf: false, isAbstract: false, isFinalSpecialization: false)
public WordCount() {
}
public WordCount(String word,Integer count) {
this.word = word;
this.count = count;
}
public String getword() {
return word;
}
public void setword(String word) {
this.word = word;
}
public Integer getcount() {
return count;
}
public void setcount(Integer count) {
this.count = count;
}
@Override
public String toString() {
return "(" + this.word + this.count + ")";
}
}
| true
|
8711c71ed667d50515b5f715ed4b7e02829da742
|
Java
|
wangyao616/17050401
|
/成薏1705040127/src/Study.java
|
GB18030
| 2,610
| 2.96875
| 3
|
[] |
no_license
|
package f;
import javax.swing.*;
import java.awt.*; //Ҫİ
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Study extends JFrame implements ActionListener{
Double y,m,p1,p2,a;
JTextField jTYearField=null;
JTextField jTNeedField=null;
JTextField jTMoneyField=null;
JTextField jTChengField=null;
JLabel jLabel1,jLabel2,jLabel3,jLabel4;
JPanel jp1,jp2,jp3,jp4,jp5;
JButton jb1; //ť
public Study(){
jTYearField = new JTextField(24);
jTNeedField = new JTextField(24);
jTMoneyField = new JTextField(24);
jTChengField = new JTextField(24);
jLabel1 = new JLabel("");
jLabel2 = new JLabel("洢");
jLabel3 = new JLabel("ֳ16λʱ洢ļ۸");
jLabel4 = new JLabel("ɱΪ");
jb1 = new JButton("");
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jp4 = new JPanel();
jp5 = new JPanel();
jb1.addActionListener(this);
//ò
this.setLayout(new GridLayout(5,1));
jp1.add(jLabel1);
jp1.add(jTYearField);
jp2.add(jb1);
jp3.add(jLabel2);
jp3.add(jTNeedField);
jp4.add(jLabel3);
jp4.add(jTMoneyField);
jp5.add(jLabel4);
jp5.add(jTChengField);
this.add(jp1);
this.add(jp2);
this.add(jp3);
this.add(jp4);
this.add(jp5);
this.setSize(500, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setTitle("");
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("")){//°ťЧ
y=Double.parseDouble(jTYearField.getText());
m=Math.pow(Math.E, 0.28*(y-1960))*4080;
p2=Math.pow(0.72, (y-1974))*m*0.048;
a=m/200*4000;
jTNeedField.setText(String.valueOf(m));
jTMoneyField.setText(String.valueOf(p2));;
jTChengField.setText(String.valueOf(a));
}
}
public static void main(String[] args){
new Study();
}
}
| true
|
d6f1e45620edca7c73db199ca3955b6bdbf850ed
|
Java
|
chankibiswas/algorithm
|
/src/main/java/com/example/algorithm/arrays/RotateArrayKTimes.java
|
UTF-8
| 635
| 3.453125
| 3
|
[] |
no_license
|
package com.example.algorithm.arrays;
public class RotateArrayKTimes {
public void rotate(final int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(final int[] nums, final int start, final int end) {
int low = start;
int high = end;
while (low < high) {
nums[low] = nums[low] + nums[high];
nums[high] = nums[low] - nums[high];
nums[low] = nums[low] - nums[high];
low++;
high--;
}
}
}
| true
|
c5be9c84c5cab0e58843e5b88bc1882ed25e09d4
|
Java
|
kirillsun1/Neverland
|
/Server/Neverland/src/test/java/ee/knk/neverland/service/impl/ProofServiceImplTest.java
|
UTF-8
| 2,318
| 2.15625
| 2
|
[] |
no_license
|
package ee.knk.neverland.service.impl;
import ee.knk.neverland.entity.Proof;
import ee.knk.neverland.entity.Quest;
import ee.knk.neverland.entity.User;
import ee.knk.neverland.repository.ProofRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Optional;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
public class ProofServiceImplTest {
@Mock
private ProofRepository proofRepository;
@InjectMocks
private ProofServiceImpl proofService;
@Mock
private User user;
@Mock
private Proof proof;
@Mock
private Quest quest;
@Test
public void testIfAddProofCallsRepo() {
when(proofRepository.saveAndFlush(proof)).thenReturn(proof);
proofService.addProof(proof);
verify(proofRepository).saveAndFlush(proof);
}
@Test
public void testIfGetUsersProofsCallsRepo() {
when(proofRepository.getProofsByUser(user)).thenReturn(new ArrayList<>());
proofService.getUsersProofs(user);
verify(proofRepository).getProofsByUser(user);
}
@Test
public void testIfGetQuestsProofsCallsRepo() {
when(proofRepository.getProofsByQuest(quest)).thenReturn(new ArrayList<>());
proofService.getQuestsProofs(quest);
verify(proofRepository).getProofsByQuest(quest);
}
@Test
public void testIfGetAllProofsCallsRepo() {
when(proofRepository.findAllAndSort()).thenReturn(new ArrayList<>());
proofService.getAllProofs();
verify(proofRepository).findAllAndSort();
}
@Test
public void testIfExistsProofWithUserAndQuestReturnsFalseIfRepoGivesEmptyOptional() {
when(proofRepository.findProofByUserAndQuest(user, quest)).thenReturn(Optional.empty());
assert (!proofService.existsProofWithUserAndQuest(user, quest));
}
@Test
public void testIfExistsProofWithUserAndQuestReturnsTrueIfRepoGivesObjectInOptional() {
when(proofRepository.findProofByUserAndQuest(user, quest)).thenReturn(Optional.of(proof));
assert (proofService.existsProofWithUserAndQuest(user, quest));
}
}
| true
|
7455621977147a570b08becaeeee67478af5162b
|
Java
|
MkHunter/zapapp
|
/AppMovil/app/src/main/java/com/penautsoft/zapapp/VerificationActivity.java
|
UTF-8
| 5,872
| 2.15625
| 2
|
[] |
no_license
|
package com.penautsoft.zapapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.penautsoft.zapapp.Networking.RequestHandler;
import java.util.HashMap;
import java.util.Map;
public class VerificationActivity extends AppCompatActivity implements Dialogs.LoadingResponseDialog.ResponseCallBack{
private LinearLayout numbersView;
private TextView[] txvNumbers;
private TextView txvPhonePlaceHolder;
private char[] numberList;
private String phone = "6673474353";
private int size = 0, idUser;
private Dialogs.LoadingResponseDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
setSupportActionBar((Toolbar) findViewById(R.id.act_veri_tool));
new Thread(new Runnable() {
@Override
public void run() {
initComponents();
phone = getIntent().getStringExtra("typedPhone");
idUser = getIntent().getIntExtra("idUser",-1);
final String text = getString(R.string.number_holder,phone != null ? phone : "");
final SpannableString spannable = new SpannableString(text);
if( phone != null)
spannable.setSpan(new StyleSpan(Typeface.BOLD),text.length()-10,text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txvPhonePlaceHolder.post(new Runnable() {
@Override
public void run() {
txvPhonePlaceHolder.setText(spannable,TextView.BufferType.SPANNABLE);
}
});
}
}).start();
}
private void initComponents(){
numbersView = findViewById(R.id.act_veri_number_list);
txvPhonePlaceHolder = findViewById(R.id.act_veri_phone_place);
txvNumbers = new TextView[5];
numberList = new char[5];
LinearLayout view;
for (int i = 0; i < numbersView.getChildCount(); i++) {
view = (LinearLayout) numbersView.getChildAt(i);
txvNumbers[i] = (TextView) view.getChildAt(0);
}
}
private void popActivity(){
Intent intent = new Intent(this,Login.class);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if( id == android.R.id.home)
popActivity();
return super.onOptionsItemSelected(item);
}
public void typeNumber(View view){
if( size < 5){
TextView txv = (TextView) view;
String txt = txv.getText().toString();
numberList[size] = txt.charAt(0);
txvNumbers[size].setText(txt);
size++;
}
}
public void deleteNumber(View view){
if( size > 0){
size--;
numberList[size] = ' ';
txvNumbers[size].setText("");
}
}
public void verificate(View view){
String msg = "Codigo Ingresado: "+String.valueOf(numberList);
Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
if( size == 5) {
dialog = Dialogs.LoadingResponseDialog.display(getSupportFragmentManager(), this);
RequestHandler handler = new RequestHandler(this);
RequestHandler.PUT postHandler = handler.put();
try{
String url = getResources().getString(R.string.host)
+"api/Register"; //Rutas Nueva/Oficial
Map<String,Object> body = new HashMap<>();
body.put("idUsuario",idUser);
body.put("codigo",String.valueOf(numberList));
postHandler.verifyAccount(url, body, new RequestHandler.callBack() {
@Override
public void respuesta(Object response) {
Map<String,Object> data = (Map<String, Object>) response;
boolean successRegister = (boolean) data.get("status");
Object[] bundle = new Object[6];
if( !successRegister ){
bundle[0] = "Cerrar";
bundle[1] = "No se pudo verificar el numero";
bundle[2] = R.drawable.dialog_top_icon_error;
}else{
bundle[0] = "Ir al login";
bundle[1] = "Cuenta verificada exitasamente";
bundle[2] = R.drawable.dialog_top_icon_success;
}
dialog.showResponse(successRegister,bundle);
}
@Override
public void error(VolleyError msg) {
Toast.makeText(VerificationActivity.this,"Error",Toast.LENGTH_SHORT).show();
}
});
}catch(Exception e){
e.printStackTrace();
}
}
}
@Override
public void onBackPressed() {
popActivity();
}
@Override
public void onTouch(boolean sucess) {
if( sucess ) {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
}else{
dialog.dismissDialog();
}
}
}
| true
|
5c96d1577250c168d2a0510f53009a7afcf4e7fa
|
Java
|
svsaikumar/lara
|
/lara/sep-4th batch/java/36.Exception handling/part-1/src/X.java
|
UTF-8
| 348
| 2.9375
| 3
|
[] |
no_license
|
class X
{
public static void main(String[] args)
{
System.out.println("main begin");
try
{
int i = 10;
i = 10/0;
}
catch (ArithmeticException ex) //throwable
{
ex = null;
}
System.out.println("main end" + ex);
}
}
//here "ex" is argument to catch(i.e.,it is local to catch)
//we can't use it outside of catch
| true
|
162bf638e343293451fa5d8c50ce446f4a71f1b2
|
Java
|
shantanuranjan/RestaurantReservation
|
/src/com/reservation/rest/controller/OwnerController.java
|
UTF-8
| 3,790
| 2.40625
| 2
|
[] |
no_license
|
package com.reservation.rest.controller;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.reservation.appresponse.AppResponse;
import com.reservation.daos.OwnerDAO;
import com.reservation.daos.ReserveDAO;
import com.reservation.exception.AppException;
import com.reservation.models.Message;
import com.reservation.models.Owner;
import com.reservation.models.Reservation;
@Path("/owner")
public class OwnerController {
@GET
@Path("/verifylogin/{username}/{password}")
@Produces(MediaType.APPLICATION_JSON)
public AppResponse verifyLogin(@PathParam("username") String username,@PathParam("password") String password){
AppResponse resp = new AppResponse();
try {
OwnerDAO dao=new OwnerDAO();
Owner own = dao.verifyLogin(username,password);
resp.setPayload(own);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@POST
@Path("/update/{userOwner}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public AppResponse addReservation(Owner own,@PathParam("userOwner") String userOwner) {
AppResponse resp = new AppResponse();
try {
OwnerDAO dao = new OwnerDAO();
own = dao.updateOwner(own,userOwner);
resp.setMessage("Information updated");
resp.setPayload(own);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@GET
@Path("/searchOwner/{usernameOwner}")
@Produces(MediaType.APPLICATION_JSON)
public AppResponse searchOwner(@PathParam("usernameOwner") String usernameOwner){
AppResponse resp = new AppResponse();
try {
OwnerDAO dao=new OwnerDAO();
Owner own = dao.searchOwner(usernameOwner);
resp.setPayload(own);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@POST
@Path("/message")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public AppResponse sendMessage(Message msg) {
AppResponse resp = new AppResponse();
try {
OwnerDAO dao = new OwnerDAO();
msg = dao.sendMessage(msg);
resp.setMessage("Thank you for Contacting us.Your message has successfully reached to our system.");
resp.setPayload(msg);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@POST
@Path("/delete/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public AppResponse removeReservation(@PathParam("id") int id) {
AppResponse resp = new AppResponse();
try {
OwnerDAO dao = new OwnerDAO();
String str = dao.removeReservation(id);
resp.setMessage("Reservation successfully deleted");
resp.setPayload(str);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@POST
@Path("/addOwner/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public AppResponse addReservationOwner(Reservation res,@PathParam("id") int tableno) {
AppResponse resp = new AppResponse();
try {
OwnerDAO dao = new OwnerDAO();
res = dao.addReservationOwner(res,tableno);
resp.setMessage("Reservation has been added to the system.");
resp.setPayload(res);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
}
| true
|
e07234aa0bfa99f62ca306ace6ac50df568a1669
|
Java
|
andrecezario/digiteca
|
/src/aplicacao/administrador/eventos/MenuItemAddLivroEstanteListener.java
|
UTF-8
| 4,747
| 2.59375
| 3
|
[] |
no_license
|
package aplicacao.administrador.eventos;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
import aplicacao.FacadeAdministrador;
import aplicacao.eventos_sistema.BotaoCancelarListener;
public class MenuItemAddLivroEstanteListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//Janela
JFrame adicionarFrame = new JFrame();
adicionarFrame.setTitle("Sistema DigiTeca - Adicionar Livro a Estante");
adicionarFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
adicionarFrame.setLocation(200, 200);
//Container
Container ct = adicionarFrame.getContentPane();
ct.setLayout(new BorderLayout());
ct.setBackground(Color.white);
// Borda
int tamanho_borda = 30;
JPanel panelEast = new JPanel();
panelEast.setOpaque(true);
panelEast.setPreferredSize(new Dimension(tamanho_borda, tamanho_borda));
panelEast.setBackground(Color.WHITE);
JPanel panelWest = new JPanel();
panelWest.setOpaque(true);
panelWest.setPreferredSize(new Dimension(tamanho_borda, tamanho_borda));
panelWest.setBackground(Color.WHITE);
//Painel Texto
MaskFormatter mascaraIsbn = null;
MaskFormatter mascaraId = null;
try {
mascaraIsbn = new MaskFormatter("###-##-###-####-#");
mascaraId = new MaskFormatter("U-###");
mascaraIsbn.setPlaceholderCharacter('_');
mascaraId.setPlaceholderCharacter('_');
} catch (ParseException excp) {
JOptionPane.showMessageDialog(null, excp.getMessage());
System.exit(-1);
}
// Seta as máscaras nos objetos JFormattedTextField
JFormattedTextField campoIdEstante = new JFormattedTextField(mascaraId);
JFormattedTextField campoIsbn = new JFormattedTextField(mascaraIsbn);
JPanel painel = new JPanel();
painel.setLayout(new FlowLayout());
painel.setBackground(Color.white);
JLabel idEstante= new JLabel("Digite o ID da estante:");
painel.add(idEstante);
painel.add(campoIdEstante);
JLabel isbn = new JLabel("Digite o ISBN do livro (OS LIVROS DEVEM ESTAR PREVIAMENTE CADASTRADOS):");
painel.add(isbn);
painel.add(campoIsbn);
//Icone do rotulo incial (Adicionar livro a estante)
Icon iconeRotulo = new ImageIcon("src/aplicacao/icones/rotAddLivroEstante.png");
JLabel rotulo = new JLabel(iconeRotulo);
rotulo.setBackground(Color.white);
//Botoes
JPanel painelBotoes = new JPanel();
painelBotoes.setBackground(Color.white);
Icon icone1 = new ImageIcon("src/aplicacao/icones/iconeEntrar.png");
Icon icone2 = new ImageIcon("src/aplicacao/icones/iconeRemover.png");
JButton botaoCadastrar = new JButton("Adicionar", icone1);
JButton botaoCancelar = new JButton("Cancelar", icone2);
painelBotoes.add(botaoCancelar);
painelBotoes.add(botaoCadastrar);
ct.add(rotulo,BorderLayout.NORTH);
ct.add(painel,BorderLayout.CENTER);
ct.add(panelWest, BorderLayout.WEST);
ct.add(panelEast, BorderLayout.EAST);
ct.add(painelBotoes,BorderLayout.SOUTH);
//Tratando o evento do botao cadastrar
BotaoAddLivroEstanteListener ouvinteCadastrar = new BotaoAddLivroEstanteListener(campoIsbn,campoIdEstante,adicionarFrame);
botaoCadastrar.addActionListener(ouvinteCadastrar);
//Tratando o evento do botao cancelar
BotaoCancelarListener ouvinteCancelar = new BotaoCancelarListener(adicionarFrame);
botaoCancelar.addActionListener(ouvinteCancelar);
adicionarFrame.pack();
adicionarFrame.setResizable(false);
adicionarFrame.setVisible(true);
}
//Usando uma classe interna para tratar o evento do "botao cadastrar" para registrar uma estante no sistema
private class BotaoAddLivroEstanteListener implements ActionListener{
private FacadeAdministrador fachadaAdm = new FacadeAdministrador();
private JTextField idEstante;
private JTextField isbn;
private JFrame janela;
public BotaoAddLivroEstanteListener(JTextField isbn,JTextField idEstante, JFrame janela) {
this.idEstante = idEstante;
this.isbn = isbn;
this.janela = janela;
}
@Override
public void actionPerformed(ActionEvent e) {
fachadaAdm.adicionarLivroEstante(isbn.getText(),idEstante.getText());
janela.dispose();
}
}
}
| true
|
3573a68fdd99a3641aa950df06ca7144a173ad1a
|
Java
|
barileanna/4AInf1920
|
/016_Bottiglia/src/it/itis/cuneo/nonTrovatoException.java
|
UTF-8
| 547
| 2.6875
| 3
|
[] |
no_license
|
package it.itis.cuneo;
/**
* Created by inf.barilea1810 on 04/11/2019.
*/
public class nonTrovatoException extends Exception{
private int codice;
private String descrizione;
public nonTrovatoException(int codice, String descrizione) {
this.codice = codice;
this.descrizione = descrizione;
}
@Override
public String toString() {
return "Valore{" +
"codice=" + codice +
", descrizione='" + descrizione + '\'' +
'}';
}
}
| true
|
8409ae667ac21195e04bb0fcd7062fede5099073
|
Java
|
lsflsf520/commons
|
/common-tools/src/main/java/com/xyz/tools/common/utils/BaseConfig.java
|
UTF-8
| 8,896
| 2.390625
| 2
|
[] |
no_license
|
package com.xyz.tools.common.utils;
import java.io.File;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import com.xyz.tools.common.exception.BaseRuntimeException;
/**
* 默认classpath下的conf/commons.properties, 不需要spring
*
* @author lsf 2012-2-8 下午5:01:28
*/
public final class BaseConfig {
private BaseConfig() {
}
public enum FileName {
application, redis
}
private static final Map<FileName, Configuration> CONF_MAP = new ConcurrentHashMap<FileName, Configuration>(4);
private static final Logger LOG = LoggerFactory.getLogger(BaseConfig.class);
static {
init();
}
public synchronized static void init() {
FileName[] values = FileName.values();
// CONF_MAP.clear();
for (FileName fileName : values) {
try {
String filePath = getPath(fileName + ".properties");
if (StringUtils.isBlank(filePath)) {
System.out.println("file '" + fileName + ".properties' not exists in classpath, then try to parse '"
+ fileName + ".xml'");
filePath = getPath(fileName + ".xml");
if (StringUtils.isBlank(filePath)) {
System.out.println("No properties file or xml file named '" + fileName
+ "' exists in classpath or java.user.dir '" + System.getProperty("user.dir") + "'");
continue;
}
CONF_MAP.put(fileName, new XMLConfiguration(filePath));
System.out.println("found file '" + fileName + "'.xml in path '" + filePath + "'");
continue;
}
CONF_MAP.put(fileName, new PropertiesConfiguration(filePath));
System.out.println("found file '" + fileName + "'.properties in path '" + filePath + "'");
} catch (ConfigurationException e) {
System.err.println(fileName + ".properties file parsed error. msg(" + e.getMessage() + ")");
e.printStackTrace();
}
}
}
public static String getPath(String fileName) {
String filePath = fileName;
if (new File(filePath).exists()) {
return fileName;
}
String fileSuffix = fileName.startsWith(File.separator) || fileName.startsWith("\\") ? fileName
: File.separator + fileName;
String configDir = System.getProperty("project.config.dir");
filePath = configDir + fileSuffix;
if (new File(filePath).exists()) {
return filePath;
}
String userDir = System.getProperty("user.dir");
filePath = userDir + fileSuffix;
if (new File(filePath).exists()) {
return filePath;
}
URL url = BaseConfig.class.getResource(fileSuffix);
if (url == null) {
url = BaseConfig.class.getClassLoader().getResource(fileName);
return url == null ? null : url.toString();
}
return url.toString();
}
/**
*
* @param key
* *.properties文件中的key
* @return 在CONFIG_FILE_NAME_SET这个集合指定的所有配置文件中,挨个查找key的值,返回第一个找到的值.
* 如果一个都没找到,则返回null
*/
public static String getValue(String key) {
return getValue(key, null);
}
/**
*
* @param key
* @return
*/
public static Integer getInt(String key) {
String val = getValue(key);
return parseInt(key, val, null);
}
/**
*
* @param key
* @param defVal
* @return
*/
public static int getInt(String key, int defVal) {
String val = getValue(key);
return parseInt(key, val, defVal);
}
/**
*
* @param key
* @return
*/
public static Boolean getBool(String key) {
String val = getValue(key);
if ("true".equalsIgnoreCase(val)) {
return true;
}
return false;
}
public static String[] getValueArr(String key) {
FileName[] fileNames = FileName.values();
for (FileName fileName : fileNames) {
Configuration config = CONF_MAP.get(fileName);
if (config == null) {
// LOG.warn("file with name '" +fileName + "' not found!");
continue;
}
return config.getStringArray(key);
}
return null;
}
public static int[] getIntArr(String key) {
String[] valArr = getValueArr(key);
if (valArr == null || valArr.length <= 0) {
return new int[0];
}
int[] valIntArr = new int[valArr.length];
for (int index = 0; index < valArr.length; index++) {
valIntArr[index] = parseInt(key, valArr[index], null);
}
return valIntArr;
}
private static int parseInt(String key, String val, Integer defaultVal) {
if (StringUtils.isBlank(val)) {
return defaultVal;
}
if (RegexUtil.isInt(val)) {
return Integer.valueOf(val);
}
if (defaultVal != null) {
return defaultVal;
}
throw new BaseRuntimeException("ILLEGAL_DATA",
"value '" + val + "' is not integer or not defined for key '" + key + "'");
}
/**
*
* @param key
* *.properties文件中的key
* @param defaultVal
* 在*.properties中找不到key所对应的值时,返回该值
* @return 在FileName这个枚举类指定的所有配置文件中,挨个查找key的值,返回第一个找到的值. 如果一个都没找到,则返回defaultVal
*/
public static String getValue(String key, String defaultVal) {
FileName[] fileNames = FileName.values();
for (FileName fileName : fileNames) {
Configuration config = CONF_MAP.get(fileName);
String value = null;
if (config == null) {
// LOG.warn("file with name '" +fileName + "' not found!");
continue;
}
String[] values = config.getStringArray(key);
if (values != null && values.length > 1) {
for (int index = 0; index < values.length; index++) {
values[index] = replaceVariables(values[index]);
}
value = StringUtils.join(values, ",");
} else {
value = config.getString(key);
value = replaceVariables(value);
}
if (!StringUtils.isBlank(value)) {
// LOG.debug("find value for key("+key+") in config file
// '"+fileName+".properties'");
return value;
}
}
return defaultVal;
}
private static String replaceVariables(String value) {
if (StringUtils.isNotBlank(value)) {
List<String> paramNames = RegexUtil.getParamNames(value);
if (!CollectionUtils.isEmpty(paramNames)) {
for (String paramName : paramNames) {
String paramVal = getValue(paramName);
if (StringUtils.isNotBlank(paramVal)) {
value = RegexUtil.replaceParamName(value, paramName, paramVal);
}
}
}
}
return value;
}
/**
* 根据前缀获取键值对信息, 其中的key不包含prefix
*
* @param prefix
* @return
*/
public static Map<String, String> getKvMapWithoutPrefix(String prefix) {
Map<String, String> kvMap = new LinkedHashMap<>();
FileName[] fileNames = FileName.values();
for (FileName fileName : fileNames) {
Configuration config = CONF_MAP.get(fileName);
String value = null;
if (config == null) {
// LOG.warn("file with name '" +fileName + "' not found!");
continue;
}
Iterator<String> itr = config.getKeys(prefix);
while (itr.hasNext()) {
String key = itr.next();
String[] values = config.getStringArray(key);
if (values != null && values.length > 1) {
value = StringUtils.join(values, ",");
} else {
value = config.getString(key);
}
String suffix = key.replace(prefix, "");
if (suffix.startsWith(".")) {
suffix = suffix.substring(1);
}
kvMap.put(suffix, value);
}
}
return kvMap;
}
/**
* 根据前缀获取键值对信息
*
* @param prefix
* @return
*/
public static Map<String, String> getKvMap(String prefix) {
Map<String, String> kvMap = new LinkedHashMap<>();
FileName[] fileNames = FileName.values();
for (FileName fileName : fileNames) {
Configuration config = CONF_MAP.get(fileName);
String value = null;
if (config == null) {
// LOG.warn("file with name '" +fileName + "' not found!");
continue;
}
Iterator<String> itr = config.getKeys(prefix);
while (itr.hasNext()) {
String key = itr.next();
String[] values = config.getStringArray(key);
if (values != null && values.length > 1) {
value = StringUtils.join(values, ",");
} else {
value = config.getString(key);
}
kvMap.put(key, value);
}
}
return kvMap;
}
}
| true
|
7eea3096f2375e7cf80beb4b406690c4a7322715
|
Java
|
journeymanavi/expertalk-angularjs
|
/fifaworldcup/src/main/java/com/equalexperts/config/SpringWebConfig.java
|
UTF-8
| 1,465
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.equalexperts.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* Created by avinash on 23/6/14.
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.equalexperts")
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/template/**").addResourceLocations("/template/");
registry.addResourceHandler("/WEB-INF/**").addResourceLocations("/WEB-INF/");
}
@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
return resolver;
}
}
| true
|
74571124bbdd84e660490f1ef127070d06164284
|
Java
|
AdamczykMaciej/JavaGUI
|
/GUI4_AM/GUI4_AM_S15170/src/zad2/ReverseTest.java
|
UTF-8
| 1,164
| 3.59375
| 4
|
[] |
no_license
|
/**
*
* @author Adamczyk Maciej S15170
*
*/
package zad2;
public class ReverseTest {
public static void main(String[] args) {
Reversible[] revers = new Reversible[] {
new ReversibleString("Cat"),
new ReversibleDouble(2),
new ReversibleDouble(3),
new ReversibleString("Dog"),
new ReversibleString("Alice has a cat and a dog"),
new ReversibleDouble(10),
};
System.out.println("Normal:");
for (Reversible r : revers) {
System.out.println(r);
}
for (Reversible r : revers) {
r.reverse();
}
System.out.println("Reversed:");
for (Reversible r : revers) {
System.out.println(r);
}
System.out.println("Restored and changed:");
for (Reversible r : revers) {
r.reverse();
if(r instanceof ReversibleString){
System.out.println("Text "+r);
}
else if(r instanceof ReversibleDouble){
System.out.println(((ReversibleDouble) r).getNumber()+10);
}
}
}
}
| true
|
15273bde71d410f29704e4ef022b62a68c75595f
|
Java
|
cash2one/91
|
/zz91/ast1949-service/src/main/java/com/ast/ast1949/service/autocaiji/impl/AutoCaijiServiceImpl.java
|
UTF-8
| 11,221
| 2.15625
| 2
|
[] |
no_license
|
package com.ast.ast1949.service.autocaiji.impl;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import com.ast.ast1949.domain.autocaiji.AutoCaiji;
import com.ast.ast1949.persist.autocaiji.AutoCaijiDAO;
import com.ast.ast1949.service.autocaiji.AutoCaijiService;
import com.zz91.util.datetime.DateUtil;
import com.zz91.util.lang.StringUtils;
@Component("autoCaijiService")
public class AutoCaijiServiceImpl implements AutoCaijiService {
@Resource
private AutoCaijiDAO autoCaijiDAO;
@Override
public List<AutoCaiji> queryListByFromTo(String fromStr, String toStr) throws ParseException{
Date from = null, to = null;
if (StringUtils.isNotEmpty(fromStr)) {
try {
from = DateUtil.getDate(fromStr, "yyyy-MM-dd");
} catch (ParseException e) {
from = new Date();
}
} else {
from = DateUtil.getDateAfterDays(DateUtil.getDate(new Date(), "yyyy-MM-dd"), -1);
}
if (StringUtils.isNotEmpty(toStr)) {
try {
to = DateUtil.getDate(toStr, "yyyy-MM-dd");
} catch (ParseException e) {
to = new Date();
}
} else {
to = DateUtil.getDate(new Date(), "yyyy-MM-dd");
}
Integer id;
try {
id = DateUtil.getIntervalDays(from, to);
} catch (ParseException e) {
id = 31;
}
if (id.intValue() > 30) {
from = DateUtil.getDateAfterDays(to, -30);
}
List<AutoCaiji> list = autoCaijiDAO.queryListLog(DateUtil.toString(from, "yyyy-MM-dd"),DateUtil.toString(to, "yyyy-MM-dd"));
List<AutoCaiji> newList = new ArrayList<AutoCaiji>();
fromStr = DateUtil.toString(from, "yyyy-MM-dd");
toStr = DateUtil.toString(to, "yyyy-MM-dd");
if (fromStr.equals(toStr)) {
for (AutoCaiji autoCaiji : list) {
JSONObject jb = JSONObject.fromObject(autoCaiji.getLog());
if ("success".equals(autoCaiji.getType())) {
autoCaiji.setDefaultTime(jb.get("defaultTime").toString());
autoCaiji.setEarlyTime(jb.get("catchTime").toString());
autoCaiji.setLateTime(jb.get("catchTime").toString());
} else {
autoCaiji.setDefaultTime(jb.get("defaultTime").toString());
autoCaiji.setNum(1);
}
}
return list;
} else {
for (AutoCaiji autoCaiji : list) {
Integer flg = 0;
String title = autoCaiji.getTitle();
String url = autoCaiji.getUrl();
JSONObject jb = JSONObject.fromObject(autoCaiji.getLog());
String time = jb.get("defaultTime").toString();
autoCaiji.setDefaultTime(jb.get("defaultTime").toString());
if (newList.size() == 0) {
if ("success".equals(autoCaiji.getType())) {
autoCaiji.setEarlyTime(jb.get("catchTime").toString());
autoCaiji.setLateTime(jb.get("catchTime").toString());
} else {
autoCaiji.setNum(1);
}
newList.add(autoCaiji);
} else {
for (AutoCaiji otherautoCaiji : newList) {
if(url.equals(otherautoCaiji.getUrl()) && title.equals(otherautoCaiji.getTitle())
&& time.equals(otherautoCaiji.getDefaultTime())) {
if ("success".equals(autoCaiji.getType())) {
otherautoCaiji.setNum(otherautoCaiji.getNum());
String catchTime = jb.get("catchTime").toString();
if (StringUtils.isNotEmpty(otherautoCaiji.getEarlyTime()) && StringUtils.isNotEmpty(otherautoCaiji.getLateTime())) {
String earlyTime = otherautoCaiji.getEarlyTime();
String lateTime = otherautoCaiji.getLateTime();
Date t1 = (Date) DateUtil.getDate(catchTime, "HH:mm");
Date t2 = (Date) DateUtil.getDate(earlyTime, "HH:mm");
Date t3 = (Date) DateUtil.getDate(lateTime, "HH:mm");
if (t1.getTime()-t2.getTime() < 0) {
otherautoCaiji.setEarlyTime(catchTime);
} else if (t1.getTime()-t3.getTime() > 0){
otherautoCaiji.setLateTime(catchTime);
}
} else {
otherautoCaiji.setEarlyTime(catchTime);
otherautoCaiji.setLateTime(catchTime);
}
flg = 1;
break;
} else {
if (otherautoCaiji.getNum() != null) {
otherautoCaiji.setNum(otherautoCaiji.getNum()+1);
} else {
otherautoCaiji.setNum(1);
}
otherautoCaiji.setEarlyTime(otherautoCaiji.getEarlyTime());
otherautoCaiji.setLateTime(otherautoCaiji.getLateTime());
flg = 1;
break;
}
}
}
if (flg == 0) {
if ("success".equals(autoCaiji.getType())) {
autoCaiji.setEarlyTime(jb.get("catchTime").toString());
autoCaiji.setLateTime(jb.get("catchTime").toString());
} else {
autoCaiji.setNum(1);
}
newList.add(autoCaiji);
}
}
}
return newList;
}
}
/* @Override
public PageDto<AutoCaiji> queryPageByFromTo(PageDto<AutoCaiji> page,
String fromStr, String toStr) throws ParseException {
Date from = null, to = null;
if (StringUtils.isNotEmpty(fromStr)) {
try {
from = DateUtil.getDate(fromStr, "yyyy-MM-dd");
} catch (ParseException e) {
from = new Date();
}
} else {
from = DateUtil.getDateAfterDays(DateUtil.getDate(new Date(), "yyyy-MM-dd"), -1);
}
if (StringUtils.isNotEmpty(toStr)) {
try {
to = DateUtil.getDate(toStr, "yyyy-MM-dd");
} catch (ParseException e) {
to = new Date();
}
} else {
to = DateUtil.getDate(new Date(), "yyyy-MM-dd");
}
if (to.getTime() - from.getTime() < 0) {
to = from;
}
Integer id;
try {
id = DateUtil.getIntervalDays(from, to);
} catch (ParseException e) {
id = 31;
}
if (id.intValue() > 30) {
from = DateUtil.getDateAfterDays(to, -30);
}
if (type.equals("success")) {
List<AutoCaiji> list = autoCaijiDAO.queryListLog(DateUtil.toString(from, "yyyy-MM-dd"),DateUtil.toString(to, "yyyy-MM-dd"));
List<AutoCaiji> newList = new ArrayList<AutoCaiji>();
fromStr = DateUtil.toString(from, "yyyy-MM-dd");
toStr = DateUtil.toString(to, "yyyy-MM-dd");
if (fromStr.equals(toStr)) {
for (AutoCaiji autoCaiji : list) {
JSONObject jb = JSONObject.fromObject(autoCaiji.getLog());
autoCaiji.setDefaultTime(jb.get("defaultTime").toString());
autoCaiji.setEarlyTime(jb.get("catchTime").toString());
autoCaiji.setLateTime(jb.get("catchTime").toString());
}
page.setTotalRecords(list.size());
page.setRecords(list);
} else {
for (AutoCaiji autoCaiji : list) {
Integer flg = 0;
String title = autoCaiji.getTitle();
String url = autoCaiji.getUrl();
JSONObject jb = JSONObject.fromObject(autoCaiji.getLog());
String time = jb.get("defaultTime").toString();
autoCaiji.setDefaultTime(jb.get("defaultTime").toString());
if (newList.size() == 0) {
autoCaiji.setEarlyTime(jb.get("catchTime").toString());
autoCaiji.setLateTime(jb.get("catchTime").toString());
newList.add(autoCaiji);
} else {
for (AutoCaiji otherautoCaiji : newList) {
if(url.equals(otherautoCaiji.getUrl()) && title.equals(otherautoCaiji.getTitle())
&& time.equals(otherautoCaiji.getDefaultTime())) {
String catchTime = jb.get("catchTime").toString();
String earlyTime = otherautoCaiji.getEarlyTime();
String lateTime = otherautoCaiji.getLateTime();
Date t1 = (Date) DateUtil.getDate(catchTime, "HH:mm");
Date t2 = (Date) DateUtil.getDate(earlyTime, "HH:mm");
Date t3 = (Date) DateUtil.getDate(lateTime, "HH:mm");
if (t1.getTime()-t2.getTime() < 0) {
otherautoCaiji.setEarlyTime(catchTime);
} else if (t1.getTime()-t3.getTime() > 0){
otherautoCaiji.setLateTime(catchTime);
}
flg = 1;
break;
}
}
if (flg == 0) {
autoCaiji.setEarlyTime(jb.get("catchTime").toString());
autoCaiji.setLateTime(jb.get("catchTime").toString());
newList.add(autoCaiji);
}
}
}
page.setTotalRecords(newList.size());
page.setRecords(newList);
}
} else {
page.setTotalRecords(autoCaijiDAO.queryCount(DateUtil.toString(from, "yyyy-MM-dd"),DateUtil.toString(to, "yyyy-MM-dd")));
page.setRecords(autoCaijiDAO.queryPageLog(page,DateUtil.toString(from, "yyyy-MM-dd"),DateUtil.toString(to, "yyyy-MM-dd")));
}
return page;
}*/
}
| true
|
f2d9527624784b4bb38f199af513dc91248208ed
|
Java
|
youmeng-shao/weixin
|
/src/main/java/com/sz/mapper/TablesMapper.java
|
UTF-8
| 1,525
| 2.5625
| 3
|
[] |
no_license
|
package com.sz.mapper;
import com.sz.pojo.Tables;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TablesMapper {
/**
* 增加餐桌
* @Param Tables (包括内部桌号,对应的类型 state 都为0, 餐桌的id自动生成的
* @return int
* */
int saveTable(Tables table);
/**
* 根据tableId 查找table
* @Param tableId
* @return tables对象
* */
Tables selectById(@Param("tableId") Integer tableId);
/**
* 更新餐桌的信息
* @Param 对象tables
* @return int
* */
int updetaTables(Tables table);
/**
* 删除餐桌
* @Param tableId
* @return int
* */
int deleteBytableId(@Param("tableId") Integer tableId);
/**
* 查找所有的餐桌
* @return List元素类型Tables
* */
List<Tables> selectAll();
/*******************微信小程序端需要的功能***************************/
/**
* 返回每种类型的餐桌空闲信息,供顾客筛选
* @Param 餐桌类型id
* @return 餐桌对象tables
* */
Tables selectTablesByCategoryId(@Param("categoryId") Integer categoryId);
/**
* 改变餐桌的状态,把桌号状态置为1
* */
void updetaTablesState(@Param("tableId") Integer tableId);
/**
* 客人改变桌号,需要把当前选择的桌号状态置为 0
* */
void updateCurrentTableIdState(@Param("currentTableId") Integer currentTableId);
}
| true
|
095b61adb10aa42ed9401604494613b7958cae66
|
Java
|
JuanPavon/Ejercicios-Programacion
|
/EjTema4/Ej8Tema4.java
|
UTF-8
| 1,709
| 3.640625
| 4
|
[] |
no_license
|
public class Ej8Tema4 {
public static void main (String [] args) {
System.out.println("Este programa calcula la media de tres notas");
System.out.println("Introduce la primera nota");
double n1 = Double.parseDouble(System.console().readLine());
if (0 < n1) {
System.out.println("Introduce otra nota");
double n2 = Double.parseDouble(System.console().readLine());
if (0 < n2) {
System.out.println("Introduce la última nota");
double n3 = Double.parseDouble(System.console().readLine());
if (0 < n3) {
double media = ((n1 + n2 + n3) / 3);
//aqui empieza el ej 8
if ((0 < media) && (media < 4)) {
System.out.println("La media es " + media + ", insuficiente");
}
if (media == 5) {
System.out.println("La media es " + media + ", suficiente");
}
if (media == 6) {
System.out.println("La media es " + media + ", bien");
}
if ((media == 7) || (media == 8)) {
System.out.println("La media es " + media + ", notable");
}
if ((media == 9) || (media == 10)) {
System.out.println("La media es " + media + ", sobresaliente");
}
// aqui termina el ej 8
} else {
System.out.println("El dato introducido no es correcto");
}
} else {
System.out.println("El dato introducido no es correcto");
}
} else {
System.out.println("El dato introducido no es correcto");
}
}
}
| true
|
3d7651593f9c43b1aee97700cd9aa3c9f3a2e5ff
|
Java
|
kawankfb/android_social_media_client
|
/app/src/main/java/com/example/mvvm/model/PostModel.java
|
UTF-8
| 1,795
| 2.28125
| 2
|
[] |
no_license
|
package com.example.mvvm.model;
import com.example.mvvm.network.RetrofitInstance;
public class PostModel {
public PostModel(String created_at, String updated_at, String text, String file, int user_id, int id, int discussion_id) {
this.created_at = created_at;
this.updated_at = updated_at;
this.text = text;
this.file = file;
this.user_id = user_id;
this.id = id;
this.discussion_id = discussion_id;
}
public String getUrl(){
return RetrofitInstance.BASE_URL+"profile_picture/"+user_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDiscussion_id() {
return discussion_id;
}
public void setDiscussion_id(int discussion_id) {
this.discussion_id = discussion_id;
}
String created_at;
String updated_at;
String text;
String file;
int user_id;
int id;
int discussion_id;
public String getUserName() {
return "anonymous";
}
}
| true
|
e3544f331e085f096b23c9517437e4b3ef4e7ae5
|
Java
|
leeef/Novel
|
/app/src/main/java/com/bx/philosopher/ui/activity/MainActivity.java
|
UTF-8
| 6,553
| 1.835938
| 2
|
[
"MIT"
] |
permissive
|
package com.bx.philosopher.ui.activity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.fragment.app.Fragment;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.bx.philosopher.R;
import com.bx.philosopher.base.activity.BaseTabActivity;
import com.bx.philosopher.base.fragment.BaseLazyFragment;
import com.bx.philosopher.ui.fragment.tabfragment.BookshelfFragment;
import com.bx.philosopher.ui.fragment.tabfragment.ExploreFragment;
import com.bx.philosopher.ui.fragment.tabfragment.LibraryFragment;
import com.bx.philosopher.ui.fragment.tabfragment.PersonSettingFragment;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pub.devrel.easypermissions.EasyPermissions;
public class MainActivity extends BaseTabActivity implements EasyPermissions.PermissionCallbacks {
/*************Constant**********/
private static final String TAG = "MainActivity";
private static final int WAIT_INTERVAL = 2000;
private static final int PERMISSIONS_REQUEST_STORAGE = 1;
static final String[] PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
// LocationService locationService;
/***************Object*********************/
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
/*****************Params*********************/
private boolean isPrepareFinish = false;
@Override
protected int getContentId() {
return R.layout.activity_base_tab;
}
private int tabIndex = 0;//当前展示的页面 默认第一个
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected List<Fragment> createTabFragments() {
initFragment();
return mFragmentList;
}
@Override
protected void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
tabIndex = getIntent().getIntExtra("tabIndex", 0);
}
public static void startActivity(Context context, int tabIndex) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("tabIndex", tabIndex);
context.startActivity(intent);
}
private void initFragment() {
Fragment exploreFragment = new ExploreFragment();
Fragment libraryFragment = new LibraryFragment();
Fragment bookshelfFragment = new BookshelfFragment();
Fragment personSettingFragment = new PersonSettingFragment();
mFragmentList.add(exploreFragment);
mFragmentList.add(libraryFragment);
mFragmentList.add(bookshelfFragment);
mFragmentList.add(personSettingFragment);
}
@Override
protected List<String> createTabTitles() {
String[] titles = getResources().getStringArray(R.array.tab_title);
return Arrays.asList(titles);
}
@Override
protected void initWidget() {
super.initWidget();
setTab(tabIndex);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (menu != null && menu instanceof MenuBuilder) {
try {
Method method = menu.getClass().
getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
method.setAccessible(true);
method.invoke(menu, true);
} catch (Exception e) {
e.printStackTrace();
}
}
return super.onPreparePanel(featureId, view, menu);
}
// void startLocation() {
// locationService = new LocationService();
// locationService.registerListener(bdAbstractLocationListener);
// locationService.start();
// }
@Override
protected void onDestroy() {
super.onDestroy();
// if (locationService != null) {
// locationService.unregisterListener(bdAbstractLocationListener);
// }
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onBackPressed() {
for (Fragment fragment : mFragmentList) {
if (fragment != null) {
if (fragment instanceof BaseLazyFragment) {
if (((BaseLazyFragment) fragment).onBackPressed()) return;
}
}
}
if (!isPrepareFinish) {
mVp.postDelayed(
() -> isPrepareFinish = false, WAIT_INTERVAL
);
isPrepareFinish = true;
Toast.makeText(this, "Press exit again", Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed();
}
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
// switch (requestCode) {
// case LOCATION_REQUEST:
// startLocation();
// break;
// }
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
}
private BDAbstractLocationListener bdAbstractLocationListener = new BDAbstractLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
String addr = location.getAddrStr(); //获取详细地址信息
String country = location.getCountry(); //获取国家
String province = location.getProvince(); //获取省份
String city = location.getCity(); //获取城市
String district = location.getDistrict(); //获取区县
String street = location.getStreet(); //获取街道信息
Log.i(TAG, addr);
}
};
}
| true
|
02ba79c296bcf1b0ea9c526e94c20a9ed42b7dcd
|
Java
|
zwang87/test
|
/test/ConcurrentDoc.java
|
UTF-8
| 2,206
| 2.1875
| 2
|
[] |
no_license
|
// the glue between a Doc and the sharing interface
package test;
import java.awt.Component;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentDoc extends Doc implements DocSync
{
//
public ConcurrentDoc(Component component)
{
super(component);
}
synchronized public boolean registerChangeWatcherClient(DocSync.ChangeWatcherClient c) {
if (cwc == null) {
cwc = c;
return true;
}
// already registered a watcher
return false;
}
synchronized public void unregisterChangeWatcherClient(DocSync.ChangeWatcherClient c) {
if (cwc == c) {
cwc = null;
}
}
@Override
synchronized void replaceText(int lo, int hi, String src, boolean markForUndo) {
// TODO: markForUndo
super.replaceText(lo, hi, src, markForUndo);
if (cwc != null) {
cwc.docChanged(this, lo, hi, src, text);
}
}
@Override
synchronized void setCaret(int i) {
super.setCaret(i);
cwc.caretMoved(this, caret, selectionStart, selectionEnd, isVaryingNumber);
}
@Override synchronized void setSelection(int start, int end) {
super.setSelection(start, end);
cwc.caretMoved(this, caret, selectionStart, selectionEnd, isVaryingNumber);
}
public synchronized void replaceState(String s, int caret, int selectionStart, int selectionEnd, boolean isVaryingNumber) {
this.caret = caret;
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
this.isVaryingNumber = isVaryingNumber;
/*
if (isSynchronizedScroll)
this.indexAtTopOfScreen = indexAtTopOfScreen;
*/
if (!text.equals(s)) {
text = s;
isDamage = true;
root.isDamage = true;
}
}
public boolean isTextApproved() {
// TODO: get approval for a change (to suppress upload of invalid code)
return true;
}
//wz
public void updateCursorList(int[] caretStartInfo, int[] caretEndInfo, String[] colorInfo, String[] userIdInfo)
{
updateCaretList(caretStartInfo, caretEndInfo, colorInfo, userIdInfo);
}
///wz
DocSync.ChangeWatcherClient cwc;
}
| true
|
402a5ca00d377e2dacfbb6c5a7a3a85f1bdc65d8
|
Java
|
xjwhhh/Dingo
|
/src/main/java/dao/bean/ShowDaoBean.java
|
UTF-8
| 7,293
| 2.4375
| 2
|
[] |
no_license
|
package dao.bean;
import dao.HibernateUtil;
import dao.ShowDao;
import model.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class ShowDaoBean extends BaseDaoBean implements ShowDao {
private static ShowDaoBean showDao = new ShowDaoBean();
public static ShowDaoBean getInstance() {
return showDao;
}
public ResultMessage save(Show show) {
return super.save(show);
}
public Show findById(int showId) {
return (Show) super.load(Show.class, showId);
}
public List<Show> findByType(String showType) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
List<Show> showList = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("FROM Show as S where S.showType=:showType");
query.setParameter("showType", showType);
showList = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return showList;
}
public List<Show> findByState(String progressType) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
List<Show> showList = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("FROM Show as S where S.progressType=:progressType");
query.setParameter("progressType", progressType);
showList = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return showList;
}
public ResultMessage update(Show show) {
return super.update(show);
}
public List<Show> findByVenueId(int venueId) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
List<Show> showList = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("FROM Show as S where S.venueId=:venueId");
query.setParameter("venueId", venueId);
showList = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return showList;
}
public List<Show> findByUserId(int userId) {
return null;
}
public ResultMessage saveShowSeat(ShowSeat showSeat) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createSQLQuery("insert into showseat(cost, description, level,seatId, showId, booked) VALUE (?,?,?,?,?,?)");
query.setParameter(0, showSeat.getCost());
query.setParameter(1, showSeat.getDescription());
query.setParameter(2, showSeat.getLevel());
query.setParameter(3, showSeat.getSeatId());
query.setParameter(4, showSeat.getShow().getId());
query.setParameter(5, showSeat.isBooked());
query.executeUpdate();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return ResultMessage.SUCCESS;
}
public ShowSeat findShowSeat(int showSeatId) {
System.out.println(showSeatId);
return (ShowSeat) super.load(ShowSeat.class, showSeatId);
}
// public List<ShowSeat> findShowSeatListByShowId(int showId) {
// Session session = HibernateUtil.getSession();
// Transaction tx = null;
// List<ShowSeat> showSeatList = null;
// try {
// tx = session.beginTransaction();
// Query query = session.createQuery("FROM ShowSeat as S where S.showId=:showId");
// query.setParameter("showId", showId);
// showSeatList = query.list();
// tx.commit();
// } catch (HibernateException e) {
// if (tx != null) tx.rollback();
// e.printStackTrace();
// } finally {
// session.close();
// }
// return showSeatList;
// }
// public List<ShowSeat> findUnbookedShowSeatListByShowId(int showId) {
// Session session = HibernateUtil.getSession();
// Transaction tx = null;
// List<ShowSeat> showSeatList = null;
// try {
// tx = session.beginTransaction();
// Query query = session.createQuery("FROM ShowSeat as S where S.show=:showId and S.booked=:booked");
// query.setParameter("showId", showId);
// query.setParameter("booked", false);
// showSeatList = query.list();
// tx.commit();
// } catch (HibernateException e) {
// if (tx != null) tx.rollback();
// e.printStackTrace();
// } finally {
// session.close();
// }
// return showSeatList;
// }
public List<ShowEarning> findUnSettledShowEarning() {
Session session = HibernateUtil.getSession();
Transaction tx = null;
List<ShowEarning> showEarningList = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("FROM ShowEarning as S where S.settled=:settled");
query.setParameter("settled", false);
showEarningList = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return showEarningList;
}
public ShowEarning findShowEarningById(int showEarningId) {
return (ShowEarning) super.load(ShowEarning.class, showEarningId);
}
public ResultMessage updateShowEarning(ShowEarning showEarning) {
return super.update(showEarning);
}
public ShowEarning findShowEarningByShowId(int showId) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
List<ShowEarning> showEarningList = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("FROM ShowEarning as S where S.showId=:showId");
query.setParameter("showId", showId);
showEarningList = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
if (showEarningList.size() > 0) {
return showEarningList.get(0);
} else {
ShowEarning showEarning = new ShowEarning();
showEarning.setId(-1);
return showEarning;
}
}
}
| true
|
d9cb7b35b176bfbacc3a65c4a60de02a001cce01
|
Java
|
jgk9380/wxApp
|
/wxMid/src/org/dao/WxPerQrCodeDao.java
|
UTF-8
| 441
| 1.578125
| 2
|
[] |
no_license
|
package org.dao;
import java.math.BigDecimal;
import org.entity.WxApp;
import org.entity.WxPerQrCode;
import org.springframework.data.repository.CrudRepository;
import org.wxenum.ScenenFlag;
public interface WxPerQrCodeDao extends CrudRepository<WxPerQrCode, String> {
WxPerQrCode findByTicket(String ticket);
WxPerQrCode findByUserId(long userId);
WxPerQrCode findBySencenId(BigDecimal sencenId);
}
| true
|
654966a5af5694363c53f17dcc5fd74ce737f62b
|
Java
|
fengshiqing/java
|
/SpringBoot/src/main/java/com/kunning/springboot/pojo/XmlObject.java
|
UTF-8
| 581
| 1.78125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.kunning.springboot.pojo;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@XStreamAlias("XmlObject")
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class XmlObject {
@XStreamAlias("param_1")
private String param_1;
@XStreamAlias("param_2")
private String param_2;
@XStreamAlias("param_3")
private String param_3;
@XStreamAlias("param_4")
private String param_4;
}
| true
|
fff8ab920140e405e275cbe0cbcf1879c7d72954
|
Java
|
momoDevDL/ivvq-projet-2021-money-et-dystopie
|
/moneyetdystopie-back/src/test/java/org/ups/m2dl/moneyetdystopieback/services/card_service_test/CardServiceTest.java
|
UTF-8
| 889
| 2.5
| 2
|
[] |
no_license
|
package org.ups.m2dl.moneyetdystopieback.services.card_service_test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.ups.m2dl.moneyetdystopieback.services.CardService;
class CardServiceTest {
@ParameterizedTest
@ValueSource(
strings = { "", "8532", "9999999999999999", "00000000000000000" }
)
void whenVerifyIncorrectNumber_thenCardNumberIsIncorrect(
String cardNumber
) {
CardService service = new CardService(cardNumber);
Assertions.assertFalse(service.isCardNumberValid());
}
@Test
void whenVerifyCorrectNumber_thenCardNumberIsCorrect() {
CardService service = new CardService("9999999999999995");
Assertions.assertTrue(service.isCardNumberValid());
}
}
| true
|
9c10b105e5c79c7c498149c28e2c81688255e039
|
Java
|
kschafer2/java-design-patterns
|
/src/main/java/design/patterns/composite/oneasmany/OneAsManyCompositeDemo.java
|
UTF-8
| 707
| 3.28125
| 3
|
[] |
no_license
|
package design.patterns.composite.oneasmany;
import design.patterns.composite.oneasmany.model.NeuralLayer;
import design.patterns.composite.oneasmany.model.Neuron;
//One As Many
// A Neuron masquerading as a group of objects allows a Neuron
// and a NeuralLayer to share the same connectTo implementation
public class OneAsManyCompositeDemo {
public static void main(String[] args) {
Neuron neuron = new Neuron();
Neuron neuron2 = new Neuron();
NeuralLayer layer = new NeuralLayer();
NeuralLayer layer2 = new NeuralLayer();
neuron.connectTo(neuron2);
neuron.connectTo(layer);
layer.connectTo(neuron);
layer.connectTo(layer2);
}
}
| true
|
c9cc27f34d32384fab90fe325eaf98c136af026e
|
Java
|
liangbingtao/JavaLife
|
/DesignPattern/src/main/java/com/neo/creator/Factory/StaticFactory/LatteCoffee.java
|
UTF-8
| 220
| 2.109375
| 2
|
[] |
no_license
|
package com.neo.creator.Factory.StaticFactory;
/**
* @Description Author neo
* Date 2021/3/19 17:24
*/
public class LatteCoffee extends Coffee {
public String getName() {
return "拿铁咖啡";
}
}
| true
|
a91bae88cc40c50c1fb253932006875f18603b59
|
Java
|
vckadam/Software-Design
|
/src/com/vckadam/oopdesign/NorthWind/dao/order/OrderDaoImpl.java
|
UTF-8
| 4,092
| 2.6875
| 3
|
[] |
no_license
|
package com.vckadam.oopdesign.NorthWind.dao.order;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.vckadam.oopdesign.NorthWind.dao.customer.CustomerDao;
import com.vckadam.oopdesign.NorthWind.dao.customer.CustomerDaoImpl;
import com.vckadam.oopdesign.NorthWind.model.Customer;
import com.vckadam.oopdesign.NorthWind.model.Order;
public class OrderDaoImpl implements OrderDao{
private List<Order> orderList;
private Map<Integer,List<Order>> ordersInyear;
private static final String FILENAME = "C:\\Users\\kadam\\workspace\\SoftwareDesign\\src\\com\\vckadam\\oopdesign\\NorthWind\\dao\\order\\ordertext";
public OrderDaoImpl() throws IOException, NumberFormatException, ParseException {
this.orderList = new ArrayList<Order>();
this.ordersInyear = new HashMap<Integer,List<Order>>();
loadList();
populateMap();
}
@Override
public List<String> companyPacedOrderIn(int year) throws IOException {
List<String> ret = new ArrayList<String>();
List<Order> orders = ordersInyear.get(year);
//System.out.println(orders.toString());
if(orders == null) return ret;
CustomerDao customerDao = new CustomerDaoImpl();
Map<String,Customer> customerMap = customerDao.getCustomerMap();
//System.out.println(customerMap.toString());
for(Order order : orders) {
String key = order.getCustomerId();
if(customerMap.containsKey(key)) {
ret.add(customerMap.get(key).getCompanyName());
}
}
return ret;
}
public void populateMap() {
Calendar ca = Calendar.getInstance();
for(Order order : orderList) {
ca.setTime(order.getOrderDate());
int key = ca.get(Calendar.YEAR);
//System.out.println(key);
if(!ordersInyear.containsKey(key)) {
ordersInyear.put(key, new ArrayList<Order>());
}
ordersInyear.get(key).add(order);
}
}
public void loadList() throws IOException, NumberFormatException, ParseException{
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
SimpleDateFormat parser=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
try {
reader = new BufferedReader(new FileReader(FILENAME));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
for(String line : lines) {
String[] strA = line.split(", ");
//System.out.println(Arrays.toString(strA));
Order order = new Order(
Integer.valueOf(strA[0]),
strA[1].substring(1,strA[1].length()-1),
Integer.valueOf(strA[2]),
parser.parse(strA[3].substring(1,strA[3].length()-1)),
parser.parse(strA[4].substring(1,strA[4].length()-1)),
parser.parse(strA[5].substring(1,strA[5].length()-1)),
Integer.valueOf(strA[6]),
Double.valueOf(strA[7].substring(1,strA[7].length()-1)),
strA[8].substring(1,strA[8].length()-1),
strA[9].substring(1,strA[9].length()-1),
strA[10].substring(1,strA[10].length()-1),
strA[11].equals("NULL")?null:strA[11].substring(1,strA[11].length()-1),
strA[12].substring(1,strA[12].length()-1),
strA[13].substring(1,strA[13].length()-1)
);
this.orderList.add(order);
}
/*for(Order or: orderList) {
System.out.println(or.toString());
}*/
}
@Override
public List<Order> sortFromExpensiveToCheapest() {
List<Order> ret = new ArrayList<Order>(this.orderList);
Comparator<Order> comp = new Comparator<Order>() {
public int compare(Order or1, Order or2) {
double freight1 = or1.getFreight();
double freight2 = or2.getFreight();
if(freight1 >= freight2) return -1;
else return 1;
}
};
Collections.sort(ret, comp);
return ret;
}
@Override
public List<Order> getOrderList() {
return this.orderList;
}
}
| true
|
736a84a82cfed71446325ec0197071c31e9ff4de
|
Java
|
sdgdsffdsfff/ClickMonitor
|
/src/main/java/com/taodian/monitor/storm/DataSpout.java
|
UTF-8
| 228
| 1.960938
| 2
|
[
"MIT"
] |
permissive
|
package com.taodian.monitor.storm;
/**
* 数据输入流
*
* @author deonwu
*/
public interface DataSpout {
public void prepare(TopologyContext context);
public DataCell nextDataCell();
public boolean isClosed();
}
| true
|
36db8f86b77af85f4930ec7b965037a3352e2682
|
Java
|
apple/servicetalk
|
/servicetalk-router-api/src/main/java/io/servicetalk/router/api/RouteExecutionStrategyFactory.java
|
UTF-8
| 1,371
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright © 2020 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.router.api;
/**
* A factory that creates an execution strategy for different {@link RouteExecutionStrategy#id() id}s of
* {@link RouteExecutionStrategy} annotation.
*
* @param <ES> protocol-specific execution strategy implementation
*/
@FunctionalInterface
public interface RouteExecutionStrategyFactory<ES> {
/**
* Gets an execution strategy for the specified {@code id}{@link RouteExecutionStrategy#id() id} of
* {@link RouteExecutionStrategy} annotation.
*
* @param id of {@link RouteExecutionStrategy}
* @return {@link ES} implementation
* @throws IllegalArgumentException if {@code id} is unknown and no fallback {@link ES} could be used
*/
ES get(String id);
}
| true
|
a90f4a10275d8d2a0703190fc327896384904ed7
|
Java
|
mrchildren1982/demo2
|
/src/test/java/com/example/demo/domain/utils/CalculatorTest.java
|
UTF-8
| 547
| 2.984375
| 3
|
[] |
no_license
|
package com.example.demo.domain.utils;
import static org.junit.Assert.*;
import org.junit.Test;
import com.example.demo.utils.Calculator;
public class CalculatorTest {
@Test
public void 単価100数量5でcalcメソッドを呼び出しで500を返す() throws Exception {
//given:テストデータを定義
int price = 100;
int count = 5;
int expected = 500;
//when:テスト対象のメソッドを実行する
int actual = Calculator.calc(price, count);
//then
assertEquals(expected, actual);
}
}
| true
|
a8aa6e00f70bdfbfea300b2edf56f0c5a7bc9684
|
Java
|
soonggi/eclipse-workspace-se
|
/23.JDBC[java DataBase Connectivity]/src/dao/address/first/AddressDao1TestMain.java
|
UTF-8
| 510
| 2.234375
| 2
|
[] |
no_license
|
package dao.address.first;
public class AddressDao1TestMain {
public static void main(String[] args) throws Exception{
AddressDao1 addressDao1=new AddressDao1();
System.out.println("1.insert");
addressDao1.insert();
System.out.println("2.update");
addressDao1.updateByNo();
System.out.println("3.delete");
addressDao1.deleteByNo();
System.out.println("4.selectByNo");
addressDao1.selectByNo();
System.out.println("5.selectAll");
addressDao1.selectAll();
}
}
| true
|
328371578fd1d46a2326f6f2dc4e59a8905ee675
|
Java
|
ivvan-grishchenko/26_JavaST_2021
|
/Task04ClassesUML/src/by.training.classesuml/service/impl/EngineGenerateThenReadImpl.java
|
UTF-8
| 876
| 2.640625
| 3
|
[] |
no_license
|
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class EngineGenerateThenReadImpl implements GenerateToFileThenRead<Engine>{
private List<Engine> engines = new ArrayList<>();
@Override
public List<Engine> generateThenRead() throws ServiceException {
try {
DAOFactory daoFactory = DAOFactory.getInstance();
DataGenerator engineGenerator = daoFactory.getDataGenerator();
EngineDAO engineDAO = daoFactory.getEngineDAO();
String source = "src/by.training.classesUML/resources/engineData.txt";
engineGenerator.writeEngineIntoFile(source, engineGenerator.generateEngine());
engines.add(engineDAO.createEngineFromFile(new File(source)));
} catch (DAOException e) {
throw new ServiceException(e);
}
return engines;
}
}
| true
|
1e72971da64529abf3fecd196f43fea67d27b284
|
Java
|
34744/SpaceMarine
|
/blood dragon/src/model/Officier.java
|
ISO-8859-1
| 1,751
| 2.6875
| 3
|
[] |
no_license
|
package model;
public class Officier {
private String nomOfficier, typeOfficier, mainDroiteOfficier,
mainGaucheOfficier, equipementOfficier;
public Officier(String nomOfficier, String typeOfficier,
String mainDroiteOfficier, String mainGaucheOfficier,
String equipementOfficier) {
super();
this.nomOfficier = nomOfficier;
this.typeOfficier = typeOfficier;
this.mainDroiteOfficier = mainDroiteOfficier;
this.mainGaucheOfficier = mainGaucheOfficier;
this.equipementOfficier = equipementOfficier;
}
public String getNomOfficier() {
return nomOfficier;
}
public void setNomOfficier(String nomOfficier) {
this.nomOfficier = nomOfficier;
}
public String getTypeOfficier() {
return typeOfficier;
}
public void setTypeOfficier(String typeOfficier) {
this.typeOfficier = typeOfficier;
}
public String getMainDroiteOfficier() {
return mainDroiteOfficier;
}
public void setMainDroiteOfficier(String mainDroiteOfficier) {
this.mainDroiteOfficier = mainDroiteOfficier;
}
public String getMainGaucheOfficier() {
return mainGaucheOfficier;
}
public void setMainGaucheOfficier(String mainGaucheOfficier) {
this.mainGaucheOfficier = mainGaucheOfficier;
}
public String getEquipementOfficier() {
return equipementOfficier;
}
public void setEquipementOfficier(String equipementOfficier) {
this.equipementOfficier = equipementOfficier;
}
public String toString() {
String message;
message = this.typeOfficier + " " + this.nomOfficier
+ " est quip d'une " + this.mainDroiteOfficier + " et d'un "
+ this.mainGaucheOfficier;
if (this.equipementOfficier.equals("Racteur dorseaux")) {
message += " et possde des " + this.equipementOfficier;
}
return message;
}
}
| true
|
b3999bb3776b3015e3b7d0ba76bdb4aa0e82c095
|
Java
|
elenbeilina/vsu
|
/src/main/java/com/aqualen/vsu/dto/TournamentForParticipant.java
|
UTF-8
| 996
| 2.203125
| 2
|
[] |
no_license
|
package com.aqualen.vsu.dto;
import com.aqualen.vsu.entity.Participants;
import com.aqualen.vsu.entity.Technology;
import com.aqualen.vsu.entity.Tournament;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TournamentForParticipant {
private Long tournamentId;
private String tournamentName;
private List<Technology> technologies;
private String task;
private long grade;
public static TournamentForParticipant toDto(Participants from) {
Tournament tournament = from.getTournament();
return TournamentForParticipant.builder()
.tournamentId(tournament.getId())
.tournamentName(tournament.getName())
.technologies(tournament.getTechnologies())
.task(from.getTask())
.grade(from.getGrade())
.build();
}
}
| true
|