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
92f9bbf3f2dfb2fec8d4d2dde1b94a3b3854f48e
Java
warith313/multi_downloader
/android/src/main/java/com/iraqtechno/multidownloader/TaskDbHelper.java
UTF-8
2,786
2.28125
2
[ "Apache-2.0" ]
permissive
package com.iraqtechno.multidownloader; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.iraqtechno.multidownloader.TaskContract.TaskEntry; public class TaskDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 2; public static final String DATABASE_NAME = "download_tasks.db"; private static TaskDbHelper instance = null; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TaskEntry.TABLE_NAME + " (" + TaskEntry._ID + " INTEGER PRIMARY KEY," + TaskEntry.COLUMN_NAME_TASK_ID + " VARCHAR(256), " + TaskEntry.COLUMN_NAME_URL + " TEXT, " + TaskEntry.COLUMN_NAME_STATUS + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_NAME_PROGRESS + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_NAME_FILE_NAME + " TEXT, " + TaskEntry.COLUMN_NAME_IMAGE + " TEXT, " + TaskEntry.COLUMN_NAME_SRT + " TEXT, " + TaskEntry.COLUMN_NAME_NAME + " TEXT, " + TaskEntry.COLUMN_NAME_SAVED_DIR + " TEXT, " + TaskEntry.COLUMN_NAME_HEADERS + " TEXT, " + TaskEntry.COLUMN_NAME_MIME_TYPE + " VARCHAR(128), " + TaskEntry.COLUMN_NAME_RESUMABLE + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_TIME_CREATED + " INTEGER DEFAULT 0" + ")"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TaskEntry.TABLE_NAME; public static TaskDbHelper getInstance(Context ctx) { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. // See this article for more information: http://bit.ly/6LRzfx if (instance == null) { instance = new TaskDbHelper(ctx.getApplicationContext()); } return instance; } private TaskDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
true
dc3b10bef979372f3bced1fd40b94a86691463c6
Java
rmeijer61/titanbank
/src/java/edu/spcollege/titanbank/bll/UserLoginStatus.java
UTF-8
2,259
2.765625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.spcollege.titanbank.bll; import java.util.ArrayList; /** * * @author rmeijer */ public class UserLoginStatus { private User user; private String userName = ""; private final java.util.Date loginDate = new java.util.Date(); // loggedIn will contain logins for a particular user, not all users // There will always be a check for multiple logins and cleanup will // be done if multiple logins are discovered private ArrayList<UserLoginStatus> loggedIn; public UserLoginStatus(User user) { this.userName = user.getUserName(); } // Method for checking the login status public UserLoginStatus(String userid) { this.userName = userid; } public java.util.Date getLoginDate() { return loginDate; } public boolean updateUserLoginActivity() { // TODO - update the database return true; } public boolean removeUserLoginActivity(User user) { // TODO - Currently, there is no data // The ArrayList should be populated via database query this.loggedIn = new ArrayList<>(); // Find the user login(s) find(user.getUserName()); // Remove the logins from the database for(UserLoginStatus ula: loggedIn){ if (ula.getUserName().equals(userName)) { // Remove the login from the database } } return true; } public String getUserName() { return userName; } public boolean isLoggedIn(String userid){ return find(userid) != null; } private ArrayList<UserLoginStatus> find(String userid){ // TODO - Currently, there is no data // The ArrayList should be populated via database query this.loggedIn = new ArrayList<>(); // Multiple login attempts? for(UserLoginStatus ula: loggedIn){ if (ula.getUserName().equals(userName)) return loggedIn; } return loggedIn; } }
true
3fb84ae0b1daf29027a9fe2def085f3a05a7b4d2
Java
Akshay-Bangde/GYM-Managment-
/app/src/main/java/com/example/smile/adapters/Enquiry_Adapter.java
UTF-8
6,416
1.945313
2
[]
no_license
package com.example.smile.adapters; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.smile.R; import com.example.smile.dataObjects.Enquiry_Model; import com.example.smile.utils.CategoryCallBackInterface; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.example.smile.activities.SignInActivity.BaseURL; public class Enquiry_Adapter extends RecyclerView.Adapter<Enquiry_Adapter.EviewHolder> { private Context mcontext; private ArrayList<Enquiry_Model> enquiryModelArrayList; private CategoryCallBackInterface categoryCallBackInterface; String Delete_URL=BaseURL+"InquiryGrid"; public Enquiry_Adapter(Context mcontext, ArrayList<Enquiry_Model> enquiryModelArrayList) { this.mcontext = mcontext; this.enquiryModelArrayList = enquiryModelArrayList; this.categoryCallBackInterface = (CategoryCallBackInterface) mcontext; } @Override public Enquiry_Adapter.EviewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { LayoutInflater layoutInflater=LayoutInflater.from(viewGroup.getContext()); View listItem= layoutInflater.inflate(R.layout.content_enquiry_grid, viewGroup, false); EviewHolder eviewHolder = new EviewHolder(listItem); return eviewHolder; } @Override public void onBindViewHolder(Enquiry_Adapter.EviewHolder eviewHolder, final int i) { eviewHolder.msrno.setText(enquiryModelArrayList.get(i).getE_serial_id()); eviewHolder.mDate.setText(enquiryModelArrayList.get(i).getE_enqDate()); eviewHolder.mName.setText(enquiryModelArrayList.get(i).getE_name()); eviewHolder.mContact.setText(enquiryModelArrayList.get(i).getE_contact()); eviewHolder.mEmail.setText(enquiryModelArrayList.get(i).getE_email()); eviewHolder.mCity.setText(enquiryModelArrayList.get(i).getE_city()); eviewHolder.mRemark.setText(enquiryModelArrayList.get(i).getE_remark()); eviewHolder.mStatus.setText(enquiryModelArrayList.get(i).getE_enqStatus()); eviewHolder.mFollowDate.setText(enquiryModelArrayList.get(i).getE_followUp()); eviewHolder.eDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(mcontext); dialog.setContentView(R.layout.log_out_alert_dialog_box); TextView mesg = dialog.findViewById(R.id.message); mesg.setText("Do You Want To Delete This Record ?"); Button nobtn = dialog.findViewById(R.id.text_no); Button yesbtn = dialog.findViewById(R.id.text_yes); nobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); yesbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); String id = enquiryModelArrayList.get(i).getE_serial_id(); categoryCallBackInterface.onDeleteItemListener(i); DeleteHandler handler = new DeleteHandler(id, i); String result = null; try { result = handler.execute(Delete_URL).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } }); } public class DeleteHandler extends AsyncTask<String, Void, String> { OkHttpClient client = new OkHttpClient(); String id; int position; public DeleteHandler(String id, int pos) { this.id = id; this.position = pos; } @Override protected String doInBackground(String... params) { RequestBody formBody = new FormBody.Builder() .add("id", id) .build(); Request request = new Request.Builder() .post(formBody) .url(Delete_URL) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { } }); return null; } } @Override public int getItemCount() { return enquiryModelArrayList.size(); } class EviewHolder extends RecyclerView.ViewHolder { TextView msrno,mDate,mName,mContact,mEmail,mCity,mRemark,mStatus,mFollowDate; Button eDelete; EviewHolder( View itemView) { super(itemView); msrno=itemView.findViewById(R.id.e_srno); mDate=itemView.findViewById(R.id.enq_date); mName=itemView.findViewById(R.id.e_name); mContact=itemView.findViewById(R.id.e_contact); mEmail=itemView.findViewById(R.id.e_email); mCity=itemView.findViewById(R.id.e_city); mRemark=itemView.findViewById(R.id.e_remark); mStatus=itemView.findViewById(R.id.e_status); mFollowDate=itemView.findViewById(R.id.e_nextfd); eDelete=itemView.findViewById(R.id.enq_delete); } } }
true
cd4533878265a8cd0f2ff0d8bf8c2fe2bc43c363
Java
geniussportsgroup/SoyAnnotations
/src/test/java/example/renderer/SettingsRenderer.java
UTF-8
836
2.546875
3
[ "MIT" ]
permissive
package example.renderer; import com.geniussports.soy.context.RendererFactoryContext; import com.geniussports.soy.factories.rendering.Renderer; import com.geniussports.soy.factories.rendering.RendererFactoryContextAware; import example.models.Setting; import javax.annotation.Nullable; public class SettingsRenderer implements Renderer<Object>, RendererFactoryContextAware { private RendererFactoryContext factoryContext; @Override public void setRendererFactoryContext(RendererFactoryContext context) { this.factoryContext = context; } @Nullable @Override public String render(@Nullable Object instanceObject) { if (instanceObject instanceof Setting) { return ((Setting) instanceObject).toString(factoryContext); } else { return null; } } }
true
237ade3b456d3abf6ff5a2c6f4d64d229e7b8a81
Java
jbunkley18/gsu-java
/testListner.java
UTF-8
797
3.34375
3
[]
no_license
import java.awt.*; import java.awt.event.*; import javax.swing.*; class buttonWithListner extends JFrame implements ActionListener{ // constructor buttonWithListner(String title){ super (title); setLayout (new FlowLayout()); setBounds (50,50, 200, 200); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); JLabel l1 = new JLabel (" painting class 101 "); add(l1); JButton b1 = new JButton("push me"); add(b1); // Who is going to listen when you click the button? b1.addActionListener( this ); } public void actionPerformed(ActionEvent evt) { getContentPane().setBackground(Color.BLUE); repaint(); } } public class testListner { public static void main(String[] args) { buttonWithListner blfrm = new buttonWithListner("Painting button"); blfrm.setVisible(true); } }
true
a7c8b41b278bb6a0d8eeb18e2d4529b59a3249fc
Java
Cpp-Ai-Project/AndroidProject
/app/src/main/java/com/example/maximum/cppai/Frontend/MainActivity.java
UTF-8
5,217
2.03125
2
[]
no_license
package com.example.maximum.cppai.Frontend; import android.content.DialogInterface; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.Toast; import com.example.maximum.cppai.Backend.API; import com.example.maximum.cppai.Backend.Query; import com.example.maximum.cppai.Backend.Response; import com.example.maximum.cppai.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class MainActivity extends AppCompatActivity { public static final String CELSIUS_KEY = "celsius", NICKNAME_KEY = "nickname"; private ImageButton mic; private EditText input; private RecyclerView history; private List<Response> responses; private ResponseViewAdapter adapter; private boolean menuOpen = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setSupportActionBar((Toolbar)findViewById(R.id.my_toolbar)); mic = (ImageButton) findViewById(R.id.mic); input=(EditText)findViewById(R.id.input); responses = new ArrayList<>(); adapter = new ResponseViewAdapter(responses); history = (RecyclerView)findViewById(R.id.requests); history.setAdapter(adapter); history.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(this); history.setLayoutManager(layoutManager); mic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Response response = new Query().execute(input.getText().toString()).get(); // Log.d("Response", response.toString()); responses.add(response); adapter.notifyDataSetChanged(); //Toast.makeText(MainActivity.this, response.getDetailedDescription(), Toast.LENGTH_SHORT).show(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.clear: responses.clear(); adapter.notifyDataSetChanged(); // settings.edit(). Toast.makeText(this, "Cleared history", Toast.LENGTH_SHORT).show(); return true; case R.id.settings: showSettings(); return true; default: return super.onContextItemSelected(item); } } public void showSettings(){ final AlertDialog.Builder settingsBuilder = new AlertDialog.Builder(MainActivity.this); View sView = getLayoutInflater().inflate(R.layout.settings_dialog,null); final SharedPreferences settings = getSharedPreferences("Settings",MODE_PRIVATE); final EditText nickname = (EditText)sView.findViewById(R.id.nickname); nickname.setText(settings.getString(NICKNAME_KEY,"")); final RadioButton celsius = (RadioButton)sView.findViewById(R.id.celsius); RadioButton fahrenheit = (RadioButton)sView.findViewById(R.id.fahrenheit); if(settings.getBoolean(CELSIUS_KEY,true)) celsius.setChecked(true); else fahrenheit.setChecked(true); settingsBuilder.setTitle("Settings"); settingsBuilder.setNegativeButton("Discard", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); settingsBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { settings.edit().putBoolean(CELSIUS_KEY,celsius.isChecked()).putString(NICKNAME_KEY,nickname.getText().toString().trim()).apply(); Toast.makeText(MainActivity.this, "name: "+nickname.getText().toString()+"\ntemp: "+(celsius.isChecked()?"Celsius":"fahrenheit"), Toast.LENGTH_SHORT).show(); } }); settingsBuilder.setView(sView); settingsBuilder.create().show(); } }
true
884c0e62651472bd036d61da8414667921548155
Java
PVoLan/TestVideoCam
/WS/TestVideoCam/src/ru/pvolan/event/CustomEventListener.java
UTF-8
91
1.890625
2
[]
no_license
package ru.pvolan.event; public interface CustomEventListener { public void onEvent(); }
true
e2c3f5f21ad535e4e11403dc683aafb8f5b810b9
Java
laurenuclark/cmpt220Urena-Clark
/2/Ex3_4.java
UTF-8
1,504
3.640625
4
[]
no_license
/** * file: Ex1_3 * author: Lauren Urena-Clark * course: CMPT 220 * assignment: exercise 1.3 * due date: January, 31, 2017 * *This file contians the declaration of the * Ex1_3 abstract data type. */ /** *exercise 1_3 *This class converts a Celsius value to Farenheit. * This file will print the word "JAVA" by * making a pattern using the * corresponding letters for each letter of the word */ import java.util.Scanner; public class Ex3_4 { public static void main(String[] strings) { int randomMonth = (int) (Math.random() * 12) + 1; if (randomMonth ==1){ System.out.print("January"); } else if (randomMonth ==2){ System.out.print("Febuary"); } else if (randomMonth ==3){ System.out.print("March"); } else if (randomMonth ==4){ System.out.print("April"); } else if (randomMonth ==5){ System.out.print("May"); } else if (randomMonth ==6){ System.out.print("June"); } else if (randomMonth ==7){ System.out.print("July"); } else if (randomMonth ==8){ System.out.print("August"); } else if (randomMonth ==9){ System.out.print("September"); } else if (randomMonth ==10){ System.out.print("October"); } else if (randomMonth ==11){ System.out.print("November"); } else if (randomMonth ==12){ System.out.print("December"); } } }
true
b411d0d217938a3757042bce4143a34b29326564
Java
martinezmatias/GenPat-data-C3
/junit_cluster/3171/src_19.java
UTF-8
1,529
2.328125
2
[]
no_license
package org.junit.experimental.theories.test.runner; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import java.util.List; import org.hamcrest.Matcher; import org.junit.Test; import org.junit.experimental.theories.matchers.api.Each; import org.junit.experimental.theories.methods.api.DataPoint; import org.junit.experimental.theories.methods.api.Theory; import org.junit.experimental.theories.runner.api.Theories; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; public class DataPointMethodTest { @RunWith(Theories.class) public static class HasDataPointMethod { @DataPoint public int oneHundred() { return 100; } @Theory public void allIntsOk(int x) { } } @RunWith(Theories.class) public static class HasUglyDataPointMethod { @DataPoint public int oneHundred() { return 100; } @DataPoint public int oneUglyHundred() { throw new RuntimeException(); } @Theory public void allIntsOk(int x) { } } @Test public void pickUpDataPointMethods() { assertThat(failures(HasDataPointMethod.class), empty()); } @Test public void ignoreExceptionsFromDataPointMethods() { assertThat(failures(HasUglyDataPointMethod.class), empty()); } private List<Failure> failures(Class<?> type) { return JUnitCore.runClasses(type).getFailures(); } private Matcher<Iterable<Failure>> empty() { Matcher<Failure> nullValue= nullValue(); return Each.each(nullValue); } }
true
4862def04bd1401869aca404da5eec5f0cdf4453
Java
a18575759226/parent
/shop-service/src/main/java/com/xmg/shop/mapper/ProductSkuMapper.java
UTF-8
630
2.09375
2
[]
no_license
package com.xmg.shop.mapper; import com.xmg.shop.domain.ProductSku; import java.util.List; public interface ProductSkuMapper { int deleteByPrimaryKey(Long id); int insert(ProductSku record); ProductSku selectByPrimaryKey(Long id); List<ProductSku> selectAll(); int updateByPrimaryKey(ProductSku record); /** * 根据产品id查询产品的sku属性 * @param productId * @return */ List<ProductSku> listProductSkuById(Long productId); /** * 通过产品id删除该商品的所有sku属性 * @param productId */ void deleteByProductId(Long productId); }
true
5b2169f0f9fbf4e07a859f59dc29797ceb86541b
Java
i1rr/job4j_design
/src/main/java/ru/job4j/design/menu/MenuManager.java
UTF-8
1,549
3.15625
3
[]
no_license
package ru.job4j.design.menu; import java.util.ArrayList; import java.util.List; public abstract class MenuManager { private List<MenuManager> subMenuList = new ArrayList<>(); private Output out; public MenuManager(Output out) { this.out = out; } protected abstract String getName(); protected abstract boolean execute(Action actionName); void printSubMenu(int prevMenuIndex, String legacyBuildIndex, String separator) { int currentIndex = 1; String legacyIndex = ""; legacyIndex = legacyBuildIndex.equals("") ? prevMenuIndex + "." : legacyBuildIndex + prevMenuIndex + "."; String sep = separator + "---"; for (MenuManager menuManager : subMenuList) { out.println(sep + " " + menuManager.getName() + " " + legacyIndex + currentIndex); menuManager.printSubMenu(currentIndex, legacyIndex, sep); currentIndex++; } } public boolean add(String parentName, String childName, Action actionName) { if (getName().equals(parentName)) { subMenuList.add(new Menu(out, childName, actionName)); return true; } else { for (MenuManager menu : subMenuList) { if (menu.getName().equals(parentName)) { menu.subMenuList.add(new Menu(out, childName, actionName)); return true; } menu.add(parentName, childName, actionName); } } return false; } }
true
e2b1ebd263394927b55f768d44c7d01767d80916
Java
paul-ippolito1954/cmpt220ippolito
/Labs/Lab1/Average_calc.java
UTF-8
1,007
3.765625
4
[]
no_license
/* Paul Ippolito CMPT220 1/30/17 This program gets input from the user of their averages for each of the four rubrics from the CMPT220 course and then calculates the final average. */ import java.util.Scanner; public class Average_calc { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the following as a percentage :"); //Gets input and converts midterm grade System.out.println("Midterm exam: "); double midterm = input.nextDouble() * 0.20; //Gets input for final exam System.out.println("Final Exam: "); double finExam = input.nextDouble() * 0.20; //Gets project average System.out.println("Projects: "); double project = input.nextDouble() * 0.20; //Gets input for Homework and Labs System.out.println("Homework and Labs: "); double hwLabs = input.nextDouble() * 0.40; //Calculates final average of user double fin = midterm + finExam + project + hwLabs; System.out.println("Your final average is " + fin + "%."); } }
true
6b6f30924868f383cdb457e0bc4dfe9503a89c3b
Java
egordoga/words
/app/src/main/java/com/e/words/view/adapter/ArticleFragmentPagerAdapter.java
UTF-8
1,448
2.390625
2
[]
no_license
package com.e.words.view.adapter; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.viewpager2.adapter.FragmentStateAdapter; import com.e.words.entity.dto.WordObj; import com.e.words.view.fragment.ArticleFragment; import com.e.words.view.fragment.FullWordFragment; import java.util.List; public class ArticleFragmentPagerAdapter extends FragmentStateAdapter { private final WordObj wordObj; private final WordObj smallWord; private final String json; private final List<byte[]> sounds; private final boolean isPresent; public ArticleFragmentPagerAdapter(Fragment fm, WordObj wordObj, WordObj smallWord, String json, List<byte[]> sounds, boolean isPresent) { super(fm); this.wordObj = wordObj; this.smallWord = smallWord; this.json = json; this.sounds = sounds; this.isPresent = isPresent; } @NonNull @Override public Fragment createFragment(int position) { switch (position) { case 0: return ArticleFragment.newInstance(wordObj); case 1: case 2: return FullWordFragment.newInstance(wordObj, smallWord, position, json, sounds, isPresent); default: return new ArticleFragment(); } } @Override public int getItemCount() { return 3; } }
true
b34fb5a41b6296a7cabfb54b3042ca6112572b08
Java
suifengJC614/cloudwiz-snmp
/snmp-web/src/main/java/cn/cloudwiz/dalian/snmp/controller/MonitorDeviceController.java
UTF-8
4,574
2.109375
2
[]
no_license
package cn.cloudwiz.dalian.snmp.controller; import cn.cloudwiz.dalian.commons.utils.JsonUtils; import cn.cloudwiz.dalian.snmp.api.device.*; import cn.cloudwiz.dalian.snmp.utils.ProjectionUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.io.input.ReaderInputStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.projection.TargetAware; import org.springframework.web.bind.annotation.*; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringBufferInputStream; import java.nio.charset.Charset; @RestController @RequestMapping("device") @Api(description = "监控设备相关接口文档") public class MonitorDeviceController { @Autowired private DeviceService devicebs; @Autowired private ProjectionFactory proxyFactory; @ApiOperation("创建监控设备信息") @ApiImplicitParam(name = "device", value = "监控设备信息", paramType = "body") @RequestMapping(method = RequestMethod.POST) public RestResponse<Long> create(@RequestBody MonitorDevice device) { SnmpVersion version = device.getVersion(); device = proxyFactory.createProjection(NullKeyDevice.class, ((TargetAware) device).getTarget()); device = proxyFactory.createProjection(version.getDataType(), JsonUtils.fromJson(JsonUtils.toJson(device))); Long savedKey = devicebs.save(device); return RestResponse.success(1L); } @ApiOperation("查询监控设备信息") @ApiImplicitParams({ @ApiImplicitParam(name = "exporterName", value = "exporter名称,模糊查询", paramType = "query"), @ApiImplicitParam(name = "deviceName", value = "device名称,模糊查询", paramType = "query"), @ApiImplicitParam(name = "brandKey", value = "品牌ID", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", paramType = "query"), @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query") }) @RequestMapping(method = RequestMethod.GET) public RestResponse<Page<MonitorDevice>> find(DeviceParams params, Pageable pageable) { Page<MonitorDevice> result = devicebs.getMonitorDevices(params, pageable); return RestResponse.success(result); } @ApiOperation("获取指定的监控设备信息") @ApiImplicitParam(name = "key", value = "监控设备ID", paramType = "path", required = true) @RequestMapping(path = "{key:\\d+}", method = RequestMethod.GET) public RestResponse<MonitorDevice> get(@PathVariable("key") Long key) { MonitorDevice result = devicebs.getMonitorDevice(key); return RestResponse.success(result); } @ApiOperation(value = "修改指定的监控设备信息", notes = "body的json内容只需要放要修改的字段即可,其他的不变") @ApiImplicitParams({ @ApiImplicitParam(name = "key", value = "监控设备ID", paramType = "path", required = true), @ApiImplicitParam(name = "device", value = "要修改的监控设备信息", paramType = "body") }) @RequestMapping(path = "{key:\\d+}", method = RequestMethod.PUT) public RestResponse<Void> update(@PathVariable("key") Long key, @RequestBody MonitorDevice device){ SnmpVersion version = device.getVersion(); device = proxyFactory.createProjection(version.getDataType(), ((TargetAware) device).getTarget()); devicebs.save(ProjectionUtils.mergeKey(version.getDataType(), key, device, proxyFactory)); return RestResponse.success(); } @ApiOperation("删除指定的监控设备信息") @ApiImplicitParam(name = "key", value = "监控设备ID", paramType = "path", required = true) @RequestMapping(path = "{key:\\d+}", method = RequestMethod.DELETE) public RestResponse<Void> delete(@PathVariable("key") Long key) { devicebs.remove(key); return RestResponse.success(); } public interface NullKeyDevice extends CommunityDevice, SecurityDevice { @Value("#{null}") public Long getKey(); @Value("#{target.version}") public SnmpVersion getVersion(); } }
true
46b94651a6bf24c1c3b3c86ee430f7000554b498
Java
freedom541/cclTest
/ccl-jersey-jetty-web/src/main/java/com/ccl/jersey/repository/SimpleUserRepository.java
UTF-8
1,588
2.65625
3
[]
no_license
package com.ccl.jersey.repository; import com.ccl.jersey.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by ccl on 17/8/15. */ @Repository public class SimpleUserRepository { @Autowired private JdbcTemplate jdbcTemplate; public List<User> findAll() { // Find all customers, thanks Java 8, you can create a custom RowMapper like this : List<User> result = jdbcTemplate.query( "SELECT id, name FROM user", (rs, rowNum) -> new User(rs.getInt("id"),rs.getString("name")) ); return result; } public void addUser(String name) { int temp = jdbcTemplate.update("INSERT INTO user(name) VALUES (?)", name); if (temp > 0) { System.out.println("插入成功!"); }else{ System.out.println("插入失败"); } } public void updateUser(int id, String name) { int temp = jdbcTemplate.update("UPDATE user SET name = ? where id = ?", name, id); if (temp > 0) { System.out.println("修改成功!"); }else{ System.out.println("修改失败"); } } public void deleteUser(int id) { int temp = jdbcTemplate.update("DELETE FROM user where id = ?", id); if (temp > 0) { System.out.println("删除成功!"); }else{ System.out.println("删除失败"); } } }
true
4373382f98561797fe51238990e02e2b0abf9f90
Java
mofangwan23/LimsOA
/app/src/main/java/cn/flyrise/feep/main/NewMainMessageContract.java
UTF-8
928
1.929688
2
[]
no_license
package cn.flyrise.feep.main; import com.hyphenate.chat.EMConversation; import java.util.List; import cn.flyrise.feep.main.message.MessageVO; /** * @author ZYP * @since 2017-04-01 14:04 */ public interface NewMainMessageContract { interface IView { String ALL_MESSAGE_READ = "A";//标记全部消息为已读 void onMessageLoadSuccess(List<MessageVO> messageVOs); void onConversationLoadSuccess(List<EMConversation> messages); void showLoading(); void hideLoading(); void onCircleMessageIdListSuccess(List<String> messageIds);//获取朋友圈消息id void onCircleMessageReadSuccess();//朋友圈消息已读成功 } interface IPresenter { void start(); void fetchMessageList(); void fetchConversationList(); void allMessageListRead(String categorys); void requestCircleMessageList(int totalCount, int pageNumber); void circleMessageListRead(List<String> messageIds); } }
true
0748f54ef4cd76784b576a6877d0fee518061773
Java
ajinkyagawade/WebPrototype
/WebPrototype/src/main/java/prototype/beans/ConfigMongoDB.java
UTF-8
1,156
2.265625
2
[]
no_license
package prototype.beans; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; @Configuration public class ConfigMongoDB { @Bean public MongoTemplate mongoTemplate() throws IOException { Properties properties = new Properties(); String userDir = System.getProperty("user.dir"); InputStream inputProperties = new FileInputStream(userDir + "/PrototypeConfig.properties"); properties.load(inputProperties); String uri = properties.getProperty("MongoDBConnectionString"); MongoClientURI mongoClientUri = new MongoClientURI(uri); SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient( mongoClientUri), properties.getProperty("DatabaseName")); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory); return mongoTemplate; } }
true
551368b491c9f0ad08a1f9835c98b0cbc62ca75f
Java
hgcummings/jarspec
/src/test/java/io/hgc/jarspec/RulesSpec.java
UTF-8
1,436
2.21875
2
[ "MIT" ]
permissive
package io.hgc.jarspec; import io.hgc.jarspec.fixtures.rules.ErrorInRuleSpec; import io.hgc.jarspec.fixtures.rules.ExpensiveDependencySpec; import io.hgc.jarspec.fixtures.rules.SharedStateSpec; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(JarSpecJUnitRunner.class) public class RulesSpec implements Specification { @Override public SpecificationNode root() { return describe("TestRule behaviour", it("should apply rules correctly", () -> { Result result = new JUnitCore().run(SharedStateSpec.class); assertEquals(3, result.getRunCount()); assertEquals(0, result.getFailureCount()); }), it("should apply block-level rules correctly", () -> { Result result = new JUnitCore().run(ExpensiveDependencySpec.class); assertEquals(3, result.getRunCount()); assertEquals(0, result.getFailureCount()); }), it("should report failures in block-level rules as test errors", () -> { Result result = new JUnitCore().run(ErrorInRuleSpec.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); }) ); } }
true
75daa69f6589df4d748b1c2ca70a5e1565d3a634
Java
smitha94/ExampleJavacode
/src/NumberDisplay.java
UTF-8
773
3.78125
4
[ "MIT" ]
permissive
public class NumberDisplay { private int limit; private int value; public NumberDisplay(int rollOverLimit) { limit = rollOverLimit; value = 0; } public void setValue(int replacementValue) { if((replacementValue >= 0) && (replacementValue < limit)) { value = replacementValue; } } public int getValue() { return value; } public String getDisplayValue() { if( value < 10 ) { return "0" + value; } else { return "" + value; } } public void increment() { value = (value + 1) % limit; } }
true
215d530257319db359b0bfac3c25259c127fced2
Java
song121382/defence-nevermore
/nevermore-auth/src/main/java/com/defence/nevermore/auth/config/MybatisConfig.java
UTF-8
322
1.671875
2
[]
no_license
package com.defence.nevermore.auth.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * @Description: java类作用描述 * @Author: */ @MapperScan(basePackages = "com.defence.nevermore.auth.mapper") @Configuration public class MybatisConfig { }
true
373268098116e247f948ca61e6b5eb191c62e506
Java
tient3481/duan2
/src/main/java/com/fpt/hr_management/daoImpl/leave/LeaveEmployeeUpdate.java
UTF-8
1,209
2.46875
2
[]
no_license
package com.fpt.hr_management.daoImpl.leave; import java.sql.Connection; import java.sql.PreparedStatement; import com.fpt.hr_management.connection.DbConnection; import com.fpt.hr_management.listener.request.leave.LeaveUpdateRequest; public class LeaveEmployeeUpdate { public void update(LeaveUpdateRequest request) { Connection con = null; PreparedStatement pstm = null; String sql = "update employee_leave set employee_accept = ?, accept_status = ?, last_modifier_by = ? where id = ?"; try { con = DbConnection.getConnection(); if (con != null) { pstm = con.prepareStatement(sql); pstm.setString(1, request.getEmployee_accept()); pstm.setInt(2, request.getAccept_status()); pstm.setString(3, request.getLast_modifier_by()); pstm.setInt(4, request.getIdRecord()); pstm.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); } finally { DbConnection.close(con, pstm, null, null); } } // public static void main(String[] args) { // LeaveEmployeeUpdate main = new LeaveEmployeeUpdate(); // LeaveUpdateRequest request = new LeaveUpdateRequest(); // request.setIdRecord(11); // request.setAccept_status(0); // main.update(request); // } }
true
14e71ed00d540f9b7b93ad08a4667d32043348aa
Java
about3751/springmvc
/src/main/java/com/lc/demo/test/test_interface/Java8Test.java
UTF-8
204
1.507813
2
[]
no_license
package com.lc.demo.test.test_interface; import com.lc.demo.entities.Book; /** * Created by leich on 2017/3/30. */ public class Java8Test implements TestJava8{ public Java8Test() { } }
true
7e7c718194d43354271e25ec82971c9f47248d8a
Java
yx7ing/INFS3634-Assignment-Group-7
/INFS3634AssignmentGroup7/app/src/main/java/com/example/yxting/infs3634assignmentgroup7/Lesson3_7.java
UTF-8
8,724
1.96875
2
[]
no_license
package com.example.yxting.infs3634assignmentgroup7; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Build; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Lesson3_7 extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private static final String TAG = "Lesson3_7"; // Instantiate database DBHelper db = new DBHelper(this); NavigationView navigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Update the database to show this lesson has been viewed Log.e(TAG, TAG + " view status is " + db.getLesson(307).getViewed()); db.updateLesson(new DBLesson(307, 1)); Log.e(TAG, TAG + " view status is " + db.getLesson(307).getViewed()); // If all sub-lessons have been viewed // AND the trophy for the lesson has not yet been earned // reward it to the user and show a toast if (db.getTrophy(13).getEarned() == 0 && db.getLesson(301).getViewed() == 1 && db.getLesson(302).getViewed() == 1 && db.getLesson(303).getViewed() == 1 && db.getLesson(304).getViewed() == 1 && db.getLesson(305).getViewed() == 1 && db.getLesson(306).getViewed() == 1 && db.getLesson(307).getViewed() == 1 && db.getLesson(308).getViewed() == 1 && db.getLesson(309).getViewed() == 1 && db.getLesson(310).getViewed() == 1 && db.getLesson(311).getViewed() == 1 && db.getLesson(312).getViewed() == 1) { db.updateTrophy(new DBTrophy(13, 1)); Toast.makeText(this, "You got a trophy for completing Lesson 3!", Toast.LENGTH_LONG).show(); } Log.e(TAG, "Trophy 3 status is " + db.getTrophy(13).getEarned()); setContentView(R.layout.activity_lesson3_7); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("INFS3617 Study Helper"); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); navigationView.getMenu().getItem(1).setChecked(true); TextView textView = findViewById(R.id.lesson3_7TextView); textView.setTextColor(Color.parseColor("#FF9933")); textView.setTypeface(textView.getTypeface(), Typeface.BOLD); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP,30); final ListView listView = findViewById(R.id.lesson3_7ListView); RequestQueue queue = Volley.newRequestQueue(this); String url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=IPv6&exlimit=1"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e(TAG, response); Pattern pattern = Pattern.compile("<p>(.*?)</p>|<ol>(.*?)</ol>|<ul>(?!<li>DHCP|<li>IPv6)(.*?)</ul>|<span id=\\\\\"((?!Stateless_address_autoconfiguration_.28SLAAC.29|Examples|See_also|References|External_links).*?)\\\\\">"); Matcher matcher = pattern.matcher(response); ArrayList<String> content = new ArrayList<>(); content.add("\nIPv6"); while (matcher.find()){ String s = matcher.group(); s = s.replaceAll("</li>\\\\n<li>", "\n"); s = s.replaceAll("\\\\u00e9", "e"); s = s.replaceAll("\\\\u2013|\\\\u2014|\\\\u2212", " - "); s = s.replaceAll("\\\\u00d7", "x"); s = s.replaceAll("_|\\\\n|\\\\u00a0", " "); s = s.replaceAll("\\\\\"", "\""); s = s.replaceAll("<link(.*?)>", ""); s = s.replaceAll("<sup>", "^"); s = s.replaceAll("<p>|</p>|<b>|</b>|<i>|</i>|<ul>|</ul>|<li>|</li>|<ol>|</ol>|<span>|</span>|</sup>|\\\"|>", ""); content.add(s); } ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Lesson3_7.this,android.R.layout.simple_list_item_1,content){ @Override public View getView(int position, View convertView, ViewGroup parent){ TextView item = (TextView) super.getView(position,convertView,parent); String itemText = super.getItem(position); if (itemText.matches("<span id=.+") || position == 0){ item.setTypeface(item.getTypeface(), Typeface.BOLD_ITALIC); item.setTextSize(TypedValue.COMPLEX_UNIT_DIP,20); item.setText(itemText.replaceAll("<span id=", "\n")); } else { item.setTypeface(null,Typeface.NORMAL); item.setTextSize(14); } return item; } }; listView.setAdapter(arrayAdapter); arrayAdapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) {} }); queue.add(stringRequest); } @Override protected void onRestart() { super.onRestart(); navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); navigationView.getMenu().getItem(1).setChecked(true); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_home) { Intent i = new Intent(this, Home.class); startActivity(i); } else if (id == R.id.nav_lessons) { Intent i = new Intent(this, Lessons.class); startActivity(i); } else if (id == R.id.nav_review) { Intent i = new Intent(this, Review.class); startActivity(i); } else if (id == R.id.nav_quiz) { Intent i = new Intent(this, Quiz.class); startActivity(i); } else if (id == R.id.nav_accolades) { Intent i = new Intent(this, Accolades.class); startActivity(i); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
true
cd637c02b56f808c3981ad37842a10d40cdf9597
Java
Luther0812/JAVA_Study
/Test_02/Chapter_Test_019.java
UTF-8
424
3
3
[]
no_license
/**Language:Java Standard Edition * Author:Luther */ package Test_02; /** * * */ import java.util.Scanner; public class Chapter_Test_019 { public static void main(String[] args){ double random = System.currentTimeMillis(); double remainFirst = random / 250000000; double remainSecond = remainFirst / 1000; int remain = (int)(remainSecond + 65); char ran = (char)(remain); System.out.print(ran); } }
true
db7ca095f7e930b6be997ae0f2bc7c6c9ff2a959
Java
632215/yuqu
/app/src/main/java/com/a32/yuqu/fragment/FriendFragment.java
UTF-8
10,883
1.75
2
[]
no_license
package com.a32.yuqu.fragment; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import com.a32.yuqu.R; import com.a32.yuqu.activity.ChatActivity; import com.a32.yuqu.activity.FriendApplyActivity; import com.a32.yuqu.activity.MainActivity; import com.a32.yuqu.adapter.ContactAdapter; import com.a32.yuqu.adapter.FriendAdapter; import com.a32.yuqu.applicaption.MyApplicaption; import com.a32.yuqu.base.BaseFragment; import com.a32.yuqu.bean.UserBean; import com.a32.yuqu.bean.UserInfo; import com.a32.yuqu.db.EaseUser; import com.a32.yuqu.db.InviteMessage; import com.a32.yuqu.db.InviteMessgeDao; import com.a32.yuqu.http.HttpMethods; import com.a32.yuqu.http.HttpResult; import com.a32.yuqu.http.progress.ProgressSubscriber; import com.a32.yuqu.http.progress.SubscriberOnNextListener; import com.a32.yuqu.utils.CommonUtils; import com.a32.yuqu.utils.CommonlyUtils; import com.a32.yuqu.view.FillListView; import com.a32.yuqu.view.MyPopWindows; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.hyphenate.EMValueCallBack; import com.hyphenate.chat.EMChatManager; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMContact; import com.hyphenate.chat.EMContactManager; import com.hyphenate.exceptions.HyphenateException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import butterknife.Bind; /** * Created by 32 on 2016/12/30. */ public class FriendFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ScrollView>, View.OnClickListener { @Bind(R.id.pullRefresh) PullToRefreshScrollView pullRefresh; //联系人列表的listView @Bind(R.id.listView) FillListView listView; //新的朋友 @Bind(R.id.newContactLayout) LinearLayout newContact; @Bind(R.id.tips) TextView tips; protected List<EaseUser> contactList = new ArrayList<EaseUser>(); private List<String> nameList; protected Map<String, EaseUser> contactsMap; private FriendAdapter adapter; private MyPopWindows popWindows;//右上角弹出框 private TextView btnCancle; private TextView btnSure; private InviteMessgeDao inviteMessgeDao; private boolean flag = false;//是否含有未处理的邀请,false为没有,true为有 @Override protected int getLayoutId() { return R.layout.fragment_friend; } @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void initView(View view, Bundle savedInstanceState) { pullRefresh.setMode(PullToRefreshBase.Mode.BOTH); pullRefresh.setOnRefreshListener(this); initFriendData(); newContact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //进入好友申请页面 // inviteMessgeDao.deleteMessage(); startActivity(new Intent(getActivity(), FriendApplyActivity.class)); } }); } //查看是否有好友请求 @RequiresApi(api = Build.VERSION_CODES.M) private void initNewContactData() { inviteMessgeDao = new InviteMessgeDao(getActivity()); // List<InviteMessage> msgsList = inviteMessgeDao.getMessagesList(); // for(InviteMessage msg:msgsList){ // if (msg.getStatus().equals(InviteMessage.InviteMesageStatus.BEINVITEED)){ // flag=true; // } // } // if (flag==false) { // tips.setVisibility(View.INVISIBLE); // } else { // tips.setVisibility(View.VISIBLE); // } if (inviteMessgeDao.getUnreadMessagesCount() >0) { tips.setVisibility(View.VISIBLE); } else { tips.setVisibility(View.INVISIBLE); } } private void getheadPath(final String name) { SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<UserBean>() { @Override public void onNext(UserBean info) { if (info != null) { UserInfo objectInfo = new UserInfo(); objectInfo.setUserName(info.getName()); objectInfo.setUserHead(info.getHead()); objectInfo.setUserPhone(name); CommonlyUtils.saveObjectUser(objectInfo); startActivity(new Intent(getActivity(), ChatActivity.class)); } } @Override public void onError(String Msg) { } }; Map<String, String> map = new HashMap<>(); map.put("phone", name); HttpMethods.getInstance().getheadPath(new ProgressSubscriber<HttpResult<UserBean>>(onNextListener, this.getActivity(), false), map); } //初始化好友列表 private void initFriendData() { adapter = new FriendAdapter(getActivity(), contactList); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { getheadPath(adapter.getItem(arg2).getUsername()); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { Log.i(MyApplicaption.Tag, listView.getItemAtPosition(i) + "长按"); getObjectInfo(adapter.getItem(i).getUsername()); showPopWindows(); return true; } }); } private void getObjectInfo(final String username) { SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<UserBean>() { @Override public void onNext(UserBean info) { if (info != null) { UserInfo objectInfo = new UserInfo(); objectInfo.setUserName(info.getName()); objectInfo.setUserHead(info.getHead()); objectInfo.setUserPhone(username); CommonlyUtils.saveObjectUser(objectInfo); } } @Override public void onError(String Msg) { } }; Map<String, String> map = new HashMap<>(); map.put("phone", username); HttpMethods.getInstance().getheadPath(new ProgressSubscriber<HttpResult<UserBean>>(onNextListener, this.getActivity(), false), map); } public void showPopWindows() { popWindows = new MyPopWindows(getActivity()); popWindows.setContentView(View.inflate(getActivity(), R.layout.deletefriend, null)); popWindows.showAtLocation(getView(), Gravity.CENTER, 0, 0); View views = popWindows.getContentView(); btnCancle = (TextView) views.findViewById(R.id.btnCancle); btnSure = (TextView) views.findViewById(R.id.btnSure); btnCancle.setOnClickListener(this); btnSure.setOnClickListener(this); } /** * 获取联系人列表,并过滤掉黑名单和排序 */ protected void getContactList() { contactList.clear(); // 获取联系人列表 contactsMap = MyApplicaption.getInstance().getContactList(); if (contactsMap == null) { return; } pullRefresh.onRefreshComplete(); //同步 synchronized (this.contactsMap) { Iterator<Map.Entry<String, EaseUser>> iterator = contactsMap.entrySet().iterator(); List<String> blackList = EMClient.getInstance().contactManager().getBlackListUsernames(); while (iterator.hasNext()) { Map.Entry<String, EaseUser> entry = iterator.next(); // 兼容以前的通讯录里的已有的数据显示,加上此判断,如果是新集成的可以去掉此判断 if (!entry.getKey().equals("item_new_friends") && !entry.getKey().equals("item_groups") && !entry.getKey().equals("item_chatroom") && !entry.getKey().equals("item_robots")) { if (!blackList.contains(entry.getKey())) { // 不显示黑名单中的用户 EaseUser user = entry.getValue(); CommonUtils.setUserInitialLetter(user); contactList.add(user); } } } } // 排序 Collections.sort(contactList, new Comparator<EaseUser>() { @Override public int compare(EaseUser lhs, EaseUser rhs) { if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) { return lhs.getNick().compareTo(rhs.getNick()); } else { if ("#".equals(lhs.getInitialLetter())) { return 1; } else if ("#".equals(rhs.getInitialLetter())) { return -1; } return lhs.getInitialLetter().compareTo(rhs.getInitialLetter()); } } }); if (contactList == null) { return; } Log.i(MyApplicaption.Tag, String.valueOf(contactList.size())); adapter.setData(contactList); } @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onResume() { super.onResume(); initNewContactData(); getContactList(); } @Override public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) { getContactList(); } @Override public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) { getContactList(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnCancle: popWindows.dismiss(); break; case R.id.btnSure: popWindows.dismiss(); try { EMClient.getInstance().contactManager().deleteContact(CommonlyUtils.getObjectUser().getUserPhone()); getContactList(); } catch (HyphenateException e) { e.printStackTrace(); } break; } } }
true
24729e5f8ee6a76b22eaa1df19bb42b5d92f2742
Java
cedooo/web
/src/main/java/tk/cedoo/manage/AddNodeAction.java
UTF-8
4,585
2.234375
2
[]
no_license
package tk.cedoo.manage; import org.apache.ibatis.session.SqlSession; import tk.cedoo.common.DoActionResult; import tk.cedoo.db.DBManager; import tk.cedoo.po.Link; import tk.cedoo.po.LinkStyle; import tk.cedoo.po.Node; import tk.cedoo.po.NodeStyle; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class AddNodeAction extends ActionSupport { /** * */ private static final long serialVersionUID = -2168932732227318058L; private static final int P_C_TYPE_ID = (Integer) ActionContext.getContext().getApplication().get("parentAndChildTypeID"); //父子关系 类型ID private static final int NODE_TYPE_ID = (Integer) ActionContext.getContext().getApplication().get("clazzNodeTypeID"); //'类型'节点 ID private static final int CONTENT_TYPE_ID = (Integer) ActionContext.getContext().getApplication().get("leafNodeTypeID"); //'叶子'节点 ID private static final int ROOT_NODE_ID = (Integer) ActionContext.getContext().getApplication().get("rootNodeID"); //节点类型 ID private static final String QUESTION_ICON = "/images/common/question.ico"; private NodeStyle nodeStyle = null; private Node node = null; private LinkStyle linkStyle = null; private Link link = null; private String addType = null; private DoActionResult doResult = new DoActionResult(); //执行结果 @Override public String execute() throws Exception { System.out.println("添加分类action"); try{ if(link==null){ link = new Link(); } if(link.getSNodeID()<1){ link.setSNodeID(ROOT_NODE_ID); } if(linkStyle == null){ link.setLinkStyleID(4); //TODO 写死了!! link.setLinkTypeID(P_C_TYPE_ID); } if(node!=null){ if("clazz".equals(addType)){ node.setNodeTypeID(NODE_TYPE_ID); }else if("leaf".equals(addType)){ node.setNodeTypeID(CONTENT_TYPE_ID); }else{ throw new Exception("添加类型错误,不能添加。"); } if(null == nodeStyle.getImg() || "".equals(nodeStyle.getImg())){ nodeStyle.setImg(QUESTION_ICON); } }else{ throw new Exception("struts 注入node失败"); } }catch(Exception e){ System.err.println("参数错误,添加失败"); e.printStackTrace(); return ERROR; } doResult.reset(); SqlSession ss = DBManager.getSqlSessionFactory().openSession(); System.out.println("===添加-参数====="); System.out.println(nodeStyle); System.out.println(node); System.out.println(linkStyle); System.out.println(link); System.out.println("============"); boolean debug = false; if(debug){ return SUCCESS; } System.out.println("=====开始执行添加动作====="); try{ //添加节点样式 ss.insert("tk.cedoo.manage.insertNodeStyle", nodeStyle); doResult.setInfo("成功添加节点样式:id=" + nodeStyle.getNodeStyleID()); //添加节点 node.setNodeStyleID(nodeStyle.getNodeStyleID()); ss.insert("tk.cedoo.manage.insertClazzNode", node); doResult.setInfo("成功添加节点:id=" + node.getNodeID()); //添加连接样式 if(linkStyle != null){ ss.insert("tk.cedoo.manage.insertLinkStyle", linkStyle); doResult.setInfo("成功添加连接样式:id=" + linkStyle.getLinkStyleID()); link.setLinkStyleID(linkStyle.getLinkStyleID()); } //添加连接 link.seteNodeID(node.getNodeID()); ss.insert("tk.cedoo.manage.insertLink", link); doResult.setState(DoActionResult.STAT_SUCCESS); doResult.setInfo("成功完成添加动作"); }catch(Exception e){ e.printStackTrace(); doResult.setState(DoActionResult.STAT_FAIL); doResult.setInfo("添加失败"); ss.rollback(); ss.close(); return ERROR; } ss.commit(); ss.close(); System.out.println("=====结束执行添加动作====="); System.out.println("执行结果:" + doResult); return SUCCESS; } public String getAddType() { return addType; } public void setAddType(String addType) { this.addType = addType; } public NodeStyle getNodeStyle() { return nodeStyle; } public void setNodeStyle(NodeStyle nodeStyle) { this.nodeStyle = nodeStyle; } public Node getNode() { return node; } public void setNode(Node node) { this.node = node; } public LinkStyle getLinkStyle() { return linkStyle; } public void setLinkStyle(LinkStyle linkStyle) { this.linkStyle = linkStyle; } public Link getLink() { return link; } public void setLink(Link link) { this.link = link; } public DoActionResult getDoResult() { return doResult; } public void setDoResult(DoActionResult doResult) { this.doResult = doResult; } }
true
6eb0499b7071280d985671b763a81b591f1963fa
Java
lchowdhury/IntelljiProjects
/PracticeSwap.java
UTF-8
604
3.453125
3
[]
no_license
public class PracticeSwap { public static void main(String[] args) { String x= "Framework"; String y= "Automation"; System.out.println("before swapping"); System.out.println("value of x: "+x); System.out.println("value of y; "+y); x = x+y;// FrameworkAutomation y = x.substring(0,x.length()-y.length());//FrameworkAutomation-Automation=Framework x = x.substring(y.length());//Automation System.out.println("after swapping"); System.out.println(x); System.out.println(y); } }
true
ffc6daac33d1d97688f499d971b86125a187fb2f
Java
minthubk/Telematics
/TelematicsTest/src/com/hsuyucheng/telematics/playing/test/SubtitleTest.java
UTF-8
1,294
2.59375
3
[]
no_license
package com.hsuyucheng.telematics.playing.test; import com.hsuyucheng.telematics.playing.Subtitle; import junit.framework.TestCase; public class SubtitleTest extends TestCase { private Subtitle mSubtitle; private String mSubPath = "/mnt/sdcard/TelematicsTest/test.sub"; protected void setUp() throws Exception { super.setUp(); mSubtitle = new Subtitle(mSubPath); } protected void tearDown() throws Exception { super.tearDown(); mSubtitle = null; } public void testGetSub() { int MINISECONDS = 1000; assertTrue(mSubtitle.getSub(3 * MINISECONDS).contains("09:03:09")); assertFalse(mSubtitle.getSub(3 * MINISECONDS).contains("09:03:12")); assertTrue(mSubtitle.getSub(7 * MINISECONDS).contains("09:03:14")); assertFalse(mSubtitle.getSub(7 * MINISECONDS).contains("09:03:17")); } public void testGetSubtitlePath() { String video = "/mnt/sdcard/TelematicsTest/test.mp4"; assertEquals(mSubPath, Subtitle.getSubtitlePath(video)); video = new String("/mnt/sdcard/TelematicsTest/test.mp3"); assertNull(Subtitle.getSubtitlePath(video)); video = new String("/mnt/sdcard/TelematicsTest/test"); assertNull(Subtitle.getSubtitlePath(video)); video = new String(""); assertNull(Subtitle.getSubtitlePath(video)); } }
true
724c800514dc86e343783d6a6340e57fa6ca84bc
Java
Y-Zheng2011/LeetCode
/src/LCWeek175/LCWeek175_2.java
UTF-8
675
3.21875
3
[]
no_license
public class LCWeek175_2 { public int minSteps(String s, String t) { int[] sets = build(s); int[] sett = build(t); int ret = 0; for (int i = 0; i < 26; i++) { if (sets[i] > sett[i]) { ret += sets[i] - sett[i]; } } return ret; } private int[] build(String s) { int[] ret = new int[26]; for (int i = 0; i < s.length(); i++) { ret[s.charAt(i)-'a']++; } return ret; } public static void main(String[] args) { LCWeek175_2 ans = new LCWeek175_2(); System.out.println(ans.minSteps("friend", "family")); } }
true
cfc5b9f551492e69bd5fe19ee418232d3e9ee950
Java
Ritesh1325/Selenium_HybridFramework_Assignment
/src/test/java/Selenium_Practice/Assignment2.java
UTF-8
2,113
2.484375
2
[]
no_license
package Selenium_Practice; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import io.github.bonigarcia.wdm.WebDriverManager; public class Assignment2 { static WebDriver d; final static String appPath = "https://www.google.co.in/maps?hl=en"; final static String searchTxt = "wankhede stadium"; final static String screenShotFilePath = "./Screenshots/Assignment2.html"; public static String screenShotName = null; @FindBy(id = "searchboxinput") @CacheLookup WebElement searchBox; public Assignment2(WebDriver d) { this.d = d; PageFactory.initElements(d, this); } @Test(priority=1) public void launchApp() throws InterruptedException { new Assignment2(d); WebDriverManager.chromedriver().setup(); d = new ChromeDriver(); d.manage().window().maximize(); d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); d.get(appPath); Thread.sleep(3000); } @Test(priority=2) public void sendSearchTxt() throws InterruptedException, IOException { launchApp(); searchBox.sendKeys(searchTxt); Thread.sleep(3000); Assignment2.takeScreenShot(); } public static String getCustomeDate() { String date = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss").format(new Date()); return date; } public static void takeScreenShot() throws IOException { TakesScreenshot ts = (TakesScreenshot)d; File scr = ts.getScreenshotAs(OutputType.FILE); screenShotName = d.getTitle(); String screenShotPath = screenShotName+getCustomeDate()+".png"; File dest = new File(screenShotPath); FileUtils.copyDirectory(scr, dest); } }
true
b62931a151bd0fa12518c8aeeb5f9c09883f8f16
Java
BPI-SINOVOIP/BPI-A64-Android8
/android/tools/tradefederation/core/prod-tests/src/com/android/wireless/tests/WifiStressTest.java
UTF-8
15,956
1.6875
2
[]
no_license
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.wireless.tests; import com.android.ddmlib.IDevice; import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner; import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; import com.android.tradefed.config.Option; import com.android.tradefed.device.DeviceNotAvailableException; import com.android.tradefed.device.ITestDevice; import com.android.tradefed.log.LogUtil.CLog; import com.android.tradefed.result.BugreportCollector; import com.android.tradefed.result.FileInputStreamSource; import com.android.tradefed.result.ITestInvocationListener; import com.android.tradefed.result.InputStreamSource; import com.android.tradefed.result.LogDataType; import com.android.tradefed.testtype.IDeviceTest; import com.android.tradefed.testtype.IRemoteTest; import com.android.tradefed.util.FileUtil; import com.android.tradefed.util.RegexTrie; import com.android.tradefed.util.RunUtil; import com.android.tradefed.util.StreamUtil; import org.junit.Assert; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Run the WiFi stress tests. This test stresses WiFi soft ap, WiFi scanning * and WiFi reconnection in which device switches between cellular and WiFi connection. */ public class WifiStressTest implements IRemoteTest, IDeviceTest { private ITestDevice mTestDevice = null; private static final long START_TIMER = 5 * 60 * 1000; //5 minutes // Define instrumentation test package and runner. private static final String TEST_PACKAGE_NAME = "com.android.connectivitymanagertest"; private static final String TEST_RUNNER_NAME = ".ConnectivityManagerStressTestRunner"; private static final Pattern ITERATION_PATTERN = Pattern.compile("^iteration (\\d+) out of (\\d+)"); private static final int AP_TEST_TIMER = 3 * 60 * 60 * 1000; // 3 hours private static final int SCAN_TEST_TIMER = 30 * 60 * 1000; // 30 minutes private static final int RECONNECT_TEST_TIMER = 12 * 60 * 60 * 1000; // 12 hours private String mOutputFile = "WifiStressTestOutput.txt"; /** * Stores the test cases that we should consider running. * <p/> * This currently consists of "ap", "scanning", and "reconnection" tests. */ private List<TestInfo> mTestList = null; private static class TestInfo { public String mTestName = null; public String mTestClass = null; public String mTestMethod = null; public String mTestMetricsName = null; public int mTestTimer; public RegexTrie<String> mPatternMap = null; @Override public String toString() { return String.format("TestInfo: mTestName(%s), mTestClass(%s), mTestMethod(%s)," + " mTestMetricsName(%s), mPatternMap(%s), mTestTimer(%d)", mTestName, mTestClass, mTestMethod, mTestMetricsName, mPatternMap.toString(), mTestTimer); } } @Option(name="ap-iteration", description="The number of iterations to run soft ap stress test") private String mApIteration = "100"; @Option(name="idle-time", description="The device idle time after screen off") private String mIdleTime = "30"; // 30 seconds @Option(name="reconnect-iteration", description="The number of iterations to run WiFi reconnection stress test") private String mReconnectionIteration = "100"; @Option(name="reconnect-password", description="The password for the above ssid in WiFi reconnection stress test") private String mReconnectionPassword = "androidwifi"; @Option(name="reconnect-ssid", description="The ssid for WiFi recoonection stress test") private String mReconnectionSsid = "securenetdhcp"; @Option(name="reconnection-test", description="Option to run the wifi reconnection stress test") private boolean mReconnectionTestFlag = true; @Option(name="scan-iteration", description="The number of iterations to run WiFi scanning test") private String mScanIteration = "100"; @Option(name="scan-test", description="Option to run the scan stress test") private boolean mScanTestFlag = true; @Option(name="skip-set-device-screen-timeout", description="Option to skip screen timeout configuration") private boolean mSkipSetDeviceScreenTimeout = false; @Option(name="tether-test", description="Option to run the tethering stress test") private boolean mTetherTestFlag = true; @Option(name="wifi-only") private boolean mWifiOnly = false; private void setupTests() { if (mTestList != null) { return; } mTestList = new ArrayList<>(3); // Add WiFi AP stress test TestInfo t = new TestInfo(); t.mTestName = "WifiAPStress"; t.mTestClass = "com.android.connectivitymanagertest.stress.WifiApStress"; t.mTestMethod = "testWifiHotSpot"; t.mTestMetricsName = "wifi_stress"; t.mTestTimer = AP_TEST_TIMER; t.mPatternMap = new RegexTrie<>(); t.mPatternMap.put("wifi_ap_stress", ITERATION_PATTERN); if (mTetherTestFlag) { mTestList.add(t); } // Add WiFi scanning test t = new TestInfo(); t.mTestName = "WifiScanning"; t.mTestClass = "com.android.connectivitymanagertest.stress.WifiStressTest"; t.mTestMethod = "testWifiScanning"; t.mTestMetricsName = "wifi_scan_performance"; t.mTestTimer = SCAN_TEST_TIMER; t.mPatternMap = new RegexTrie<>(); t.mPatternMap.put("avg_scan_time", "^average scanning time is (\\d+)"); t.mPatternMap.put("scan_quality","ssid appear (\\d+) out of (\\d+) scan iterations"); if (mScanTestFlag) { mTestList.add(t); } // Add WiFi reconnection test t = new TestInfo(); t.mTestName = "WifiReconnectionStress"; t.mTestClass = "com.android.connectivitymanagertest.stress.WifiStressTest"; t.mTestMethod = "testWifiReconnectionAfterSleep"; t.mTestMetricsName = "wifi_stress"; t.mTestTimer = RECONNECT_TEST_TIMER; t.mPatternMap = new RegexTrie<>(); t.mPatternMap.put("wifi_reconnection_stress", ITERATION_PATTERN); if (mReconnectionTestFlag) { mTestList.add(t); } } /** * Configure screen timeout property * @throws DeviceNotAvailableException */ private void setDeviceScreenTimeout() throws DeviceNotAvailableException { // Set device screen_off_timeout as svc power can be set to false in the Wi-Fi test String command = ("sqlite3 /data/data/com.android.providers.settings/databases/settings.db " + "\"UPDATE system SET value=\'600000\' WHERE name=\'screen_off_timeout\';\""); CLog.d("Command to set screen timeout value to 10 minutes: %s", command); mTestDevice.executeShellCommand(command); // reboot to allow the setting to take effect, post setup will be taken care by the reboot mTestDevice.reboot(); } /** * Enable/disable screen never timeout property * @param on * @throws DeviceNotAvailableException */ private void setScreenProperty(boolean on) throws DeviceNotAvailableException { CLog.d("set svc power stay on " + on); mTestDevice.executeShellCommand("svc power stayon " + on); } @Override public void setDevice(ITestDevice testDevice) { mTestDevice = testDevice; } @Override public ITestDevice getDevice() { return mTestDevice; } /** * Run the Wi-Fi stress test * Collect results and post results to dashboard */ @Override public void run(ITestInvocationListener standardListener) throws DeviceNotAvailableException { Assert.assertNotNull(mTestDevice); setupTests(); if (!mSkipSetDeviceScreenTimeout) { setDeviceScreenTimeout(); } RunUtil.getDefault().sleep(START_TIMER); if (!mWifiOnly) { final RadioHelper radioHelper = new RadioHelper(mTestDevice); Assert.assertTrue("Radio activation failed", radioHelper.radioActivation()); Assert.assertTrue("Data setup failed", radioHelper.waitForDataSetup()); } IRemoteAndroidTestRunner runner = new RemoteAndroidTestRunner( TEST_PACKAGE_NAME, TEST_RUNNER_NAME, mTestDevice.getIDevice()); runner.addInstrumentationArg("softap_iterations", mApIteration); runner.addInstrumentationArg("scan_iterations", mScanIteration); runner.addInstrumentationArg("reconnect_iterations", mReconnectionIteration); runner.addInstrumentationArg("reconnect_ssid", mReconnectionSsid); runner.addInstrumentationArg("reconnect_password", mReconnectionPassword); runner.addInstrumentationArg("sleep_time", mIdleTime); if (mWifiOnly) { runner.addInstrumentationArg("wifi-only", String.valueOf(mWifiOnly)); } // Add bugreport listener for failed test BugreportCollector bugListener = new BugreportCollector(standardListener, mTestDevice); bugListener.addPredicate(BugreportCollector.AFTER_FAILED_TESTCASES); // Device may reboot during the test, to capture a bugreport after that, // wait for 30 seconds for device to be online, otherwise, bugreport will be empty bugListener.setDeviceWaitTime(30); for (TestInfo testCase : mTestList) { // for Wi-Fi reconnection test, if ("WifiReconnectionStress".equals(testCase.mTestName)) { setScreenProperty(false); } else { setScreenProperty(true); } CLog.d("TestInfo: " + testCase.toString()); runner.setClassName(testCase.mTestClass); runner.setMethodName(testCase.mTestClass, testCase.mTestMethod); runner.setMaxTimeToOutputResponse(testCase.mTestTimer, TimeUnit.MILLISECONDS); bugListener.setDescriptiveName(testCase.mTestName); mTestDevice.runInstrumentationTests(runner, bugListener); logOutputFile(testCase, bugListener); cleanOutputFiles(); } } /** * Collect test results, report test results to dash board. * * @param test * @param listener */ private void logOutputFile(TestInfo test, ITestInvocationListener listener) throws DeviceNotAvailableException { File resFile = null; InputStreamSource outputSource = null; try { resFile = mTestDevice.pullFileFromExternal(mOutputFile); if (resFile != null) { // Save a copy of the output file CLog.d("Sending %d byte file %s into the logosphere!", resFile.length(), resFile); outputSource = new FileInputStreamSource(resFile); listener.testLog(String.format("result-%s.txt", test.mTestName), LogDataType.TEXT, outputSource); // Parse the results file and post results to test listener parseOutputFile(test, resFile, listener); } } finally { FileUtil.deleteFile(resFile); StreamUtil.cancel(outputSource); } } private void parseOutputFile(TestInfo test, File dataFile, ITestInvocationListener listener) { Map<String, String> runMetrics = new HashMap<>(); Map<String, String> runScanMetrics = null; boolean isScanningTest = "WifiScanning".equals(test.mTestName); Integer iteration = null; BufferedReader br = null; try { br = new BufferedReader(new FileReader(dataFile)); String line = null; while ((line = br.readLine()) != null) { List<List<String>> capture = new ArrayList<>(1); String key = test.mPatternMap.retrieve(capture, line); if (key != null) { CLog.d("In output file of test case %s: retrieve key: %s, " + "catpure: %s", test.mTestName, key, capture.toString()); //Save results in the metrics if ("scan_quality".equals(key)) { // For scanning test, calculate the scan quality int count = Integer.parseInt(capture.get(0).get(0)); int total = Integer.parseInt(capture.get(0).get(1)); int quality = 0; if (total != 0) { quality = (100 * count) / total; } runMetrics.put(key, Integer.toString(quality)); } else { runMetrics.put(key, capture.get(0).get(0)); } } else { // For scanning test, iterations will also be counted. if (isScanningTest) { Matcher m = ITERATION_PATTERN.matcher(line); if (m.matches()) { iteration = Integer.parseInt(m.group(1)); } } } } if (isScanningTest) { runScanMetrics = new HashMap<>(1); if (iteration == null) { // no matching is found CLog.d("No iteration logs found in %s, set to 0", mOutputFile); iteration = Integer.valueOf(0); } runScanMetrics.put("wifi_scan_stress", iteration.toString()); } // Report results reportMetrics(test.mTestMetricsName, listener, runMetrics); if (isScanningTest) { reportMetrics("wifi_stress", listener, runScanMetrics); } } catch (IOException e) { CLog.e("IOException while reading from data stream"); CLog.e(e); return; } finally { StreamUtil.close(br); } } /** * Report run metrics by creating an empty test run to stick them in * <p /> * Exposed for unit testing */ private void reportMetrics(String metricsName, ITestInvocationListener listener, Map<String, String> metrics) { // Create an empty testRun to report the parsed runMetrics CLog.d("About to report metrics to %s: %s", metricsName, metrics); listener.testRunStarted(metricsName, 0); listener.testRunEnded(0, metrics); } /** * Clean up output files from the last test run */ private void cleanOutputFiles() throws DeviceNotAvailableException { CLog.d("Remove output file: %s", mOutputFile); String extStore = mTestDevice.getMountPoint(IDevice.MNT_EXTERNAL_STORAGE); mTestDevice.executeShellCommand(String.format("rm %s/%s", extStore, mOutputFile)); } }
true
357e846f98fb7035c0f3375758f4c98a5d6c49bd
Java
liuyong520/msgsrv-extend
/src/test/java/com/nnk/msgsrv/AnnotationMain.java
UTF-8
749
1.875
2
[]
no_license
package com.nnk.msgsrv; import nnk.msgsrv.server.MsgSrvLongConnector; import org.apache.log4j.PropertyConfigurator; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class AnnotationMain { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.scan("com.nnk.msgsrv"); annotationConfigApplicationContext.refresh(); PropertyConfigurator.configure("config/log4j.properties"); MsgSrvLongConnector msgSrvLongConnector = new MsgSrvLongConnector("config/msgsrv-refund.xml"); msgSrvLongConnector.start(); } }
true
76cfcd09c259bba8f3e3d2486726f67c7cb69cf0
Java
Samat220/Gorilla-Game
/Game.java
UTF-8
908
3.5
4
[]
no_license
import java.util.ArrayList; //The game class describes how game is created and run public class Game { //Gorilla game has 2 players and a map Player player1; Player player2; Map map; //Bellow are setters and getters for two players and the map public void setPlayer1() { this.player1 = new Player(0, 1); } public Player getPlayer1() { return this.player1; } public void setPlayer2() { this.player2 = new Player(0, 2); } public Player getPlayer2() { return this.player2; } public void setMap(ArrayList<Building> city, Integer xBoundary, Integer yBoundary) { this.map = new Map(city, xBoundary, yBoundary); } public Map getMap() { return this.map; } public void runGame() { //method for actually running the game //It would involve registering hits, updating scores, destroying buildings, determining the win } }
true
90d6aa22e7400a489ab27bd3a166c05d210d721e
Java
DyAutoTest/WebAutoTest
/src/main/java/com/dy/AutoTest/MerchantPortal/PageObject/myinfo/AccountInfoPage.java
UTF-8
482
1.804688
2
[]
no_license
package com.dy.AutoTest.MerchantPortal.PageObject.myinfo; import org.openqa.selenium.WebDriver; import com.dy.AutoTest.web.actions.DoPlus; import com.dy.AutoTest.web.api.SuperPage; public class AccountInfoPage extends SuperPage { public AccountInfoPage(WebDriver driver) { super(driver); du.loadLocator("MP_Loc_MainMenuPage"); } public void setWaitTime(long waitTime) { du = new DoPlus(driver); du.waitTime = waitTime; du.loadLocator("MP_Loc_MainMenuPage"); } }
true
81641811080aa1180b633d932dc864b18aad0320
Java
zaproxy/zaproxy
/zap/src/main/java/org/parosproxy/paros/network/DecoratedSocketsSslSocketFactory.java
UTF-8
4,418
2.4375
2
[ "Apache-2.0" ]
permissive
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2014 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.parosproxy.paros.network; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; /** * A {@code SSLSocketFactory} that allows to decorate {@code SSLSocket}s after creation but before * returning them. * * @see SSLSocketFactory * @see SslSocketDecorator * @deprecated (2.12.0) Implementation details, do not use. */ @Deprecated public class DecoratedSocketsSslSocketFactory extends SSLSocketFactory { private final SSLSocketFactory delegate; private final SslSocketDecorator socketDecorator; public DecoratedSocketsSslSocketFactory( final SSLSocketFactory delegate, SslSocketDecorator socketDecorator) { super(); if (delegate == null) { throw new IllegalArgumentException("Parameter delegate must not be null."); } if (socketDecorator == null) { throw new IllegalArgumentException("Parameter socketDecorator must not be null."); } this.delegate = delegate; this.socketDecorator = socketDecorator; } private void decorate(final SSLSocket sslSocket) { socketDecorator.decorate(sslSocket); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } @Override public Socket createSocket() throws IOException { Socket socket = delegate.createSocket(); decorate((SSLSocket) socket); return socket; } @Override public Socket createSocket(final String host, final int port) throws IOException, UnknownHostException { Socket socket = delegate.createSocket(host, port); decorate((SSLSocket) socket); return socket; } @Override public Socket createSocket( final Socket s, final String host, final int port, final boolean autoClose) throws IOException { Socket socket = delegate.createSocket(s, host, port, autoClose); decorate((SSLSocket) socket); return socket; } @Override public Socket createSocket( final String host, final int port, final InetAddress localHost, final int localPort) throws IOException, UnknownHostException { Socket socket = delegate.createSocket(host, port, localHost, localPort); decorate((SSLSocket) socket); return socket; } @Override public Socket createSocket(final InetAddress host, final int port) throws IOException { Socket socket = delegate.createSocket(host, port); decorate((SSLSocket) socket); return socket; } @Override public Socket createSocket( final InetAddress address, final int port, final InetAddress localAddress, final int localPort) throws IOException { Socket socket = delegate.createSocket(address, port, localAddress, localPort); decorate((SSLSocket) socket); return socket; } /** * Decorator of {@code SSLSocket}s for {@code DecoratedSocketsSslSocketFactory}ies. * * @see SSLSocket * @see DecoratedSocketsSslSocketFactory * @see #decorate(SSLSocket) */ public interface SslSocketDecorator { /** * Decorates the given SSL socket. * * @param sslSocket the SSL socket that will be decorated. */ void decorate(SSLSocket sslSocket); } }
true
f49451592ae55dc3f62e06538804a6bb4f65da77
Java
jacky-cyber/work
/A2017010-大庆龙南医院自助机项目/02.Engineering/03.Code/01.server/trunk/ssm/src/test/java/com/test/BankServiceTest.java
UTF-8
2,720
2.296875
2
[]
no_license
package com.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lenovohit.ssm.payment.support.bankPay.config.Constants; import com.lenovohit.ssm.payment.support.bankPay.model.builder.BankRefundRequestBuilder; import com.lenovohit.ssm.payment.support.bankPay.model.result.BankRefundResult; import com.lenovohit.ssm.payment.support.bankPay.service.BankTradeService; import com.lenovohit.ssm.payment.support.bankPay.service.impl.BankTradeServiceImpl; /** * Created by zyus. * 简单main函数,用于测试银行Socket 接口 */ public class BankServiceTest { private static Log log = LogFactory.getLog(BankServiceTest.class); public static void main(String[] args) { BankServiceTest main = new BankServiceTest(); // 系统商商测试交易保障接口api // main.test_monitor_sys(); // POS厂商测试交易保障接口api // main.test_monitor_pos(); // 测试交易保障接口调度 // main.test_monitor_schedule_logic(); // 测试当面付2.0支付(使用未集成交易保障接口的当面付2.0服务) // main.test_trade_pay(tradeService); // 测试查询当面付2.0交易 // main.test_trade_query(); // 测试当面付2.0退货 // main.test_trade_refund(); // 测试当面付2.0生成支付二维码 main.test_trade_refund(); } // 测试当面付2.0退款 public void test_trade_refund() { BankRefundRequestBuilder builder = new BankRefundRequestBuilder() .setLength("136").setCode(Constants.TRADE_CODE_REFUND) .setHisCode(Constants.HIS_CODE).setBankCode("1030") .setOutTradeNo("SR17040812345678") .setOutTradeDate("20170408") .setOutTradeTime("173430") .setCardBankCode("1030") .setAccount("acconut") .setAccountName("AccountName") .setAmount("12.00"); BankTradeServiceImpl.ClientBuilder clientBuilder = new BankTradeServiceImpl.ClientBuilder() .setFrontIp("127.0.0.1") .setFrontPort(2017); BankTradeService bankTradeService = new BankTradeServiceImpl.ClientBuilder().build(clientBuilder); BankRefundResult result = bankTradeService.tradeRefund(builder); System.out.println("service response" + result); switch (result.getTradeStatus()) { case SUCCESS: log.info("银行退款成功,退款流水号: "); break; case REFUNDING: log.info("银行退款处理中,退款流水号: "); break; case FAILED: log.error("银行退款失败!!!"); break; case UNKNOWN: log.error("系统异常,银行退款状态未知!!!"); break; } } }
true
70a5fb8e4f99c5f209c394cebee5095663d46519
Java
mateuszryczek/Combiner
/src/main/java/com/mime/combiner/operation/Operation.java
UTF-8
199
1.820313
2
[]
no_license
package com.mime.combiner.operation; import com.mime.combiner.exception.WrongDataTypeException; public interface Operation { Object apply(Object a, Object b) throws WrongDataTypeException; }
true
38788b7641a63fe234ff1c1d59f3c34096e6aaed
Java
siggsa/FlightSimTools
/src/com/company/Route.java
UTF-8
826
3.46875
3
[]
no_license
package com.company; import java.util.LinkedList; public class Route { private LinkedList<Waypoint> route; public Route(){ this.route = new LinkedList<Waypoint>(); } public void AddWaypoint(Waypoint waypoint) { route.add(waypoint); } public void RemoveLastWaypoint() { if (route.isEmpty()){ return; } route.removeLast(); } public double getRouteLength(){ Calculator calc = new Calculator(); double routeDist = 0; for (int i = 1; i < route.size(); i++){ routeDist += calc.DistanceFromWaypointToWaypoint(route.get(i-1),route.get(i)); } return routeDist; } public void clearRoute() { route.clear(); } public int getSize() { return route.size(); } }
true
8d9f04d7d74d21788efa09d3171141abb0f75a30
Java
infinispan/infinispan
/server/router/src/main/java/org/infinispan/server/router/routes/resp/RespServerRouteDestination.java
UTF-8
352
1.867188
2
[ "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
permissive
package org.infinispan.server.router.routes.resp; import org.infinispan.server.resp.RespServer; import org.infinispan.server.router.routes.RouteDestination; public class RespServerRouteDestination extends RouteDestination<RespServer> { public RespServerRouteDestination(String name, RespServer respServer) { super(name, respServer); } }
true
99c2221109e4a041f12373351c91b55a1b627276
Java
Novoselov-pavel/npn.vita-soft
/src/main/java/com/npn/vita/soft/controllers/RequestController.java
UTF-8
6,935
2.484375
2
[]
no_license
package com.npn.vita.soft.controllers; import com.npn.vita.soft.model.request.Request; import com.npn.vita.soft.model.request.services.interfaces.RequestInterface; import com.npn.vita.soft.model.security.UserRoles; import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.security.Principal; import java.util.List; /** * Provides controllers for all action with {@link Request}. */ @RestController @RequestMapping("/api/requests") public class RequestController { private final Logger logger = LoggerFactory.getLogger(RequestController.class); private RequestInterface service; /** * Creates a Request, request body should be a Json object with charset UTF-8 and with not Null parameters: * "message" and "header". * Returns HTTP status 400 on error. * * @param principal {@link Principal} * @param body Json object */ @Secured(UserRoles.Code.USER) @PostMapping(value = "/add", consumes = {"application/json;charset=UTF-8"}) public void createRequest(Principal principal, @RequestBody String body) { try { service.addNewRequest(body, principal.getName()); } catch (ParseException exception) { logger.warn("Failed to create a request, request body parsing error", exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } catch (IllegalArgumentException exception) { logger.warn("Failed to create a request, illegal message parts", exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * Return the user's requests. * Returns HTTP status 400 on error. * * @param principal {@link Principal} * @return array of Json objects in charset UTF-8 */ @Secured(UserRoles.Code.USER) @GetMapping(value = "/getMyRequests", produces = {"application/json;charset=UTF-8"}) public List<Request> getUserRequest(Principal principal){ try { return service.getRequestsByUserName(principal.getName()); } catch (IllegalArgumentException exception) { logger.warn("Failed to get requests", exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * * Return the user's request by id. * Returns HTTP status 400 on error. * * @param id request's id * @param principal {@link Principal} * @return {@link Request} as Json object */ @Secured(UserRoles.Code.USER) @GetMapping(value = "/{id}", produces = {"application/json;charset=UTF-8"}) public Request getUserRequest(@PathVariable(value = "id") Long id, Principal principal){ try { return service.getRequestByIdAndUserName(id,principal.getName()); } catch (IllegalArgumentException exception) { logger.warn("Failed to get a request", exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * Updates the user's request with state "RAW" by id. * Request body should be a Json object with charset UTF-8 and with not Null parameters: * "message" and "header". * Returns HTTP status 400 on error. * * @param id request's id * @param principal {@link Principal} * @param body Json object */ @Secured(UserRoles.Code.USER) @PutMapping(value = "/{id}/updateRawRequest", consumes = {"application/json;charset=UTF-8"}) public void updateRawRequest(@PathVariable(value = "id") Long id, Principal principal, @RequestBody String body) { try { service.updateRequest(id, body, principal.getName()); } catch (ParseException exception) { logger.warn("Failed to update a request", exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } catch (IllegalArgumentException exception) { logger.warn("Failed to update a request", exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * Sends the user's request. * Returns HTTP status 400 on error. * * @param id request's id * @param principal {@link Principal} */ @Secured(UserRoles.Code.USER) @PutMapping(value = "/{id}/send") public void sendRequest(@PathVariable(value = "id") Long id, Principal principal) { try { service.sendRequest(id, principal.getName()); } catch (IllegalArgumentException exception) { logger.warn("Failed to send a request with id = " + id, exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * Accepts the user's request. * Returns HTTP status 400 on error. * * @param id request's id */ @Secured(UserRoles.Code.OPERATOR) @PutMapping(value = "/{id}/accept") public void acceptRequest(@PathVariable(value = "id") Long id){ try { service.acceptRequest(id); }catch (IllegalArgumentException | IllegalStateException exception) { logger.warn("Failed to accept a request with id = " + id, exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * Rejects the user's request. * Returns HTTP status 400 on error. * * @param id request's id */ @Secured(UserRoles.Code.OPERATOR) @PutMapping(value = "/{id}/reject") public void rejectRequest(@PathVariable(value = "id") Long id){ try { service.rejectRequest(id); }catch (IllegalArgumentException | IllegalStateException exception) { logger.warn("Failed to reject a request with id = " + id, exception); throw new ResponseStatusException(HttpStatus.BAD_REQUEST,exception.getMessage()); } } /** * Returns all the requests with status "SEND". * * @return array of Json objects in charset UTF-8 */ @Secured(UserRoles.Code.OPERATOR) @GetMapping(value = "/getSendedRequests", produces = {"application/json;charset=UTF-8"}) public String getSendedRequest() { return service.getSendedRequestWithFormat(); } /** * Sets the requests' service. * * @param service */ @Autowired public void setService(RequestInterface service) { this.service = service; } }
true
8b768806193215b4bcb2aefe87b407e3ad631b87
Java
saikatHi6/sold-auction
/src/main/java/com/nasdaq/auction/soldauction/model/UserType.java
UTF-8
89
1.570313
2
[]
no_license
package com.nasdaq.auction.soldauction.model; public enum UserType { SELLER,BUYER }
true
9ab4e23e5d4146853f460f9cd34324e820b1894c
Java
rajnishkg/Java_study
/mafs-core-data/src/main/java/com/mikealbert/data/entity/LogBook.java
UTF-8
1,953
2.140625
2
[]
no_license
package com.mikealbert.data.entity; import java.io.Serializable; import java.util.List; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The persistent class for the VISION.LOG_BOOKS database table. * @author sibley */ @Entity @Table(name="LOG_BOOKS") public class LogBook extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="LBK_SEQ") @SequenceGenerator(name="LBK_SEQ", sequenceName="LBK_SEQ", allocationSize=1) @Column(name = "LBK_ID", nullable=false) private Long lbkId; @Size(min = 1, max = 60) @Column(name = "NAME") private String name; @Size(min = 1, max = 20) @Column(name = "TYPE") private String type; @Size(min = 1, max = 80) @Column(name = "DESCRIPTION") private String description; @OneToMany(mappedBy = "logBook", cascade=CascadeType.ALL, fetch = FetchType.LAZY) private List<ObjectLogBook> objectLogBooks; public LogBook() {} public Long getLbkId() { return lbkId; } public void setLbkId(Long lbkId) { this.lbkId = lbkId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<ObjectLogBook> getObjectLogBooks() { return objectLogBooks; } public void setObjectLogBooks(List<ObjectLogBook> objectLogBooks) { this.objectLogBooks = objectLogBooks; } @Override public String toString() { return "com.mikealbert.data.entity.LogBook[ code=" + getLbkId() + " ]"; } }
true
8ec8b2d98d34ae42b837180aab136185ccbf9a51
Java
sangeetha2898/MyFirstProject
/MyFirstProject/src/Duplicate_Element.java
UTF-8
411
3.203125
3
[]
no_license
import java.io.*; public class Duplicate_Element { public static void main(String[] args) { int a[]= {4,7,6,2,3,1,9,3}; for(int i = 0; i < a.length; i++) { for(int j = i + 1; j < a.length; j++) { if(a[i] == a[j]) { System.out.print("Duplicate Element:"); System.out.println(a[j]); } } } } }
true
1cda2e0517044b662df8ebac354249eb6695c243
Java
ivanbravi/RinascimentoFramework
/src/gamesearch/players/evaluators/BehaviouralEvaluation.java
UTF-8
6,574
2.15625
2
[ "MIT" ]
permissive
package gamesearch.players.evaluators; import gamesearch.players.evaluators.matrix.GridGenerator; import gamesearch.players.evaluators.matrix.LoadGridGenerator; import gamesearch.players.evaluators.matrix.NormalisedMatrixSimilarity; import gamesearch.players.evaluators.matrix.MatrixEvaluator; import gamesearch.players.extractor.BehavioursExtractor; import gamesearch.players.extractor.StatsExtractor; import log.LogGroup; import log.Logger; import mapelites.behaviours.BehaviourReader; import mapelites.core.binning.Binning; import statistics.GameStats; import statistics.types.NumericalStatistic; import statistics.types.StatisticInterface; import utils.filters2D.*; import utils.ops2D.Data; import utils.ops2D.Init2D; import utils.ops2D.Math2D; import utils.ops2D.ToString2D; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class BehaviouralEvaluation implements PlayersEvaluator{ private transient BehavioursExtractor extractor; private transient StatsExtractor performanceExtractor; private double[][] targetDistribution; private MatrixEvaluator evaluator; private Filter2D[] preProcessingFilters; private BehaviouralEvaluationDelegate delegate; public static boolean logEvaluations = true; public static LogGroup lg; public static ToString2D.Format logFormat = new ToString2D.Format("","","\t", "\n"); public BehaviouralEvaluation(String behavioursFile, StatsExtractor performanceExtractor, GridGenerator gg, MatrixEvaluator evaluator, Filter2D[] preProcessingFilters){ this.extractor = new BehavioursExtractor(behavioursFile); this.performanceExtractor = performanceExtractor; this.targetDistribution = gg.samplesGrid(extractor.axisBins(0), extractor.axisBins(1)); this.evaluator = evaluator; this.preProcessingFilters = preProcessingFilters; } private double[][] extractMatrixFromData(HashMap<Double, GameStats> data){ double[][] empiricalDistribution = Init2D.copyShape(targetDistribution); Init2D.init(empiricalDistribution,Double.NEGATIVE_INFINITY); for(Map.Entry<Double, GameStats> e: data.entrySet()){ GameStats stats = e.getValue(); double[] newBehaviour = extractor.extractBehaviours(stats); int[] newCoordinates = extractor.place(newBehaviour); double newPerformance = performanceExtractor.extract(stats).getAsDouble(); int x = newCoordinates[0]; int y = newCoordinates[1]; if(empiricalDistribution[x][y]<newPerformance) empiricalDistribution[x][y] = newPerformance; } return empiricalDistribution; } public void setDelegate(BehaviouralEvaluationDelegate delegate){ this.delegate = delegate; } @Override public NumericalStatistic evaluateWithStatistic(HashMap<Double, GameStats> data, String logID) { double[][] empiricalDistribution = extractMatrixFromData(data); double[][] filteredDistribution; delegate.empiricalMatrix(empiricalDistribution); filteredDistribution = applyFiltersUntilConvergence(empiricalDistribution, preProcessingFilters); delegate.filteredMatrix(filteredDistribution); NumericalStatistic filteredEvaluation = evaluator.evaluateWithStatistics(targetDistribution, filteredDistribution); if(logEvaluations){ NumericalStatistic empiricalEvaluation = evaluator.evaluateWithStatistics(targetDistribution, empiricalDistribution); logEvaluation( empiricalDistribution, filteredDistribution, empiricalEvaluation.value(), filteredEvaluation.value(), logID ); Logger.saveAtom(data,Logger.atomDestination(lg.folderPath()+"evalData["+logID+"]")); } return filteredEvaluation; } private static void logEvaluation(double[][] empiricalDistribution, double[][] filteredDistribution, double empiricalEvaluation, double filteredEvaluation, String logIdD){ if(!logEvaluations) return; String empiricalString = ToString2D.matrixToString(empiricalDistribution, logFormat,false); String filteredString = ToString2D.matrixToString(filteredDistribution, logFormat,false); BehaviouralEvaluationLog log = new BehaviouralEvaluationLog( empiricalString, filteredString, empiricalEvaluation, filteredEvaluation ); Logger.saveAtom(log,Logger.atomDestination(lg.folderPath()+"evalLog["+logIdD+"]")); } private static double[][] applyFilters(double[][] data, Filter2D[] filters){ double[][] r = data; for(int i=0; i<filters.length; i++){ r = filters[i].apply(r); } return r; } private static double[][] applyFiltersUntilConvergence(double[][] data, Filter2D[] filters){ double[][] r = data; // System.out.println(ToString2D.matrixToString(r,ToString2D.defaultFormat,false)); // System.out.println(); do{ r = applyFilters(r,filters); // System.out.println(ToString2D.matrixToString(r,ToString2D.defaultFormat,false)); // System.out.println(); }while(Math2D.contains(r,Double.NEGATIVE_INFINITY)); return r; } public double[][] getTargetDistribution() { return Init2D.copy(targetDistribution); } public static void main(String[] args) { String gridGeneratorFile = "assets/game_search/grid.json"; String behavioursFile = "assets/game_search/behaviours_8x8.json"; BehaviouralEvaluation.lg = new LogGroup("tmp/TEST - "+ (new SimpleDateFormat("yy:MM:dd:HH:mm:ss")).format(new Date())+"/"); GridGenerator eg = LoadGridGenerator.load(gridGeneratorFile); BehaviourReader br = new BehaviourReader(behavioursFile); Binning[] bins = br.getLinearBins(); double[] xAxis = BehaviourReader.getAxis(bins[0]); double[] yAxis = BehaviourReader.getAxis(bins[1]); double[][] targetGrid = eg.samplesGrid(xAxis,yAxis); double[][] empiricalData = Init2D.copy(Data.elInf10x10); // Try with elInf10x10 for example of good filtering double[][] filteredData; if(Math2D.areNotCompatible(empiricalData,targetGrid)){ String warning = "[WARNING:Behavioural Evaluation]\nThe matrices empiricalData and targetGrid are not compatible!"; System.out.println(warning); lg.add("WARNING_BE",warning); lg.saveLog(); return; } MatrixEvaluator evaluator = new NormalisedMatrixSimilarity(); Filter2D[] filters = new Filter2D[]{new InfFiller(new Mean(1),0.8)}; filteredData = applyFiltersUntilConvergence(empiricalData,filters); StatisticInterface evaluation = evaluator.evaluateWithStatistics(empiricalData,targetGrid); StatisticInterface evaluationFiltered = evaluator.evaluateWithStatistics(filteredData,targetGrid); logEvaluation(empiricalData,filteredData,evaluation.value(),evaluationFiltered.value(),"0"); lg.saveLog(); } }
true
8271aa6048cc642349a680d3ba39a5401975513c
Java
tyhgg/smdfly-facepay
/code/facepay-code/facepay/src/main/java/com/tyhgg/asr/system/entity/OrgInfoPageEntity.java
UTF-8
2,423
1.71875
2
[]
no_license
package com.tyhgg.asr.system.entity; import java.io.Serializable; import com.tyhgg.core.framework.entity.PageEntity; public class OrgInfoPageEntity extends PageEntity implements Serializable { private static final long serialVersionUID = 1961146260473841208L; private int id; private String orgId; private String orgName; private String orgFullName; private String orgNameEn; private String pid; private String specificId; private String superOrgId; private int orgLevel; private String isChild; private String orgStatus; private int sortId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId; } public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getSpecificId() { return specificId; } public void setSpecificId(String specificId) { this.specificId = specificId; } public String getSuperOrgId() { return superOrgId; } public void setSuperOrgId(String superOrgId) { this.superOrgId = superOrgId; } public int getOrgLevel() { return orgLevel; } public void setOrgLevel(int orgLevel) { this.orgLevel = orgLevel; } public String getIsChild() { return isChild; } public void setIsChild(String isChild) { this.isChild = isChild; } public String getOrgStatus() { return orgStatus; } public void setOrgStatus(String orgStatus) { this.orgStatus = orgStatus; } public int getSortId() { return sortId; } public void setSortId(int sortId) { this.sortId = sortId; } public String getOrgFullName() { return orgFullName; } public void setOrgFullName(String orgFullName) { this.orgFullName = orgFullName; } public String getOrgNameEn() { return orgNameEn; } public void setOrgNameEn(String orgNameEn) { this.orgNameEn = orgNameEn; } @Override public String toString() { return "OrgInfoPageEntity [id=" + id + ", orgId=" + orgId + ", orgName=" + orgName + ", orgFullName=" + orgFullName + ", orgNameEn=" + orgNameEn + ", pid=" + pid + ", specificId=" + specificId + ", superOrgId=" + superOrgId + ", orgLevel=" + orgLevel + ", isChild=" + isChild + ", orgStatus=" + orgStatus + ", sortId=" + sortId + "]"; } }
true
eeb9915ce890059dc045cde2e3755bffb138bd0d
Java
MicroHero-Taken/HeroTaken
/HeroJDBC/src/main/java/_04shop/ShopBean.java
UTF-8
2,193
2.765625
3
[]
no_license
package _04shop; import java.io.Serializable; import java.sql.Blob; public class ShopBean implements Serializable{ private static final long serialVersionUID = 1L; private Integer heroNo; private String heroName; private Integer heroPrice; private Blob heroSkin1; private Blob heroSkin2; private Blob heroSkin3; private Blob heroSkin4; private Blob heroSkin5; public ShopBean() { } public ShopBean(Integer heroNo, String heroName, Integer heroPrice) { super(); this.heroNo = heroNo; this.heroName = heroName; this.heroPrice = heroPrice; } @Override public String toString() { return "ShopBean [heroNo=" + heroNo + ", heroName=" + heroName + ", heroPrice=" + heroPrice + ", heroSkin1=" + heroSkin1 + ", heroSkin2=" + heroSkin2 + ", heroSkin3=" + heroSkin3 + ", heroSkin4=" + heroSkin4 + ", heroSkin5=" + heroSkin5 + "]" +"\n"; } // ----------------------------------Get/Set--------------------------------------- public Integer getHeroNo() { return heroNo; } public void setHeroNo(Integer heroNo) { this.heroNo = heroNo; } public String getHeroName() { return heroName; } public void setHeroName(String heroName) { this.heroName = heroName; } public Integer getHeroPrice() { return heroPrice; } public void setHeroPrice(Integer heroPrice) { this.heroPrice = heroPrice; } public Blob getHeroSkin1() { return heroSkin1; } public void setHeroSkin1(Blob heroSkin1) { this.heroSkin1 = heroSkin1; } public Blob getHeroSkin2() { return heroSkin2; } public void setHeroSkin2(Blob heroSkin2) { this.heroSkin2 = heroSkin2; } public Blob getHeroSkin3() { return heroSkin3; } public void setHeroSkin3(Blob heroSkin3) { this.heroSkin3 = heroSkin3; } public Blob getHeroSkin4() { return heroSkin4; } public void setHeroSkin4(Blob heroSkin4) { this.heroSkin4 = heroSkin4; } public Blob getHeroSkin5() { return heroSkin5; } public void setHeroSkin5(Blob heroSkin5) { this.heroSkin5 = heroSkin5; } public static long getSerialversionuid() { return serialVersionUID; } }
true
3a5be6d6c8c6facce6a21f604c05a525fddc8a90
Java
vmelnychuk/java-concurrency
/src/main/java/model/Counter.java
UTF-8
140
2.671875
3
[]
no_license
package model; public interface Counter<T> { void inc(); void dec(); T getCounterValue(); void setCounterValue(T value); }
true
9676bc3341c292c45cd2f365951d1d503b715a53
Java
jonathak/mug
/src/java/Fart.java
UTF-8
296
2.46875
2
[]
no_license
public class Fart { public static void main(String[] args) { //Crap x = new Crap(); String y = Crap.fart(" ..from Fart.main().. "); System.out.println(y); Double p = Crap.matic(new Double[]{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }); System.out.println(p); } }
true
fe465c78a48aea57176571bdba3d0303ce86e69b
Java
theminecoder/AppBase
/src/main/java/me/theminecoder/appbase/logger/ConsoleWriterHandler.java
UTF-8
4,504
2.640625
3
[]
no_license
/* * Copyright (c) 2015, geNAZt * * This code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package me.theminecoder.appbase.logger; import jline.console.ConsoleReader; import me.theminecoder.appbase.util.ConsoleColor; import org.fusesource.jansi.Ansi; import java.io.IOException; import java.util.EnumMap; import java.util.Map; import java.util.logging.Handler; import java.util.logging.LogRecord; /** * A handler which prints out colored messages to a jLine ConsoleReader * * @author geNAZt * @version 1.0 */ public class ConsoleWriterHandler extends Handler { private final Map<ConsoleColor, String> replacements = new EnumMap<>(ConsoleColor.class); private final ConsoleColor[] colors = ConsoleColor.values(); private final ConsoleReader console; /** * Construct a new ConsoleWriterHandler * * @param console to print all log messages to */ public ConsoleWriterHandler(ConsoleReader console) { this.console = console; replacements.put(ConsoleColor.BLACK, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString()); replacements.put(ConsoleColor.DARK_BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString()); replacements.put(ConsoleColor.DARK_GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString()); replacements.put(ConsoleColor.DARK_AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString()); replacements.put(ConsoleColor.DARK_RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString()); replacements.put(ConsoleColor.DARK_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString()); replacements.put(ConsoleColor.GOLD, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString()); replacements.put(ConsoleColor.GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString()); replacements.put(ConsoleColor.DARK_GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString()); replacements.put(ConsoleColor.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString()); replacements.put(ConsoleColor.GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString()); replacements.put(ConsoleColor.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString()); replacements.put(ConsoleColor.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString()); replacements.put(ConsoleColor.LIGHT_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString()); replacements.put(ConsoleColor.YELLOW, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString()); replacements.put(ConsoleColor.WHITE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString()); replacements.put(ConsoleColor.MAGIC, Ansi.ansi().a(Ansi.Attribute.BLINK_SLOW).toString()); replacements.put(ConsoleColor.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString()); replacements.put(ConsoleColor.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString()); replacements.put(ConsoleColor.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString()); replacements.put(ConsoleColor.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString()); replacements.put(ConsoleColor.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString()); } /** * Replace all colors to the ANSI Codes * * @param message to print to the console */ public void print(String message) { // Replace all colors for (ConsoleColor color : colors) { message = message.replaceAll("(?i)" + color.toString(), replacements.get(color)); } // Print to the console try { console.print(ConsoleReader.RESET_LINE + message + Ansi.ansi().reset().toString()); console.drawLine(); console.flush(); } catch (IOException ex) { // Ignored } } @Override public void publish(LogRecord record) { print(getFormatter().format(record)); } @Override public void flush() { } @Override public void close() throws SecurityException { } }
true
4620dd52b168ea92195009e743eb1ae8f7d1cbac
Java
shangV2/lightning
/lightning.open/src/main/java/com/qing/askengine/model/WordFreq.java
UTF-8
691
2.84375
3
[ "Apache-2.0" ]
permissive
package com.qing.askengine.model; public class WordFreq implements Comparable<WordFreq> { private String word; private int freq; public WordFreq(String word, int freq) { super(); this.word = word; this.freq = freq; } @Override public int compareTo(WordFreq o) { return word.compareTo(o.word); } @Override public boolean equals(Object obj) { return word.equals(((WordFreq)obj).word); } @Override public int hashCode() { return word.hashCode(); } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public int getFreq() { return freq; } public void setFreq(int freq) { this.freq = freq; } }
true
1a788edfcff532ba61d82a8084a20d19c8fd5854
Java
chinaccj/tcc-transaction
/tcc-demo/demo-itemcenter/demo-itemcenter.facade/src/main/java/com/touna/tcc/demo/itemcenter/facade/intf/ItemFacade.java
UTF-8
1,983
1.9375
2
[]
no_license
package com.touna.tcc.demo.itemcenter.facade.intf; import com.touna.tcc.core.TccContext; import com.touna.tcc.core.TwoPhaseBusinessAction; /** * Created by chenchaojian on 17/5/27. */ public interface ItemFacade { /** * * @param xid * @param productId * @param amount */ @TwoPhaseBusinessAction(commitMethod="sellCommit",rollbackMethod="sellRollback") void sell(String xid,String productId,Integer amount); void sellCommit(String xid,TccContext tccContext); void testRollbackException(String xid, TccContext tccContext) ; void sellRollback(String xid,TccContext tccContext); /** 容错测试 **/ /** * 容错测试 * TG 为test group 简称 */ /** * 正常调用 * @param xid */ @TwoPhaseBusinessAction(commitMethod="testCommit",rollbackMethod="testRollback") void test(String xid); void testCommit(String xid,TccContext tccContext); void testRollback(String xid,TccContext tccContext); /** * 模拟api1 try 失败场景。 rollback成功 * @param xid */ @TwoPhaseBusinessAction(commitMethod="tryFailCommit",rollbackMethod="tryFailRollback") void tryFail(String xid); void tryFailCommit(String xid,TccContext tccContext); void tryFailRollback(String xid,TccContext tccContext); /** * try 超时。 * @param xid */ @TwoPhaseBusinessAction(commitMethod="tryTimeoutCommit",rollbackMethod="tryTimeoutRollback") void tryTimeout(String xid); void tryTimeoutCommit(String xid,TccContext tccContext); void tryTimeoutRollback(String xid,TccContext tccContext); /** * UnSpecifications。 * @param xid */ @TwoPhaseBusinessAction(commitMethod="unSpecificationsCommit",rollbackMethod="unSpecificationsRollback") void unSpecifications(String xid); void unSpecificationsCommit(String xid); void unSpecificationsRollback(String xid); }
true
0d866c524bdbcbce8bb0a901597b7bff5a010bfe
Java
zkywalker/zky
/app/src/main/java/org/zky/zky/utils/ScreenUtils.java
UTF-8
1,958
2.859375
3
[ "Apache-2.0" ]
permissive
package org.zky.zky.utils; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Matrix; import android.util.TypedValue; public class ScreenUtils { /** * dp2px */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 另一种实现,目测这种更好 * @param context 1 * @param value 2 * @return 3 */ public static int dp2px(Context context,int value) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics()); } /** * px2dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** *根据设备信息获取当前分辨率下指定单位对应的像素大小; * px,dip,sp -> px */ public float getRawSize(Context c, int unit, float size) { Resources r; if (c == null){ r = Resources.getSystem(); }else{ r = c.getResources(); } return TypedValue.applyDimension(unit, size, r.getDisplayMetrics()); } public static Bitmap zoomImg(Bitmap bm, float newWidth , float newHeight){ // 获得图片的宽高 int width = bm.getWidth(); int height = bm.getHeight(); // 计算缩放比例 float scaleWidth = newWidth / width; float scaleHeight = newHeight / height; // 取得想要缩放的matrix参数 Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的图片 return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); } }
true
bba54cb69c8beb48d4e8d1a6f2697b0d4000227b
Java
Polux-Proyecto/ProyectPolux
/src/java/com/commercewebapp/objects/Precios.java
UTF-8
1,601
2.5625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.commercewebapp.objects; /** * * @author Mauricio Aguilar */ public class Precios { private String precioUnitario, cargoEnvio, totalPagar; private int cantidad; public Precios (double precioU, int cantidad){ double dCargoEnvio = cantidad*precioU*0.1; double dtotalPagar = cantidad*precioU + dCargoEnvio; dCargoEnvio = (double) Math.round(dCargoEnvio * 100d / 100d); dtotalPagar = (double) Math.round(dtotalPagar * 100d / 100d); this.setPrecioUnitario(Double.toString(precioU)); this.setCargoEnvio(Double.toString(dCargoEnvio)); this.setTotalPagar(Double.toString(dtotalPagar)); this.setCantidad(cantidad); } public int getCantidad() { return cantidad; } private void setCantidad(int cantidad) { this.cantidad = cantidad; } public String getPrecioUnitario() { return precioUnitario; } private void setPrecioUnitario(String precioUnitario) { this.precioUnitario = precioUnitario; } public String getCargoEnvio() { return cargoEnvio; } private void setCargoEnvio(String cargoEnvio) { this.cargoEnvio = cargoEnvio; } public String getTotalPagar() { return totalPagar; } private void setTotalPagar(String totalPagar) { this.totalPagar = totalPagar; } }
true
4f6f33519932fd17b6e626b42ee10a5a87fdafee
Java
hivemq/hivemq-community-edition
/src/main/java/com/hivemq/extensions/auth/AuthContext.java
UTF-8
5,931
1.8125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019-present HiveMQ GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hivemq.extensions.auth; import com.hivemq.bootstrap.ClientConnectionContext; import com.hivemq.extension.sdk.api.annotations.NotNull; import com.hivemq.extensions.executor.task.PluginInOutTaskContext; import com.hivemq.mqtt.handler.auth.MqttAuthSender; import com.hivemq.mqtt.message.mqtt5.Mqtt5UserProperties; import com.hivemq.mqtt.message.reason.Mqtt5AuthReasonCode; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; abstract class AuthContext<T extends AuthOutput<?>> extends PluginInOutTaskContext<T> implements Supplier<T> { private static final Logger log = LoggerFactory.getLogger(AuthContext.class); final @NotNull ChannelHandlerContext ctx; final @NotNull MqttAuthSender authSender; private final int authenticatorsCount; private int counter; private @NotNull AuthenticationState state = AuthenticationState.UNDECIDED; @NotNull T output; AuthContext( final @NotNull String identifier, final @NotNull ChannelHandlerContext ctx, final @NotNull MqttAuthSender authSender, final int authenticatorsCount, final @NotNull T output) { super(identifier); this.ctx = ctx; this.authSender = authSender; this.authenticatorsCount = authenticatorsCount; this.output = output; } @Override public void pluginPost(final @NotNull T output) { if (output.isTimedOut()) { switch (output.getTimeoutFallback()) { case FAILURE: output.failByTimeout(); break; case SUCCESS: output.nextByTimeout(); break; } } else if ((output.getAuthenticationState() == AuthenticationState.UNDECIDED) && output.isAuthenticatorPresent()) { output.failByUndecided(); } if (!state.isFinal() && (output.getAuthenticationState() != AuthenticationState.UNDECIDED)) { state = output.getAuthenticationState(); } if (++counter < authenticatorsCount) { if (!state.isFinal()) { this.output = createNextOutput(output); } } else { finishExtensionFlow(output); } } abstract @NotNull T createNextOutput(@NotNull T prevOutput); @Override public @NotNull T get() { return output; } private void finishExtensionFlow(final @NotNull T output) { if (!ctx.channel().isActive()) { return; } try { ctx.executor().execute(() -> { switch (state) { case CONTINUE: continueAuthentication(output); break; case SUCCESS: succeedAuthentication(output); break; case FAILED: case NEXT_EXTENSION_OR_DEFAULT: failAuthentication(output); break; case UNDECIDED: assert !output.isAuthenticatorPresent(); // happens only if all providers return null undecidedAuthentication(output); } }); } catch (final RejectedExecutionException ex) { if (!ctx.executor().isShutdown()) { final ClientConnectionContext clientConnectionContext = ClientConnectionContext.of(ctx.channel()); log.error("Execution of authentication was rejected for client with IP {}.", clientConnectionContext.getChannelIP().orElse("UNKNOWN"), ex); } } } private void continueAuthentication(final @NotNull T output) { final ChannelFuture authFuture = authSender.sendAuth(ctx.channel(), output.getAuthenticationData(), Mqtt5AuthReasonCode.CONTINUE_AUTHENTICATION, Mqtt5UserProperties.of(output.getOutboundUserProperties().asInternalList()), output.getReasonString()); authFuture.addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { final ScheduledFuture<?> timeoutFuture = ctx.executor().schedule(this::onTimeout, output.getTimeout(), TimeUnit.SECONDS); ClientConnectionContext.of(ctx.channel()).setAuthFuture(timeoutFuture); } else if (future.channel().isActive()) { onSendException(future.cause()); } }); } void succeedAuthentication(final @NotNull T output) { ClientConnectionContext.of(ctx.channel()).setAuthPermissions(output.getDefaultPermissions()); } abstract void failAuthentication(@NotNull T output); abstract void undecidedAuthentication(@NotNull T output); abstract void onTimeout(); abstract void onSendException(@NotNull Throwable cause); }
true
a365197b2a28710c2a9769ddeb51e1fe5635a8a2
Java
xu-chao/ssm-base
/src/main/java/com/java/activiti/service/MyTypeService.java
GB18030
2,034
1.945313
2
[]
no_license
package com.java.activiti.service; import com.java.activiti.model.Menu; import com.java.activiti.model.MyType; import com.java.activiti.pojo.GlobalResultVO; import com.java.activiti.pojo.Tree; import java.util.List; public interface MyTypeService { /** * @author LIUHD * typeCode * @description findMyTypeByTypeCode * @date 2020/1/13 16:09 * @Version 1.0 */ public List<MyType> findMyTypeByTypeCode(String typeCode); /** * * @Title: selectMyTypeByTypeCode * @Description: öͣʾö * @author: * @param typeCode * @return */ public List<MyType> selectMyTypeByTypeCode(String typeCode); // // /** // * // * @Title: addMenu // * @Description: // * @author: _dd43 // * @param Menu // * @return // */ // GlobalResultVO addMenu(Menu Menu); // // /** // * // * @Title: deleteMenuById // * @Description: idɾ // * @author: // * @param menuid // * @return // */ // GlobalResultVO deleteMenuById(String menuid); // // /** // * // * @Title: updateMenuById // * @Description: id޸ // * @author: // * @param Menu // * @return // */ // GlobalResultVO updateMenuById(Menu Menu); // /** // * // * @Title: findMenuByUserid // * @Description: useridضӦ˵ // * @param userid // * @return Menu // * @author // * @date 20192168:43:39 // */ // Menu findMenuByUserid(String userid); // /** // * // * @Title: findMenuListByUserid // * @Description: useridضӦ˵б // * @param userid // * @return List<Menu> // * @author // * @date 20192178:55:10 // */ // List<Menu> findMenuListByUserid(String userid); }
true
590ff4e15c0d6d54b559a3863cfe0701cac927b3
Java
barrymoe1/practice-set-3
/PS3/src/Account.java
UTF-8
2,130
3.671875
4
[]
no_license
import java.util.Date; public class Account { private int id;//Private int data field named id for the account private double balance; // double data field named balance for the account private double annualInterestRate; //Private double data field named annualInterestRate or account private Date dateCreated; //Stores the date for when the account was created //no arg construtor that creates a default account Account () { id =0; //testing balance=0.0; annualInterestRate= 0.0; } //Constructor which creates the account with the specified id and initial balance Account(int acctId, double acctBalance, double acctAnnualInterestRate) { id = acctId; balance = acctBalance; annualInterestRate = acctAnnualInterestRate; } //Accessor method for id public int getId() { return id; } //Accessor method for balance public double getBalance() { return balance; } //Accessor method for Annual Interest Rate public double getAnnualInterestRate() { return annualInterestRate; } //Mutator method for id public void setId(int acctId) { id = acctId; } //Mutator method for balance public void setBalance(double acctBalance) { balance =acctBalance; } //Mutator method for annualInterestRate public void setannualInterestRate(double acctAnnualInterestRate) { annualInterestRate =acctAnnualInterestRate; } //Accessor method for dateCreated public void setDateCreated(Date acctDateCreated) { dateCreated = acctDateCreated; } //Method named getMonthlyInterestRate() that returns the monthly interest rate double getMonthlyInterestRate() { return annualInterestRate/12; } //Method named withdraw that withdraws a specified amount from the account double withdraw(double withdrawAmount) throws InsufficientFundsException { if (withdrawAmount > balance) { throw new InsufficientFundsException(withdrawAmount); } return balance -= withdrawAmount; } //Method named deposit that deposits a specified amount into the account double deposit(double depositAmount) { return balance += depositAmount; } }
true
bc6a24ab371d3ecfa48ebd5eeb295c585a079ea0
Java
LordSerius/biolaboratory
/biolaboratory-core/src/main/java/hu/bioinformatics/biolaboratory/sequence/BiologicalSequence.java
UTF-8
39,191
2.875
3
[]
no_license
package hu.bioinformatics.biolaboratory.sequence; import hu.bioinformatics.biolaboratory.utils.ArgumentValidator; import hu.bioinformatics.biolaboratory.utils.SequenceUtils; import hu.bioinformatics.biolaboratory.utils.datastructures.CountableOccurrenceMap; import hu.bioinformatics.biolaboratory.utils.datastructures.OccurrenceMap; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.google.common.base.Preconditions.checkArgument; import static hu.bioinformatics.biolaboratory.utils.ArgumentValidator.checkNotBlankString; import static hu.bioinformatics.biolaboratory.utils.ArgumentValidator.checkNotNegativeNumber; import static hu.bioinformatics.biolaboratory.utils.ArgumentValidator.checkNotNullArgument; import static hu.bioinformatics.biolaboratory.utils.ArgumentValidator.checkPositiveNumber; import static hu.bioinformatics.biolaboratory.utils.ArgumentValidator.checkSmallerNumberTo; import static hu.bioinformatics.biolaboratory.utils.ArgumentValidator.checkSmallerOrEqualNumberTo; /** * Represents an immutable abstract biological sequence, which can be a DNA, RNA or a protein. Contains all of the common * operations, what are interpretable for all biological sequences. * * @author Attila Radi */ public abstract class BiologicalSequence<TYPE extends BiologicalSequence, ELEMENT extends SequenceElement> { protected final String sequence; protected final int sequenceLength; private final String name; private ELEMENT[] sequenceAsElements; private CountableOccurrenceMap<ELEMENT> elementOccurrences = null; /** * Validates the name is not null. * * @param name The name to validate. * @return The name, if it is valid. * @throws IllegalArgumentException If name is null. */ protected static String validateName(final String name) { return checkNotNullArgument("Name", name).trim(); } /** * Executes initial validation and format on the input sequence. * * @param sequence The sequence to validate and format. * @return The formatted sequence. * @throws IllegalArgumentException If sequence is blank. */ protected static String formatSequence(final String sequence) { return checkNotBlankString("Biological sequence", sequence).trim().toUpperCase(); } /** * Creates a biological sequence from its elements. The name will be empty. * * @param sequenceElements The elements of the biological sequence in array. */ @SafeVarargs protected BiologicalSequence(final ELEMENT... sequenceElements) { this("", sequenceElements); } /** * Creates a biological sequence from its elements. * * @param name The name of the biological sequence. * @param sequenceElements The elements of the biological sequence in array. */ @SafeVarargs protected BiologicalSequence(final String name, final ELEMENT... sequenceElements) { this(name, Arrays.asList(sequenceElements)); this.sequenceAsElements = sequenceElements.clone(); } /** * Creates a biological sequence from its elements. The name will be empty. * * @param sequenceElementList The elements of the biological sequence in {@link List} collection. */ protected BiologicalSequence(final List<ELEMENT> sequenceElementList) { this("", sequenceElementList); } /** * Creates a biological sequence from its elements. * * @param name The name of the biological sequence. * @param sequenceElementList The elements of the biological sequence in {@link List} collection. */ protected BiologicalSequence(final String name, final List<ELEMENT> sequenceElementList) { this.sequence = new String(createLetterList(sequenceElementList)); this.sequenceLength = sequence.length(); this.name = name; } /** * Creates a biological sequence from {@link String}. The name will be empty. * * @param sequence The biological sequence as {@link String}. */ protected BiologicalSequence(final String sequence) { this("", sequence); } /** * Creates a biological sequence from {@link String}. * * @param name The name of the biological sequence. * @param sequence The biological sequence as {@link String}. */ protected BiologicalSequence(final String name, final String sequence) { this.sequence = sequence; this.sequenceLength = sequence.length(); this.name = name; } /** * Construct a TYPE {@link BiologicalSequence} from name and sequence element array. * * @param sequenceElements The sequence element array (varargs). * @return The TYPE {@link BiologicalSequence} from the sequence. */ @SafeVarargs protected final TYPE construct(final ELEMENT... sequenceElements) { return construct("", sequenceElements); } /** * Construct a TYPE {@link BiologicalSequence} from name and sequence element array. * * @param name The name of the biological sequence. * @param sequenceElements The sequence element array (varargs). * @return The TYPE {@link BiologicalSequence} from the sequence. */ @SafeVarargs protected final TYPE construct(final String name, final ELEMENT... sequenceElements) { return construct(name, Arrays.asList(sequenceElements)); } /** * Construct a TYPE {@link BiologicalSequence} from sequence element {@link List}. * * @param sequenceElementList The sequence element {@link List}. * @return The TYPE {@link BiologicalSequence} from the sequence. */ protected final TYPE construct(final List<ELEMENT> sequenceElementList) { return construct("", sequenceElementList); } /** * Construct a TYPE {@link BiologicalSequence} from name and sequence element {@link List}. * * @param name The name of the biological sequence. * @param sequenceElementList The sequence element {@link List}. * @return The TYPE {@link BiologicalSequence} from the sequence. */ protected final TYPE construct(final String name, final List<ELEMENT> sequenceElementList) { return construct(name, new String(createLetterList(sequenceElementList))); } private char[] createLetterList(final List<ELEMENT> sequenceElementList) { int length = sequenceElementList.size(); char[] letters = new char[length]; int i = 0; for (ELEMENT element : sequenceElementList) { letters[i++] = element.getLetter(); } return letters; } /** * Construct a TYPE {@link BiologicalSequence} from the given sequence {@link String}. * * @param sequence The sequence {@link String}. * @return The TYPE {@link BiologicalSequence} from the sequence. */ protected final TYPE construct(final String sequence) { return construct("", sequence); } /** * Calls the constructor of the inherited class. * * @param name The name of the sequence. * @param sequence The String sequence of the biological sequence. * @return The instance of the inherited class */ protected abstract TYPE construct(final String name, final String sequence); /** * Creates a copy of the {@link BiologicalSequence}. * * @return The copy of the {@link BiologicalSequence}. */ public final TYPE copy() { return construct(name, sequence); } /** * Getter of the biological sequence. * * @return sequence */ public final String getSequence() { return sequence; } /** * Getter of the name. * * @return The name. */ public String getName() { return name; } /** * Returns with a new {@link BiologicalSequence} with the given name. * * @param name The new name. * @return Tha new {@link BiologicalSequence} with the given name. * @throws IllegalArgumentException If name is null. */ public TYPE changeName(final String name) { checkNotNullArgument("Sequence", name); return construct(name.trim(), sequence); } /** * Get the ELEMENT from the target index. * * @param index The index which should smaller than length. * @return The ELEMENT at the target index. * @throws IllegalArgumentException If index is smaller than 0. * @throws IllegalArgumentException If index is greater than sequence length. */ public final ELEMENT getElement(final int index) { checkNotNegativeNumber("Index", index); checkSmallerNumberTo("Index", index, "sequence length", sequenceLength); return loadSequenceAsElements()[index]; } /** * Get the biological sequence as an immutable typed array of its elements. The method realizes a lazy loading method. * * @return An immutable map of typed elements. */ public final ELEMENT[] getSequenceAsElements() { return Arrays.copyOf(loadSequenceAsElements(), sequenceLength); } private synchronized ELEMENT[] loadSequenceAsElements() { if (sequenceAsElements == null) { sequenceAsElements = createEmptyElementArray(); IntStream.range(0, sequenceLength) .forEach(index -> sequenceAsElements[index] = findSequenceElement(sequence.charAt(index))); } return sequenceAsElements; } /** * Creates an ELEMENT array with the appropriate size of the available {@link SequenceElement}s. * * @return An array with the appropriate size of {@link SequenceElement}s. */ protected abstract ELEMENT[] createEmptyElementArray(); /** * Getter of the biological sequence length. * * @return sequenceLength */ public final int getSequenceLength() { return sequenceLength; } /** * Immutable getter of the element occurrences. It calculates the occurrences at the first call. * * @return The element occurrences. */ public final CountableOccurrenceMap<ELEMENT> getElementOccurrences() { return collectSequenceElementOccurrences().copy(); } /** * Get the ratio of the target element according to the full sequence. * * @param element The desirable element. * @return The ratio of the target element. * @throws IllegalArgumentException If element is null. */ public final double getElementRatio(final ELEMENT element) { return collectSequenceElementOccurrences().occurrenceRatio(element); } /** * Get the ratio of the target elements according to the full sequence. * * @param elements The desirable elements. * @return The ratio of the target elements. * @throws IllegalArgumentException If elements are null. */ @SafeVarargs public final double getElementsRatio(final ELEMENT... elements) { return collectSequenceElementOccurrences().accumulatedOccurrenceRatio(elements); } /** * Get the ratio of the target elements according to the full sequence. * * @param elementSet The desirable elements. * @return The ratio of the target elements. * @throws IllegalArgumentException If elementSet contains null value. */ public final double getElementsRatio(final Set<ELEMENT> elementSet) { return collectSequenceElementOccurrences().accumulatedOccurrenceRatio(elementSet); } /** * Get the number of the target element. * * @param element The desired element. * @return The element number in the {@link BiologicalSequence} * @throws IllegalArgumentException If element is null. */ public final int getElementNumber(final ELEMENT element) { return collectSequenceElementOccurrences().getOccurrence(element); } /** * Get the number of the target elements. * * @param elements The desired elements. * @return The sum of the target elements in the {@link BiologicalSequence}. * @throws IllegalArgumentException If elements are null. */ @SafeVarargs public final int getElementsNumber(final ELEMENT... elements) { return collectSequenceElementOccurrences().sumOccurrences(elements); } /** * Get the number of the target elements. * * @param elementSet The desired elements. * @return The sum of the target elements in the {@link BiologicalSequence}. * @throws IllegalArgumentException If elementSet contains null value. */ public final int getElementsNumber(final Set<ELEMENT> elementSet) { return collectSequenceElementOccurrences().sumOccurrences(elementSet); } /** * Create a {@link CountableOccurrenceMap} about the sequence elements. * * @return A {@link CountableOccurrenceMap} about the occurrences. */ protected final synchronized CountableOccurrenceMap<ELEMENT> collectSequenceElementOccurrences() { if (elementOccurrences == null) { elementOccurrences = CountableOccurrenceMap.build(getElementSet()); ELEMENT[] sequenceAsElements = loadSequenceAsElements(); IntStream.range(0, sequenceLength) .forEach(index -> elementOccurrences.increase(sequenceAsElements[index])); } return elementOccurrences; } /** * Return the possible {@link SequenceElement}s for this {@link BiologicalSequence} type. * * @return All possible {@link SequenceElement} for this {@link BiologicalSequence}. */ protected abstract ELEMENT[] getElementArray(); /** * Return the possible {@link SequenceElement}s for this {@link BiologicalSequence} type in a {@link Set}. * * @return All possible {@link SequenceElement} for this {@link BiologicalSequence} in a {@link Set}. */ protected abstract Set<ELEMENT> getElementSet(); /** * Return with the {@link SequenceElement} representation of the given letter. * * @param sequenceElementLetter A sequence element letter. * @return The {@link SequenceElement} representation of the given letter. */ protected abstract ELEMENT findSequenceElement(final char sequenceElementLetter); @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || !obj.getClass().equals(getClass())) return false; BiologicalSequence rightHand = (BiologicalSequence) obj; return sequenceLength == rightHand.sequenceLength && sequence.equals(rightHand.sequence); } @Override public int hashCode() { return sequence.hashCode(); } @Override public String toString() { return getBiologicalSequenceTypeName() + " = {" + sequence + "}"; } /** * Get the name of the sequence type (e.g. DNA). * * @return The name of the sequence type. */ protected abstract String getBiologicalSequenceTypeName(); /** * Append the given biological sequence to the end. * * @param otherBiologicalSequence The biological sequence to append. * @return A new {@link BiologicalSequence} which stands from the sequence of the original {@link BiologicalSequence} * and the sequence of the other {@link BiologicalSequence}. * @throws IllegalArgumentException If otherBiologicalSequence is null. * @throws IllegalArgumentException If otherBiological sequence type differs than the objects type. */ public final TYPE append(final TYPE otherBiologicalSequence) { return construct(sequence + validateType(otherBiologicalSequence).getSequence()); } /** * Append the given biological sequence element to the end. * * @param element The element to append. * @return A new {@link BiologicalSequence} which stands from the sequence of the original {@link BiologicalSequence} * and the appended element. * @throws IllegalArgumentException If element is null. */ public final TYPE append(final ELEMENT element) { return construct(sequence + validateElement(element).getLetter()); } private ELEMENT validateElement(final ELEMENT element) { checkNotNullArgument("Element", element); checkArgument(getElementSet().contains(element), "Element has invalid type"); return element; } /** * Cuts a {@link BiologicalSequence} part from the start position to the end of the {@link BiologicalSequence}'s length. * * @param startPosition The beginning element position in the {@link BiologicalSequence} inclusive. * @return The {@link BiologicalSequence} part from start position (inclusive) to the end. * @throws IllegalArgumentException If startPosition is negative number. * @throws IllegalArgumentException If startPosition is bigger or equals than sequence length. */ public final TYPE cut(final int startPosition) { return cut(startPosition, sequenceLength); } /** * Cuts a {@link BiologicalSequence} part about the given index and return it to the caller. The cut operation includes the start * position, but excludes the end position. * * @param startPosition The beginning element position in the {@link BiologicalSequence} inclusive. * @param endPosition The end element position in the {@link BiologicalSequence} exclusive. * @return The {@link BiologicalSequence} part from start position (inclusive) to end position (exclusive). * @throws IllegalArgumentException If startPosition is negative number. * @throws IllegalArgumentException If endPosition is bigger or equals than sequence length. * @throws IllegalArgumentException If startPosition is greater or equal than endPosition. */ public final TYPE cut(final int startPosition, final int endPosition) { checkNotNegativeNumber("Start position", startPosition); checkSmallerOrEqualNumberTo("End position", endPosition, "sequence length", sequenceLength); checkSmallerNumberTo("Start position", startPosition, "end position", endPosition); return construct(sequence.substring(startPosition, endPosition)); } /** * Count the occurrences of the given pattern inside the {@link BiologicalSequence} sequence. * The sequence parts can overlap. * * @see BiologicalSequence#findPatternsWithMismatch(BiologicalSequence, int) * @param pattern The pattern {@link BiologicalSequence}. * @return The number of found patterns. * @throws IllegalArgumentException If pattern is null. */ public int patternCount(final TYPE pattern) { return patternMatching(pattern).size(); } /** * Count the occurrences of the given pattern inside the {@link BiologicalSequence} sequence with maximum * of <i>d</i> mismatch. * The sequence parts can overlap. * * @see BiologicalSequence#findPatternsWithMismatch(BiologicalSequence, int) * @param pattern The pattern {@link BiologicalSequence}. * @param d The maximum permitted mismatch. * @return The number of found patterns. * @throws IllegalArgumentException If pattern is null. * @throws IllegalArgumentException If <i>d</i> is negative number. */ public int patternCountWithMismatches(final TYPE pattern, final int d) { return patternMatchingWithMismatches(pattern, d).size(); } /** * Return the beginning index of all occurrences of the given pattern inside the {@link BiologicalSequence} * sequence. The sequence parts can overlap. * * @see BiologicalSequence#findPatternsWithMismatch(BiologicalSequence, int) * @param pattern The pattern {@link BiologicalSequence}. * @return The beginning indexes of found patterns. * @throws IllegalArgumentException If pattern is null. */ public List<Integer> patternMatching(final TYPE pattern) { return patternMatchingWithMismatches(pattern, 0); } /** * Return the beginning index of all occurrences of the given pattern inside the {@link BiologicalSequence} * sequence with maximum of <i>d</i> mismatch. The sequence parts can overlap. * * @see BiologicalSequence#findPatternsWithMismatch(BiologicalSequence, int) * @param pattern he pattern {@link BiologicalSequence}. * @param d The maximum permitted mismatch. * @return The position of found patterns. * @throws IllegalArgumentException If pattern is null. * @throws IllegalArgumentException If <i>d</i> is negative number. */ public List<Integer> patternMatchingWithMismatches(final TYPE pattern, final int d) { checkNotNegativeNumber("Maximum different value (d)", d); return findPatternsWithMismatch(validatePattern(pattern), d); } private TYPE validatePattern(final TYPE pattern) { validateType(pattern); checkSmallerOrEqualNumberTo("Pattern length", pattern.sequenceLength, "sequence length", sequenceLength); return pattern; } /** * Returns with the smallest mismatch number of pattern and subsequences. * * @param pattern A pattern for compare against the subsequences. * @return The minimum mismatches between pattern and the subsequences. * @throws IllegalArgumentException If pattern is null. */ public int findMinimumMismatchSubSequenceNumber(final TYPE pattern) { validatePattern(pattern); final int patternLength = pattern.sequenceLength; return IntStream.rangeClosed(0, sequenceLength - patternLength) .parallel() .map(index -> SequenceUtils.hammingDistance( sequence.substring(index, index + patternLength), pattern.sequence)) .min() .orElse(Integer.MAX_VALUE); } /** * The work of the algorithm: * <ol> * <li>Cut a template sequence from the beginning of the biological sequence which length equals to * the pattern's length.</li> * <li>Compares the template with the pattern.</li> * <li>If the pattern against the template has at most <i>d</i> mismatches then add the * first index of the template inside the biological sequence to the return values.</li> * <li>The next template will be constructed from the second element to the end of * the template concatenated with the next character of the biological sequence after this template.</li> * <li>Returns to the 2. point until the loop variable reaches the difference of the * biological sequence length and the pattern length.</li> * </ol> * * @param pattern The pattern to find. * @return The first indices of the occurrences inside the {@link TYPE} sequence. * @throws IllegalArgumentException If pattern is null. * @throws IllegalArgumentException If <i>d</i> is negative number. */ private List<Integer> findPatternsWithMismatch(final TYPE pattern, final int d) { int lengthDiff = sequenceLength - pattern.sequenceLength; return IntStream.rangeClosed(0, lengthDiff) .parallel() .filter(index -> SequenceUtils.hammingDistanceMismatchComparator( sequence.substring(index, index + pattern.sequenceLength), pattern.sequence, d) != SequenceUtils.GREATER) .sorted() .boxed() .collect(Collectors.toList()); } /** * Get the most frequent <i>k</i> occurrences in the biological sequence. * * @param k The findable <i>k</i> long sequences. * @return The most frequent <i>k</i> long occurrences. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. */ public Set<TYPE> findMostFrequentSubSequences(final int k) { return findMostFrequentMismatchSubSequences(k, 0); } /** * Get the most frequent <i>k</i> occurrences which has at most <i>d</i> different * elements in the biological sequence. * * @param k The findable <i>k</i> long sequences. * @param d The maximum permitted different elements. * @return The most frequent <i>k</i> long occurrences with at most <i>d</i> mismatches. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. * @throws IllegalArgumentException If <i>d</i> is negative number. */ public Set<TYPE> findMostFrequentMismatchSubSequences(final int k, final int d) { return getMismatchOccurrenceMap(k, d).filterMostFrequentOccurrences(); } /** * Get all <i>k</i> long subsequences of the DNA. * * @param k The size of the subsequnces. * @return All <i>k</i> long subsequences in a {@link Set}. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. */ public Set<TYPE> getSubSequences(final int k) { return getMismatchSubSequences(k, 0); } /** * Get all <i>k</i> long subsequences with at most <i>d</i> mismatches of the DNA. * * @param k The size of the subsequnces. * @param d The maximum permitted different elements. * @return All <i>k</i> long subsequences with <i>d</i> mismatch in a {@link Set}. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. * @throws IllegalArgumentException If <i>d</i> is negative number. */ public Set<TYPE> getMismatchSubSequences(final int k, final int d) { return findFrequentMismatchSubSequences(k, d, 1); } /** * Get all <i>k</i> long sequences which are greater or equals than <i>t</i> in the * DNA sequence. * * @param k The findable <i>k</i> long sequences. * @param t The threshold of the occurrences of the <i>k</i> long sequences in the DNA. * @return All <i>k</i> long sequences which occurrences are greater or equals than <i>t</i>. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. * @throws IllegalArgumentException If <i>t</i> is smaller than 1. */ public Set<TYPE> findFrequentSubSequences(final int k, final int t) { return findFrequentMismatchSubSequences(k, 0, t); } /** * Get all <i>k</i> long sequences which has at most <i>d</i> different * elements and are greater or equals than <i>t</i> in the DNA sequence. * * @param k The findable <i>k</i> long sequences. * @param d The maximum permitted different elements. * @param t The threshold of the occurrences of the <i>k</i> long sequences in the DNA. * @return All <i>k</i> long sequences at most <i>d</i> mismatches which occurrences * are greater or equals than <i>t</i>. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. * @throws IllegalArgumentException If <i>d</i> is negative number. * @throws IllegalArgumentException If <i>t</i> is smaller than 1. */ public Set<TYPE> findFrequentMismatchSubSequences(final int k, final int d, final int t) { return getMismatchOccurrenceMap(k, d).filterGreaterOrEqualsOccurrences(t); } /** * This method finds the burst frequency of the DNA parts. The <i>L</i> parameter defines a * window where the method finds the occurrences of the <i>k</i> long DNA parts. * If the occurrence of a particular DNA part in this <i>L</i> window is greater or equals * than <i>t</i> the DNA part appears in the return set. * <p> * The work of the algorithm: * <ol> * <li>Picks the window from the first element to <i>L</i> in the DNA.</li> * <li>Determines the first window part from the first position to the <i>k</i> position.</li> * <li>Determines the last window part from <i>L</i> - <i>k</i> to <i>L</i>.</li> * <li>Calculates the occurrence map of the window.</li> * <li>Adds all elements from the occurrence map to the return set which occurrence is * greater or equals than <i>t</i>.</li> * <li>Decrease or remove the first window part from the occurrence list.</li> * <li>Shift the first window part with one position, the next first window part will be * from the second element from the first window part concatenated with the next element * of the DNA sequence. * <li>Shift the last window part with one position, the next first window part will be * from the second element from the last window part concatenated with the next element * of the DNA sequence.</li> * <li>Increase or put the last window part inside the occurrence map.</li> * <li>Add the last window part to the return set if it's occurrence is greater or * equal than <i>t</i></li> * <li>Return to the 6. point until the window position reaches the difference of * the DNA sequence and <i>L</i>.</li> * </ol> * * @param k The findable <i>k</i> long sequences inside the DNA sequence. * @param L The window size which determines the search area. * @param t The threshold of the occurrences. * @return A {@link Set} of <i>k</i> long sequence parts which occurrences are greater * or equal than <i>t</i> in <i>L</i> clumps. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than L. * @throws IllegalArgumentException If <i>L</i> is smaller than 1. * @throws IllegalArgumentException If <i>L</i> is bigger or equal than sequence length. * @throws IllegalArgumentException If <i>t</i> is smaller than 1. */ @SuppressWarnings("unchecked") public Set<TYPE> findPatternsInClumps(final int k, final int L, final int t) { checkPositiveNumber("Clump length (L)", L); checkSmallerOrEqualNumberTo("Clump length (L)", L, "sequence length", sequenceLength); checkPositiveNumber("Findable subsequence length (k)", k); checkSmallerOrEqualNumberTo("Findable subsequence length (k)", k, "clump length", L); int lengthDiff = sequenceLength - L; TYPE window = construct(sequence.substring(0, L)); String firstWindowPart = window.sequence.substring(0, k); String lastWindowPart = window.sequence.substring(L - k, L); OccurrenceMap<TYPE> occurrenceMap = window.getOccurrenceMap(k); Set<TYPE> patternSet = new HashSet<>(); patternSet.addAll(occurrenceMap.filterGreaterOrEqualsOccurrences(t)); for(int i = 0; i < lengthDiff; i++) { occurrenceMap.decrease(construct(firstWindowPart)); firstWindowPart = firstWindowPart.substring(1) + sequence.charAt(i + k); lastWindowPart = lastWindowPart.substring(1) + sequence.charAt(i + L); TYPE lastWindowDna = construct(lastWindowPart); if (occurrenceMap.increase(lastWindowDna) >= t) { patternSet.add(lastWindowDna); } } return patternSet; } /** * Get the <i>k</i> long subsequences and their occurrence number in {@link OccurrenceMap}. * * @param k The parameter for the <i>k</i> long subsequences. * @return An {@link OccurrenceMap} with the subsequences. */ protected final OccurrenceMap<TYPE> getOccurrenceMap(final int k) { return getMismatchOccurrenceMap(k, 0); } /** * The method returns with the occurrence of the <i>k</i> long patterns which has at most * <i>d</i> mismatches than an existing pattern in the sequence. * <p> * The work of the algorithm: * <ol> * <li>Generates the maximum <i>d</i> mismatches for the first <i>k</i> long subsequence * in a mismatch map.</li> * <li>A sliding window separates the mismatch set's elements according to the first * disappearing character is equals with the <i>i</i>. element in the sequence. * <ul> * <li>If the first element of the pattern equals with the <i>i</i>. element of * the sequence, the Hamming-distance doesn't change, the new pattern will * appear in the next run (new mismatch set).</li> * <li>If the first element of the pattern is not equal than the <i>i</i>. element of * the sequence, the Hamming-distance decreases, so the algorithm will have to * generate mismatch instances from the new pattern (generator set).</li> * </ul> * The new element will be the pattern from the 1. position of the end, concatenated * with the <i>i</i>. element of the sequence. * </li> * <li>If <i>d</i> greater than 0 add the subsequence from i + 1. to i + k. to the * generator set.</li> * <li>Generates the next mismatch pattern from the generator set. The algorithm * iterates over every generator element and substitute every element at the last * position in the pattern.</li> * <li>Add these 4 element to the new mismatch set.</li> * <li>Continue at 4. point until the last generator element.</li> * <li>The new mismatch set will be the next mismatch map in the next run.</li> * <li>Continue from 2. point until the sliding widow reaches the end of the sequence.</li> * </ol> * * @param k The <i>k</i> long subsequences. * @param d The maximum permitted different elements. * @return The occurrence map of the sequence elements and their mismatches. * @throws IllegalArgumentException If <i>k</i> is smaller than 1. * @throws IllegalArgumentException If <i>k</i> is bigger than sequence length. * @throws IllegalArgumentException If <i>d</i> is negative number. */ @SuppressWarnings("unchecked") protected final OccurrenceMap<TYPE> getMismatchOccurrenceMap(final int k, final int d) { checkPositiveNumber("Findable subsequence (k)", k); checkSmallerOrEqualNumberTo("Findable subsequence (k)", k, "sequence length", sequenceLength); OccurrenceMap<TYPE> occurrenceMap = OccurrenceMap.build(); int lengthDiff = sequenceLength - k; Set<TYPE> mismatchSet = construct(sequence.substring(0, k)) .generateMismatches(d); for (int i = 0; i < lengthDiff; i++) { Set<TYPE> nextMismatchesSet = new HashSet<TYPE>(); Set<TYPE> generatedMismatchesSet = new HashSet<TYPE>(); for (TYPE mismatchPattern : mismatchSet) { occurrenceMap.increase(mismatchPattern); TYPE nextMismatchPattern = construct(mismatchPattern.sequence.substring(1) + sequence.charAt(i + k)); if (sequence.charAt(i) == mismatchPattern.sequence.charAt(0)) nextMismatchesSet.add(nextMismatchPattern); else generatedMismatchesSet.add(nextMismatchPattern); } if (d > 0) { generatedMismatchesSet.add(construct(sequence.substring(i + 1, i + k) + sequence.charAt(i + k))); } for (TYPE generatedMismatchPattern : generatedMismatchesSet) { char[] charArray = generatedMismatchPattern.sequence.toCharArray(); ELEMENT[] elementArray = getElementArray(); for (ELEMENT element : elementArray) { charArray[k - 1] = element.getLetter(); nextMismatchesSet.add(construct(new String(charArray))); } } mismatchSet = nextMismatchesSet; } mismatchSet.forEach(occurrenceMap::increase); return occurrenceMap; } /** * Generate {@link BiologicalSequence}s from this sequence which have at most <i>d</i> different * elements. * * @param d The maximum permitted different elements. * @return All elements which are different at most <i>d</i> elements. * @throws IllegalArgumentException If <i>d</i> is negative number. */ public Set<TYPE> generateMismatches(final int d) { checkNotNegativeNumber("Maximum mismatch number (d)", d); Map<String, Integer> mismatchMap = new HashMap<>(); ELEMENT[] elementArray = getElementArray(); for (ELEMENT element : elementArray) { char elementLetter = element.getLetter(); if (sequence.charAt(0) == elementLetter) { mismatchMap.put(Character.toString(elementLetter), 0); } else if (d > 0) { mismatchMap.put(Character.toString(elementLetter), 1); } } for (int i = 1; i < sequenceLength; i++) { Map<String, Integer> newMismatchMap = new HashMap<>(); for (String prefix : mismatchMap.keySet()){ int mismatchCount = mismatchMap.get(prefix); for (ELEMENT element : elementArray) { char elementLetter = element.getLetter(); if (sequence.charAt(i) == elementLetter) { newMismatchMap.put(prefix + elementLetter, mismatchCount); } else if (mismatchCount < d) { newMismatchMap.put(prefix + elementLetter, mismatchCount + 1); } } } mismatchMap = newMismatchMap; } return mismatchMap.keySet().stream().map(this::construct).collect(Collectors.toSet()); } /** * Compares the {@link BiologicalSequence}'s sequence with the other {@link BiologicalSequence}'s sequence and calculates * the number of the different elements at the same sequence position. * * @param otherBiologicalSequence The other {@link BiologicalSequence} compare with. * @return The number of the different elements at the same positions. * @throws IllegalArgumentException If otherBiologicalSequence has different length. */ public int getMismatchNumber(final TYPE otherBiologicalSequence) { validateType(otherBiologicalSequence); return SequenceUtils.hammingDistance(sequence, otherBiologicalSequence.sequence); } private TYPE validateType(final TYPE otherBiologicalSequence) { return ArgumentValidator.checkSameTypeTo("Other biological sequence", otherBiologicalSequence, getBiologicalSequenceTypeName(), this); } }
true
6797dd8321fa707cedd1940708998d8f6bc14d2d
Java
Syquel/reactorstate-maven
/reactorstate-maven-common/src/test/java/de/syquel/maven/reactorstate/common/SavedReactorStateManagerTest.java
UTF-8
7,647
2.046875
2
[ "Apache-2.0" ]
permissive
package de.syquel.maven.reactorstate.common; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import java.io.File; import java.util.Arrays; import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.project.ProjectBuilder; import org.hamcrest.MatcherAssert; import org.junit.Rule; import org.junit.Test; import de.syquel.maven.reactorstate.common.data.MavenProjectState; import io.takari.maven.testing.TestMavenRuntime; import io.takari.maven.testing.TestResources; public class SavedReactorStateManagerTest { @Rule public final TestResources resources = new TestResources(); @Rule public final TestMavenRuntime testMavenRuntime = new TestMavenRuntime(); @Test public void testRestoreTopLevelState() throws Exception { // given final File baseDir = resources.getBasedir("maven-project-stub"); final MavenProject topLevelProject = testMavenRuntime.readMavenProject(baseDir); final MavenProject module1Project = testMavenRuntime.readMavenProject(new File(baseDir, "module1")); final MavenProject module2Project = testMavenRuntime.readMavenProject(new File(baseDir, "module2")); final MavenProject module3Project = testMavenRuntime.readMavenProject(new File(module1Project.getBasedir(), "module3")); final MavenSession session = testMavenRuntime.newMavenSession(topLevelProject); session.setProjects(Arrays.asList(topLevelProject, module1Project, module2Project, module3Project)); final ProjectBuilder projectBuilder = testMavenRuntime.lookup(ProjectBuilder.class); final MavenProjectHelper projectHelper = testMavenRuntime.lookup(MavenProjectHelper.class); // when final SavedReactorStateManager reactorStateManager = SavedReactorStateManager.create(session, projectBuilder); MatcherAssert.assertThat( "Exactly four saved project states are present", reactorStateManager.getProjectStates().size(), is(4) ); final MavenProjectState topLevelProjectState = reactorStateManager.getProjectState(topLevelProject); MatcherAssert.assertThat("Project POM is for top-level project", topLevelProjectState.getPom().getFile(), is(topLevelProject.getFile())); MatcherAssert.assertThat( "Main artifact is the project POM", topLevelProjectState.getMainArtifactState().getArtifact(), is(topLevelProjectState.getPom()) ); MatcherAssert.assertThat("Top-level artifact is not resolved", topLevelProject.getArtifact().getFile(), nullValue(File.class)); MatcherAssert.assertThat("Top-level has no artifacts attached", topLevelProjectState.getAttachedArtifactStates().size(), is(0)); MatcherAssert.assertThat("Sub-module1 artifact is not resolved", module1Project.getArtifact().getFile(), nullValue(File.class)); MatcherAssert.assertThat("Sub-module2 artifact is not resolved", module2Project.getArtifact().getFile(), nullValue(File.class)); MatcherAssert.assertThat("Sub-module2 has no artifacts attached", module2Project.getAttachedArtifacts().size(), is(0)); reactorStateManager.restoreProjectStates(session, projectHelper); // then MatcherAssert.assertThat("Top-level artifact is resolved", topLevelProject.getArtifact().getFile(), is(topLevelProject.getFile())); final Artifact module3MainArtifact = module3Project.getArtifact(); MatcherAssert.assertThat( "Sub-module3 artifact is resolved", module3MainArtifact.getFile(), is(module3Project.getBasedir().toPath().resolve("target/reactorstate-maven-extension-stub-module3-1.0-SNAPSHOT.jar").toFile()) ); MatcherAssert.assertThat( "Sub-module3 artifact is of type 'jar'", module3MainArtifact.getType(), is("jar") ); MatcherAssert.assertThat( "Sub-module3 artifact language is 'java'", module3MainArtifact.getArtifactHandler().getLanguage(), is("java") ); MatcherAssert.assertThat( "Sub-module2 artifact is resolved", module2Project.getArtifact().getFile(), is(module2Project.getBasedir().toPath().resolve("target/reactorstate-maven-extension-stub-module2-1.0-SNAPSHOT.jar").toFile()) ); final Artifact module2AttachedArtifact = module2Project.getAttachedArtifacts().get(0); MatcherAssert.assertThat( "Sub-module2 has javadoc artifact attached", module2AttachedArtifact.getId(), is("de.syquel.maven.reactorstate:reactorstate-maven-extension-stub-module2:jar:javadoc:1.0-SNAPSHOT") ); MatcherAssert.assertThat( "Sub-module2 has javadoc artifact file attached", module2AttachedArtifact.getFile(), is(module2Project.getBasedir().toPath().resolve("target/reactorstate-maven-extension-stub-module2-1.0-SNAPSHOT-javadoc.jar").toFile()) ); } @Test public void testRestoreSubModuleState() throws Exception { // given final File baseDir = resources.getBasedir("maven-project-stub"); final MavenProject topLevelProject = testMavenRuntime.readMavenProject(baseDir); final MavenProject module1Project = testMavenRuntime.readMavenProject(new File(baseDir, "module1")); final MavenProject module2Project = testMavenRuntime.readMavenProject(new File(baseDir, "module2")); final MavenProject module3Project = testMavenRuntime.readMavenProject(new File(module1Project.getBasedir(), "module3")); final MavenSession session = testMavenRuntime.newMavenSession(module2Project); final ProjectBuilder projectBuilder = testMavenRuntime.lookup(ProjectBuilder.class); final MavenProjectHelper projectHelper = testMavenRuntime.lookup(MavenProjectHelper.class); // when final SavedReactorStateManager reactorStateManager = SavedReactorStateManager.create(session, projectBuilder); MatcherAssert.assertThat( "Top-level project state is present", reactorStateManager.getProjectState(topLevelProject), notNullValue(MavenProjectState.class) ); MatcherAssert.assertThat( "Sub-module1 project state is present", reactorStateManager.getProjectState(module1Project), notNullValue(MavenProjectState.class) ); MatcherAssert.assertThat( "Sub-module2 project state is present", reactorStateManager.getProjectState(module2Project), notNullValue(MavenProjectState.class) ); MatcherAssert.assertThat( "Sub-module3 project state is present", reactorStateManager.getProjectState(module3Project), notNullValue(MavenProjectState.class) ); reactorStateManager.restoreProjectStates(session, projectHelper); // then final List<MavenProject> sessionProjects = session.getProjects(); MatcherAssert.assertThat("Maven session contains only one project", sessionProjects.size(), is(1)); MatcherAssert.assertThat("Maven session contains only Sub-module2", sessionProjects.get(0), is(module2Project)); MatcherAssert.assertThat( "Sub-module2 artifact is resolved", module2Project.getArtifact().getFile(), is(module2Project.getBasedir().toPath().resolve("target/reactorstate-maven-extension-stub-module2-1.0-SNAPSHOT.jar").toFile()) ); final Artifact module2AttachedArtifact = module2Project.getAttachedArtifacts().get(0); MatcherAssert.assertThat( "Sub-module2 has javadoc artifact attached", module2AttachedArtifact.getId(), is("de.syquel.maven.reactorstate:reactorstate-maven-extension-stub-module2:jar:javadoc:1.0-SNAPSHOT") ); MatcherAssert.assertThat( "Sub-module2 has javadoc artifact file attached", module2AttachedArtifact.getFile(), is(module2Project.getBasedir().toPath().resolve("target/reactorstate-maven-extension-stub-module2-1.0-SNAPSHOT-javadoc.jar").toFile()) ); } }
true
e524306273b38caebbf6f89e159a460ec68ae64d
Java
enzomotta/etcd4j
/src/main/java/com/enzomotta/etcd4j/EtcdResponse.java
UTF-8
495
1.867188
2
[ "Apache-2.0" ]
permissive
package com.enzomotta.etcd4j; public class EtcdResponse { // General values public String action; public String key; public String value; public long index; // For set operations public String prevValue; public boolean newKey; // For TTL keys public String expiration; public Integer ttl; // For listings public boolean dir; // For errors public Integer errorCode; public String message; public String cause; public boolean isError() { return errorCode != null; } }
true
9315d5a6cd06c29ef29e0275e097dc74c0135707
Java
girispeaks/MyRepo
/workspace/Sample/src/seleniumPractice/FlipKart.java
UTF-8
961
2.3125
2
[]
no_license
package seleniumPractice; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class FlipKart { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.gecko.driver", "C://Users//gramakrishn6//Desktop//Jars//geckodriver-v0.17.0-win64//geckodriver.exe"); WebDriver driver=new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); driver.navigate().to("https://www.flipkart.com/"); List<WebElement> items=driver.findElements(By.xpath("//div[@class='col gu12']/div[starts-with(@class,'_1GRhLX')]/div[1]/div/h2")); for(int i=0;i<items.size();i++) System.out.println(items.get(i).getText()); } }
true
065239138ead0dcd0501602a27a8601237af414f
Java
awesome-urch/Nistores
/app/src/main/java/com/nistores/awesomeurch/nistores/folders/helpers/InitiatedOrder.java
UTF-8
641
2.234375
2
[]
no_license
package com.nistores.awesomeurch.nistores.folders.helpers; public class InitiatedOrder { private String id; private String order_id; private String initiated_date; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getOrder_id() { return order_id; } public void setOrder_id(String order_id) { this.order_id = order_id; } public String getInitiated_date() { return initiated_date; } public void setInitiated_date(String initiated_date) { this.initiated_date = initiated_date; } }
true
1fb85724a250e383b5a8fe764f8796dbd0e1ebda
Java
TscholponChicago/java-project
/src/array/Search.java
UTF-8
791
3.609375
4
[]
no_license
package array; import java.util.Arrays; public class Search { public static void main(String[] args) { //TASK declare array and store elements{23,-3,55,67,-9} // print out index of -3 if it exists in the array // if it does not exists print zero int elements[] = {34, 55, 67, -3, 90}; for(int a = 0; a < elements.length; a++) { if(elements[a] == 55) { System.out.println(a); break; } } //Arrays.sort(elements);// if we dont put this method it will not find what we are looking for/ //it will give just unpredictible result System.out.println(Arrays.toString(elements)); int result = Arrays.binarySearch(elements, 55);// binaySearch is best way to find specific element, System.out.println(result); // -(1) - 1 ==> -2 } }
true
3a1901ee83df2756606d45d28745019ea62d7f54
Java
Amine-er/citt-wellmart
/wellmart-app/src/main/java/com/citt/wellmart/services/CategoryService.java
UTF-8
650
2.140625
2
[]
no_license
package com.citt.wellmart.services; import com.citt.wellmart.entities.Category; import com.citt.wellmart.repositories.CategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CategoryService { @Autowired private CategoryRepository categoryRepository; public Category saveCategory(Category city){ return categoryRepository.save(city);} public List<Category> getAllCategory(){ return categoryRepository.findAll(); } public void deleteCategoryById(Long id){ categoryRepository.deleteById(id); } }
true
0b5d344f404b301afaa1aed3d03f88823fa993c4
Java
2103Java/Curriculum-Resources
/Week6/BasicPlanetProject/src/main/java/com/revature/MainDriverForORM.java
UTF-8
1,006
2.40625
2
[]
no_license
package com.revature; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.revature.dao.PlanetDao; import com.revature.models.Planet; public class MainDriverForORM { public static ApplicationContext appContext = new ClassPathXmlApplicationContext("beans-annotations.xml"); public static void main(String[] args) { PlanetDao pDao = appContext.getBean("PlanetDao",PlanetDao.class); // PlanetDao pDao = appContext.getBean("PlanetDaoBetterBean",PlanetDao.class); Planet p = new Planet(0,"Earth 1", 0); Planet p1 = new Planet(0,"Earth 2", 0); Planet p2 = new Planet(0,"Earth 3", 0); Planet p3 = new Planet(0,"Earth 4", 0); Planet p4 = new Planet(0,"Earth 5", 0); Planet p5 = new Planet(0,"Mars", 0); pDao.insertPlanet(p1); pDao.insertPlanet(p2); pDao.insertPlanet(p3); pDao.insertPlanet(p4); pDao.insertPlanet(p5); System.out.println(pDao.selectAllPlanet()); } }
true
1d043e3ac2dabd934e2987ca5fe3bf0a59175fce
Java
NataVK/test
/src/main/java/com/shop/backend/repository/ItemRepository.java
UTF-8
534
1.664063
2
[]
no_license
package com.shop.backend.repository; import com.shop.backend.domain.Item; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import javax.persistence.OrderBy; import java.util.List; /** * Created with IntelliJ IDEA. * User: bambastik * Date: 2/20/14 * Time: 10:34 AM * To change this template use File | Settings | File Templates. */ public interface ItemRepository extends JpaRepository<Item, Long> { }
true
b1f18a032ea42364a6b1ac4531f01103b6279ede
Java
fuquanming/fcc
/fcc-web-manage/src/main/java/com/fcc/web/sys/service/impl/RoleServiceImpl.java
UTF-8
7,293
2.0625
2
[]
no_license
package com.fcc.web.sys.service.impl; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.fcc.commons.core.service.BaseService; import com.fcc.commons.data.ListPage; import com.fcc.commons.execption.RefusedException; import com.fcc.web.sys.dao.RoleDao; import com.fcc.web.sys.dao.RoleModuleRightDao; import com.fcc.web.sys.model.Operate; import com.fcc.web.sys.model.Role; import com.fcc.web.sys.model.RoleModuleRight; import com.fcc.web.sys.service.CacheService; import com.fcc.web.sys.service.RoleModuleRightService; import com.fcc.web.sys.service.RoleService; /** * <p>Description:系统管理 角色</p> * <p>Copyright:Copyright (c) 2009 </p> * @author 傅泉明 * @version v1.0 */ @Service public class RoleServiceImpl implements RoleService { @Autowired private BaseService baseService; @Resource private RoleDao roleDao; @Resource private RoleModuleRightDao roleModuleRightDao; @Resource private RoleModuleRightService roleModuleRightService; @Resource private CacheService cacheService; /** * @see com.fcc.web.sys.service.RoleService#add(com.fcc.web.sys.model.Role) **/ @Override @Transactional(rollbackFor = Exception.class) public void add(Role role) { baseService.add(role); } /** * @see com.fcc.web.sys.service.RoleService#add(com.fcc.web.sys.model.Role, java.lang.String[]) **/ @Override @Transactional(rollbackFor = Exception.class) public void add(Role role, String[] moduleRight) throws RefusedException { baseService.add(role); roleModuleRightService.addRight(role.getRoleId(), moduleRight); } /** * @see com.fcc.web.sys.service.RoleService#edit(com.fcc.web.sys.model.Role, java.lang.String[]) **/ @Override @Transactional(rollbackFor = Exception.class) public void edit(Role role, String[] moduleRight) throws RefusedException { baseService.edit(role); roleModuleRightService.addRight(role.getRoleId(), moduleRight); } /** * @see com.fcc.web.sys.service.RoleService#delete(java.lang.String[]) **/ @Override @Transactional(rollbackFor = Exception.class) public void delete(String[] roleIds) throws Exception { if (roleIds != null && roleIds.length > 0) { roleModuleRightDao.deleteByRoleIds(roleIds); roleDao.delete(roleIds); roleDao.deleteRoleByRoleId(roleIds); } } /** * @see com.fcc.web.sys.service.RoleService#getRole(java.lang.String) **/ @Override @Transactional(readOnly = true) public Role getRole(String roleId) { Role role = null; if (Role.ROOT.getRoleId().equals(roleId)) { role = Role.ROOT; } else { role = (Role) baseService.get(Role.class, roleId); } return role; } /** * @see com.fcc.web.sys.service.RoleService#getRoleWithModuleRight(java.lang.String) **/ @Override @Transactional(readOnly = true) public Role getRoleWithModuleRight(String roleId) { Role role = getRole(roleId); if (role != null) { List<RoleModuleRight> dataList = roleModuleRightService.getRoleModuleRight(roleId); role.setRoleModuleRights(new HashSet<RoleModuleRight>(dataList.size())); role.getRoleModuleRights().addAll(dataList); } return role; }; @Override @Transactional(readOnly = true) public List<Role> getRoleByUserType(String userType) { return roleDao.getRoleByUserType(userType); } /** * @see com.fcc.web.sys.service.RoleService#queryPage(int, int, java.util.Map) **/ @Override @Transactional(readOnly = true) public ListPage queryPage(int pageNo, int pageSize, Map<String, Object> param) { return roleDao.queryPage(pageNo, pageSize, param); } @Override public String getRoleId(Map<String, List<String>> moduleRightMap) { String roleId = null; if (moduleRightMap != null) { Set<String> moduleIdSet = moduleRightMap.keySet(); Map<String, RoleModuleRight> dataMap = new HashMap<String, RoleModuleRight>(); for (Iterator<String> it = moduleIdSet.iterator(); it.hasNext();) { String moduleId = it.next(); List<String> operateIdList = moduleRightMap.get(moduleId); RoleModuleRight right = new RoleModuleRight(); right.setRoleId(roleId); right.setModuleId(moduleId); long rightVal = 0; for (String operateId : operateIdList) { Operate operate = cacheService.getOperateMap().get(operateId); if (operate != null) { rightVal += operate.getOperateValue(); } } right.setRightValue(rightVal); dataMap.put(moduleId, right); } // 比较缓存的dataMap Map<String, Map<String, RoleModuleRight>> roleMap = cacheService.getRoleModuleRightMap(); Set<String> roleSet = roleMap.keySet(); for (Iterator<String> it = roleSet.iterator(); it.hasNext();) { String rId = it.next(); Map<String, RoleModuleRight> roleRightMap = roleMap.get(rId); if (roleRightMap.size() != dataMap.size()) continue;// 模块数量不对 Set<String> moduleSet = roleRightMap.keySet(); boolean moduleFlag = true; for (Iterator<String> iterator = moduleSet.iterator(); iterator.hasNext();) { String moduleId = iterator.next(); RoleModuleRight right = roleRightMap.get(moduleId); // dataMap.moduleId RoleModuleRight dataRight = dataMap.get(moduleId); if (dataRight == null) { moduleFlag = false; break;// 缓存角色无该模块 } if (right.getRightValue() != dataRight.getRightValue()) { moduleFlag = false; break;// 缓存角色无该模块权限 } } if (moduleFlag == false) continue; roleId = rId; break; } if (roleId == null) { if (dataMap.size() > 0) { roleId = RandomStringUtils.random(10, true, true); // 赋值 cacheService.getRoleModuleRightMap().put(roleId, dataMap); } } } return roleId; } }
true
86cc6b150b1dc94674c5c698ff9ae962127f0f45
Java
TaylorPlambeck/Speech-to-Text-Translator
/Capture.java
UTF-8
5,887
2.75
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.Arrays; import javax.sound.sampled.*; public class Capture extends JFrame { protected static boolean running; static ByteArrayOutputStream out; static File wavFile = new File(SpeechGUI.PathArray[0]); //location of file to be saved static AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE; // format of audio file public Capture() { super("Capture Sound Demo"); setDefaultCloseOperation(EXIT_ON_CLOSE); Container content = getContentPane(); final JButton capture = new JButton("Capture"); final JButton stop = new JButton("Stop"); final JButton play = new JButton("Play"); capture.setEnabled(true); stop.setEnabled(false); play.setEnabled(false); ActionListener captureListener = new ActionListener() { public void actionPerformed(ActionEvent e) { capture.setEnabled(false); stop.setEnabled(true); play.setEnabled(false); captureAudio(); } }; capture.addActionListener(captureListener); content.add(capture, BorderLayout.NORTH); ActionListener stopListener = new ActionListener() { public void actionPerformed(ActionEvent e) { capture.setEnabled(true); stop.setEnabled(false); play.setEnabled(true); running = false; } }; stop.addActionListener(stopListener); content.add(stop, BorderLayout.CENTER); ActionListener playListener = new ActionListener() { public void actionPerformed(ActionEvent e) { playAudio(); } }; play.addActionListener(playListener); content.add(play, BorderLayout.SOUTH); } public static void captureAudio() { try { final AudioFormat format = getFormat(); DataLine.Info info = new DataLine.Info( TargetDataLine.class, format); final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { int bufferSize = (int)format.getSampleRate() * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; public void run() { out = new ByteArrayOutputStream(); running = true; try { while (running) { int count = line.read(buffer, 0, buffer.length); if (count > 0) { out.write(buffer, 0, count); } } Save(); //this was added also, saves whatever was recorded and closes out.close(); line.stop(); //added these two line commands so i can record multiple times in one session line.close(); //this is where you should shut the line off } catch (IOException e) { System.err.println("I/O problems: " + e); System.exit(-1); } } }; Thread captureThread = new Thread(runner); captureThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); System.exit(-2); } } public static void Save() { byte audio[] = out.toByteArray(); InputStream input = new ByteArrayInputStream(audio); final AudioFormat format = getFormat(); final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize()); try { AudioSystem.write(ais, fileType, wavFile); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }// this is what actually puts my recording to the file, with filetype of choice } private void playAudio() { byte audio[] = out.toByteArray(); InputStream input = new ByteArrayInputStream(audio); final AudioFormat format = getFormat(); final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize()); try { AudioSystem.write(ais, fileType, wavFile); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }// this actually puts my recording to my file and filetype of choice try { DataLine.Info info = new DataLine.Info( SourceDataLine.class, format); final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { int bufferSize = (int) format.getSampleRate() * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; public void run() { try { int count; while ((count = ais.read( buffer, 0, buffer.length)) != -1) { if (count > 0) { line.write(buffer, 0, count); } } line.drain(); line.close(); } catch (IOException e) { System.err.println("I/O problems: " + e); System.exit(-3); } } }; Thread playThread = new Thread(runner); playThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); System.exit(-4); } // AudioSystem.write(ais, fileType, wavFile);// this actually puts my recording to my file and filetype of choice } public static AudioFormat getFormat() { float sampleRate = 16000; //was 8000 int sampleSizeInBits = 8; int channels = 2; //was 1. boolean signed = true; boolean bigEndian = true; return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); } public static void main(String args[]) { JFrame frame = new Capture(); frame.pack(); frame.show(); } }
true
675f9109dc86d63c820158a5410b5b62c3b6696f
Java
coopci/ddia
/ddia-common/src/coopci/ddia/UidResult.java
UTF-8
87
1.539063
2
[]
no_license
package coopci.ddia; public class UidResult extends Result { public long uid = -2; }
true
1b27f15e270dcbcee4cccfbe034f2314c163349b
Java
ChoiHeekyeong/megajava
/day12/src/크롤링/네이버증권_크롤링2.java
UHC
1,533
2.859375
3
[]
no_license
package ũѸ; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class ̹_ũѸ2 { public static void main(String[] args) { String[] codes = {"068270", "005930", "004310"}; for (int i = 0; i < codes.length; i++) { Document doc = null; //ó try { doc = Jsoup.connect("https://finance.naver.com/item/main.nhn?code="+codes[i]).get(); } catch (IOException e) { System.out.println("ũѸ ϴ ߻. ʿ!"); } Elements list = doc.select("span.code"); String code = list.get(0).text(); //ڵ尡 index = 0 . System.out.println("ڵ: " + code); Elements list3 = doc.select(".wrap_company a"); String name = list3.get(0).text(); //ȸ index = 0 . System.out.println("ȸ: " + name); //簡 ã //Elements list4 = doc.select("no_today"); // blind ãƳ. Elements list4 = doc.select("span.blind"); //System.out.println(list4); System.out.println("簡: "+list4.get(12).text()); // ã System.out.println(": "+list4.get(16).text()); // ã System.out.println(": "+list4.get(20).text()); System.out.println("----------------------------------------"); } } }
true
fe6c8a29cb5e9b7bfe9e2df7df04603c55d06d97
Java
100hor/Nosql-ppt
/src/main/java/com/nosql/SQLRepository/PrinterSQLRepository.java
UTF-8
364
1.960938
2
[]
no_license
package com.nosql.SQLRepository; import com.nosql.SQLEntity.PrinterSQL; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface PrinterSQLRepository extends JpaRepository<PrinterSQL, Long> { Optional<PrinterSQL> findFirstByName(String name); }
true
f2485d2eb1fb69c3cd0c98cda0f272a741d33822
Java
roki021/KTSNWT2020_T21
/server/src/test/java/com/culturaloffers/maps/repositories/GuestRepositoryIntegrationTest.java
UTF-8
1,624
1.960938
2
[]
no_license
package com.culturaloffers.maps.repositories; import com.culturaloffers.maps.model.Guest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static com.culturaloffers.maps.constants.UserConstants.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(SpringRunner.class) @DataJpaTest @TestPropertySource("classpath:test-user-geo.properties") public class GuestRepositoryIntegrationTest { @Autowired private GuestRepository guestRepository; @Test public void testFindByUsername() { Guest guest = guestRepository.findByUsername(DB_GUEST_USERNAME); assertEquals(DB_GUEST_USERNAME, guest.getUsername()); } @Test public void testFindByEmailAddress() { Guest guest = guestRepository.findByEmailAddress(DB_GUEST_EMAIL_ADDRESS); assertEquals(DB_GUEST_EMAIL_ADDRESS, guest.getEmailAddress()); } @Test public void testFindAll() { List<Guest> guests = guestRepository.findAll(PageRequest.of(DB_USER_PAGE, DB_USER_SIZE)).getContent(); assertEquals(DB_GUEST_EXPECTED, guests.size()); } @Test public void testFindByUsernameAdmin() { Guest guest = guestRepository.findByUsername(DB_ADMIN_USERNAME); assertNull(guest); } }
true
cadda36fd16489f9b6e136a87179f45bcd4f6f5e
Java
erdemolkun/instant-rates
/app/src/main/java/dynoapps/exchange_rates/provider/ProviderSourceCallbackAdapter.java
UTF-8
367
2.171875
2
[ "Apache-2.0" ]
permissive
package dynoapps.exchange_rates.provider; /** * Created by erdemmac on 05/12/2016. */ /*** * Adapter class for {@link IPollingSource.SourceCallback} */ public class ProviderSourceCallbackAdapter<T> implements IPollingSource.SourceCallback<T> { @Override public void onResult(T value,int type) { } @Override public void onError() { } }
true
150e74df3409ac42be4788b1f88ad2ca75d55211
Java
nosdeedson/Beyond-School
/beyondschool/src/main/java/br/com/edson/manageBean/EditarPerfil.java
UTF-8
6,685
2.078125
2
[]
no_license
package br.com.edson.manageBean; import java.io.Serializable; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.faces.application.Application; import javax.faces.application.FacesMessage; import javax.faces.application.ViewHandler; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.PersistenceException; import javax.servlet.http.HttpSession; import javax.swing.JOptionPane; import br.com.edson.Model.Aluno; import br.com.edson.Model.Funcionario; import br.com.edson.Model.Pessoa; import br.com.edson.Model.Responsavel; import br.com.edson.Model.Usuario; import br.com.edson.repository.AlunosBD; import br.com.edson.repository.FuncionariosBD; import br.com.edson.repository.ResponsaveisBD; import br.com.edson.repository.UsuariosBD; import br.com.edson.service.NegocioException; import br.com.edson.service.ValidarEmail; @Named @javax.faces.view.ViewScoped public class EditarPerfil implements Serializable { private static final long serialVersionUID = 1L; @Inject private Usuario user; @Inject private UsuariosBD usersBD; @Inject private Aluno aluno; @Inject private AlunosBD alunosBD; @Inject private Funcionario func; @Inject private FuncionariosBD funcionariosBD; @Inject private Responsavel responsavel; @Inject private ResponsaveisBD responsaveisBD; @Inject private EntityManager em; private String name; private String email; private String nomeUser; private String nascimento; HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); public void setaUser() throws NullPointerException, ParseException { user = (Usuario) session.getAttribute("usuario"); switch (user.getTipoAcesso()) { case "admin": func = funcionariosBD.porId(user.getPessoa().getIdPessoa()); setaAtributos(user, func); break; case "aluno": aluno = alunosBD.porId(user.getPessoa().getIdPessoa()); setaAtributos(user, aluno); break; case "professor": func = funcionariosBD.porId(user.getPessoa().getIdPessoa()); setaAtributos(user, func); break; case "responsavel": responsavel = responsaveisBD.porId(user.getPessoa().getIdPessoa()); setaAtributos(user, responsavel); break; } } private void setaAtributos(Usuario user, Pessoa p) throws ParseException { name = p.getNomeCompleto(); DateFormat data = new SimpleDateFormat("dd/MM/yyyy"); nascimento = data.format(p.getDataNascimento()); nomeUser = user.getNomeUsuario(); email = user.getEmail(); } public void editar() throws Exception { FacesContext context = FacesContext.getCurrentInstance(); EntityTransaction et = this.em.getTransaction(); try { switch (user.getTipoAcesso()) { case "admin":{ boolean emailValido = ValidarEmail.isValidEmail(email); if(!emailValido) throw new NegocioException("Email inválido"); boolean retorno = preparaPessoa(func); boolean retorno1 = preparauser(user); et.begin(); if( retorno) funcionariosBD.atualizaFuncionario(func); if( retorno1) usersBD.salvarUser(user); et.commit(); break; } case "aluno":{ boolean emailValido = ValidarEmail.isValidEmail(email); if(!emailValido) throw new NegocioException("Email inválido"); boolean retorno = preparaPessoa(aluno); boolean retorno1 = preparauser(user); et.begin(); if( retorno) alunosBD.atualizaAluno(aluno); if( retorno1) usersBD.salvarUser(user); et.commit(); break; } case "professor":{ boolean emailValido = ValidarEmail.isValidEmail(email); if(!emailValido) throw new NegocioException("Email inválido"); boolean retorno = preparaPessoa(func); boolean retorno1 = preparauser(user); et.begin(); if( retorno) funcionariosBD.atualizaFuncionario(func); if( retorno1) usersBD.salvarUser(user); et.commit(); break; } case "responsavel": boolean emailValido = ValidarEmail.isValidEmail(email); if(!emailValido) throw new NegocioException("Email inválido"); boolean retorno = preparaPessoa(responsavel); boolean retorno1 = preparauser(user); et.begin(); if( retorno) responsaveisBD.atualizaResponsavel(responsavel); if( retorno1) usersBD.salvarUser(user); et.commit(); break; } context.addMessage(null, new FacesMessage("Informações editadas com sucesso.")); } catch ( Exception e) { et.rollback(); e.printStackTrace(); FacesMessage msg = new FacesMessage(e.getMessage()); msg.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(null, msg); }finally { name = ""; email = ""; nascimento =""; nomeUser = ""; } } private boolean preparaPessoa( Pessoa p) throws ParseException { boolean flagPessoa = false; if( !name.equals(p.getNomeCompleto())) { p.setNomeCompleto(name); flagPessoa = true; } DateFormat data = new SimpleDateFormat("dd/MM/yyyy"); String niver = data.format(p.getDataNascimento()); if(!nascimento.equals(niver)) { p.setDataNascimento(new SimpleDateFormat("dd/MM/yyyy").parse(nascimento)); flagPessoa = true; } return flagPessoa; } private boolean preparauser( Usuario user) { boolean flagUser = false; if(!nomeUser.equals(user.getNomeUsuario())) { user.setNomeUsuario(nomeUser); flagUser= true; } if(!email.equals(user.getEmail())) { user.setEmail(email); flagUser = true; } return flagUser; } //getters and setters public Usuario getUser() { return user; } public void setUser(Usuario user) { this.user = user; } public Aluno getAluno() { return aluno; } public void setAluno(Aluno aluno) { this.aluno = aluno; } public Funcionario getFunc() { return func; } public void setFunc(Funcionario func) { this.func = func; } public Responsavel getResponsavel() { return responsavel; } public void setResponsavel(Responsavel responsavel) { this.responsavel = responsavel; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNomeUser() { return nomeUser; } public void setNomeUser(String nomeUser) { this.nomeUser = nomeUser; } public String getNascimento() { return nascimento; } public void setNascimento(String nascimento) { this.nascimento = nascimento; } }
true
84e4dd349f88b057229c708c30b459911ab7a95c
Java
nendraharyo/presensimahasiswa-sourcecode
/com/google/android/gms/maps/GoogleMapOptions.java
UTF-8
12,270
1.523438
2
[]
no_license
package com.google.android.gms.maps; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.os.Parcel; import android.util.AttributeSet; import com.google.android.gms.R.styleable; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import com.google.android.gms.maps.model.CameraPosition; public final class GoogleMapOptions implements SafeParcelable { public static final zza CREATOR; private final int mVersionCode; private Boolean zzaRP; private Boolean zzaRQ; private int zzaRR = -1; private CameraPosition zzaRS; private Boolean zzaRT; private Boolean zzaRU; private Boolean zzaRV; private Boolean zzaRW; private Boolean zzaRX; private Boolean zzaRY; private Boolean zzaRZ; private Boolean zzaSa; private Boolean zzaSb; static { zza localzza = new com/google/android/gms/maps/zza; localzza.<init>(); CREATOR = localzza; } public GoogleMapOptions() { this.mVersionCode = 1; } GoogleMapOptions(int paramInt1, byte paramByte1, byte paramByte2, int paramInt2, CameraPosition paramCameraPosition, byte paramByte3, byte paramByte4, byte paramByte5, byte paramByte6, byte paramByte7, byte paramByte8, byte paramByte9, byte paramByte10, byte paramByte11) { this.mVersionCode = paramInt1; Boolean localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte1); this.zzaRP = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte2); this.zzaRQ = localBoolean; this.zzaRR = paramInt2; this.zzaRS = paramCameraPosition; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte3); this.zzaRT = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte4); this.zzaRU = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte5); this.zzaRV = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte6); this.zzaRW = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte7); this.zzaRX = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte8); this.zzaRY = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte9); this.zzaRZ = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte10); this.zzaSa = localBoolean; localBoolean = com.google.android.gms.maps.internal.zza.zza(paramByte11); this.zzaSb = localBoolean; } public static GoogleMapOptions createFromAttributes(Context paramContext, AttributeSet paramAttributeSet) { boolean bool1 = true; Object localObject1; if (paramAttributeSet == null) { localObject1 = null; } for (;;) { return (GoogleMapOptions)localObject1; localObject1 = paramContext.getResources(); Object localObject2 = R.styleable.MapAttrs; localObject2 = ((Resources)localObject1).obtainAttributes(paramAttributeSet, (int[])localObject2); localObject1 = new com/google/android/gms/maps/GoogleMapOptions; ((GoogleMapOptions)localObject1).<init>(); int i = R.styleable.MapAttrs_mapType; boolean bool2 = ((TypedArray)localObject2).hasValue(i); if (bool2) { j = R.styleable.MapAttrs_mapType; int i19 = -1; j = ((TypedArray)localObject2).getInt(j, i19); ((GoogleMapOptions)localObject1).mapType(j); } int j = R.styleable.MapAttrs_zOrderOnTop; boolean bool3 = ((TypedArray)localObject2).hasValue(j); if (bool3) { int k = R.styleable.MapAttrs_zOrderOnTop; boolean bool4 = ((TypedArray)localObject2).getBoolean(k, false); ((GoogleMapOptions)localObject1).zOrderOnTop(bool4); } int m = R.styleable.MapAttrs_useViewLifecycle; boolean bool5 = ((TypedArray)localObject2).hasValue(m); if (bool5) { int n = R.styleable.MapAttrs_useViewLifecycle; boolean bool6 = ((TypedArray)localObject2).getBoolean(n, false); ((GoogleMapOptions)localObject1).useViewLifecycleInFragment(bool6); } int i1 = R.styleable.MapAttrs_uiCompass; boolean bool7 = ((TypedArray)localObject2).hasValue(i1); if (bool7) { int i2 = R.styleable.MapAttrs_uiCompass; boolean bool8 = ((TypedArray)localObject2).getBoolean(i2, bool1); ((GoogleMapOptions)localObject1).compassEnabled(bool8); } int i3 = R.styleable.MapAttrs_uiRotateGestures; boolean bool9 = ((TypedArray)localObject2).hasValue(i3); if (bool9) { int i4 = R.styleable.MapAttrs_uiRotateGestures; boolean bool10 = ((TypedArray)localObject2).getBoolean(i4, bool1); ((GoogleMapOptions)localObject1).rotateGesturesEnabled(bool10); } int i5 = R.styleable.MapAttrs_uiScrollGestures; boolean bool11 = ((TypedArray)localObject2).hasValue(i5); if (bool11) { int i6 = R.styleable.MapAttrs_uiScrollGestures; boolean bool12 = ((TypedArray)localObject2).getBoolean(i6, bool1); ((GoogleMapOptions)localObject1).scrollGesturesEnabled(bool12); } int i7 = R.styleable.MapAttrs_uiTiltGestures; boolean bool13 = ((TypedArray)localObject2).hasValue(i7); if (bool13) { int i8 = R.styleable.MapAttrs_uiTiltGestures; boolean bool14 = ((TypedArray)localObject2).getBoolean(i8, bool1); ((GoogleMapOptions)localObject1).tiltGesturesEnabled(bool14); } int i9 = R.styleable.MapAttrs_uiZoomGestures; boolean bool15 = ((TypedArray)localObject2).hasValue(i9); if (bool15) { int i10 = R.styleable.MapAttrs_uiZoomGestures; boolean bool16 = ((TypedArray)localObject2).getBoolean(i10, bool1); ((GoogleMapOptions)localObject1).zoomGesturesEnabled(bool16); } int i11 = R.styleable.MapAttrs_uiZoomControls; boolean bool17 = ((TypedArray)localObject2).hasValue(i11); if (bool17) { int i12 = R.styleable.MapAttrs_uiZoomControls; boolean bool18 = ((TypedArray)localObject2).getBoolean(i12, bool1); ((GoogleMapOptions)localObject1).zoomControlsEnabled(bool18); } int i13 = R.styleable.MapAttrs_liteMode; boolean bool19 = ((TypedArray)localObject2).hasValue(i13); if (bool19) { int i14 = R.styleable.MapAttrs_liteMode; boolean bool20 = ((TypedArray)localObject2).getBoolean(i14, false); ((GoogleMapOptions)localObject1).liteMode(bool20); } int i15 = R.styleable.MapAttrs_uiMapToolbar; boolean bool21 = ((TypedArray)localObject2).hasValue(i15); if (bool21) { int i16 = R.styleable.MapAttrs_uiMapToolbar; boolean bool22 = ((TypedArray)localObject2).getBoolean(i16, bool1); ((GoogleMapOptions)localObject1).mapToolbarEnabled(bool22); } int i17 = R.styleable.MapAttrs_ambientEnabled; boolean bool23 = ((TypedArray)localObject2).hasValue(i17); if (bool23) { int i18 = R.styleable.MapAttrs_ambientEnabled; boolean bool24 = ((TypedArray)localObject2).getBoolean(i18, false); ((GoogleMapOptions)localObject1).ambientEnabled(bool24); } CameraPosition localCameraPosition = CameraPosition.createFromAttributes(paramContext, paramAttributeSet); ((GoogleMapOptions)localObject1).camera(localCameraPosition); ((TypedArray)localObject2).recycle(); } } public GoogleMapOptions ambientEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaSb = localBoolean; return this; } public GoogleMapOptions camera(CameraPosition paramCameraPosition) { this.zzaRS = paramCameraPosition; return this; } public GoogleMapOptions compassEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRU = localBoolean; return this; } public int describeContents() { return 0; } public Boolean getAmbientEnabled() { return this.zzaSb; } public CameraPosition getCamera() { return this.zzaRS; } public Boolean getCompassEnabled() { return this.zzaRU; } public Boolean getLiteMode() { return this.zzaRZ; } public Boolean getMapToolbarEnabled() { return this.zzaSa; } public int getMapType() { return this.zzaRR; } public Boolean getRotateGesturesEnabled() { return this.zzaRY; } public Boolean getScrollGesturesEnabled() { return this.zzaRV; } public Boolean getTiltGesturesEnabled() { return this.zzaRX; } public Boolean getUseViewLifecycleInFragment() { return this.zzaRQ; } int getVersionCode() { return this.mVersionCode; } public Boolean getZOrderOnTop() { return this.zzaRP; } public Boolean getZoomControlsEnabled() { return this.zzaRT; } public Boolean getZoomGesturesEnabled() { return this.zzaRW; } public GoogleMapOptions liteMode(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRZ = localBoolean; return this; } public GoogleMapOptions mapToolbarEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaSa = localBoolean; return this; } public GoogleMapOptions mapType(int paramInt) { this.zzaRR = paramInt; return this; } public GoogleMapOptions rotateGesturesEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRY = localBoolean; return this; } public GoogleMapOptions scrollGesturesEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRV = localBoolean; return this; } public GoogleMapOptions tiltGesturesEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRX = localBoolean; return this; } public GoogleMapOptions useViewLifecycleInFragment(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRQ = localBoolean; return this; } public void writeToParcel(Parcel paramParcel, int paramInt) { zza.zza(this, paramParcel, paramInt); } public GoogleMapOptions zOrderOnTop(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRP = localBoolean; return this; } public GoogleMapOptions zoomControlsEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRT = localBoolean; return this; } public GoogleMapOptions zoomGesturesEnabled(boolean paramBoolean) { Boolean localBoolean = Boolean.valueOf(paramBoolean); this.zzaRW = localBoolean; return this; } byte zzzK() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRP); } byte zzzL() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRQ); } byte zzzM() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRT); } byte zzzN() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRU); } byte zzzO() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRV); } byte zzzP() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRW); } byte zzzQ() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRX); } byte zzzR() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRY); } byte zzzS() { return com.google.android.gms.maps.internal.zza.zze(this.zzaRZ); } byte zzzT() { return com.google.android.gms.maps.internal.zza.zze(this.zzaSa); } byte zzzU() { return com.google.android.gms.maps.internal.zza.zze(this.zzaSb); } } /* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\com\google\android\gms\maps\GoogleMapOptions.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
true
6be7c431870e7a8b44727457e4ae6db11b6a3e80
Java
rajvpatil5/Eclipse-New-Version
/DummyDemo/src/test/java/com/pages/EcomTestPage.java
UTF-8
943
1.609375
2
[]
no_license
package com.pages; import org.openqa.selenium.By; public class EcomTestPage { public static By textEmail = By.xpath("//input[@name='email']"); public static By textPhone = By.xpath("//input[@name='phone']"); public static By textAmount = By.xpath("//*[@id='form-section']/form/div[1]/div[3]/div/div[2]/div[1]/input"); public static By submitBtn = By.xpath("//button[@type='submit']"); // Card Modal public static By checkoutFrame = By.xpath("//iframe[@class='razorpay-checkout-frame']"); public static By cardBtn = By.xpath("//*[@id='form-common']/div[1]/div/div/div[2]/div/div/button[1]"); public static By cardNumber = By.xpath("//input[@id='card_number']"); public static By cardExpiry = By.xpath("//input[@id='card_expiry']"); public static By cardName = By.xpath("//input[@id='card_name']"); public static By cardCvv = By.xpath("//input[@id='card_cvv']"); public static By payBtn = By.xpath("//span[@id='footer-cta']"); }
true
31957f4887df8db77e107cde32df96b2383e8bcf
Java
dev-comp/xmpp-bot
/src/main/java/com/bftcom/devcomp/api/IDeliveryHandler.java
UTF-8
157
1.78125
2
[]
no_license
package com.bftcom.devcomp.api; /** * @author ikka * @date: 24.09.2016. */ public interface IDeliveryHandler { void handleDelivery(Message message); }
true
e0d7dcc217e121f6f67237f5be2adaa07c42abfe
Java
vanishedzhou/FinanceCrawler
/src/main/java/tongji/zzy/model/DisclosureInfo.java
UTF-8
1,333
2
2
[]
no_license
package tongji.zzy.model; import com.fasterxml.jackson.annotation.JsonIgnore; public class DisclosureInfo extends BaseInfo { public String companyCode; public String companyName; public String disclosureCategory; @JsonIgnore public static final String index = "disclosure"; @JsonIgnore public String typeDisclosureSource = ""; @JsonIgnore public String documentDisclosureSection = ""; public String getTypeDisclosureSource() { return typeDisclosureSource; } public void setTypeDisclosureSource(String typeDisclosureSource) { this.typeDisclosureSource = typeDisclosureSource; } public String getDocumentDisclosureSection() { return documentDisclosureSection; } public void setDocumentDisclosureSection(String documentDisclosureSection) { this.documentDisclosureSection = documentDisclosureSection; } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public String getCompanyName() { return companyName; } public void setCompanyName(String companySimpleName) { this.companyName = companySimpleName; } public String getDisclosureCategory() { return disclosureCategory; } public void setDisclosureCategory(String disclosureCategory) { this.disclosureCategory = disclosureCategory; } }
true
8d921060ff23d01b8f2cbc6d3276c7c77b004a1e
Java
aconstantinou123/Hotel-Java-Project
/src/main/java/Rooms/Restaurant.java
UTF-8
714
3.015625
3
[]
no_license
package Rooms; public class Restaurant extends Room { protected int tablesBooked; protected String currentMenu; public Restaurant(int capacity, String currentMenu) { super(capacity); this.tablesBooked = 0; this.currentMenu = currentMenu; } public String getCurrentMenu() { return currentMenu; } public void setMenu(String menu) { this.currentMenu = menu; } public int getTablesBooked() { return tablesBooked; } public void setTablesBooked(int tablesBooked) { this.tablesBooked += tablesBooked; } public void cancelTablesBooked(int tablesBooked) { this.tablesBooked -= tablesBooked; } }
true
e31a41338ada2783d72b11e26451fac1b320565b
Java
ZuzannaM/SpringAop
/SpringAop/src/main/java/com/moleda/zuzanna/SpringAop/App.java
UTF-8
831
2.3125
2
[]
no_license
package com.moleda.zuzanna.SpringAop; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.moleda.zuzanna.SpringAop.service.FactoryBeanService; import com.moleda.zuzanna.SpringAop.service.ShapeService; public class App { public static void main(String[] args) { // AbstractApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml"); // cxt.registerShutdownHook(); // ShapeService shapeService = cxt.getBean("shapeService", ShapeService.class); FactoryBeanService factory = new FactoryBeanService(); ShapeService shapeService = (ShapeService) factory.getBean("shapeService"); shapeService.getCircle(); // System.out.println(shapeService.getCircle().getName()); } }
true
a2e435d060ae2708c5161ff564b57de0fc4fc2dd
Java
MrRmk/SpringBoot-React-Demo
/src/main/java/com/example/dream/bean/User.java
UTF-8
3,962
2.296875
2
[]
no_license
package com.example.dream.bean; import java.sql.Timestamp; public class User { private String id; // 账号 private String password; // 密码 private String avatar; // 头像路径 private String nickName; // 昵称 private String name; // 姓名 private int sex; // 性别 1:男/2:女 private String summary; // 简介 private String qq; // qq private String tel; //手机 private String school; // 学校 private String education; // 学历 private String certificate; // 资格证书 private String position; // 职位 private Timestamp registerTime; // 注册时间 private int status; // 用户状态:1:可用/0:不可用 private int isAdmin; //管理员 1:是/0:不是 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getCertificate() { return certificate; } public void setCertificate(String certificate) { this.certificate = certificate; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Timestamp getRegisterTime() { return registerTime; } public void setRegisterTime(Timestamp registerTime) { this.registerTime = registerTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getIsAdmin() { return isAdmin; } public void setIsAdmin(int isAdmin) { this.isAdmin = isAdmin; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", password='" + password + '\'' + ", avatar='" + avatar + '\'' + ", nickName='" + nickName + '\'' + ", name='" + name + '\'' + ", sex=" + sex + ", summary='" + summary + '\'' + ", qq='" + qq + '\'' + ", tel='" + tel + '\'' + ", school='" + school + '\'' + ", education='" + education + '\'' + ", certificate='" + certificate + '\'' + ", position='" + position + '\'' + ", registerTime=" + registerTime + ", status=" + status + ", isAdmin=" + isAdmin + '}'; } }
true
3c2f2b63d7393c2c9d160c1976954f7750bc77ae
Java
AnilRdyAleti/ImageLoader
/app/src/main/java/me/anil/imageloader/modules/homescreen/HomeScreenPresenter.java
UTF-8
1,615
2.15625
2
[]
no_license
package me.anil.imageloader.modules.homescreen; import android.support.annotation.NonNull; import android.util.Log; import java.util.ArrayList; import me.anil.imageloader.base.BasePresenter; import me.anil.imageloader.network.RestClient; import me.anil.imageloader.repository.FeedResponse; import rx.Observable; import rx.Subscriber; public class HomeScreenPresenter extends BasePresenter<HomeScreenView> { private static final String TAG = "HomeScreenPresenter"; private RestClient restClient; public HomeScreenPresenter(RestClient restClient) { this.restClient = restClient; } void getAllImages() { if (view != null) view.showProgressDialog(); final Observable<ArrayList<FeedResponse>> allImages = restClient.createNewApi().getAllImages(); Subscriber<ArrayList<FeedResponse>> feedObservable = getImageSubscriber(); addSubscription(allImages, feedObservable); } @NonNull private Subscriber<ArrayList<FeedResponse>> getImageSubscriber() { return new Subscriber<ArrayList<FeedResponse>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.d(TAG, "onError() called with: e = [" + e + "]"); view.onError(e); view.hideProgressDialog(); } @Override public void onNext(ArrayList<FeedResponse> images) { view.hideProgressDialog(); view.populateImages(images); } }; } }
true
781cbc052b728f0aa93fa90f25d90f0acecc27e7
Java
NadineHernandez/Java-Program
/NadineHernandezU1M5Summative/src/main/java/com/company/NadineHernandezU1M5Summative/dao/BookDao.java
UTF-8
364
2.078125
2
[]
no_license
package com.company.NadineHernandezU1M5Summative.dao; import com.company.NadineHernandezU1M5Summative.dto.Book; import java.util.List; public interface BookDao { Book addBook(Book book); Book readBook(int id); List<Book> readAllBooks(); void updateBook(Book book); void removeBook(int id); List<Book> findBooksByAuthor(int author_id); }
true
23ff85ea4cdec17dbe33d448a3df2565f305e1e7
Java
gitnds/YuJiaNew
/app/src/main/java/com/strong/yujiaapp/activity/HumanInfoActivity.java
UTF-8
5,091
2.046875
2
[]
no_license
package com.strong.yujiaapp.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.strong.yujiaapp.R; import com.strong.yujiaapp.base.BaseActivity; import com.strong.yujiaapp.fragment.InfoRFragment; import com.strong.yujiaapp.fragment.InfoSFragment; import com.strong.yujiaapp.fragment.MyFragmentPagerAdapter; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/8/22. */ public class HumanInfoActivity extends BaseActivity { private LinearLayout ll_return; private TextView tv_title; private Button finish; private ViewPager viewPager; private RadioGroup radioGroup; private RadioButton rb_info_s, rb_info_r; private LinearLayout ll_add; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.humaninfo); getSupportActionBar().hide(); initView(); initData(); initEvent(); } public void initView() { ll_return = (LinearLayout) findViewById(R.id.ll_return); tv_title = (TextView) findViewById(R.id.tv_title); ll_add = (LinearLayout)findViewById(R.id.ll_add); finish = (Button) findViewById(R.id.finish); /** * RadioGroup部分 */ radioGroup = (RadioGroup) findViewById(R.id.radioGroup); rb_info_s = (RadioButton) findViewById(R.id.rb_info_s); rb_info_r = (RadioButton) findViewById(R.id.rb_info_r); //RadioGroup选中状态改变监听 radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_info_s: viewPager.setCurrentItem(0, true); break; case R.id.rb_info_r: viewPager.setCurrentItem(1, true); break; } } }); /** * ViewPager部分 */ viewPager = (ViewPager) findViewById(R.id.viewPager); InfoSFragment infosfragment = new InfoSFragment(); InfoRFragment inforfragment = new InfoRFragment(); List<Fragment> alFragment = new ArrayList<Fragment>(); alFragment.add(infosfragment); alFragment.add(inforfragment); //ViewPager设置适配器 viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), alFragment)); //ViewPager显示第一个Fragment viewPager.setCurrentItem(0); //ViewPager页面切换监听 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case 0: radioGroup.check(R.id.rb_info_s); break; case 1: radioGroup.check(R.id.rb_info_r); break; } } @Override public void onPageScrollStateChanged(int state) { } }); Intent intent = getIntent(); String type = intent.getStringExtra("type"); switch (type) { case "s": rb_info_s.setChecked(true); break; case "r": rb_info_r.setChecked(true); break; } } public void initData() { tv_title.setText("地址薄"); } public void initEvent() { ll_return.setOnClickListener(returnClickListener); ll_add.setOnClickListener(addinfoClickListener); finish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String computer = "传回来的数据"; Intent intent = new Intent(HumanInfoActivity.this, OrderActivity.class).putExtra("computer", computer); setResult(10, intent); finish(); } }); } View.OnClickListener addinfoClickListener = new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(HumanInfoActivity.this,"增加信息",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(HumanInfoActivity.this,AddInfoActivity.class); startActivityForResult(intent,1); } }; }
true
8228a68474606ee053b5e8a85574bbf0e772960f
Java
WihauShe/SnowyMoney_android
/server/src/cn/cslg/service/IReportService.java
UTF-8
359
1.78125
2
[]
no_license
package cn.cslg.service; import cn.cslg.entity.Report; import java.util.List; public interface IReportService { boolean addReport(String ruser,String reason,String evidence); boolean deleteReport(int id); List<Report> getAllReports(); List<Report> findReportByCondition(int from,int rows); int getCountByCondition(int from,int rows); }
true
84185e2f1329fa878e8c60b765841ec4ce1f5ed0
Java
11657/_3jieduan
/src/main/java/com/qf/controller/kucunController.java
UTF-8
1,591
2.203125
2
[]
no_license
package com.qf.controller; import com.qf.pojo.kucun; import com.qf.service.kucunService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.ui.Model; import javax.servlet.http.HttpSession; import java.util.List; @Controller @RequestMapping("/crm_html") public class kucunController { @Autowired private kucunService kucunService; @GetMapping("/kucun2") @ResponseBody public List<kucun> getAllkucun() { return kucunService.getAllkucun(); } @RequestMapping("/add4") public String add( kucun ls,Model model) { kucunService.getAdd(ls); return "add"; } @RequestMapping("/del4") public String del(@RequestParam("id") int id) { int ok=kucunService.delkucun(id); System.out.println(ok>0); return "222"; } @GetMapping ("/update4") public String update(kucun sh, Model model, HttpSession session) { Object obj = session.getAttribute("id"); if (obj!=null){ int id = (Integer) obj; sh.setId(id); kucunService.updatekucun(sh); session.removeAttribute("id"); }else{ session.setAttribute("id",sh.getId()); } System.out.println(sh); return "303"; } }
true
a1d3ca61c8ee6c5aba3995893cb01c7e94691bbd
Java
BenniaoManfei/BenniaoManfei
/src/main/java/service/wx/impl/WxServiceImpl.java
UTF-8
5,409
2.25
2
[]
no_license
package service.wx.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import model.bean.wx.MaterialNews; import model.bean.wx.WxAccessToken; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.client.ClientProtocolException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import service.wx.WxService; import ResultInfo.ResultInfo; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import common.constant.WxConstants; import common.util.http.MediaUploadRequestExecutor; import common.util.http.RequestExecutor; import common.util.http.SimpleGetRequestExecutor; import common.util.http.SimplePostRequestExecutor; public class WxServiceImpl implements WxService { /** * 全局的是否正在刷新access token的锁 */ protected final Object globalAccessTokenRefreshLock = new Object(); public boolean checkSignature(String timestamp, String nonce, String signature) { List<String> list = new ArrayList<String>(); list.add(WxConstants.TOKEN); list.add(timestamp); list.add(nonce); // 1) 将token、timestamp、nonce三个参数进行字典序排序 // Arrays.sort(arr); Collections.sort(list); // 2) 将三个参数字符串拼接成一个字符串进行sha1加密 StringBuffer buffer = new StringBuffer(); for (String string : list) { buffer.append(string); } String sha1Str = DigestUtils.sha1Hex(buffer.toString()); // 3)开发者获得加密后的字符串可与signature对比,标识该请求来自微信 boolean isWx = sha1Str.equals(signature); return isWx; } public WxAccessToken getToken() { synchronized (globalAccessTokenRefreshLock) { WxAccessToken token = WxAccessToken.getToken(); if (token != null) { return token; } String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + WxConstants.APPID + "&secret=" + WxConstants.APPSECRET; RequestExecutor<String, String> requestExecutor = new SimpleGetRequestExecutor(); CloseableHttpClient httpclient = HttpClients.createDefault(); try { String response = requestExecutor.execute(httpclient, null, url, null); return WxAccessToken.fromJson(response); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } public String[] getCallbackip() { WxAccessToken access_token = getToken(); if (access_token == null) { return null; } String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?" + "access_token=" + access_token.getAccessToken(); RequestExecutor<String, String> requestExecutor = new SimpleGetRequestExecutor(); CloseableHttpClient httpclient = HttpClients.createDefault(); try { String response = requestExecutor.execute(httpclient, null, url, null); JSONObject demoJson = JSONObject.parseObject(response); Integer errcode = demoJson.getIntValue("errcode"); if (errcode != null && errcode.intValue() != 0) { return null; } JSONArray jsonArray = demoJson.getJSONArray("ip_list"); String[] a = new String[1]; a = jsonArray.toArray(a); return a; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public ResultInfo<Object> createMenu(String menu) { ResultInfo<Object> result = new ResultInfo<Object>(); WxAccessToken access_token = getToken(); if (access_token == null) { result.code = 0; result.msg = "获取ACCESS_TOKEN失败!"; return result; } RequestExecutor<String, String> executor = new SimplePostRequestExecutor(); CloseableHttpClient httpclient = HttpClients.createDefault(); String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token.getAccessToken(); // menu = // "{\"button\":[{\"type\":\"click\",\"name\":\"项目管理\",\"key\":\"20_PROMANAGE\"},{\"type\":\"click\",\"name\":\"机构运作\",\"key\":\"30_ORGANIZATION\"},{\"name\":\"日常工作\",\"sub_button\":[{\"type\":\"click\",\"name\":\"待办工单\",\"key\":\"01_WAITING\"},{\"type\":\"click\",\"name\":\"已办工单\",\"key\":\"02_FINISH\"},{\"type\":\"click\",\"name\":\"我的工单\",\"key\":\"03_MYJOB\"},{\"type\":\"click\",\"name\":\"公告消息箱\",\"key\":\"04_MESSAGEBOX\"},{\"type\":\"click\",\"name\":\"签到\",\"key\":\"05_SIGN\"}]}]}"; System.out.println(menu); try { String response = executor.execute(httpclient, null, url, menu); System.out.println(response); JSONObject demoJson = JSONObject.parseObject(response); Integer errcode = demoJson.getIntValue("errcode"); if (errcode != null && errcode.intValue() != 0) { result.code = -errcode; result.msg = demoJson.getString("errmsg"); return result; } else { result.code = 1; result.msg = "菜单创建成功!"; return result; } } catch (ClientProtocolException e) { e.printStackTrace(); result.code = -1; result.msg = "请求出现错误"; return result; } catch (IOException e) { e.printStackTrace(); result.code = -1; result.msg = "请求出现错误!"; return result; } } }
true
7394afdf7cdf11224d046fc56c3079ec08b9d043
Java
panfront/hello2019
/src/com/hollycrm/test/StringEncoding.java
UTF-8
729
3
3
[]
no_license
package com.hollycrm.test; import java.util.Arrays; public class StringEncoding { public static void main(String[] args) throws Exception { String s = "abc中文"; System.out.println(s); f(s,null); f(s,"GBK"); f(s,"UTF-8"); } /* * charset 字符集 * encoding字符编码 */ private static void f(String s, String charset) throws Exception{ byte [ ]a ; String b; if(charset ==null){ a=s.getBytes(); b=new String(a,"UTF-8"); }else{ a=s.getBytes(charset); b= new String(a,charset); } System.out.println(charset+"\t"+ Arrays.toString(a)); System.out.println(b); } }
true
3ef6e829ac946f1f2fde85a1556f576e821ab258
Java
JyothiReddyguduru/Library-Management-system
/src/main/java/com/booknow/controllers/BookCopyController.java
UTF-8
1,959
2.65625
3
[]
no_license
package com.booknow.controllers; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.booknow.entities.BookHistory; import com.booknow.services.BookNowService; /* * @Author : Lasya Bentula * @Last Modified On 11/27/2020 */ @RestController public class BookCopyController { @Autowired BookNowService bookNowService; /** * method to fetch all issued books for return page * @return list of book history */ @GetMapping("/books/issued") public List<BookHistory> getAllIssuedBooks() { return bookNowService.getAllIssuedBooks(); } /** * method to issue a book to a given username * @param data */ @RequestMapping(value = "/issueBook", method = RequestMethod.POST) public void issueBook(@RequestBody Map<String, String> data) { String username = data.get("username"); String isbn = data.get("isbn"); bookNowService.issueBook(username, isbn); } /** * method to return book and calculate fines * @param data */ @RequestMapping(value = "/returnBook", method = RequestMethod.POST) public void returnBook(@RequestBody Map<String, String> data) { String username = data.get("username"); String isbn = data.get("isbn"); bookNowService.returnBook(username, isbn); } /** * method to calculate fines * @param username * @param isbn * @return */ @GetMapping("/bookCopy/fine") public Double getFineForBookCopy(@RequestParam(value = "username") String username, @RequestParam(value = "isbn") String isbn) { return bookNowService.calculateFineAmount(username, isbn); } }
true
e90de35f83f8578a51e9c3e5bb0ac4fbcd46e55d
Java
jandejongh/jqueues
/src/main/java/org/javades/jqueues/r5/extensions/visitscounter/SimQueueVisitsCounterStateHandler.java
UTF-8
6,689
2.28125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010-2018 Jan de Jongh <jfcmdejongh@gmail.com>, TNO. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.javades.jqueues.r5.extensions.visitscounter; import java.util.HashMap; import java.util.Map; import org.javades.jqueues.r5.entity.jq.job.SimJob; import org.javades.jqueues.r5.entity.jq.queue.SimQueue; import org.javades.jqueues.r5.util.predictor.queues.SimQueuePredictor_FB_v; import org.javades.jqueues.r5.util.predictor.queues.SimQueuePredictor_Pattern; import org.javades.jqueues.r5.util.predictor.state.DefaultSimQueueState; import org.javades.jqueues.r5.util.predictor.state.SimQueueStateHandler; /** A {@link SimQueueStateHandler} for counting per-job visits to a {@link SimQueue}. * * @see SimQueuePredictor_FB_v * @see SimQueuePredictor_Pattern * * @author Jan de Jongh, TNO * * <p> * Copyright (C) 2005-2017 Jan de Jongh, TNO * * <p> * This file is covered by the LICENSE file in the root of this project. * */ public final class SimQueueVisitsCounterStateHandler implements SimQueueStateHandler { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // SimQueueStateHandler // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Returns "SimQueueVisitsCounterStateHandler". * * @return "SimQueueVisitsCounterStateHandler". * */ @Override public final String getHandlerName () { return "SimQueueVisitsCounterStateHandler"; } @Override public final void initHandler (final DefaultSimQueueState queueState) { if (queueState == null) throw new IllegalArgumentException (); if (this.queueState != null) throw new IllegalStateException (); this.queueState = queueState; this.totalNumberOfVisits = 0; this.numberOfVisitsPerJob.clear (); } @Override public void resetHandler (final DefaultSimQueueState queueState) { if (queueState == null || queueState != this.queueState) throw new IllegalArgumentException (); this.totalNumberOfVisits = 0; this.numberOfVisitsPerJob.clear (); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // DEFAULT QUEUE STATE // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private DefaultSimQueueState queueState = null; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TOTAL NUMBER OF VISITS // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private int totalNumberOfVisits = 0; public final int getTotalNumberOfVisits () { return this.totalNumberOfVisits; } public final void incTotalNumberOfVisits () { this.totalNumberOfVisits++; } public final void resetTotalNumberOfVisits () { this.totalNumberOfVisits = 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // NUMBER OF VISITS PER JOB // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private final Map<SimJob, Integer> numberOfVisitsPerJob = new HashMap<> (); /** Gets the number of visits recorded for the given job. * * @param job The job, non-{@code null}. * * @return The number of visits recorded for the given job. * * @throws IllegalArgumentException If the job is {@code null} or if the job has not visited the queue (yet). * */ public final int getNumberOfVisitsForJob (final SimJob job) { if (job == null || ! this.numberOfVisitsPerJob.containsKey (job)) throw new IllegalArgumentException (); return this.numberOfVisitsPerJob.get (job); } /** Checks whether the given job has visited the queue at least once. * * @param job The job, non-{@code null}. * * @return {@code true} if the given job has visited the queue at least once. * * @throws IllegalArgumentException If the job is {@code null}. * */ public final boolean containsJob (final SimJob job) { return this.numberOfVisitsPerJob.containsKey (job); } /** Adds a first-time visiting job, and sets its number of visits to unity. * * @param job The job, non-{@code null}. * * @throws IllegalArgumentException If the job is {@code null} or if the job has already visited the queue before. * */ public final void newJob (final SimJob job) { if (job == null) throw new IllegalArgumentException (); if (this.numberOfVisitsPerJob.containsKey (job)) throw new IllegalArgumentException (); this.numberOfVisitsPerJob.put (job, 1); } /** Increments the number of visits to the queue of the given job. * * @param job The job, non-{@code null}. * * @throws IllegalArgumentException If the job is {@code null} or if the job has not visited the queue (yet). * */ public final void incNumberOfVisitsForJob (final SimJob job) { if (job == null) throw new IllegalArgumentException (); if (! this.numberOfVisitsPerJob.containsKey (job)) throw new IllegalArgumentException (); this.numberOfVisitsPerJob.put (job, this.numberOfVisitsPerJob.get (job) + 1); } /** Removes the given job from the internal queue-visits administration, but insists it is known. * * @param job The job, non-{@code null}. * * @throws IllegalArgumentException If the job is {@code null} or if the job has not visited the queue (yet). * */ public final void removeJob (final SimJob job) { if (job == null) throw new IllegalArgumentException (); if (! this.numberOfVisitsPerJob.containsKey (job)) throw new IllegalArgumentException (); this.numberOfVisitsPerJob.remove (job); } }
true
79ad1056fc60a5e80a26ed20d29bd8fc8457556f
Java
RavinduDharmasena/AF_Project
/spring_project/payment/src/main/java/com/creativelabs/payment/repository/DrugRepository.java
UTF-8
333
2.0625
2
[]
no_license
package com.creativelabs.payment.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.creativelabs.payment.model.Drug; @Repository public interface DrugRepository extends MongoRepository<Drug,String> { Drug findOneByDrugid(String drugid); }
true
d3b3ab7bc6490878cd3674725707b4187e956b18
Java
wingersoftprojects/EIHDMS
/src/java/eihdms/Deadline_extension.java
UTF-8
17,501
2.140625
2
[]
no_license
/** * "Visual Paradigm: DO NOT MODIFY THIS FILE!" * * This is an automatic generated file. It will be regenerated every time * you generate persistence class. * * Modifying its content may cause the program not work, or your work may lost. */ /** * Licensee: rlumala * License Type: Purchased */ package eihdms; import org.orm.*; import org.hibernate.Query; import org.hibernate.LockMode; import java.util.List; import java.io.Serializable; import javax.persistence.*; @Entity @org.hibernate.annotations.Proxy(lazy=false) @Table(name="deadline_extension") public class Deadline_extension implements Serializable { public Deadline_extension() { } public static Deadline_extension loadDeadline_extensionByORMID(int deadline_extension_id) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return loadDeadline_extensionByORMID(session, deadline_extension_id); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension getDeadline_extensionByORMID(int deadline_extension_id) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return getDeadline_extensionByORMID(session, deadline_extension_id); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByORMID(int deadline_extension_id, org.hibernate.LockMode lockMode) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return loadDeadline_extensionByORMID(session, deadline_extension_id, lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension getDeadline_extensionByORMID(int deadline_extension_id, org.hibernate.LockMode lockMode) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return getDeadline_extensionByORMID(session, deadline_extension_id, lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByORMID(PersistentSession session, int deadline_extension_id) throws PersistentException { try { return (Deadline_extension) session.load(eihdms.Deadline_extension.class, new Integer(deadline_extension_id)); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension getDeadline_extensionByORMID(PersistentSession session, int deadline_extension_id) throws PersistentException { try { return (Deadline_extension) session.get(eihdms.Deadline_extension.class, new Integer(deadline_extension_id)); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByORMID(PersistentSession session, int deadline_extension_id, org.hibernate.LockMode lockMode) throws PersistentException { try { return (Deadline_extension) session.load(eihdms.Deadline_extension.class, new Integer(deadline_extension_id), lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension getDeadline_extensionByORMID(PersistentSession session, int deadline_extension_id, org.hibernate.LockMode lockMode) throws PersistentException { try { return (Deadline_extension) session.get(eihdms.Deadline_extension.class, new Integer(deadline_extension_id), lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static List queryDeadline_extension(String condition, String orderBy) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return queryDeadline_extension(session, condition, orderBy); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static List queryDeadline_extension(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return queryDeadline_extension(session, condition, orderBy, lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension[] listDeadline_extensionByQuery(String condition, String orderBy) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return listDeadline_extensionByQuery(session, condition, orderBy); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension[] listDeadline_extensionByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return listDeadline_extensionByQuery(session, condition, orderBy, lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static List queryDeadline_extension(PersistentSession session, String condition, String orderBy) throws PersistentException { StringBuffer sb = new StringBuffer("From eihdms.Deadline_extension as Deadline_extension"); if (condition != null) sb.append(" Where ").append(condition); if (orderBy != null) sb.append(" Order By ").append(orderBy); try { Query query = session.createQuery(sb.toString()); return query.list(); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static List queryDeadline_extension(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { StringBuffer sb = new StringBuffer("From eihdms.Deadline_extension as Deadline_extension"); if (condition != null) sb.append(" Where ").append(condition); if (orderBy != null) sb.append(" Order By ").append(orderBy); try { Query query = session.createQuery(sb.toString()); query.setLockMode("Deadline_extension", lockMode); return query.list(); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension[] listDeadline_extensionByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException { try { List list = queryDeadline_extension(session, condition, orderBy); return (Deadline_extension[]) list.toArray(new Deadline_extension[list.size()]); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension[] listDeadline_extensionByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { try { List list = queryDeadline_extension(session, condition, orderBy, lockMode); return (Deadline_extension[]) list.toArray(new Deadline_extension[list.size()]); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByQuery(String condition, String orderBy) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return loadDeadline_extensionByQuery(session, condition, orderBy); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return loadDeadline_extensionByQuery(session, condition, orderBy, lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException { Deadline_extension[] deadline_extensions = listDeadline_extensionByQuery(session, condition, orderBy); if (deadline_extensions != null && deadline_extensions.length > 0) return deadline_extensions[0]; else return null; } public static Deadline_extension loadDeadline_extensionByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { Deadline_extension[] deadline_extensions = listDeadline_extensionByQuery(session, condition, orderBy, lockMode); if (deadline_extensions != null && deadline_extensions.length > 0) return deadline_extensions[0]; else return null; } public static java.util.Iterator iterateDeadline_extensionByQuery(String condition, String orderBy) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return iterateDeadline_extensionByQuery(session, condition, orderBy); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static java.util.Iterator iterateDeadline_extensionByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { try { PersistentSession session = EIHDMSPersistentManager.instance().getSession(); return iterateDeadline_extensionByQuery(session, condition, orderBy, lockMode); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static java.util.Iterator iterateDeadline_extensionByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException { StringBuffer sb = new StringBuffer("From eihdms.Deadline_extension as Deadline_extension"); if (condition != null) sb.append(" Where ").append(condition); if (orderBy != null) sb.append(" Order By ").append(orderBy); try { Query query = session.createQuery(sb.toString()); return query.iterate(); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static java.util.Iterator iterateDeadline_extensionByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException { StringBuffer sb = new StringBuffer("From eihdms.Deadline_extension as Deadline_extension"); if (condition != null) sb.append(" Where ").append(condition); if (orderBy != null) sb.append(" Order By ").append(orderBy); try { Query query = session.createQuery(sb.toString()); query.setLockMode("Deadline_extension", lockMode); return query.iterate(); } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public static Deadline_extension loadDeadline_extensionByCriteria(Deadline_extensionCriteria deadline_extensionCriteria) { Deadline_extension[] deadline_extensions = listDeadline_extensionByCriteria(deadline_extensionCriteria); if(deadline_extensions == null || deadline_extensions.length == 0) { return null; } return deadline_extensions[0]; } public static Deadline_extension[] listDeadline_extensionByCriteria(Deadline_extensionCriteria deadline_extensionCriteria) { return deadline_extensionCriteria.listDeadline_extension(); } public static Deadline_extension createDeadline_extension() { return new eihdms.Deadline_extension(); } public boolean save() throws PersistentException { try { EIHDMSPersistentManager.instance().saveObject(this); return true; } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public boolean delete() throws PersistentException { try { EIHDMSPersistentManager.instance().deleteObject(this); return true; } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public boolean refresh() throws PersistentException { try { EIHDMSPersistentManager.instance().getSession().refresh(this); return true; } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public boolean evict() throws PersistentException { try { EIHDMSPersistentManager.instance().getSession().evict(this); return true; } catch (Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public boolean deleteAndDissociate()throws PersistentException { try { if(getReport_form_deadline() != null) { getReport_form_deadline().setDeadline_extension(null); } return delete(); } catch(Exception e) { e.printStackTrace(); throw new PersistentException(e); } } public boolean deleteAndDissociate(org.orm.PersistentSession session)throws PersistentException { try { if(getReport_form_deadline() != null) { getReport_form_deadline().setDeadline_extension(null); } try { session.delete(this); return true; } catch (Exception e) { return false; } } catch(Exception e) { e.printStackTrace(); throw new PersistentException(e); } } @Column(name="deadline_extension_id", nullable=false, length=11) @Id @GeneratedValue(generator="EIHDMS_DEADLINE_EXTENSION_DEADLINE_EXTENSION_ID_GENERATOR") @org.hibernate.annotations.GenericGenerator(name="EIHDMS_DEADLINE_EXTENSION_DEADLINE_EXTENSION_ID_GENERATOR", strategy="native") private int deadline_extension_id; @OneToOne(optional=false, targetEntity=eihdms.Report_form_deadline.class, fetch=FetchType.LAZY) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK}) @JoinColumns(value={ @JoinColumn(name="report_form_deadline_id", referencedColumnName="report_form_deadline_id", nullable=false) }, foreignKey=@ForeignKey(name="FKdeadline_e392986")) @org.hibernate.annotations.LazyToOne(value=org.hibernate.annotations.LazyToOneOption.NO_PROXY) private eihdms.Report_form_deadline report_form_deadline; @Column(name="extended_to_date", nullable=false) private java.sql.Timestamp extended_to_date; @Column(name="is_deleted", nullable=false, length=1) private int is_deleted; @Column(name="is_active", nullable=false, length=1) private int is_active; @Column(name="add_date", nullable=true) private java.sql.Timestamp add_date; @Column(name="add_by", nullable=true, length=10) private Integer add_by; @Column(name="last_edit_date", nullable=true) private java.sql.Timestamp last_edit_date; @Column(name="last_edit_by", nullable=true, length=10) private Integer last_edit_by; private void setDeadline_extension_id(int value) { this.deadline_extension_id = value; } public int getDeadline_extension_id() { return deadline_extension_id; } public int getORMID() { return getDeadline_extension_id(); } public void setExtended_to_date(java.sql.Timestamp value) { this.extended_to_date = value; } public java.sql.Timestamp getExtended_to_date() { return extended_to_date; } public void setIs_deleted(int value) { this.is_deleted = value; } public int getIs_deleted() { return is_deleted; } public void setIs_active(int value) { this.is_active = value; } public int getIs_active() { return is_active; } public void setAdd_date(java.sql.Timestamp value) { this.add_date = value; } public java.sql.Timestamp getAdd_date() { return add_date; } public void setAdd_by(int value) { setAdd_by(new Integer(value)); } public void setAdd_by(Integer value) { this.add_by = value; } public Integer getAdd_by() { return add_by; } public void setLast_edit_date(java.sql.Timestamp value) { this.last_edit_date = value; } public java.sql.Timestamp getLast_edit_date() { return last_edit_date; } public void setLast_edit_by(int value) { setLast_edit_by(new Integer(value)); } public void setLast_edit_by(Integer value) { this.last_edit_by = value; } public Integer getLast_edit_by() { return last_edit_by; } public void setReport_form_deadline(eihdms.Report_form_deadline value) { this.report_form_deadline = value; } public eihdms.Report_form_deadline getReport_form_deadline() { return report_form_deadline; } public boolean equals(Object obj) { if (obj == null) { return false; } Deadline_extension object = (Deadline_extension) obj; return (this.getDeadline_extension_id() == object.getDeadline_extension_id()); } public int hashCode() { int hash = 3; return hash; } public String toString() { return String.valueOf(getDeadline_extension_id()); } }
true
2f4ab24ef3824a9469650bd15595592c9f2b358b
Java
hanseul-Choi/programmers
/level2_java/게임 맵 최단거리/game_short_path.java
UTF-8
1,471
3.015625
3
[]
no_license
import java.util.*; class Solution { public static int[] dx = {0, 1, -1, 0}; public static int[] dy = {-1, 0, 0, 1}; //하 우 좌 상 (유리한 순서대로) public static int N,M; public static int[][] map; public static int[][] visit; public class Node { int x; int y; Node(int x, int y) { this.x = x; this.y = y; } } public int solution(int[][] maps) { int answer = 0; N = maps.length; M = maps[0].length; map = maps; visit = new int[N][M]; bfs(); if(visit[N-1][M-1] == 0) { answer = -1; } else answer = visit[N-1][M-1]; return answer; } public void bfs() { Queue<Node> q = new LinkedList<>(); q.add(new Node(0,0)); visit[0][0] = 1; while(!q.isEmpty()) { Node cur = q.poll(); for(int i=0; i<4; i++) { int nextX = cur.x + dx[i]; int nextY = cur.y + dy[i]; if(nextX < 0 || nextY < 0 || nextX >= M || nextY >= N) continue; if(visit[nextY][nextX] != 0|| map[nextY][nextX] == 0) continue; q.add(new Node(nextX, nextY)); visit[nextY][nextX] = visit[cur.y][cur.x] + 1; } } } }
true
c8a70a14f14d5aebc7e00edc7bd09eaa8e1fad41
Java
vicky-2020/AutoTest
/Chapter5/src/main/java/com/course/testng/IgnoreTest.java
UTF-8
392
2.4375
2
[]
no_license
package com.course.testng; import org.testng.annotations.Test; public class IgnoreTest { @Test public void ignore1(){ System.out.print("ignore1 running"); } @Test(enabled = false) public void ignore2(){ System.out.print("ignore1 running"); } @Test(enabled = true) public void ignore3(){ System.out.print("ignore3 running"); } }
true
a12aa0a4e98b2dee479c369d83075d047dfdec6d
Java
vodinhhung/Algorithm_practicing
/HUST/BeginningJava/src/tutorial/javabasic/exception/AgeUntils.java
UTF-8
348
3.40625
3
[]
no_license
package tutorial.javabasic.exception; public class AgeUntils { public static void checkAge(int age) throws TooYoungException, TooOldException { if(age < 18) throw new TooYoungException("Age " +age+ " too young."); else if (age > 40) throw new TooOldException("Age " +age+ " too old"); else System.out.println("Age "+age+ " OK"); } }
true
f81ba27707cc4703aa59db1c2f2a40811a721c4d
Java
iivaan/PaxoDataCompare
/src/main/java/com/paxovision/db/lettercase/CaseConversion.java
UTF-8
432
2.859375
3
[]
no_license
package com.paxovision.db.lettercase; /** * Conversion of the case of a {@link String}. */ public interface CaseConversion { /** * Returns the name of the conversion. * @return The name of the conversion. */ String getConversionName(); /** * Converts the {@link String} in parameter to another. * @param value The {@link String} to convert. * @return The result. */ String convert(String value); }
true
31a49eddff784b13b86fc97fccf415a448dbfa25
Java
jbosstools/jbosstools-openshift
/plugins/org.jboss.tools.openshift.common.core/src/org/jboss/tools/openshift/common/core/connection/IConnectionsRegistryListener.java
UTF-8
1,438
1.929688
2
[]
no_license
/******************************************************************************* * Copyright (c) 2012-2014 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.openshift.common.core.connection; /** * A listener that gets notified of changes (additions, removals, modifications) of connections contained within the connections model. * * @author Rob Stryker * @author Andre Dietisheim * @author Jeff Cantrill */ public interface IConnectionsRegistryListener { /** * Be alerted that a connection has been added * @param connection */ public void connectionAdded(IConnection connection); /** * Be alerted that a connection has been removed * @param connection */ public void connectionRemoved(IConnection connection); /** * Be alerted that a connection has been changed * @param connection * @param the name of the property * @param the old value of the property * @param the new value of the property */ public void connectionChanged(IConnection connection, String property, Object oldValue, Object newValue); }
true
43b3f2a0aa7fac10a43b902f1422ad2a4385a144
Java
AbhishekTag/RLMS
/src/main/java/com/rlms/dao/CompanyDaoImpl.java
UTF-8
4,736
2.125
2
[]
no_license
package com.rlms.dao; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.rlms.constants.RLMSConstants; import com.rlms.contract.CompanyDtlsDTO; import com.rlms.contract.UserMetaInfo; import com.rlms.model.RlmsBranchMaster; import com.rlms.model.RlmsCompanyBranchMapDtls; import com.rlms.model.RlmsCompanyMaster; @Repository("companyDao") public class CompanyDaoImpl implements CompanyDao{ @Autowired private SessionFactory sessionFactory; public CompanyDaoImpl() { super(); // TODO Auto-generated constructor stub } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void saveCompanyM(RlmsCompanyMaster rlmsCompanyMaster){ this.sessionFactory.getCurrentSession().save(rlmsCompanyMaster); } public RlmsCompanyMaster getCompanyByEmailID(String emailID){ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(RlmsCompanyMaster.class); criteria.add(Restrictions.eq("emailId", emailID)); criteria.add(Restrictions.eq("activeFlag", RLMSConstants.ACTIVE.getId())); RlmsCompanyMaster companyMaster = (RlmsCompanyMaster) criteria.uniqueResult(); return companyMaster; } @SuppressWarnings("unchecked") public List<RlmsCompanyMaster> getAllCompanies(Integer companyId){ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(RlmsCompanyMaster.class); if(null != companyId){ criteria.add(Restrictions.eq("companyId", companyId)); } criteria.add(Restrictions.eq("activeFlag", RLMSConstants.ACTIVE.getId())); List<RlmsCompanyMaster> listOfAllCompanies = criteria.list(); return listOfAllCompanies; } @SuppressWarnings("unchecked") public RlmsCompanyMaster getCompanyById(Integer companyId){ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(RlmsCompanyMaster.class); criteria.add(Restrictions.eq("companyId", companyId)); criteria.add(Restrictions.eq("activeFlag", RLMSConstants.ACTIVE.getId())); RlmsCompanyMaster companyMaster = (RlmsCompanyMaster) criteria.uniqueResult(); return companyMaster; } public RlmsCompanyBranchMapDtls getCompanyBranchMapById(Integer companyBranchMapId){ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(RlmsCompanyBranchMapDtls.class); criteria.add(Restrictions.eq("companyBranchMapId", companyBranchMapId)); criteria.add(Restrictions.eq("activeFlag", RLMSConstants.ACTIVE.getId())); RlmsCompanyBranchMapDtls companyBranchMapDtls = (RlmsCompanyBranchMapDtls) criteria.uniqueResult(); return companyBranchMapDtls; } public void updateCompanyM(RlmsCompanyMaster rlmsCompanyMaster){ this.sessionFactory.getCurrentSession().update(rlmsCompanyMaster); } public void deleteCompanyM(CompanyDtlsDTO companyDtlsDTO,UserMetaInfo metaInfo){ Query q = this.sessionFactory.getCurrentSession().createQuery("update RlmsCompanyMaster set activeFlag=:activeFlag,status=:status,updatedDate=:updatedDate,updatedBy=:updatedBy where companyId=:companyId"); q.setParameter("companyId", companyDtlsDTO.getCompanyId()); q.setParameter("activeFlag", RLMSConstants.INACTIVE.getId()); q.setParameter("status", RLMSConstants.INACTIVE.getId()); q.setParameter("updatedDate", new Date()); q.setParameter("updatedBy", metaInfo.getUserId()); q.executeUpdate(); } public void updateBranchDetails(RlmsBranchMaster rlmsBranchMaster){ this.sessionFactory.getCurrentSession().update(rlmsBranchMaster); } /*@SuppressWarnings("unchecked") public RlmsCompanyRoleMap getCompanyRole(Integer companyId, Integer spocRoleId){ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(RlmsCompanyRoleMap.class); criteria.add(Restrictions.eq("rlmsSpocRoleMaster.spocRoleId", spocRoleId)); criteria.add(Restrictions.eq("rlmsCompanyMaster.companyId", companyId)); RlmsCompanyRoleMap companyRoleMap = (RlmsCompanyRoleMap) criteria.uniqueResult(); return companyRoleMap; }*/ @SuppressWarnings("unchecked") public List<RlmsCompanyMaster> getAllCompaniesForDashboard(Integer companyId){ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(RlmsCompanyMaster.class); if(null != companyId){ criteria.add(Restrictions.eq("companyId", companyId)); }; List<RlmsCompanyMaster> listOfAllCompanies = criteria.list(); return listOfAllCompanies; } }
true
8dc616525acf5f81aec43fb0f0ffc93113a22edb
Java
andeemarks/checkstyle-edn-listener
/test/org/corvine/checkstyle/EdnListenerTest.java
UTF-8
1,651
2.28125
2
[]
no_license
package org.corvine.checkstyle; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.util.Arrays; import static org.junit.Assert.assertEquals; public class EdnListenerTest { private EdnListener listener; private ByteArrayOutputStream stub; private PrintWriter stubWriter; @Before public void setup() { listener = new EdnListener(); stub = new ByteArrayOutputStream(); stubWriter = new PrintWriter(stub); } @Test public void shouldEmitAllAuditEventFieldswithDefaultNamesInEdn() { AuditEvent event = new AuditEvent("src", "file", new LocalizedMessage(23, 45, "", "", null, "module-id", org.corvine.checkstyle.EdnListener.class, "Hello")); listener.printEvent(stubWriter, event); stubWriter.flush(); assertEquals("{:source-file \"file\" :line 23 :column 45 :severity \"error\" :message \"Hello\" :source \"org.corvine.checkstyle.EdnListener\"}", stub.toString().trim()); } @Test public void shouldOnlyIncludeFieldsWhenSpecified() { listener.setFields(new String[]{"source-file", "message", "line"}); AuditEvent event = new AuditEvent("src", "file", new LocalizedMessage(23, 45, "", "", null, "module-id", org.corvine.checkstyle.EdnListener.class, "Hello")); listener.printEvent(stubWriter, event); stubWriter.flush(); assertEquals("{:source-file \"file\" :line 23 :message \"Hello\"}", stub.toString().trim()); } }
true
b26c20b8f853aa647da60c07f5bac9d8d8432bbf
Java
GODueol/Door
/app/src/main/java/com/teamdoor/android/door/SettingActivity/PushAlarmActivity.java
UTF-8
4,345
2.109375
2
[]
no_license
package com.teamdoor.android.door.SettingActivity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.CompoundButton; import android.widget.Switch; import com.teamdoor.android.door.R; import com.teamdoor.android.door.Util.SharedPreferencesUtil; /** * Created by Kwon on 2018-01-04. */ public class PushAlarmActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { Toolbar toolbar = null; private SharedPreferencesUtil SPUtil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.setting_alarm_activity); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // 툴바 뒤로가기 버튼 getSupportActionBar().setDisplayHomeAsUpEnabled(true); //액션바 아이콘을 업 네비게이션 형태로 표시합니다. getSupportActionBar().setDisplayShowHomeEnabled(true); //홈 아이콘을 숨김처리합니다. getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_keyboard_arrow_left_black_36dp); SPUtil = new SharedPreferencesUtil(getApplicationContext()); Switch switch_vibrate = (Switch) findViewById(R.id.switch0); Switch switch_chat = (Switch) findViewById(R.id.switch1); Switch switch_follow = (Switch) findViewById(R.id.switch2); Switch switch_friend = (Switch) findViewById(R.id.switch3); Switch switch_post = (Switch) findViewById(R.id.switch5); Switch switch_answer = (Switch) findViewById(R.id.switch6); Switch switch_like = (Switch) findViewById(R.id.switch7); boolean isCheck = SPUtil.getSwitchState(getString(R.string.alertChat)); switch_chat.setChecked(isCheck); isCheck = SPUtil.getSwitchState(getString(R.string.alertFolow)); switch_follow.setChecked(isCheck); isCheck = SPUtil.getSwitchState(getString(R.string.alertFriend)); switch_friend.setChecked(isCheck); isCheck = SPUtil.getSwitchState(getString(R.string.alertPost)); switch_post.setChecked(isCheck); isCheck = SPUtil.getSwitchState(getString(R.string.alertAnswer)); switch_answer.setChecked(isCheck); isCheck = SPUtil.getSwitchState(getString(R.string.alertLike)); switch_like.setChecked(isCheck); isCheck = SPUtil.getSwitchState(getString(R.string.set_vibrate)); switch_vibrate.setChecked(isCheck); switch_vibrate.setOnCheckedChangeListener(this); switch_chat.setOnCheckedChangeListener(this); switch_follow.setOnCheckedChangeListener(this); switch_friend.setOnCheckedChangeListener(this); switch_post.setOnCheckedChangeListener(this); switch_answer.setOnCheckedChangeListener(this); switch_like.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) { int button = compoundButton.getId(); String switch_name = null; switch (button) { case R.id.switch0: switch_name = getString(R.string.set_vibrate); break; case R.id.switch1: switch_name = getString(R.string.alertChat); break; case R.id.switch2: switch_name = getString(R.string.alertFolow); break; case R.id.switch3: switch_name = getString(R.string.alertFriend); break; case R.id.switch5: switch_name = getString(R.string.alertPost); break; case R.id.switch6: switch_name = getString(R.string.alertAnswer); break; case R.id.switch7: switch_name = getString(R.string.alertLike); break; } SPUtil.setSwitchState(switch_name, isCheck); } // 뒤로가기 버튼 기능 public boolean onOptionsItemSelected(android.view.MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
true
981f3455df1e0d16ac9a6592123b9b4515397023
Java
Warald/cs108
/src/quiz/model/QuizQuestionAttemptGraded.java
UTF-8
91
1.6875
2
[]
no_license
package quiz.model; public enum QuizQuestionAttemptGraded { undone, incomplete, done }
true