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
df04b67d777287e1900b9db3e6698ab1f1b0e15c
Java
Amberllo/TuCamera
/app/src/com/mixcolours/photoshare/custom/ui/CuterFragment.java
UTF-8
5,994
1.828125
2
[]
no_license
package com.mixcolours.photoshare.custom.ui; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.mixcolours.photoshare.R; import org.lasque.tusdk.core.TuSdkContext; import org.lasque.tusdk.core.seles.tusdk.FilterImageViewInterface; import org.lasque.tusdk.core.view.TuSdkViewHelper; import org.lasque.tusdk.core.view.widget.button.TuSdkImageButton; import org.lasque.tusdk.core.view.widget.button.TuSdkTextButton; import org.lasque.tusdk.impl.components.edit.TuEditCuterFragment; import org.lasque.tusdk.impl.components.filter.TuEditFilterFragment; import java.util.ArrayList; import java.util.List; /** * Created by Amberllo on 16/8/22. */ public class CuterFragment extends TuEditCuterFragment{ public static int getLayoutViewId(){ return R.layout.custom_cuter_fragment_layout; } @Override public void setRootViewLayoutId(int i) { super.setRootViewLayoutId(getLayoutViewId()); } @Override protected void loadView(ViewGroup viewGroup) { super.loadView(viewGroup); this.getViewById(R.id.lsq_doneButton1).setOnClickListener(new TuSdkViewHelper.OnSafeClickListener() { @Override public void onSafeClick(View view) { handleCompleteButton(); } }); this.getViewById(R.id.lsq_cancelButton1).setOnClickListener(new TuSdkViewHelper.OnSafeClickListener() { @Override public void onSafeClick(View view) { handleBackButton(); } }); LinearLayout optBar = getOptionBar(); for(int i=0;i<optBar.getChildCount();i++){ if(optBar.getChildAt(i).getId() == R.id.lsq_trunButton1){ optBar.getChildAt(i).setOnClickListener(new TuSdkViewHelper.OnSafeClickListener() { @Override public void onSafeClick(View view) { handleTrunButton(); } }); } if(optBar.getChildAt(i).getId() == R.id.lsq_mirrorButton1){ optBar.getChildAt(i).setOnClickListener(new TuSdkViewHelper.OnSafeClickListener() { @Override public void onSafeClick(View view) { handleMirrorButton(); } }); } } } @Override public LinearLayout getOptionBar() { View scrollParent = this.getViewById(R.id.lsq_optionBar_root); LinearLayout optBar = (LinearLayout) scrollParent.findViewById(R.id.lsq_optionBar); if(optBar != null && this.getRatioTypes().length < 2) { this.showView(optBar, false); } return optBar; } @Override public List<TuSdkTextButton> getRatioButtons() { List<TuSdkTextButton> result = new ArrayList<>(); if(this.getOptionBar() != null) { LinearLayout optionBar = this.getOptionBar(); int[] ratioTypes = this.getRatioTypes(); for(int i = 0; i < ratioTypes.length; ++i) { int type = ratioTypes[i]; if( i < optionBar.getChildCount() && optionBar.getChildAt(i) instanceof TuSdkTextButton ){ final TuSdkTextButton button = (TuSdkTextButton) optionBar.getChildAt(i); this.buildRatioActionButton(type, ratioTypes.length,button); button.index = type; button.setOnClickListener(new TuSdkViewHelper.OnSafeClickListener() { @Override public void onSafeClick(View view) { handleRatioButton(button); } }); boolean select; if(this.getCurrentRatioType() <= 0) { select = false; } else { select = type == this.getCurrentRatioType(); } button.setSelected(select); // optionBar.addView(button); result.add(button); } } } return result; } protected TuSdkTextButton buildRatioActionButton(int var1, int var2,TuSdkTextButton textButton) { String var3; String var6; switch(var1) { case 1: var6 = "lsq_edit_cuter_ratio_orgin"; var3 = "lsq_style_default_ratio_orgin"; break; case 2: var6 = "lsq_edit_cuter_ratio_1_1"; var3 = "lsq_style_default_ratio_1_1"; break; case 4: var6 = "lsq_edit_cuter_ratio_2_3"; var3 = "lsq_style_default_ratio_2_3"; break; case 8: var6 = "lsq_edit_cuter_ratio_3_4"; var3 = "lsq_style_default_ratio_3_4"; break; case 16: var6 = "lsq_edit_cuter_ratio_9_16"; var3 = "lsq_style_default_ratio_9_16"; break; default: return null; } int color_orange = TuSdkContext.getColor("lsq_color_orange"); var2 = (int)Math.floor((double)(TuSdkContext.getDisplaySize().width / var2)); LinearLayout.LayoutParams params; (params = new LinearLayout.LayoutParams(var2, -1)).setMargins(0, 0, 0, 0); textButton.setLayoutParams(params); textButton.setGravity(17); var2 = TuSdkContext.dip2px(18.0F); textButton.setPadding(0, var2, 0, TuSdkContext.dip2px(10.0F)); textButton.setSelectedColor(color_orange); textButton.setText(TuSdkContext.getString(var6)); textButton.setCompoundDrawables((Drawable)null, TuSdkContext.getDrawable(var3), (Drawable)null, (Drawable)null); return textButton; } }
true
bfb0df156e5f7e998c730cd1b027d75d318e4d24
Java
nikclayton/android-squeezer
/Squeezer/src/main/java/uk/org/ngo/squeezer/download/DownloadDatabase.java
UTF-8
10,667
2.328125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2014 Kurt Aaholst <kaaholst@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.ngo.squeezer.download; import android.app.DownloadManager; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Base64; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Maintain a queue of download requests. * <p> * Enqueue a new download request via {@link #enqueueDownload(DownloadManager, String, Uri, String)} and * call {@link #popDownloadEntry(Context, long)} when a download is completed. */ public class DownloadDatabase { public static final String TAG = DownloadDatabase.class.getSimpleName(); private static class DOWNLOAD_DATABASE { private static final String NAME = "download"; private static final int VERSION = 5; private static class SONG { private static final String TABLE = "download"; private static class COLUMNS { private static final String DOWNLOAD_ID = "download_id"; private static final String URL = "url"; private static final String FILE_NAME = "file_name"; private static final String CREDENTIALS = "credentials"; private static final String TITLE = "title"; private static final String ALBUM = "album"; private static final String ARTIST = "artist"; } } } private final SQLiteDatabase db; public DownloadDatabase(Context context) { db = OpenHelper.getInstance(context).getWritableDatabase(); } private static class OpenHelper extends SQLiteOpenHelper { private static final Object mInstanceLock = new Object(); private static OpenHelper mInstance; private OpenHelper(Context context) { // calls the super constructor, requesting the default cursor // factory. super(context, DOWNLOAD_DATABASE.NAME, null, DOWNLOAD_DATABASE.VERSION); } public static OpenHelper getInstance(Context context) { if (mInstance == null) { synchronized (mInstanceLock) { if (mInstance == null) { mInstance = new OpenHelper(context); } } } return mInstance; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL("CREATE TABLE " + DOWNLOAD_DATABASE.SONG.TABLE + "(" + DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID + " INTEGER, " + DOWNLOAD_DATABASE.SONG.COLUMNS.URL + " TEXT, " + DOWNLOAD_DATABASE.SONG.COLUMNS.FILE_NAME + " TEXT, " + DOWNLOAD_DATABASE.SONG.COLUMNS.CREDENTIALS + " TEXT, " + DOWNLOAD_DATABASE.SONG.COLUMNS.TITLE + " TEXT, " + DOWNLOAD_DATABASE.SONG.COLUMNS.ALBUM + " TEXT, " + DOWNLOAD_DATABASE.SONG.COLUMNS.ARTIST + " TEXT)"); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DOWNLOAD_DATABASE.SONG.TABLE); // Upgrades just creates a new database. The database keeps track of // active downloads, so it holds only temporary information. onCreate(sqLiteDatabase); } } /** * Register a download request. */ public void registerDownload(Context context, String credentials, Uri url, @NonNull String fileName, @NonNull String title, String album, String artist) { // To avoid download manager stops processing our requests due to exceeding the rate // limit for notifications (because download manager shows a notification), we delay // enqueuing further download requests until any current enqueued requests is completed. DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); long downloadId = (activeRequests() < 4) ? enqueueDownload(downloadManager, credentials, url, title) : -1; ContentValues contentValues = new ContentValues(); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID, downloadId); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.URL, url.toString()); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.FILE_NAME, fileName); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.CREDENTIALS, credentials); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.TITLE, title); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.ALBUM, album); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.ARTIST, artist); if (db.insert(DOWNLOAD_DATABASE.SONG.TABLE, null, contentValues) == -1) { Log.w(TAG, "Could not register download entry for: " + title); if (downloadId != -1) { downloadManager.remove(downloadId); } } } /** * Enqueue a download if any pending */ private void maybeEnqueueDownload(Context context) { DownloadEntry entry = null; try (Cursor cursor = db.rawQuery("select * from " + DOWNLOAD_DATABASE.SONG.TABLE + " where " + DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID + "=?", new String[]{String.valueOf(-1)})) { if (cursor.moveToNext()) { entry = getDownloadEntry(cursor); } } if (entry != null) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); long downloadId = enqueueDownload(downloadManager, entry.credentials, entry.url, entry.title); ContentValues contentValues = new ContentValues(); contentValues.put(DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID, downloadId); db.update(DOWNLOAD_DATABASE.SONG.TABLE, contentValues, DOWNLOAD_DATABASE.SONG.COLUMNS.URL + "=?", new String[]{String.valueOf(entry.url)}); } } private long activeRequests() { try (Cursor cursor = db.rawQuery("select count(*) from " + DOWNLOAD_DATABASE.SONG.TABLE + " where " + DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID + " <>?", new String[]{String.valueOf(-1)})) { if (cursor.moveToNext()) { return cursor.getLong(0); } } return 0; } private long enqueueDownload(DownloadManager downloadManager, String credentials, Uri url, @NonNull String title) { String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); DownloadManager.Request request = new DownloadManager.Request(url) .setTitle(title) .setVisibleInDownloadsUi(false) .addRequestHeader("Authorization", "Basic " + base64EncodedCredentials); long downloadId = downloadManager.enqueue(request); Log.i(TAG, "download enqueued[" + title + "]: " + downloadId); return downloadId; } /** * Search for a previously registered download entry with the supplied id. * If an entry is found it is returned, the download is unregistered and if any pending * downloads a new one is enqueued. * * @param downloadId Download id * @return The registered download entry or null if not found */ @Nullable public DownloadEntry popDownloadEntry(Context context, long downloadId) { DownloadEntry entry = null; try (Cursor cursor = db.rawQuery("select * from " + DOWNLOAD_DATABASE.SONG.TABLE + " where " + DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID + "=?", new String[]{String.valueOf(downloadId)})) { if (cursor.moveToNext()) { entry = getDownloadEntry(cursor); } } if (entry != null) { db.delete(DOWNLOAD_DATABASE.SONG.TABLE, DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID + "=?", new String[]{String.valueOf(downloadId)}); maybeEnqueueDownload(context); } return entry; } public void iterateDownloadEntries(DownloadHandler callback) { try (Cursor cursor = db.rawQuery("select * from " + DOWNLOAD_DATABASE.SONG.TABLE, null)) { while (cursor.moveToNext()) { callback.handle(getDownloadEntry(cursor)); } } } private DownloadEntry getDownloadEntry(Cursor cursor) { DownloadEntry entry = new DownloadEntry(); entry.downloadId = cursor.getLong(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.DOWNLOAD_ID)); entry.url = Uri.parse(cursor.getString(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.URL))); entry.fileName = cursor.getString(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.FILE_NAME)); entry.credentials = cursor.getString(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.CREDENTIALS)); entry.title = cursor.getString(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.TITLE)); entry.album = cursor.getString(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.ALBUM)); entry.artist = cursor.getString(cursor.getColumnIndex(DOWNLOAD_DATABASE.SONG.COLUMNS.ARTIST)); return entry; } public void remove(Uri url) { db.delete(DOWNLOAD_DATABASE.SONG.TABLE, DOWNLOAD_DATABASE.SONG.COLUMNS.URL + "=?", new String[]{url.toString()}); } public static class DownloadEntry { public long downloadId; public Uri url; public String fileName; public String credentials; public String title; public String album; public String artist; } public interface DownloadHandler { void handle(DownloadEntry entry); } }
true
d0d112f11c6e1599787e573e54c988cba95705b0
Java
sidan001/jkd8
/src/main/java/com/chou/functional_interface/TestFunctionalInterface.java
UTF-8
527
2.90625
3
[]
no_license
package com.chou.functional_interface; import java.util.Objects; import java.util.function.Consumer; /** * Created by Administrator on 2016/12/19. */ @FunctionalInterface public interface TestFunctionalInterface<T> { void test(T t); boolean equals(Object obj); String toString(); default void defaultMethod1(){ System.out.println("hello world"); } default String concumer(T t ){ return t.toString(); } default String supplier(){ return "hello world"; } }
true
3fe091ffaf0d390b6d0a981c512f0f39b81d3245
Java
augustoerico/pcsos
/PCSOS/src/epusp/pcs/os/shared/model/attribute/Category.java
UTF-8
783
2.4375
2
[]
no_license
package epusp.pcs.os.shared.model.attribute; import java.io.Serializable; import com.google.gwt.core.client.GWT; import epusp.pcs.os.shared.client.constants.CommonWorkspaceConstants; public enum Category implements Serializable{ GeneralInfo, PhysicalProfile, MedicalData, PersonalVehicle; public String getText(){ CommonWorkspaceConstants constants = GWT.create(CommonWorkspaceConstants.class); switch (this) { case GeneralInfo: return constants.generalInfo(); case PhysicalProfile: return constants.physicalProfile(); case MedicalData: return constants.medicalData(); case PersonalVehicle: return constants.personalVehicle(); default: return ""; } } /* * Seen by IsSerializable */ Category(){ } }
true
f802b1cf562c802c30e5b1efe50ba1d9a5a79522
Java
gluo7777/Utility-Applications
/src/main/java/org/william/apps/utils/JsonUtil.java
UTF-8
1,256
2.71875
3
[]
no_license
package org.william.apps.utils; import java.util.Map.Entry; import org.william.apps.utils.pojo.TestPojo; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public enum JsonUtil { INSTANCE; private final JsonParser parser = new JsonParser(); private final Gson gson = new Gson(); public TestPojo jsonToTestPojo(String json) { // JsonObject parser.parse(json); return null; } /** * recursively walks the json structure to search for the clazz * @param json - to parse * @param clazz - to deserialize json into * @return deserialized class or null if the name of the class is not found */ public <T> T deserializeNestedObject(String json, Class<T> clazz) { return walkJsonStructure(clazz, parser.parse(json)); } protected <T> T walkJsonStructure(Class<T> clazz, JsonElement e) { T obj = null; if(e.isJsonObject()) { JsonObject o = e.getAsJsonObject(); if(o.has(clazz.getSimpleName())) obj = gson.fromJson(o.get(clazz.getSimpleName()), clazz); else { for(Entry<String, JsonElement> key : o.entrySet()) { obj = walkJsonStructure(clazz, key.getValue()); if(obj != null) break; } } } return obj; } }
true
180f619ccbf811f7526b8a5a9ecefb7aaaec6ab3
Java
yangjiahao199853/demo
/src/main/java/com/example/demo/entity/Book.java
UTF-8
845
2.015625
2
[]
no_license
package com.example.demo.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableLogic; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.enums.IdType; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data @TableName("book") public class Book { @TableId(value = "id",type = IdType.AUTO) private Long bookId; @TableField(value = "book_Name") private String bookName; private String author; private BigDecimal price; @TableField(value = "publish_Time") private Date publishTime; @TableField(value = "update_Time") private Date updateTime; @TableField(value = "booksize") private Long bookSize; private String smallImg; }
true
8db7320f0a3b1df83f88b3a779d26216ddd2486d
Java
anamn/APS-2.0
/Aps-2.0/src/br/com/aps/consequencia/DesperdicioDeAgua.java
ISO-8859-1
990
2.875
3
[]
no_license
package br.com.aps.consequencia; public class DesperdicioDeAgua extends Consequencias { public String escovarOsDentes() { return "\nSe voc escovar os dentes 3 vezes ao dia como recomandado fechando sua toneira gastaria cerca de 1.5l, e caso no feche a torneira gastaria 36l.\nEconomize feche escove aps as refeies e feche a torneira"; } public String banho() { return "\nAo tomar banhos longos voc pode chegar a gastar 135 litros de gua por banho, se tomar banho por 5min gastaria aproximadamente 45l\nEconomize tome banho mais de uma vez s quando necessario e em um espao de tempo curto"; } public String lavarLouca() { return "\nAo lavar a loua com a torneira ligada constantemente por 15 minutos, voc gasta cerca de 117 litros de gua, o que pode ser reduzido para apenas 20 litros se voc economizar. Experimente primeiro limpar os restos de comida dos pratos e panelas sem o uso da gua e aps isso, abra a torneira para molh-los. "; } }
true
26c3335960a811c5850b78e0d5bf4f7e526f059b
Java
NationalFortune/thisguys614
/src/main/java/com/pro/controller/ProductsDetails.java
UTF-8
3,861
2.21875
2
[]
no_license
package com.pro.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.pro.dao.CategoryDAO; import com.pro.dao.ProductDAO; import com.pro.entity.Category; import com.pro.entity.Product; @Controller @RequestMapping("/admin") public class ProductsDetails { @Autowired ProductDAO daoProd; @Autowired CategoryDAO daoCate; @ModelAttribute("availables") public Map<Boolean, String> getAvailable(){ Map<Boolean, String> map = new HashMap<>(); map.put(true, " Available"); map.put(false, " Not Available"); return map; } @ModelAttribute("categories") public List<Category> getCategories(){ List<Category> list = daoCate.findAll(); return list; } @RequestMapping("/product") public String product( Model model, @RequestParam("p") Optional<Integer> p, @ModelAttribute("prod") Product product ) { model.addAttribute("TitlePage", "Products Page"); model.addAttribute("views", "/views/admin/ProductsDetails.jsp"); Sort sortCD = Sort.by(Direction.DESC,"createDate"); Pageable pageable = PageRequest.of(p.orElse(0), 5, sortCD); Page<Product> page = daoProd.findAll(pageable); model.addAttribute("page", page); return "/admin/index"; } @RequestMapping("/product/edit/{id}") public String edit(Model model, @PathVariable("id") Integer id, @RequestParam("p") Optional<Integer> p) { model.addAttribute("TitlePage", "Products Page"); model.addAttribute("views", "/views/admin/ProductsDetails.jsp"); Product product = daoProd.getById(id); model.addAttribute("prod", product); Sort sortCD = Sort.by(Direction.DESC,"createDate"); Pageable pageable = PageRequest.of(p.orElse(0), 5, sortCD); Page<Product> page = daoProd.findAll(pageable); model.addAttribute("page", page); return "/admin/index"; } @RequestMapping(value = "/product/save", method = RequestMethod.POST) public String save( Model model, @Validated @ModelAttribute("prod") Product item, BindingResult result) { if(result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); System.out.println("message err: " + errors.get(0).getDefaultMessage()); model.addAttribute("errors", errors); return "redirect:/admin/product"; }else { if(item.getId() != null) { daoProd.save(item); return "redirect:/admin/product/edit/" + item.getId(); }else { daoProd.save(item); return "redirect:/admin/product"; } } } @RequestMapping(value = "/product/clear", method = RequestMethod.POST) public String clear(Model model) { Product product = new Product(); model.addAttribute("prod", product); return "redirect:/admin/product"; } @RequestMapping("/product/delete/{id}") public String delete(@PathVariable("id") Product product) { // daoProd.deleteById(id); daoProd.delete(product); return "redirect:/admin/product"; } }
true
b805581fc8e1a1c2a7e118f744798a502b80c01b
Java
PPFei5Zhou/base
/src/main/java/com/easy/base/config/security/CustomAuthenticationProvider.java
UTF-8
2,214
2.28125
2
[ "MIT" ]
permissive
package com.easy.base.config.security; import com.easy.base.service.impl.user.UserService; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Component public class CustomAuthenticationProvider implements AuthenticationProvider { @Resource private UserService userService; @Resource private HttpServletRequest request; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); CustomWebAuthenticationDetails customWebAuthenticationDetails = (CustomWebAuthenticationDetails) authentication.getDetails(); String verifyCode = customWebAuthenticationDetails.getVerifyCode(); if (!validateVerify(verifyCode)) { throw new DisabledException("验证码输入错误"); } UserDetails userDetails = userService.loadUserByUsername(username); if (!userDetails.getPassword().equals(password)) { throw new BadCredentialsException("账号或密码错误"); } return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()); } @Override public boolean supports(Class<?> aClass) { return aClass.equals(UsernamePasswordAuthenticationToken.class); } private boolean validateVerify(String verifyCode) { String validateCode = ((String) request.getSession().getAttribute("validateCode")).toLowerCase(); verifyCode = verifyCode.toLowerCase(); return validateCode.equals(verifyCode); } }
true
fb0b079dedae545cb78989f32ca060f14279b603
Java
ivanaborisavljevic/servlet-zadatak
/src/main/java/engineering/it/web/servletzadatak/model/Manufacturer.java
UTF-8
2,290
2.6875
3
[]
no_license
package engineering.it.web.servletzadatak.model; public class Manufacturer { private long PIB; private long companyNumber; private String name; private String address; private City city; public Manufacturer() { // TODO Auto-generated constructor stub } public Manufacturer(long PIB, String address, long companyNumber, String name, City city) { super(); this.PIB = PIB; this.address = address; this.companyNumber = companyNumber; this.name = name; this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public long getPIB() { return PIB; } public void setPIB(long pIB) { PIB = pIB; } public long getCompanyNumber() { return companyNumber; } public void setCompanyNumber(long companyNumber) { this.companyNumber = companyNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } @Override public String toString() { return "Manufacturer [PIB=" + PIB + ", companyNumber=" + companyNumber + ", name=" + name + ", city=" + city + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (PIB ^ (PIB >>> 32)); result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((city == null) ? 0 : city.hashCode()); result = prime * result + (int) (companyNumber ^ (companyNumber >>> 32)); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Manufacturer other = (Manufacturer) obj; if (PIB != other.PIB) return false; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (city == null) { if (other.city != null) return false; } else if (!city.equals(other.city)) return false; if (companyNumber != other.companyNumber) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
true
ed4e2189e92647e3ed373667c6b1a60f7c7d4a09
Java
Julien-PRD/L3
/Semestre 2/Java/TP3/MotDansLeTitre.java
UTF-8
652
3.078125
3
[]
no_license
/** * @author LeNomDeLEtudiant * @version 0.1 : Date : Tue Jan 19 10:46:05 CET 2021 * */ public class MotDansLeTitre implements Selectionneur { private String mot = new String(); /** * Constructeur qui permet de rentrer un mot sous forme de chaine * de caratère * @param Une chaine de caractère */ public MotDansLeTitre(String s){ mot = s; } /** * On verifie qu'un mot spécifier dans le contructeur est * present dans le titre du document * @param Un document * @return True si le mot est present dans le titre, false sinon */ public boolean estSatisfaitPar(Document d){ return(d.getTitre().indexOf(mot)!=-1); } }
true
6a02a331753aa34e5dfd6a90e405cab59b97c0fb
Java
soldiers1989/comsui
/bridgewater-deduct/src/test/java/com/suidifu/bridgewater/controller/post/BaseApiTestPost.java
UTF-8
1,729
1.859375
2
[]
no_license
package com.suidifu.bridgewater.controller.post; import java.util.HashMap; import java.util.Map; import com.suidifu.bridgewater.api.util.ApiSignUtils; /** * 贷后接口测试用 * @author zhanghongbing * */ public class BaseApiTestPost { private static final String TEST_MERCHANT_CREATE_SQL = "INSERT INTO `t_merchant_config` (`id`, `mer_id`, `secret`, `company_id`, `pub_key_path`, `pub_key`) VALUES (1, 't_merchant', '150e28698dcc8b689198f96b54b2e95a', 1, NULL, 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDl1BjinRJLLDiNc6jcOKW+nph9aNSWMaKMk0OxTdSATakyS7rwNxrLMFyJLkI9IpnHussBv1zgsHPUdZeRcHDkbcMdhYoRgpe3gZIVMJ09BMBjhAET4fensvk377L0Whzp+u9r9UxIWowH7YJuJe3yQ7R3RgYxzrPuTJYq/WeuUQIDAQAB');"; //** 本地测试用 **//* public static final String QUERY_URL_TEST = "http://127.0.0.1:9090/api/query"; public static final String MODIFY_URL_TEST = "http://127.0.0.1:9090/api/modify"; public static final String COMMAND_URL_TEST = "http://127.0.0.1:9090/api/command"; /** 测试发布用 **/ /* public static final String QUERY_URL_TEST = "http://yunxin.zufangbao.cn/api/query"; public static final String MODIFY_URL_TEST = "http://yunxin.zufangbao.cn/api/modify"; public static final String COMMAND_URL_TEST = "http://yunxin.zufangbao.cn/api/command";*/ public static final String TEST_MERID = "t_test_zfb"; public static final String TEST_SECRET = "123456"; /** t_merchant的私钥 **/ public String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOXUGOKdEkssOI1zqNw4pb6emH1o1JYxooyTQ7FN1IBNqTJLuvA3GsswXIkuQj0imce6ywG/XOCwc9R1l5FwcORtwx2FihGCl7eBkhUwnT0EwGOEARPh96ey+TfvsvRaHOn672v1TEhajAftgm4l7fJDtHdGBjHOs+5Mlir9Z65RAgMBAAECgYEArtAiUZR5yrYLGgTEhyWLZK+Le7CWKtv8MQL+tUlm/mST8s7JlVfEyJKzgCCwf4HnCJXbPiwJgFqW8B61uAmXw6cEoPftEnzvKBTyISt/iEf7DTWKGkDBnlYM9sFU6pU61jw17XEDQRtSBG6cfrlGSelqf25+c8onxu4YwTeLH/ECQQD/H69tPy0FYRvCJ5yXdXEVCKshNN01P+UdDzGtyysE/gmpalbewT+uznApa0qFntcYb8eSpUJzrUlItSCBGUpdAkEA5p4r3qF+4g5V7MBHm3+v1l9JKxYK76990AQJa122rfkY2EEVuvU+8KIAQpVflu/HpDe8QH4mQZTsZj24Skt8hQJAL5j2vrgRqzZB2ohPY8aKcXUrkEdvmdaw5SoHh7gm74iBvvTS/j4ppnBnZqLYxXMsCCgaoNZqPnCvAnygctWIFQJAHm2KLkKyohLwJV+tUwgC5E8IMWYkJUHLYNHXiFICE2xFaesUeel313oYfLCGvzx9493yubOrSoXitw63rR3OnQJBALwGSnGYodmJB5k7un0X6LlO4nSu/+SX9lweloZ1AUg15IuCIYxHAFKwOtOJmx/eMcITaLq8l1qzZ907UXY+Mfs="; /** 用于测试私钥错误,验签名失败 **/ private String invalidPrivateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAN0yqPkLXlnhM+2H/57aHsYHaHXazr9pFQun907TMvmbR04wHChVsKVgGUF1hC0FN9hfeYT5v2SXg1WJSg2tSgk7F29SpsF0I36oSLCIszxdu7ClO7c22mxEVuCjmYpJdqb6XweAZzv4Is661jXP4PdrCTHRdVTU5zR9xUByiLSVAgMBAAECgYEAhznORRonHylm9oKaygEsqQGkYdBXbnsOS6busLi6xA+iovEUdbAVIrTCG9t854z2HAgaISoRUKyztJoOtJfI1wJaQU+XL+U3JIh4jmNx/k5UzJijfvfpT7Cv3ueMtqyAGBJrkLvXjiS7O5ylaCGuB0Qz711bWGkRrVoosPM3N6ECQQD8hVQUgnHEVHZYtvFqfcoq2g/onPbSqyjdrRu35a7PvgDAZx69Mr/XggGNTgT3jJn7+2XmiGkHM1fd1Ob/3uAdAkEA4D7aE3ZgXG/PQqlm3VbE/+4MvNl8xhjqOkByBOY2ZFfWKhlRziLEPSSAh16xEJ79WgY9iti+guLRAMravGrs2QJBAOmKWYeaWKNNxiIoF7/4VDgrcpkcSf3uRB44UjFSn8kLnWBUPo6WV+x1FQBdjqRviZ4NFGIP+KqrJnFHzNgJhVUCQFzCAukMDV4PLfeQJSmna8PFz2UKva8fvTutTryyEYu+PauaX5laDjyQbc4RIEMU0Q29CRX3BA8WDYg7YPGRdTkCQQCG+pjU2FB17ZLuKRlKEdtXNV6zQFTmFc1TKhlsDTtCkWs/xwkoCfZKstuV3Uc5J4BNJDkQOGm38pDRPcUDUh2/"; public Map<String, String> getIdentityInfoMap(Map<String, String> requestParams) { Map<String, String> headers = new HashMap<String, String>(); headers.put("merId", TEST_MERID); headers.put("secret", TEST_SECRET); String signContent = ApiSignUtils.getSignCheckContent(requestParams); String sign = ApiSignUtils.rsaSign(signContent, privateKey); headers.put("sign", sign); return headers; } }
true
0fbe9ea15c14ebb5b3144c7dd5e421fbed73214e
Java
rameshanupati/Latest_Scripts
/SampleGit/src/Sample.java
UTF-8
396
1.648438
2
[]
no_license
/** * */ /** * @author aramesh * */ public class Sample { /** * @param args * * */ public void temp() { } private void display(){ // TODO Auto-generated method stub } private void hello() { // TODO Auto-generated method stub } public static void main(String[] args) { // TODO Auto-generated method stub } }
true
bd99fe435d5e892e9ac87c657c201d3560018bca
Java
97jorx/java-practicas
/TAREAS/T096-BOLETIN/src/Cifraca.java
UTF-8
1,531
3.015625
3
[]
no_license
public class Cifraca { private String s1; private String s2; private String s3; private String s4; private String s5; private int numero; public Cifraca(int numero){ } public String numero(int n) { switch(n){ case 0: s1 = "\u2b1b\u2b1b\u2b1b\u2b1b\u2b1b"; s2 = "\u2b1b\u2b1c\u2b1c\u2b1c\u2b1b"; s3 = "\u2b1b\u2b1c\u2b1c\u2b1c\u2b1b"; s4 = "\u2b1b\u2b1c\u2b1c\u2b1c\u2b1b"; s5 = "\u2b1b\u2b1b\u2b1b\u2b1b\u2b1b"; return case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; case 6: break; case 7: break; case 8: break; case 9: break; default: assert false : "Error : error inesperado"; } return null; } public String getS1() { return s1; } public String getS2() { return s2; } public String getS3() { return s3; } public String getS4() { return s4; } public String getS5() { return s5; } @Override public String toString() { return s1+""+s2+""+s3+""+s4+""+s5; } }
true
957c3afef89c6b6adadba7366017ec954d0f311c
Java
sycoumba/tpspringbootsenforage
/src/main/java/sn/senforage/dao/IUser.java
UTF-8
595
1.976563
2
[]
no_license
package sn.senforage.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import sn.senforage.entities.Roles; import sn.senforage.entities.User; @Repository public interface IUser extends JpaRepository<User,Integer>{ @Query("SELECT u FROM User u WHERE u.email=:email AND u.password=:password") public User getUserByEmailAndPasswordUser(@Param(value ="email")String email,@Param(value ="password")String password); }
true
546221a98124428a98e1e186313546293c7995c7
Java
Drakesdrs/Gavhack
/src/main/java/me/gavin/gavhack/setting/BooleanSetting.java
UTF-8
222
2.171875
2
[]
no_license
package me.gavin.gavhack.setting; public class BooleanSetting extends Setting { public boolean value; public BooleanSetting(String name, boolean value) { super(name); this.value = value; } }
true
2363eae8e3dc46adee4d2c2a8692f60534bdc783
Java
alvinjo/AccountProject
/src/main/java/business/Service.java
UTF-8
715
2
2
[]
no_license
package business; import persistence.repository.AccountDBRepo; import persistence.repository.IAccountDB; import javax.inject.Inject; public class Service { @Inject private IAccountDB repo; public Service(){ } public String getAllAccounts(){ return repo.getAllAccounts(); } public String createAccount(String account) { return repo.createAccount(account); } public String deleteAccount(String accNum){ return repo.deleteAccount(accNum); } public String updateAccount(String account){ return repo.updateAccount(account); } public String getAccountById(String accNum){ return repo.getAccountById(accNum); } }
true
22a84d4db0e87cf6b58ee4baac04e74aa9029568
Java
Kast0rTr0y/ao-plugin
/activeobjects-dbex/src/main/java/com/atlassian/dbexporter/node/NodeStreamReader.java
UTF-8
915
2.453125
2
[ "Apache-2.0" ]
permissive
package com.atlassian.dbexporter.node; import java.io.Closeable; /** * Provides streaming read access to a node graph. * * @author Erik van Zijst */ public interface NodeStreamReader extends Closeable { /** * Returns the root node of the object tree. The method can only be invoked * once. Subsequent calls will raise an {@link IllegalStateException}. * * @return the root node of the graph. * @throws IllegalStateException when the root node has already been * returned. * @throws com.atlassian.dbexporter.ImportExportException when the document could not be parsed. */ NodeParser getRootNode() throws IllegalStateException; /** * Closes all resources of the underlying document. * * @throws com.atlassian.dbexporter.ImportExportException */ void close(); }
true
fca0d3e3a776aad1ee14cb5de9364f1366721450
Java
marcos-s1/Estrutura-de-dados
/Clube_da_luta/src/clube_da_luta/Pessoa.java
UTF-8
1,364
2.59375
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 clube_da_luta; /** * * @author manto */ public abstract class Pessoa { private String titulo; private String nome; private String nacionalidade; private int idade; private float altura; private float peso; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getNacionalidade() { return nacionalidade; } public void setNacionalidade(String nacionalidade) { this.nacionalidade = nacionalidade; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public float getAltura() { return altura; } public void setAltura(float altura) { this.altura = altura; } public float getPeso() { return this.peso; } public void setPeso(float peso) { this.peso = peso; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } }
true
5289211eb089fbbce3899e60590d24a8d94f65c2
Java
yliang138/MyProjects
/MyJsonParser/src/com/example/myjsonparser/MainActivity.java
UTF-8
2,481
2.1875
2
[]
no_license
package com.example.myjsonparser; import java.util.List; import android.app.ListActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class MainActivity extends ListActivity implements OnJsonParserCompleteListener { private YahooNewsJsonParser mParser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mParser = (YahooNewsJsonParser) getLastNonConfigurationInstance(); if (mParser != null) { mParser.setListener(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: refreshNews(); return true; default: return super.onOptionsItemSelected(item); } } private void refreshNews() { mParser = JsonParserFactory.getNewParser(); mParser.setListener(this); mParser.start(Contract.NEWS_JSON_FEED); } @Override public void onJsonParserCompleted(final List<YahooNews> data) { // SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), // data, android.R.layout.simple_list_item_1, from, to) if (data != null) { setListAdapter(new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(MainActivity.this).inflate( android.R.layout.simple_list_item_1, parent, false); } ((TextView) convertView).setText(data.get(position) .toString()); return convertView; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public Object getItem(int position) { return data.get(position); } @Override public int getCount() { return data.size(); } }); } } @Override public Object onRetainNonConfigurationInstance() { return mParser; } @Override protected void onDestroy() { super.onDestroy(); if (mParser != null) { mParser.setListener(null); } } @Override public void onProgressUpdate(int progress) { // TODO Auto-generated method stub } }
true
c5e3561190eb2c5286d6f7dd1becf5da9eef1f84
Java
mrKyleWang/leetcode_practice
/src/map/RegionsCutBySlashes.java
UTF-8
3,831
3.71875
4
[]
no_license
package map; import org.junit.Assert; import org.junit.Test; /** * 959. 由斜杠划分区域 * @author KyleWang * @version 1.0 * @date 2021年01月25日 */ public class RegionsCutBySlashes { /* 在由 1 x 1 方格组成的 N x N 网格 grid 中,每个 1 x 1 方块由 /、\ 或空格构成。这些字符会将方块划分为一些共边的区域。 (请注意,反斜杠字符是转义的,因此 \ 用 "\\" 表示。)。 返回区域的数目。 示例 1: 输入: [   " /",   "/ " ] 输出:2 示例 2: 输入: [   " /",   " " ] 输出:1 示例 3: 输入: [   "\\/",   "/\\" ] 输出:4 示例 4: 输入: [   "/\\",   "\\/" ] 输出:5 示例 5: 输入: [   "//",   "/ " ] 输出:3 提示: 1 <= grid.length == grid[0].length <= 30 grid[i][j] 是 '/'、'\'、或 ' '。 */ @Test public void test() { String[] grid = {" /", "/ "}; Assert.assertEquals(2, regionsBySlashes(grid)); } @Test public void test2() { String[] grid = {" /", " "}; Assert.assertEquals(1, regionsBySlashes(grid)); } @Test public void test3() { String[] grid = {"\\/", "/\\"}; Assert.assertEquals(4, regionsBySlashes(grid)); } @Test public void test4() { String[] grid = {"/\\", "\\/"}; Assert.assertEquals(5, regionsBySlashes(grid)); } @Test public void test5() { String[] grid = {"//", "/ "}; Assert.assertEquals(3, regionsBySlashes(grid)); } /** * 将 mxm的矩阵分为(m+1)*(m+1)个节点: * 0 1 2 * 3 4 5 * 6 7 8 */ public int regionsBySlashes(String[] grid) { int m = grid.length; int[] parent = new int[(m + 1) * (m + 1)]; // 先将中间部分都置为未连接 for (int i = 1; i < m; i++) { for (int j = 1; j < m; j++) { int index = i * (m + 1) + j; parent[index] = index; } } int res = 1; for (int i = 0; i < m; i++) { char[] chars = grid[i].toCharArray(); for (int j = 0; j < m; j++) { char c = chars[j]; if (c == '/') { // 左下连右上 int ru = i * (m + 1) + j + 1; int ld = i * (m + 1) + j + m + 1; if (find(parent, ru) != find(parent, ld)) { union(parent, ru, ld); } else { res++; } } else if (c == '\\') { // 左上连右下 int lu = i * (m + 1) + j; int rd = i * (m + 1) + j + m + 2; if (find(parent, lu) != find(parent, rd)) { union(parent, lu, rd); } else { res++; } } } } return res; } private void union(int[] parent, int i, int j) { int pI = find(parent, i); int pJ = find(parent, j); if (pI != pJ) { parent[pJ] = pI; } } private int find(int[] parent, int i) { if (parent[i] != i) { parent[i] = find(parent, parent[i]); } return parent[i]; } }
true
badd6494d5f184be3aa2a4024cd5aafa5862ea1e
Java
Master-for-Rapscal/health1
/src/main/java/com/aaa/health/service/emerg/EmerGenciesServiceImpl.java
UTF-8
1,296
1.992188
2
[]
no_license
package com.aaa.health.service.emerg; import com.aaa.health.entity.area.Area; import com.aaa.health.entity.emerg.EmerGencies; import com.aaa.health.mapper.emerg.EmerGenciesMapper; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; @Service public class EmerGenciesServiceImpl implements EmerGenciesService{ @Resource private EmerGenciesMapper emerGenciesMapper; @Override public List<EmerGencies> findList(Map<String, Object> queryMap) { return emerGenciesMapper.findList(queryMap); } @Override public int getTotal(Map<String, Object> queryMap) { return emerGenciesMapper.getTotal(queryMap); } @Override public int add(EmerGencies emerGencies) { return emerGenciesMapper.add(emerGencies); } @Override public Map<String, Object> findById(Integer emgId) { return emerGenciesMapper.findById(emgId); } @Override public int update(EmerGencies emerGencies) { return emerGenciesMapper.update(emerGencies); } @Override public int delete(String ids) { return emerGenciesMapper.delete(ids); } @Override public List<Area> findArea() { return emerGenciesMapper.findArea(); } }
true
8e754e43d2e193b77fe3ffc53f3320b536de2c34
Java
oublalmed/StockFst
/src/projetfst/Produit.java
UTF-8
27,849
1.984375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetfst; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import projetfst.Fournisseur; import projetfst.Stock; /** * * @author Hp */ public class Produit extends javax.swing.JFrame { /** * Creates new form Produit */ public Produit() { initComponents(); RemplirComboStock(); RemplirComboFournisseur(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); ComboStock = new javax.swing.JComboBox(); IDProdTxt = new javax.swing.JTextField(); DesignationTxt = new javax.swing.JTextField(); RéferenceTxt = new javax.swing.JTextField(); PrixTxt = new javax.swing.JTextField(); RemiseTxt = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); AjouterProduit = new javax.swing.JButton(); SupprimerProduit = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); ChercherTxt = new javax.swing.JTextField(); ChercherProduit = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tab_Produit = new javax.swing.JTable(); ComboFourn = new javax.swing.JComboBox(); QteSTxt = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Produits"); setName("Produits"); // NOI18N jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 93, 936, -1)); jPanel1.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(45, 35, 940, -1)); jLabel1.setFont(new java.awt.Font("French Script MT", 1, 48)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Produits"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 40, 340, 50)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageProjet/icons8-product-50.png"))); // NOI18N jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(91, 37, -1, -1)); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("ID Produit"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 139, -1, -1)); jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Réference"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 191, -1, -1)); jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Designation"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 236, -1, -1)); jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Fournisseur"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 334, -1, -1)); jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Quantité "); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 480, -1, -1)); jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("Prix"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 380, -1, -1)); jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setText("Stock"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 285, -1, -1)); ComboStock.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jPanel1.add(ComboStock, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 279, 427, 28)); IDProdTxt.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jPanel1.add(IDProdTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 133, 427, 31)); DesignationTxt.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jPanel1.add(DesignationTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 230, 427, 31)); RéferenceTxt.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jPanel1.add(RéferenceTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 185, 427, 31)); PrixTxt.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jPanel1.add(PrixTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 374, 427, 31)); RemiseTxt.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jPanel1.add(RemiseTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 420, 427, 31)); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel2.setOpaque(false); jButton1.setBackground(new java.awt.Color(255, 255, 255)); jButton1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N jButton1.setText("Nouveau"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); AjouterProduit.setBackground(new java.awt.Color(255, 255, 255)); AjouterProduit.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N AjouterProduit.setText("Ajouter"); AjouterProduit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AjouterProduitActionPerformed(evt); } }); SupprimerProduit.setBackground(new java.awt.Color(255, 255, 255)); SupprimerProduit.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N SupprimerProduit.setText("Supprimer"); SupprimerProduit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SupprimerProduitActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(SupprimerProduit, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(AjouterProduit, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(AjouterProduit, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addComponent(SupprimerProduit, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(67, 67, 67) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(37, 37, 37)) ); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(715, 133, -1, -1)); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Chercher", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14), new java.awt.Color(255, 255, 255))); // NOI18N jPanel5.setOpaque(false); ChercherProduit.setBackground(new java.awt.Color(255, 255, 255)); ChercherProduit.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N ChercherProduit.setText("Chercher"); ChercherProduit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ChercherProduitActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap(175, Short.MAX_VALUE) .addComponent(ChercherTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(74, 74, 74) .addComponent(ChercherProduit, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChercherTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ChercherProduit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(15, 15, 15)) ); jPanel1.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 520, 936, -1)); tab_Produit.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID Produit", "Réference", "Designation", "Stock", "Quantité Stock", "Fournisseur", "Remise", "Prix" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); tab_Produit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tab_ProduitMouseClicked(evt); } }); jScrollPane1.setViewportView(tab_Produit); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 620, 936, 120)); ComboFourn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jPanel1.add(ComboFourn, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 328, 427, 28)); QteSTxt.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jPanel1.add(QteSTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 470, 427, 31)); jLabel11.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 255, 255)); jLabel11.setText("Remise"); jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 430, -1, -1)); jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageProjet/bg-5-full.jpg"))); // NOI18N jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, -6, 1030, 760)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed IDProdTxt.setText(""); PrixTxt.setText(""); RemiseTxt.setText(""); RéferenceTxt.setText(""); DesignationTxt.setText(""); QteSTxt.setText(""); ComboFourn.setSelectedIndex(0); ComboStock.setSelectedIndex(0); DefaultTableModel model =(DefaultTableModel) tab_Produit.getModel(); model.setRowCount(0); }//GEN-LAST:event_jButton1ActionPerformed private void AjouterProduitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AjouterProduitActionPerformed Connection cn; PreparedStatement ps; cn=connecter(); try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion"); } else { if(IDProdTxt.getText().equals("") || RéferenceTxt.getText().equals("") ||DesignationTxt.getText().equals("") || RemiseTxt.getText().equals("") || PrixTxt.getText().equals("") || QteSTxt.getText().equals("") ) {JOptionPane.showMessageDialog(this, "SVP entrer vos donneé"); } else{ ps = cn.prepareStatement("insert into produit values(?,?,?,?,?,?,?,?,?,?)"); ps.setString(1,IDProdTxt.getText()); ps.setString(2,RéferenceTxt.getText()); ps.setString(3,DesignationTxt.getText()); ps.setString(4,ComboStock.getSelectedItem().toString()); ps.setString(5,ComboFourn.getSelectedItem().toString()); ps.setString(6,RemiseTxt.getText()); ps.setString(7,PrixTxt.getText()); ps.setInt(8,ComboStock.getSelectedIndex()+1); ps.setInt(9,ComboFourn.getSelectedIndex()+1); ps.setString(10,QteSTxt.getText()); ps.executeUpdate(); ModifierStock(); JOptionPane.showMessageDialog(this, "L'ajout est fait avec succés"); }}}catch(Exception e){ JOptionPane.showMessageDialog(this, e); }//GEN-LAST:event_AjouterProduitActionPerformed } private void SupprimerProduitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SupprimerProduitActionPerformed Connection cn; PreparedStatement ps; cn=connecter(); try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion"); } else { int row = tab_Produit.getSelectedRow(); String value = (tab_Produit.getModel().getValueAt(row, 6).toString()); ps = cn.prepareStatement("delete from produit where idProduit="+value); ps.executeUpdate(); JOptionPane.showMessageDialog(this, "La suppression est fait avec succés"); ActualiserStock(); }}catch(Exception e){ JOptionPane.showMessageDialog(this, "NULL"); } }//GEN-LAST:event_SupprimerProduitActionPerformed private void ChercherProduitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ChercherProduitActionPerformed Connection cn; PreparedStatement ps; ResultSet rs; ArrayList<Products> listProduit =new ArrayList<>(); cn=connecter(); try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion");} else { ps=cn.prepareStatement("select idProduit,reference,designation,s.libelle,qteProduitStock,nomFournisseur,remise,prix from Produit p,stock s ,fournisseur f where p.idStock=s.idStock and p.idFournisseur=f.idFournisseur and reference like '%"+ChercherTxt.getText()+"%' ORDER BY p.idProduit ASC "); rs=ps.executeQuery(); Products produit; while(rs.next()) { produit= new Products(rs.getInt("idProduit"),rs.getString("reference"),rs.getString("designation"),rs.getString("libelle"),rs.getInt("qteProduitStock"),rs.getString("nomFournisseur"),rs.getInt("remise"),rs.getInt("prix")); listProduit.add(produit); } } }catch(Exception e) {JOptionPane.showMessageDialog(this, e); } DefaultTableModel model=(DefaultTableModel) tab_Produit.getModel(); Object[] row = new Object[8]; for(int i=0;i<listProduit.size();i++) { row[0]=listProduit.get(i).getIdProduit(); row[1]=listProduit.get(i).getReferenceProduit(); row[2]=listProduit.get(i).getDesignationProduit(); row[3]=listProduit.get(i).getS(); row[4]=listProduit.get(i).getQte(); row[5]=listProduit.get(i).getF(); row[6]=listProduit.get(i).getRemise(); row[7]=listProduit.get(i).getPrix(); model.addRow(row); } }//GEN-LAST:event_ChercherProduitActionPerformed private void tab_ProduitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tab_ProduitMouseClicked int row = tab_Produit.getSelectedRow(); TableModel model = tab_Produit.getModel(); IDProdTxt.setText(model.getValueAt(row,0).toString()); RéferenceTxt.setText(model.getValueAt(row,1).toString()); DesignationTxt.setText(model.getValueAt(row,2).toString()); ComboFourn.setSelectedItem(model.getValueAt(row,5).toString()); PrixTxt.setText(model.getValueAt(row,7).toString()); RemiseTxt.setText(model.getValueAt(row,6).toString()); QteSTxt.setText(model.getValueAt(row,4).toString()); ComboStock.setSelectedItem(model.getValueAt(row,3).toString()); }//GEN-LAST:event_tab_ProduitMouseClicked public void RemplirComboStock(){ Connection cn; PreparedStatement ps; cn=connecter(); try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion"); } else { ps=cn.prepareStatement("select * from stock "); ResultSet rs=ps.executeQuery(); while(rs.next()) { ComboStock.addItem(rs.getString("libelle")); } } }catch(Exception Ex){} } public void RemplirComboFournisseur(){ Connection cn; PreparedStatement ps; cn=connecter(); try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion"); } else { ps=cn.prepareStatement("select * from fournisseur"); ResultSet rs=ps.executeQuery(); while(rs.next()) { ComboFourn.addItem(rs.getString("nomFournisseur")); } } }catch(Exception Ex){} } public void ModifierStock(){ Connection cn; PreparedStatement ps; cn=connecter(); int qteStock = 0; try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion"); } else { ps=cn.prepareStatement("select nbrProduit from Stock s ,produit p where s.idStock=p.idStock and p.idProduit="+IDProdTxt.getText()); ResultSet rs=ps.executeQuery(); while(rs.next()) { qteStock=rs.getInt("nbrProduit"); } int now=qteStock+Integer.parseInt(QteSTxt.getText()); ps =cn.prepareStatement("UPDATE produit,stock SET nbrProduit="+now +" where produit.idStock=stock.idstock and idProduit="+IDProdTxt.getText()); ps.executeUpdate(); } }catch(Exception Ex){} } public void ActualiserStock() { Connection cn; PreparedStatement ps; cn=connecter(); int qtePrdAct = 0,qteStock = 0; try{ if (cn==null){ JOptionPane.showMessageDialog(this, "Pas de connexion"); } else { ps=cn.prepareStatement("select nbrProduit ,qte from Stock s ,produit p ,vente v where s.idStock=p.idStock and v.idProduit=p.idProduit and v.idProduit="+IDProdTxt.getText()); ResultSet rs=ps.executeQuery(); while(rs.next()) { qtePrdAct =rs.getInt("qte"); qteStock=rs.getInt("nbrProduit"); } int now =qteStock - qtePrdAct ; ps =cn.prepareStatement("UPDATE produit,stock SET nbrProduit="+now +" where produit.idStock=stock.idstock and idProduit="+IDProdTxt.getText()); ps.executeUpdate(); } }catch(Exception Ex){ } } /** * @param args the command line arguments */ public Connection connecter(){ String url ="jdbc:mysql://localhost:3306/gestionmagasin?zeroDateTimeBehavior=convertToNull"; Connection cn; String user="root"; String password=""; try{ cn=DriverManager.getConnection(url,user,password); return cn; }catch(Exception Ex){ return null;} } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Produit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Produit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Produit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Produit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Produit().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton AjouterProduit; private javax.swing.JButton ChercherProduit; private javax.swing.JTextField ChercherTxt; private javax.swing.JComboBox ComboFourn; private javax.swing.JComboBox ComboStock; private javax.swing.JTextField DesignationTxt; private javax.swing.JTextField IDProdTxt; private javax.swing.JTextField PrixTxt; private javax.swing.JTextField QteSTxt; private javax.swing.JTextField RemiseTxt; private javax.swing.JTextField RéferenceTxt; private javax.swing.JButton SupprimerProduit; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTable tab_Produit; // End of variables declaration//GEN-END:variables }
true
ad73cf1936e0c68692f471cff374aeb76e6108be
Java
FairWindCo/SCDCommunication
/src/ua/pp/fairwind/communications/devices/hardwaredevices/dp5/DPSpectrumValueChanel.java
UTF-8
1,066
2.390625
2
[]
no_license
package ua.pp.fairwind.communications.devices.hardwaredevices.dp5; import ua.pp.fairwind.communications.propertyes.abstraction.ValueProperty; import ua.pp.fairwind.communications.propertyes.groups.GroupProperty; import ua.pp.fairwind.communications.propertyes.software.SoftIntegerProperty; /** * Created by Сергей on 01.12.2015. */ public class DPSpectrumValueChanel extends GroupProperty { public enum SpectrumSize{ chanel256(256), chanel512(512), chanel1024(1024), chanel2048(2048), chanel4096(4096), chanel8192(8192), special(20); private SpectrumSize(int size) { this.size = size; } private int size; public int getSize() { return size; } } public DPSpectrumValueChanel(SpectrumSize size,String name, String uuid) { super(name, uuid); for(int i=0;i<size.getSize();i++){ addProperty(new SoftIntegerProperty("Chanel #"+i, ValueProperty.SOFT_OPERATION_TYPE.READ_ONLY)); } } }
true
3efc5ac819a37bc0e874625d40007d77ed18bcfc
Java
dovilemika/laboratorinis2
/app/src/main/java/com/example/corona/Validation.java
UTF-8
2,433
2.65625
3
[]
no_license
package com.example.corona; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Validation { public static final String USERNAME_REGEX_PATTERN = "^[a-zA-Z0-9]{3,20}$"; //per static prieina; public turi buti, o ne private; ir final turi buti - final galutinis, nebekeicia; tai globalus kintamasis, nes yra klases viduje, o ne funkcijoje, jis bus visur matomas public static final String PASSWORD_REGEX_PATTERN = "^[a-zA-Z0-9.!@_]{5,20}$"; // "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$" // public static final String EMAIL_REGEX_PATTERN = "^[a-zA-Z0-9@._-]{10,50}$"; public static final String EMAIL_REGEX_PATTERN = "^[A-Za-z0-9._-]+@[A-Za-z0-9]+.[A-Za-z]{2,50}$"; //"^([a-z0-9._-]+){10,50}@([a-z0-9._-]+){2,10}.[a-z]{2,}$" - simbolių skaičių reikia nurodyti trijose vietose: iki @, tarp @ ir taškelio, ir po taškelio. //reikalauja įvesti @, kadangi ji nėra laužtinių skliaustų rėmuose. public static boolean isUsernameValid(String username){ //arba true (1), arba false (0); paima parametrus, kur skliausteliuose. Siuo atveju metoda aprasome, todel tarp skliaustu rasome tipa ir kintamojo pavadinima. Si eilute yra funkcijos antraste (dar vadinama prototipu) Pattern pattern = Pattern.compile(USERNAME_REGEX_PATTERN); //sukuriamos username validacijai taisyklės pagal nurodyta sablona; musu Stringas perduodamas bibliotekos tam tikram metodui, kuris pagal musu nurodytas tam stringui taisykles sukuria sablona Matcher matcher = pattern.matcher(username); //pagal anksciau sukurtas taisykles palyginami vartotojo ivesti duomenys (username); matcher - atitikimas. Tai kaip svarstykles - susikurta sablona sveriame su tuo, ka vartotojas ivede boolean isUsernameValid = matcher.find(); //jeigu atitinka, grazins true, jeigu ne - false return isUsernameValid; } public static boolean isPasswordValid(String password){ Pattern pattern = Pattern.compile(PASSWORD_REGEX_PATTERN); Matcher matcher = pattern.matcher(password); boolean isPasswordValid = matcher.find(); return isPasswordValid; } public static boolean isEmailValid(String email){ Pattern pattern = Pattern.compile(EMAIL_REGEX_PATTERN); Matcher matcher = pattern.matcher(email); boolean isEmailValid = matcher.find(); return isEmailValid; } }
true
7c7cb6aa4bed5ada48a2d3cbdec99d565fa2cdd3
Java
hasDevang/FRS-KNN-Spark
/uwt/knn/InMemoryKnnRows.java
UTF-8
1,543
2.75
3
[]
no_license
package uwt.knn; import java.util.Arrays; import java.util.List; public class InMemoryKnnRows { double[] numericAttrs; //double[][] attributes; int rowCount = 0; KnnRow[] trainingSet; int numOfRows = 0; int[] rowIds, foldNo; String[] labels; public InMemoryKnnRows(KnnRow[] trainingSet) { this.trainingSet = trainingSet; numOfRows = trainingSet.length; KnnRow row = trainingSet[0]; int rowLength = row.getNumOfAttributes(); numericAttrs = new double[numOfRows * rowLength]; rowIds = new int[numOfRows]; foldNo = new int[numOfRows]; labels = new String[numOfRows]; //attributes = new double[numOfRows][row.getNumOfAttributes()]; for(KnnRow r:trainingSet) { addRow(r); } } public void addRow(KnnRow row) { rowIds[rowCount] = row.getId(); foldNo[rowCount] = row.getFoldNo(); labels[rowCount] = row.getLabel(); double[] attrs = row.getNumericAttributes(); int rowLength = attrs.length; numericAttrs[0+rowCount*rowLength] = row.getFoldNo(); //attributes[rowCount] = attrs; for(int i = 0; i<rowLength;i++) { numericAttrs[i+rowCount*rowLength] = attrs[i]; } rowCount++; } /*public double[][] getAttributes() { return attributes; }*/ public double[] getNumericAttrs() { return numericAttrs; } public int[] getRowIds() { return rowIds; } public int[] getFoldNo() { return foldNo; } public String[] getLabels() { return labels; } public int getNumOfRows() { return numOfRows; } public KnnRow[] getTrainingSet() { return trainingSet; } }
true
356c1a7e0c4a3bb88ea78fbb13e2673ea6701119
Java
zhouyuan93/leetcode
/src/main/java/v1/t700/T715.java
UTF-8
2,552
3.015625
3
[]
no_license
package v1.t700; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 线段树 */ public class T715 { static class RangeModule { public RangeModule() { } public void addRange(int left, int right) { update(root, 1, N, left, right-1, 1); } public boolean queryRange(int left, int right) { return query(root, 1, N, left, right-1); } public void removeRange(int left, int right) { update(root, 1, N, left, right-1, -1); } class Node { Node left, right; boolean cover; int add; } private int N = (int) 1e9; private Node root = new Node(); private void pushUp(Node node) { node.cover = node.left.cover && node.right.cover; } private void pushDown(Node node, int leftNum, int rightNum) { if (node.left == null) { node.left = new Node(); } if (node.right == null) { node.right = new Node(); } if (node.add == 0) { return; } node.left.cover = node.add == 1; node.right.cover = node.add == 1; node.left.add = node.add; node.right.add = node.add; node.add = 0; } public void update(Node node, int start, int end, int l, int r, int val) { if (l <= start && end <= r) { node.cover = val == 1; node.add = val; return; } int mid = (start + end) >> 1; pushDown(node, mid - start + 1, end - mid); if (l <= mid) { update(node.left, start, mid, l, r, val); } if (r > mid) { update(node.right, mid + 1, end, l, r, val); } pushUp(node); } public boolean query(Node node, int start, int end, int l, int r) { if (l <= start && end <= r) { return node.cover; } int mid = (start + end) >> 1; pushDown(node, mid - start + 1, end - mid); boolean ans = true; if (l <= mid) { ans = ans && query(node.left, start, mid, l, r); } if (r > mid) { ans = ans && query(node.right, mid + 1, end, l, r); } return ans; } } }
true
2c897a8cd95a60ef9efeda5f55456114a106ffd7
Java
PedroHCT/Wild-Cats-Codes
/wild_cats_banco_de_dados/src/main/java/com/wildcats/project/ProjectApplication.java
UTF-8
1,538
2.09375
2
[]
no_license
package com.wildcats.project; import com.wildcats.project.entity.User; import com.wildcats.project.request.UserRequest; import com.wildcats.project.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.event.EventListener; import java.util.Optional; @Slf4j @SpringBootApplication public class ProjectApplication extends SpringBootServletInitializer { // private final UserService userService; // // public ProjectApplication(UserService userService) { // this.userService = userService; // } public static void main(String[] args) { SpringApplication.run(ProjectApplication.class, args); } // @EventListener(ApplicationReadyEvent.class) // public void addUser() { // Optional<User> user = userService.getUserById(1); // System.out.println(user); // System.out.println(user.isPresent()); // if (!user.isPresent()) { // UserRequest userRequest = new UserRequest(); // userRequest.setCpf("18070872047"); // userRequest.setEmail("iordan9663@uorak.com"); // userRequest.setLogin("iordan9663@uorak.com"); // userRequest.setName("Iordam Soarem Pacheco"); // userRequest.setPassword("Toor80085"); // userRequest.setPosition("Analista"); // userRequest.setRole("admin"); // userService.salvar(userRequest); // } else { // return; // } // } }
true
81cd3866e70396008b6085f5a8cfa789e3133d40
Java
Ilya-Shemanuev/code_exmpl
/src/main/java/steps/WebAsserts.java
UTF-8
556
2.09375
2
[]
no_license
package steps; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import pages.ExoElement; import static util.Utility.getDriver; public class WebAsserts { public static final Wait<WebDriver> WAIT = new WebDriverWait(getDriver(), 10); public static void waitForElement(ExoElement awaitedElement) { WAIT.until(ExpectedConditions.visibilityOfElementLocated(awaitedElement.getLocator())); } }
true
c7ff980b5c7a9d10282177768286132f56caec25
Java
JackFish/book-storage-practice
/apps/backend/security/src/main/java/kr/bookstorage/security/filter/StatelessLoginFilter.java
UTF-8
4,285
2.28125
2
[]
no_license
package kr.bookstorage.security.filter; import com.fasterxml.jackson.databind.ObjectMapper; import kr.bookstorage.domain.User; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by 권성봉 on 8/10/16. */ @Slf4j public class StatelessLoginFilter extends AbstractAuthenticationProcessingFilter { private AuthenticationProvider customAuthProvider; public StatelessLoginFilter(String defaultFilterProcessesUrl, AuthenticationProvider customAuthProvider) { super(defaultFilterProcessesUrl); this.customAuthProvider = customAuthProvider; } // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { // response.setHeader("Access-Control-Allow-Origin", "*"); // response.setHeader("Access-Control-Allow-Methods", "*"); // response.setHeader("Access-Control-Allow-Headers", "*"); // response.setStatus(HttpServletResponse.SC_OK); // } else { // chain.doFilter(req, res); // } // /*if(requestMatcher.matches(request)){ // final UserDto.SocialLogin socialLogin = objectMapper.readValue(req.getInputStream(), UserDto.SocialLogin.class); // log.debug("Social Param : {}", socialLogin); // // HttpServletRequestHelper requestWrapper = new HttpServletRequestHelper(request); // // String uri = request.getRequestURI(); // int pathParamIndex = uri.indexOf(';'); // // if (pathParamIndex > 0) { // // strip everything after the first semi-colon // uri = uri.substring(0, pathParamIndex); // } // // // uri must start with context path // uri = uri.substring(request.getContextPath().length()); // // String filterProcessUrl = FILTER_PROCESS_URL.replace("*//**", "").replace("*//*", "").replace("*", ""); // // log.debug("filterProcessUrl : {}", filterProcessUrl); // // uri = uri.substring(filterProcessUrl.length()); // log.debug("uri : {}", uri); // // if(uri.startsWith("/")){ // requestWrapper.setParameter("providerId", uri.substring(1)); // } // // if(socialLogin.getExpiresIn() != 0){ // requestWrapper.setParameter("expiresIn", String.valueOf(socialLogin.getExpiresIn())); // } // // requestWrapper.setParameter("accessToken", socialLogin.getAccessToken()); // requestWrapper.setParameter("refreshToken", socialLogin.getRefreshToken()); // // if(socialLogin.isRememberMe()){ // requestWrapper.setParameter("remember-me", "yes"); // } // super.doFilter(requestWrapper, res, chain); // }else{ // super.doFilter(req, res, chain); // }*/ // } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { final User user = new ObjectMapper().readValue(request.getInputStream(), User.class); log.debug("StatelessLoginFilter User Email : {}", user.getEmail()); final UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()); return customAuthProvider.authenticate(userToken); } }
true
272f0e95fc2810d67b47501d34a851c04b5ce4be
Java
chanwoong528/codingTestPrep
/src/backtracking/Main9663.java
UTF-8
1,484
3.125
3
[]
no_license
package backtracking; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main9663 { public static int count; public static int n; public static boolean[][] board; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(br.readLine()); board = new boolean[n][n]; dfs(0); System.out.println(count); } public static void dfs(int start) { if (start == n) { count++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(board[i][j] ? 1 : 0); } System.out.println(); } System.out.println(); return; } for (int i = 0; i < n; i++) { if (canLand(start, i)) { board[i][start] = true; dfs(start + 1); board[i][start] = false; } } } public static boolean canLand(int x, int y) { for (int i = 0; i < n; i++) { if (i <= y && board[i][x] == true) { return false; } if (i <= x && board[y][i] == true) { return false; } if ((x + i < n && y + i < n) && (board[y + i][x + i] == true)) { return false; } if ((x - i >= 0 && y + i < n) && (board[y + i][x - i] == true)) { return false; } if ((x + i < n && y - i >= 0) && (board[y - i][x + i] == true)) { return false; } if ((x - i >= 0 && y - i >= 0) && (board[y - i][x - i] == true)) { return false; } } return true; } }
true
f816f1d79be5cd6da7a2993dd139def837dde101
Java
Ariah-Group/Continuity
/src/test/java/org/kuali/continuity/admin/dao/GenericAdminDAOTest.java
UTF-8
2,339
1.898438
2
[ "LGPL-2.0-or-later", "ICU", "CPL-1.0", "MPL-2.0", "Apache-2.0", "Plexus", "CDDL-1.0", "ECL-2.0" ]
permissive
// // Copyright 2011 Kuali Foundation, Inc. Licensed under the // Educational Community 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.opensource.org/licenses/ecl2.php // // 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.kuali.continuity.admin.dao; import java.util.List; import java.util.Set; import org.kuali.continuity.admin.domain.BaseAdminDomainObject; import org.kuali.continuity.admin.domain.BaseAdminOrderedDomainObject; import org.kuali.continuity.admin.service.GenericAdminService.GenericSortBy; import org.kuali.continuity.domain.SortByType; public class GenericAdminDAOTest extends AdminDAOTest { private GenericAdminDAOFactory factory; public void setFactory(GenericAdminDAOFactory factory) { this.factory = factory; } public void testInjection() throws Exception { System.out.println("DAO is " + this.factory.getClass().getName()); } @SuppressWarnings("unchecked") public void testGetGenericAdminList() throws Exception { Set<Class<? extends BaseAdminDomainObject>> refClasses = ((GenericAdminDAOFactoryImpl)this.factory).getDaoMap().keySet(); for (Class<? extends BaseAdminDomainObject> refClass : refClasses) { // this.doTestList(this.factory.getGenericAdminDAO(refClass).getListBySystemDomainId(PlanTestData.wellknown_institution)); System.out.println("----- " + refClass.getName() + " -----"); System.out.println(); try { // this.doTestList(this.factory.getGenericAdminDAO(refClass).getSubListBySystemDomainIdAndStartOrderNo(PlanTestData.wellknown_institution, 1)); SortByType sortBy = GenericSortBy.name; if (BaseAdminOrderedDomainObject.class.isAssignableFrom(refClass)) sortBy = GenericSortBy.orderNo; List list = this.factory.getGenericAdminDAO(refClass).getSortedListBySystemDomainId(29, sortBy, true); if (list != null && !list.isEmpty()) this.doTestList(list); } catch (Exception e) { e.printStackTrace(); } } } }
true
44bcb2c3b27f525d8cee67284b6331b536e6dba5
Java
hugezp/LaiHuiChuXingApi
/src/main/java/com/lhcx/model/PayActionType.java
UTF-8
393
2.40625
2
[]
no_license
package com.lhcx.model; public enum PayActionType { spending(0,"转出 "),income(1,"转入"),refund(2,"退款"),withdrawal(3,"提现"); private Integer value; private String message; private PayActionType(Integer value, String message) { this.value = value; this.message = message; } public Integer value() { return value; } public String message() { return message; } }
true
e26f01e69a83b0ff324d5b8ab70056e67a724026
Java
rohan-jha/DS_ALGO_PROBLEMS
/jha/ds/arrays/rotation/problems/HackerRankPerfTestTOBE_DEL_LATER.java
UTF-8
1,299
3.171875
3
[ "MIT" ]
permissive
package ds.arrays.rotation.problems; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class HackerRankPerfTestTOBE_DEL_LATER { public static void main(String[] args) throws Exception{ File f = new File("C:\\Users\\jharohan\\Desktop\\input.txt"); /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner s = new Scanner(f); int n = s.nextInt(); List<Integer>[] a = new ArrayList[n]; int numOfQueries = s.nextInt(); int lastAnswer = 0; for(int i=0;i<numOfQueries;i++){ if(1==s.nextInt()){ int seq = (s.nextInt()^lastAnswer)%n; if(null == a[seq]) a[seq] = new ArrayList<Integer>(); a[seq].add(s.nextInt()); }else if(2==s.nextInt()){ int seq = (s.nextInt()^lastAnswer)%n; if(null != a[seq]){ lastAnswer=a[seq].get(s.nextInt()%a[seq].size());} System.out.println(lastAnswer); } } s.close(); } static void reverseSubArray(int arr[], int i, int j){ if(i>=j) return; for(;i<j;i++,j--){ int temp = arr[i]; arr[i]=arr[j]; arr[j]=temp; } } }
true
6d220b6b572b16b71ca22ae6ef715cda0a754517
Java
iantal/AndroidPermissions
/apks/playstore_apps/com_ubercab/source/com/ubercab/motionstash/realtime/model/BarometerEventBufferInfo.java
UTF-8
1,401
2.09375
2
[ "Apache-2.0", "GPL-1.0-or-later" ]
permissive
package com.ubercab.motionstash.realtime.model; import com.ubercab.shape.Shape; @Shape public abstract class BarometerEventBufferInfo implements MotionStashEventBufferInfo { public BarometerEventBufferInfo() {} public static BarometerEventBufferInfo create(int paramInt1, int paramInt2, double paramDouble1, double paramDouble2, long paramLong1, long paramLong2, int paramInt3) { return new Shape_BarometerEventBufferInfo().setType(paramInt1).setVersion(paramInt2).setMinimumValue(paramDouble1).setMaximumValue(paramDouble2).setStartTime(paramLong1).setEndTime(paramLong2).setSampleCount(paramInt3); } public abstract long getEndTime(); public abstract double getMaximumValue(); public abstract double getMinimumValue(); public abstract int getSampleCount(); public abstract long getStartTime(); public abstract int getType(); public abstract int getVersion(); abstract BarometerEventBufferInfo setEndTime(long paramLong); abstract BarometerEventBufferInfo setMaximumValue(double paramDouble); abstract BarometerEventBufferInfo setMinimumValue(double paramDouble); abstract BarometerEventBufferInfo setSampleCount(int paramInt); abstract BarometerEventBufferInfo setStartTime(long paramLong); abstract BarometerEventBufferInfo setType(int paramInt); abstract BarometerEventBufferInfo setVersion(int paramInt); }
true
fa2f56246beddf4c3396803749ada2a347f231c9
Java
QuadFlask/caffeineoverflow
/src/main/flask/utils/FlaskUtil.java
UTF-8
26,909
2.78125
3
[]
no_license
package main.flask.utils; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; /** * * @author Flask * */ public final class FlaskUtil { public final static double RAD = 180 / Math.PI; public final static double inverseRAD = Math.PI / 180; public final static Vec2D Zpoint = new Vec2D(0, 0); public final static Color[] COLOR_BLACK2WHITE = { new Color(0x000000), new Color(0xffffff) }; public final static Color[] COLOR_WHITE2BLACK = { new Color(0xffffff), new Color(0x000000) }; public final static Color[] COLOR_FIRE = { new Color(0xff0000), new Color(0xffff00), new Color(0xffffff) }; public final static Color[] COLOR_FIRE_ALPHA = { new Color(0), new Color(0xff880000), new Color(0x88ff0000), new Color(0xccffff00), new Color(0xffffffff) }; public final static Color[] COLOR_FIRE_INVERSE = { new Color(0xffffff), new Color(0xffff00), new Color(0xff0000) }; public final static Color[] COLOR_BLUE_FIRE = { new Color(0x0000ff), new Color(0x00ffff), new Color(0xffffff) }; public final static Color[] COLOR_BLUE_FIRE_INVERSE = { new Color(0xffffff), new Color(0x00ffff), new Color(0x0000ff) }; public final static Color[] COLOR_RAINBOW = { new Color(0xff0000), new Color(0xffff00), new Color(0x00ff00), new Color(0x00ffff), new Color(0x0000ff), new Color(0xff00ff) }; public final static Color[] COLOR_RAINBOW_INVERSE = { new Color(0xff00ff), new Color(0x0000ff), new Color(0x00ffff), new Color(0x00ff00), new Color(0xffff00), new Color(0xff0000) }; public final static Color[] COLOR_RAINBOW_REDEND = { new Color(0xff0000), new Color(0xffff00), new Color(0x00ff00), new Color(0x00ffff), new Color(0x0000ff), new Color(0xff00ff), new Color(0xff0000) }; public final static Color[] COLOR_RAINBOW_REDEND_INVERSE = { new Color(0xff0000), new Color(0xff00ff), new Color(0x0000ff), new Color(0x00ffff), new Color(0x00ff00), new Color(0xffff00), new Color(0xff0000) }; public final static void trace(Object... args) { int i = 0, l = args.length - 1; for (; i < l; i++) { System.out.print(args[i] + ", "); } System.out.println(args[l]); } public final static double linearInterpolate(double from, double to, double t) { if (t >= 1) return from; else if (t <= 0) return to; return (to - from) * t + from; } public final static float linearInterpolate(float from, float to, float t) { if (t >= 1) return from; else if (t <= 0) return to; return (to - from) * t + from; } public final static Vec2D linearInterpolate(Vec2D from, Vec2D to, double t) { if (t >= 1) t = 1; else if (t <= 0) t = 0; Vec2D v = new Vec2D(); v.x = linearInterpolate(from.x, to.x, t); v.y = linearInterpolate(from.y, to.y, t); return v; } /** * ������ƽ �Լ�(S-Line) * * @param $step * : logistic ���� ���� [0, 1] * @param $from * : ó���� * @param $to * : ������ �� * @return : logistic �Լ� ���԰� */ public final static double logistic(double $step, double $from, double $to) { double gap = $to - $from; double v = 1 / (1 + Math.exp(-$step)); // (0~1) double resultv = $from + gap * v; return resultv; } /** * ������ƽ �Լ�(S-Line) : (0~1) ����ȭ * * @param $n * : ���� ���� * @return : ���� logistic�Լ��� */ public final static double unit_logistic(double $n) { double v; v = 1 / (1 + Math.exp(-8 * ($n - .5))); // (0~1) -> (0~1) if (v < 0) v = 0; else if (v > 1) v = 1; return v; } /** * ���巯ƽ ������ �Լ� * * @param t * : ���� * @param B * : Ŀ�� ����Ʈ * @return : ������ � �� */ public final static Vec2D unit_Quadratic_Bezier(double t, Vec2D B) { if (t < 0 || t > 1) return null;//throw new Error("t must in [0, 1] : + bezier_curve()"); t *= 2; Vec2D _B = new Vec2D(B.x, B.y); Vec2D P = new Vec2D(); Vec2D Unitpoint = new Vec2D(1, 1); if (t < 1) { P.x = (1 - t * t) * Zpoint.x + 2 * t * (1 - t) * B.x + t * t * Unitpoint.x; P.y = (1 - t * t) * Zpoint.y + 2 * t * (1 - t) * B.y + t * t * Unitpoint.y; } else { t = t - 1; _B.x = 1 - B.x; _B.y = 1 - B.y; P.y = 1 + (1 - t * t) * Zpoint.x + 2 * t * (1 - t) * _B.y + t * t * Unitpoint.x; P.x = 1 + (1 - t * t) * Zpoint.y + 2 * t * (1 - t) * _B.x + t * t * Unitpoint.y; } return P; } /** * ���п� ���� ��Ī�� ��� * * @param A * : ���� l �� ���� �� * @param B * : ���� l �� �ٸ��� �� * @param p * : ��Ī�� �� * @param intersection * : ������ ���Ұ����� * @return : ��Ī�� ��� */ public final static Vec2D getAxialSymmetry(Vec2D A, Vec2D B, Vec2D p, boolean intersection) { Vec2D at = new Vec2D(); double diff_x, diff_y; diff_x = A.x - B.x; diff_y = A.y - B.y; //175, 95 double l_a = diff_y / diff_x; double l_b = A.y - (l_a * A.x); // double lp_a = -1 / l_a; // double lp_b = p.y - (lp_a * p.x); at.x = (p.x + l_a * p.y - l_a * l_b) / (l_a * l_a + 1); at.y = l_a * (p.x + l_a * p.y - l_a * l_b) / (l_a * l_a + 1) + l_b; if (intersection) return at; diff_x = p.x - at.x; diff_y = p.y - at.y; at.x = at.x - diff_x; at.y = at.y - diff_y; return at; } //�����߽� ���ϱ� - Center of Mass /** * * @param p0 * : ����Ʈ0 * @param p1 * : ����Ʈ1 * @return : �� ������ ���� */ public final static Vec2D getMidPoint(Vec2D p0, Vec2D p1) { return new Vec2D((p0.x + p1.x) / 2, (p0.y + p1.y) / 2); } /** * * @param p0 * @param p1 * @param i * @return : n ���� ���� ����Ʈ */ private final static Vec2D getNdivedPoint(Vec2D p0, Vec2D p1, int i) { Vec2D v = new Vec2D(p1.x - p0.x, p1.y - p0.y); return new Vec2D(p0.x + (int) (v.x / i), p0.y + (int) (v.y / i)); } /** * �����߽� ã�� * * @param pointList * : �ٰ����� ����Ʈ ����Ʈ * @return : �����߽� */ public final static Vec2D getCenterOfMass(Vec2D[] pointList) { int i = 2; int L = pointList.length; Vec2D CofM = getMidPoint(pointList[0], pointList[1]); while (i < L) { CofM = getNdivedPoint(CofM, pointList[i], ++i); } return CofM; } public final static ArrayList getArrayFromTo(ArrayList arrlist, int from, int to) { ArrayList result = new ArrayList(); int i = 0; int L = arrlist.size(); if (from <= to) { for (i = from; i <= to; i++) { result.add(arrlist.get(i)); } } else { for (i = from; i < L; i++) { result.add(arrlist.get(i)); } for (i = 0; i <= to; i++) { result.add(arrlist.get(i)); } } return result; } public final static double demicalTo(double number, int down) { return Math.floor(number * Math.pow(10, down)) / Math.pow(10, down); } public final static Vec2D getExtendedIntersection(Vec2D a1, Vec2D a2, Vec2D b1, Vec2D b2) { double f1 = (a2.y - a1.y) / (a2.x - a1.x); double f2 = (b2.y - b1.y) / (b2.x - b1.x); if (f1 == f2) return null; Vec2D inter = new Vec2D(); if (Double.isInfinite(f1)) { inter.x = a1.x; inter.y = f2 * inter.x + b1.y; return inter; } else if (Double.isInfinite(f2)) { inter.x = b1.x; inter.y = f1 * inter.x + a1.y; return inter; } else { inter.x = (f1 * a1.x + f2 * b1.x - a1.y + b1.y) / (f1 - f2); inter.y = f2 * inter.x + b1.y; return inter; } } public final static Vec2D getIntersection(Vec2D a1, Vec2D a2, Vec2D b1, Vec2D b2) { double f1 = (a2.y - a1.y) / (a2.x - a1.x); double f2 = (b2.y - b1.y) / (b2.x - b1.x); double g1 = a1.y - f1 * a1.x; double g2 = b1.y - f2 * b1.x; if (f1 == f2) return null; Vec2D inter; if (a1.x == a2.x) inter = new Vec2D(a1.x, f2 * a1.x + g2); else if (b1.x == b2.x) inter = new Vec2D(b1.x, f1 * b1.x + g1); else { inter = new Vec2D((g2 - g1) / (f1 - f2), 0); inter.y = f1 * inter.x + g2; } if (isRect(inter, a1, a2) && isRect(inter, b1, b2)) return inter; return null; } public final static boolean isRect(Vec2D a, Vec2D b, Vec2D c) { // [b, c] if (a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) return true; return false; } public final static double getArea(Vec2D s[]) { double area = 0; int i, L = s.length - 1; for (i = 0; i < L; i++) { area += s[i].x * s[i + 1].y; area -= s[i + 1].x * s[i].y; } area += s[L].x * s[0].y; area -= s[0].x * s[L].y; return Math.abs(area * 0.5); } //�ܽ� public final static Vec2D getCircumcenter(Vec2D a, Vec2D b, Vec2D c) { double f1 = (b.x - a.x) / (a.y - b.y); Vec2D m1 = new Vec2D((a.x + b.x) / 2, (a.y + b.y) / 2); double g1 = m1.y - f1 * m1.x; double f2 = (c.x - b.x) / (b.y - c.y); Vec2D m2 = new Vec2D((b.x + c.x) / 2, (b.y + c.y) / 2); double g2 = m2.y - f2 * m2.x; if (f1 == f2) return null; else if (a.y == b.y) return new Vec2D(m1.x, f2 * m1.x + g2); else if (c.y == b.y) return new Vec2D(m2.x, f1 * m2.x + g1); double x = (g2 - g1) / (f1 - f2); return new Vec2D(x, f1 * x + g1); } public final static Vec2D[] getTangentLineOfCircle2Point(Vec2D A, double r, Vec2D point) { //TODO this is not tested getTangentLineOfCircle2Circle(A, r, point, 0); // being test return null; } public final static Vec2D[] getTangentLineOfCircle2Circle(Vec2D A, double r, Vec2D B, double R) { Vec2D[] result = new Vec2D[4]; double dx = A.x - B.x; double dy = A.y - B.y; double a, t, d = Math.sqrt(dx * dx + dy * dy); t = Math.abs(d * d + (R - r) * (R - r)); if (r < R) { a = Math.sqrt(t + r * r); //a, R Vec2D[] temp = getIntersectionCircle2Circle(A, a, B, R); result[0] = temp[0]; result[1] = temp[1]; a = Math.sqrt(t + R * R); //r, a temp = getIntersectionCircle2Circle(B, a, A, r); result[2] = temp[0]; result[3] = temp[1]; } else if (r > R) { a = Math.sqrt(t + r * r); //a, R Vec2D[] temp = getIntersectionCircle2Circle(A, a, B, R); result[0] = temp[0]; result[1] = temp[1]; a = Math.sqrt(t + R * R); //r, a temp = getIntersectionCircle2Circle(A, r, B, a); result[2] = temp[0]; result[3] = temp[1]; } else if (r == R) { a = Math.sqrt(t + r * r); //a, R Vec2D[] temp = getIntersectionCircle2Circle(A, a, B, R); result[0] = temp[0]; result[1] = temp[1]; temp = getIntersectionCircle2Circle(A, r, B, a); result[2] = temp[1]; result[3] = temp[0]; } else { return null; } return result; } public final static double getDistance(Vec2D A, Vec2D B) { double dx = A.x - B.x; double dy = A.y - B.y; return Math.sqrt(dx * dx + dy * dy); } public final static Vec2D[] getIntersectionCircle2Circle(Vec2D A, double r, Vec2D B, double R) { Vec2D[] result; double d = getDistance(A, B); if (d == 0) { // ���� ��ħ -> �ȸ����ų� ������ ���Ѱ� return null; } else if (d > R + r) { // ������ ���� return null; } else if (d == R + r) { // ���� 1�� result = new Vec2D[1]; result[0] = new Vec2D(0.5 * (A.x + B.x), 0.5 * (A.y + B.y)); } else { // ���� 2�� result = new Vec2D[2]; double k = (r * r + d * d - R * R) / (2 * r * d); double th1 = Math.acos(k); if (k >= 1) { th1 = Math.acos(k - 1) + Math.PI / 2; } if (th1 > Math.PI / 2) th1 = Math.PI - th1; double th = Math.acos((B.x - A.x) / d); if (B.x - A.x < 0) th = Math.PI - th; if (B.x - A.x <= 0 && B.y - A.y >= 0) th = Math.PI - th; else if (B.x - A.x <= 0 && B.y - A.y <= 0) th = Math.PI + th; else if (B.x - A.x >= 0 && B.y - A.y <= 0) th = 2 * Math.PI - th; result[0] = new Vec2D(A.x + r * Math.cos(th - th1), A.y + r * Math.sin(th - th1)); result[1] = new Vec2D(A.x + r * Math.cos(th + th1), A.y + r * Math.sin(th + th1)); } return result; } public final static void swap(Object obj0, Object obj1, Object temp) { temp = obj0; obj0 = obj1; obj0 = temp; } private final static int partition(int[] list, int left, int right) { int pivot, temp = 0; int low = left; int high = right - 1; pivot = list[left]; do { do { low++; } while (low <= right && list[low] > pivot); do { high--; } while (high >= left && list[high] > pivot); if (low < high) swap(list[low], list[high], temp); } while (low < high); swap(list[left], list[high], temp); return high; } // public final static quick_sort(Object list, left, right) { // if (left < right) { // var q:int = partition(list, left, right); // quick_sort(list, left, q - 1); // quick_sort(list, q+1, right); // } // } public final static void angular_sort(Vec2D[] plist) { int i = 0; int j = 0; int L = plist.length; Vec2D avgP = new Vec2D(0, 0); double[] qlist = new double[L]; double[] qlist_copy = new double[L]; Vec2D[] resultarr = new Vec2D[L]; for (i = 0; i < L; i++) { avgP.x += plist[i].x; avgP.y += plist[i].y; } avgP.multiply(1 / L); for (i = 0; i < L; i++) { qlist[i] = Math.atan2(plist[i].y - avgP.y, plist[i].x - avgP.x); } System.arraycopy(qlist, 0, qlist_copy, 0, L); Arrays.sort(qlist_copy); for (i = 0; i < L; i++) { for (j = 0; j < L; j++) { if (qlist_copy[i] == qlist[j]) { resultarr[i] = plist[j]; } } } System.arraycopy(resultarr, 0, plist, 0, L); // for (i = 0; i < L; i++) { // plist[i] = resultarr[i]; // } } public final static void angular_sort(Point[] plist) { int i = 0; int j = 0; int L = plist.length; Point avgP = new Point(); double[] qlist = new double[L]; double[] qlist_copy = new double[L]; Point[] resultarr = new Point[L]; for (; i < L; i++) { avgP.x += plist[i].x; avgP.y += plist[i].y; } avgP.x *= 1 / L; avgP.y *= 1 / L; for (i = 0; i < L; i++) { qlist[i] = Math.atan2(plist[i].y - avgP.y, plist[i].x - avgP.x); } System.arraycopy(qlist, 0, qlist_copy, 0, L); Arrays.sort(qlist_copy); for (i = 0; i < L; i++) { for (j = 0; j < L; j++) { if (qlist_copy[i] == qlist[j]) { resultarr[i] = plist[j]; } } } for (i = 0; i < L; i++) { plist[i] = resultarr[i]; } } //*************************************// // Color // //*************************************// public final static Color colorInterpolate(Color from, Color to, double t) { if (t <= 0) return from; else if (t >= 1) return to; int nr = (int) (linearInterpolate(from.getRed(), to.getRed(), t) + .5); int ng = (int) (linearInterpolate(from.getGreen(), to.getGreen(), t) + .5); int nb = (int) (linearInterpolate(from.getBlue(), to.getBlue(), t) + .5); int na = (int) (linearInterpolate(from.getAlpha(), to.getAlpha(), t) + .5); return new Color(nr, ng, nb, na); } // public final static Color colorInterpolate(Color from, Color to, double t) { // if (t < 0) // return from; // else if (t >= 1) // return to; // int nr = (int) (linearInterpolate(from.getRed(), to.getRed(), t) + .5); // int ng = (int) (linearInterpolate(from.getGreen(), to.getGreen(), t) + .5); // int nb = (int) (linearInterpolate(from.getBlue(), to.getBlue(), t) + .5); // return new Color(nr, ng, nb); // } public final static Color colorInterpolateWithalpha(Color from, Color to, double t) { if (t <= 0) return from; else if (t >= 1) return to; int na = (int) (linearInterpolate(from.getAlpha(), to.getAlpha(), t) + .5); int nr = (int) (linearInterpolate(from.getRed(), to.getRed(), t) + .5); int ng = (int) (linearInterpolate(from.getGreen(), to.getGreen(), t) + .5); int nb = (int) (linearInterpolate(from.getBlue(), to.getBlue(), t) + .5); return new Color(na, nr, ng, nb); } public final static Color colorInterpolate(Color[] list, double t) { if (t <= 0) return list[0]; else if (t >= 1) return list[list.length - 1]; int L = list.length; if (L < 2) return list[0]; float gap = 1.0f / (L - 1); double j = (double) (t * (L - 1)); int i = (int) j; return colorInterpolate(list[i], list[i + 1], (t - i * gap) * (L - 1)); } public final static int colorInterpolate(int i, int f, float t) { if (t == 0.f) { return i; } else if (t == 1.f) { return f; } int[] irgb = HEXtoRGB(i); int[] frgb = HEXtoRGB(f); int r = (int) linearInterpolate(irgb[0], frgb[0], t); int g = (int) linearInterpolate(irgb[1], frgb[1], t); int b = (int) linearInterpolate(irgb[2], frgb[2], t); return 0xff << 24 | r << 16 | g << 8 | b; } public final static int color2Int(Color c) { int nr = (int) c.getRed(); int ng = (int) c.getGreen(); int nb = (int) c.getBlue(); int na = (int) c.getAlpha(); return (na << 24) | (nr << 16) | (ng << 8) | nb; } public final static int max(int... arr) { int $big = arr[0], i = arr.length; while (i-- > 0) if ($big < arr[i]) $big = arr[i]; return $big; } public final static int min(int... arr) { int $little = arr[0], i = arr.length; while (i-- > 0) if ($little > arr[i]) $little = arr[i]; return $little; } public final static double max(double... arr) { double $big = arr[0]; int i = arr.length; while (i-- > 0) if ($big < arr[i]) $big = arr[i]; return $big; } public final static double min(double... arr) { double $little = arr[0]; int i = arr.length; while (i-- > 0) if ($little > arr[i]) $little = arr[i]; return $little; } public final static float max(float... arr) { float $big = arr[0]; int i = arr.length; while (i-- > 0) if ($big < arr[i]) $big = arr[i]; return $big; } public final static double min(float... arr) { float $little = arr[0]; int i = arr.length; while (i-- > 0) if ($little > arr[i]) $little = arr[i]; return $little; } ///////////////////// // ColorConversion // ///////////////////// public final static int getGrayMode(int hex) { int[] data; int sum = 0; if (hex >= 0xff000000) { data = HEXtoARGB(hex); sum = data[1] + data[2] + data[3]; } else { data = HEXtoRGB(hex); sum = data[0] + data[1] + data[2]; } sum /= 3.0; sum = (int) (sum + 0.5); return sum << 16 | sum << 8 | sum; } public final static double[] RGBtoHSV(double $R, double $G, double $B) { $R = ($R > 1) ? $R / 0xff : $R; $G = ($G > 1) ? $G / 0xff : $G; $B = ($B > 1) ? $B / 0xff : $B; double H = 0; double S = 0; double V = 0; double max = max($R, $G, $B); double min = min($R, $G, $B); double mmgap = max - min; //get H; if (max == min) { H = 0; } else { if ($R == max) { H = 60 * ($G - $B) / mmgap + 360; H %= 360; } else if ($G == max) { H = 60 * ($B - $R) / mmgap + 120; } else if ($B == max) { H = 60 * ($R - $G) / mmgap + 240; } else { H = 0; //throw new Error ("Exception Error : RGBtoHSV()"); } } //get S; if (max == 0) { S = 0; } else { S = mmgap / max; } //get V; V = max; double[] result = new double[] { H, S, V }; return result; } /** * * @param $R * : red * @param $G * : green * @param $B * : blue * @return : [H, S, L] */ public final static double[] RGBtoHLS(double $R, double $G, double $B) { $R = Math.abs($R); $G = Math.abs($G); $B = Math.abs($B); $R = ($R > 1) ? $R / 0xff : $R; $G = ($G > 1) ? $G / 0xff : $G; $B = ($B > 1) ? $B / 0xff : $B; double H = 0; double S = 0; double L = 0; double max = max($R, $G, $B); double min = min($R, $G, $B); double mmgap = max - min; //get H; if (max == min) { H = 0; } else { if ($R == max) { H = 60 * ($G - $B) / mmgap + 360; H %= 360; } else if ($G == max) { H = 60 * ($B - $R) / mmgap + 120; } else if ($B == max) { H = 60 * ($R - $G) / mmgap + 240; } else { H = 0; //throw new Error ("Exception Error : RGBtoHSL()"); } } //get L; L = (max + min) / 2; //get S; if (max == min) { S = 0; } else { if (L <= .5) { L = mmgap / (max + min); } else if (L > .5) { L = mmgap / (2 - (max + min)); } } double[] result = new double[] { H, S, L }; return result; } /** * * @param $HEX * : 0x000000 ��� 16��� * @return : [H, S, V] */ public final static double[] HEXtoHSV(int $HEX) { int[] RGBarr = new int[3]; double[] HSVarr = new double[3]; RGBarr = HEXtoRGB($HEX); HSVarr = RGBtoHSV(RGBarr[0], RGBarr[1], RGBarr[2]); return HSVarr; } /** * * @param $value * : 16����� * @return : [R, G, B] */ public final static int[] HEXtoRGB(int $value) { int[] returnArr = new int[3]; returnArr[2] = $value & 0xff; returnArr[1] = ($value >> 8) & 0xff; returnArr[0] = ($value >> 16) & 0xff; return returnArr; } private static int[] HEXtoARGB(int $value) { int[] returnArr = new int[4]; returnArr[3] = $value & 0xff; returnArr[2] = ($value >> 8) & 0xff; returnArr[1] = ($value >> 16) & 0xff; returnArr[0] = ($value >> 24) & 0xff; return returnArr; } public final static int HEXtoRGB(String $hex) { return Integer.parseInt($hex, 16); } /** * * @param r * : red * @param g * : green * @param b * : blue * @return : 0x000000 16����� */ public final static String RGBtoHEX(int r, int g, int b) { String sr, sg, sb; sr = Integer.toHexString(r); if (sr.length() == 1) sr = "0" + sr; sg = Integer.toHexString(g); if (sg.length() == 1) sg = "0" + sg; sb = Integer.toHexString(b); if (sb.length() == 1) sb = "0" + sb; return "0x" + sr + sg + sb; } /** * * @param $A * : alpha * @param $R * : red * @param $G * : green * @param $B * : blue * @return : 0x00000000 16����� */ public final static String RGBtoHEX(int $A, int $R, int $G, int $B) { return "0x" + Integer.toHexString($A) + Integer.toHexString($R) + Integer.toHexString($G) + Integer.toHexString($B); } /** * * @param r * : red * @param g * : green * @param b * : blue * @return : 0x000000 16����� */ public final static String RGBtoHEX(double r, double g, double b) { String sr, sg, sb; sr = Integer.toHexString((int) (r + .5)); if (sr.length() == 1) sr = "0" + sr; sg = Integer.toHexString((int) (g + .5)); if (sg.length() == 1) sg = "0" + sg; sb = Integer.toHexString((int) (b + .5)); if (sb.length() == 1) sb = "0" + sb; return "0x" + sr + sg + sb; } /** * * @param $A * : alpha * @param $R * : red * @param $G * : green * @param $B * : blue * @return : 0x00000000 16����� */ public final static String RGBtoHEX(double $A, double $R, double $G, double $B) { return "0x" + Integer.toHexString((int) ($A + .5)) + Integer.toHexString((int) ($R + .5)) + Integer.toHexString((int) ($G + .5)) + Integer.toHexString((int) ($B + .5)); } /** * * @param $H * : Hue * @param $L * : Lightness * @param $S * : Saturation * @return : 0x000000 16����� */ public final static String HLStoHEX(double $H, double $S, double $L) { double q = 0; double[] Trgb = new double[3]; double[] Crgb = new double[3]; if ($L < .5) { q = $L * (1 + $S); } else if ($L >= .5) { q = $L + $S - ($L * $S); } double Hk = $H / 360; Trgb[0] = Hk + 1 / 3; Trgb[1] = Hk; Trgb[2] = Hk - 1 / 3; int i; for (i = 0; i < 3; i++) { if (Trgb[i] < 0) { Trgb[i] = Trgb[i] + 1; } else if (Trgb[i] > 1) { Trgb[i] = Trgb[i] - 1; } Crgb[i] = Trgb[i]; } return RGBtoHEX(Crgb[0] * 255.0, Crgb[1] * 255.0, Crgb[2] * 255.0); } /** * * @param $H * : Hue * @param $S * : Saturation * @param $V * : Value, Brightness * @return : 0x000000 16����� */ public final static String HSVtoHEX(double $H, double $S, double $V) { int Hi = (int) Math.floor($H / 60 + .5) % 6; double f = $H / 60 - Math.floor($H / 60); double p = $V * (1 - $S); double q = $V * (1 - $S * f); double t = $V * (1 - $S * (1 - f)); double R; double G; double B; switch (Hi) { case 0 : { R = $V; G = t; B = p; break; } case 1 : { R = q; G = $V; B = p; break; } case 2 : { R = p; G = $V; B = t; break; } case 3 : { R = p; G = q; B = $V; break; } case 4 : { R = t; G = p; B = $V; break; } case 5 : { R = $V; G = p; B = q; break; } default : { R = G = B = 0; throw new IllegalArgumentException("ù��° �Ķ����($H)�� �߸�Ǿ���ϴ�. : " + $H); } } R *= 255.0; G *= 255.0; B *= 255.0; return RGBtoHEX(R, G, B); } public final static int HSVtoRGB(double $H, double $S, double $V) { int Hi = (int) Math.floor($H / 60.) % 6; double f = $H / 60. - Math.floor($H / 60.); double p = $V * (1 - $S); double q = $V * (1 - $S * f); double t = $V * (1 - $S * (1 - f)); double R; double G; double B; switch (Hi) { case 0 : { R = $V; G = t; B = p; break; } case 1 : { R = q; G = $V; B = p; break; } case 2 : { R = p; G = $V; B = t; break; } case 3 : { R = p; G = q; B = $V; break; } case 4 : { R = t; G = p; B = $V; break; } case 5 : { R = $V; G = p; B = q; break; } default : { //throw new Error("ù��° �Ķ����($H)�� �߸�Ǿ���ϴ�. : " +$H); R = G = B = 0; break; } } R *= 255.0; G *= 255.0; B *= 255.0; // System.out.println(((int) (R + .5)) + " " + ((int) (G + .5)) + " " + ((int) (B + .5))); //(r0 << 16) | (g0 << 8) | b0; return (((int) (R + .5)) << 16) | (((int) (G + .5)) << 8) | ((int) (B + .5)); } /* * public final static double getAverage(double sum[], double newv){ double * avg = 0; int L = sum.length; for(int i=0;i<L-1;i++){ sum[i] = sum[i+1]; * avg += sum[i]; } sum[L] = newv; avg += newv; * * return avg/L; } */ }
true
8532398d6fea7cf9924319979a11b79c38e829ff
Java
kadySoum/React_project
/THEPROJECT/src/bd/Mongo.java
UTF-8
908
2.375
2
[]
no_license
package bd; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; public class Mongo { public static void main(String[] args) { try { MongoClient mongo = new MongoClient(); MongoDatabase bd = mongo.getDatabase("ly_soumahoro_mongo"); MongoCollection<Document> mc = bd.getCollection("comments"); Document query = new Document(); query.append("id_auteur",3); query.append("nom_auteur","giraya"); query.append("date", System.currentTimeMillis()); query.append("texte"," hey!!!!"); mc.insertOne(query); MongoCursor<Document> cursor = mc.find(query).iterator(); while(cursor.hasNext()) { Document obj = cursor.next(); System.out.println(obj); } }catch ( MongoException e) { e.printStackTrace (); } } }
true
742e1b65b380b9762da8b96058868a13d263440b
Java
wikier/asciitable
/src/main/java/de/vandermeer/asciitable/v2/themes/AbstractRowTheme.java
UTF-8
2,978
2.59375
3
[ "MIT", "Apache-2.0" ]
permissive
/* Copyright 2014 Sven van der Meer <vdmeer.sven@mykolab.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.vandermeer.asciitable.v2.themes; import org.apache.commons.lang3.text.StrBuilder; /** * Abstract {@link V2_RowTheme} implementation. * * @author Sven van der Meer &lt;vdmeer.sven@mykolab.com&gt; * @version v0.2.5 build 160301 (01-Mar-16) for Java 1.7 * @since v0.0.8 */ public class AbstractRowTheme implements V2_RowTheme { /** Left border character. */ private char leftBorder; /** Mid-up border character. */ private char midBorderUp; /** Mid-all border character. */ private char midBorderAll; /** Mid-down border character. */ private char midBorderDown; /** Right border character. */ private char rightBorder; /** Mid border character. */ private char mid; /** Description of the theme. */ private String description; /** * Creates a new row theme. * @param right character right border * @param left character left border * @param mid character mid * @param midAll character mid and up and down * @param midUp character mid and up * @param midDown character mid and down * @param description row theme description * @throws TableException if any of the parameters is null or blank */ AbstractRowTheme(final char right, final char left, final char mid, final char midAll, final char midUp, final char midDown, final String description){ this.leftBorder = left; this.midBorderUp = midUp; this.midBorderAll = midAll; this.midBorderDown = midDown; this.rightBorder = right; this.mid = mid; this.description = description; ThemeValidator.validateRowTheme(this); } @Override public char getLeftBorder() { return this.leftBorder; } @Override public char getMidBorderAll() { return midBorderAll; } @Override public char getMidBorderUp() { return this.midBorderUp; } @Override public char getMidBorderDown() { return this.midBorderDown; } @Override public char getRightBorder() { return this.rightBorder; } @Override public char getMid() { return this.mid; } @Override public Object getDescription() { return this.description; } @Override public StrBuilder toDoc() { StrBuilder ret = new StrBuilder(10); ret .append(getLeftBorder()) .append(getMid()) .append(getMidBorderUp()) .append(getMid()) .append(getMidBorderAll()) .append(getMid()) .append(getMidBorderDown()) .append(getMid()) .append(getRightBorder()) ; return ret; } }
true
5181a223071c784c5d18ee45c22d48d73f6f571d
Java
jmrequioma/Mini-Statistical-Package
/Mini SP/src/main/MainFields3.java
UTF-8
1,135
2.515625
3
[]
no_license
package main; import java.util.ArrayList; import java.util.List; public class MainFields3 { private static String samplingTechnique; private static int populationSize; private static List<Data> samplingFrame = new ArrayList<Data>(); private static String dataType; public static String getSamplingTechnique() { return samplingTechnique; } public static void setSamplingTechnique(String samplingTechnique) { MainFields3.samplingTechnique = samplingTechnique; } public static int getPopulationSize() { return populationSize; } public static void setPopulationSize(int populationSize) { MainFields3.populationSize = populationSize; } public static List<Data> getSamplingFrame() { return samplingFrame; } public static void setSamplingFrame(List<Data> samplingFrame) { MainFields3.samplingFrame = samplingFrame; } public static String getDataType() { return dataType; } public static void setDataType(String dataType) { MainFields3.dataType = dataType; } public static void clearSamplingFrame() { MainFields3.samplingFrame.clear(); } }
true
63794611ef04a043d4029166a7c5043ef0618d7b
Java
felipecamatta/republica-spring
/src/main/java/com/dev/republica/repository/MoradorRepository.java
UTF-8
544
1.914063
2
[]
no_license
package com.dev.republica.repository; import com.dev.republica.model.Morador; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface MoradorRepository extends JpaRepository<Morador, Long> { Page<Morador> findByNomeContainingIgnoreCaseAndApelidoContainingIgnoreCaseAndSexoContainingIgnoreCase(String nome, String apelido, String sexo, Pageable pageable); }
true
61053d04a4ea498359813b3f4b5656616dba7672
Java
Kovaleski/workspace
/GUIChallenge/src/challengeGUI/Align.java
UTF-8
2,186
2.8125
3
[]
no_license
package challengeGUI; // Christopher Kovaleski // Challenge part 2 // COP 3330 // Due December 6, 2013 import java.awt.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Align extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField textField; private JTextField textField_1; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Align frame = new Align(); frame.setTitle("Align"); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public Align() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 360, 150); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JCheckBox chckbxSnapToGrid = new JCheckBox("Snap to Grid"); chckbxSnapToGrid.setBounds(20, 30, 97, 23); contentPane.add(chckbxSnapToGrid); JCheckBox chckbxShowGrid = new JCheckBox("Show Grid"); chckbxShowGrid.setBounds(20, 60, 97, 23); contentPane.add(chckbxShowGrid); textField = new JTextField(); textField.setBounds(150, 31, 86, 20); contentPane.add(textField); textField.setColumns(10); JLabel lblX = new JLabel("X:"); lblX.setBounds(123, 34, 46, 14); contentPane.add(lblX); textField_1 = new JTextField(); textField_1.setBounds(150, 61, 86, 20); contentPane.add(textField_1); textField_1.setColumns(10); JLabel lblY = new JLabel("Y:"); lblY.setBounds(123, 64, 46, 14); contentPane.add(lblY); JButton btnNewButton = new JButton("Ok"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); btnNewButton.setBounds(246, 11, 89, 23); contentPane.add(btnNewButton); JButton btnCancel = new JButton("Cancel"); btnCancel.setBounds(246, 44, 89, 23); contentPane.add(btnCancel); JButton btnHelp = new JButton("Help"); btnHelp.setBounds(246, 78, 89, 23); contentPane.add(btnHelp); } }
true
da72453dcc620a61523b35c6020d7878e79ad221
Java
codermaan/HashMap
/CharFrequencyByHashMap.java
UTF-8
938
3.515625
4
[]
no_license
package hashMap; import java.util.HashMap; //import java.util.Map; import java.util.Scanner; public class CharFrequencyByHashMap { static void findFrequency(String str) { HashMap<Character, Integer> hmap = new HashMap<>(); char arr[] = str.toCharArray(); for(char val : arr) { if(hmap.containsKey(val)) { int preFreq = hmap.get(val); preFreq++; hmap.put(val, preFreq); } else hmap.put(val, 1); } //print elements in order of occurance for(char val : arr) { if(hmap.get(val)!=0)System.out.print(val+""+hmap.get(val)+" "); hmap.put(val, 0); } //hmap.forEach((key,value) -> System.out.print(key+""+value+" ")); /*for (Map.Entry me : hmap.entrySet()) { ** System.out.println(me.getKey() + " " + me.getValue()); }*/ } public static void main(String[] args) { Scanner s = new Scanner(System.in); String str = s.next(); findFrequency(str); s.close(); } }
true
cdf6bf892e6e1031961aa52b79b66919ce0cf016
Java
CruxMDQ/diy
/DIYExercise/src/org/globant/emilglober/diy/db/DBHelper.java
UTF-8
3,049
2.3125
2
[]
no_license
package org.globant.emilglober.diy.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBHelper extends SQLiteOpenHelper { private static int version = 1; //11; // 9 private static String name = "DIYDB"; private static CursorFactory factory = null; // "Um, boss... instead of building a table JUST FOR THIS, why not using a JSON file?" // "We will, but first we have to get something workable up and FAST!" // TODO Implement a JSON file to read the user info! private String T_USERDATA = "USERDATA", C_ID = "_id", C_NAME = "diy_name", C_USER_EMAIL = "diy_user_email", C_RECIPIENT_EMAIL = "diy_rec_email", C_USES_METRIC = "diy_uses_metric"; private String D_USERDATA = "CREATE TABLE " + T_USERDATA + "(" + C_ID + " " + "INTEGER PRIMARY KEY" + ", " + C_NAME + " " + "TEXT NOT NULL" + ", " + C_USER_EMAIL + " " + "TEXT NOT NULL" + ", " + C_RECIPIENT_EMAIL + " " + "TEXT NOT NULL" + ", " + C_USES_METRIC + " " + "INTEGER DEFAULT 1 " + ")"; private String D_USER_INDEX = "CREATE UNIQUE INDEX " + C_NAME + " ON " + T_USERDATA + "(" + C_NAME + " ASC)"; private String T_MEASUREMENTS = "MEASUREMENTS", C_DATE = "diy_date", C_GRAMS = "diy_grams", C_POUNDS = "diy_pounds"; private String D_MEASUREMENTS = "CREATE TABLE " + T_MEASUREMENTS + "(" + C_ID + " " + "INTEGER PRIMARY KEY" + ", " + C_DATE + " " + "DATETIME NOT NULL" + ", " + C_GRAMS + " " + "INTEGER NOT NULL" + ", " + C_POUNDS + " " + "REAL NOT NULL " + ")"; private String D_MEAS_INDEX = "CREATE UNIQUE INDEX " + C_DATE + " ON " + T_MEASUREMENTS + "(" + C_DATE + " ASC)"; public DBHelper(Context context) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { Log.i(this.getClass().toString(), "Building DB"); db.execSQL(D_MEASUREMENTS); db.execSQL(D_MEAS_INDEX); db.execSQL(D_USERDATA); db.execSQL(D_USER_INDEX); Log.i(this.getClass().toString(), "Database created"); // upgradeToVersion2(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // if (oldVersion < 2) // { // try // { // upgradeToVersion2(db); // } // catch(SQLException e) // { // Log.i(this.getClass().toString(), e.getMessage()); // } // } } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); if (!db.isReadOnly()) { db.execSQL("PRAGMA foreign_keys=ON;"); } } @SuppressWarnings("unused") private void upgradeToVersion2(SQLiteDatabase db) { // db.execSQL("ALTER TABLE " + T_PROPERTIES + " ADD " + C_CONFIRMED + " INTEGER NOT NULL DEFAULT 0"); // // Log.i(this.getClass().toString(), "Update to version 2 complete"); } }
true
9b15dab03276efad022200a31e2bc24b19a426fc
Java
authrus/database
/authrus-database-engine/src/main/java/com/authrus/database/engine/index/ClusterIterator.java
UTF-8
1,790
2.609375
3
[]
no_license
package com.authrus.database.engine.index; import java.util.Collections; import java.util.Iterator; import java.util.Set; import com.authrus.database.engine.Row; public class ClusterIterator implements Iterator<Row> { private Iterator<Cluster> clusters; private Iterator<Row> tuples; private Set<Cluster> exclude; private Row next; public ClusterIterator(Iterator<Cluster> clusters) { this(clusters, Collections.EMPTY_SET); } public ClusterIterator(Iterator<Cluster> clusters, Set<Cluster> exclude) { this.clusters = clusters; this.exclude = exclude; } @Override public boolean hasNext() { if(next == null) { if(tuples == null) { // get first iterator return moveNext(); } else { if(tuples.hasNext()) { next = tuples.next(); } else { return moveNext(); } } } return true; } private boolean moveNext() { while(clusters.hasNext()) { Cluster cluster = clusters.next(); if(!exclude.contains(cluster)) { Iterator<Row> iterator = cluster.iterator(); if(iterator.hasNext()) { next = iterator.next(); tuples = iterator; return true; } } } return false; } @Override public Row next() { Row result = next; if(result == null) { if(hasNext()) { result = next; } } if(result != null) { next = null; } return result; } @Override public void remove() { throw new UnsupportedOperationException("Remove is not supported"); } }
true
136168623d357ca09ea12bebdec9487a873f4bb7
Java
CS2103AUG2017-F11-B1/main
/src/test/java/seedu/address/logic/parser/SortCommandParserTest.java
UTF-8
1,705
2.5625
3
[ "MIT" ]
permissive
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS; import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL; import static seedu.address.logic.parser.CliSyntax.PREFIX_GROUP; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import org.junit.Test; import seedu.address.logic.commands.SortCommand; //@@author sofarsophie public class SortCommandParserTest { private SortCommandParser parser = new SortCommandParser(); @Test public void parse_noArgs_returnSortCommand() { assertParseSuccess(parser, "", new SortCommand()); } @Test public void parse_validArg_returnsSortCommand() { assertParseSuccess(parser, PREFIX_ADDRESS.toString(), new SortCommand(PREFIX_ADDRESS)); } @Test public void parse_invalidArg_throwsParseException() { // Non-prefix argument assertParseFailure(parser, "name", String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE)); // Two same prefixes repeated assertParseFailure(parser, PREFIX_ADDRESS.toString() + PREFIX_ADDRESS.toString(), String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE)); } @Test public void parse_multipleArgs_throwsParseException() { assertParseFailure(parser, PREFIX_EMAIL.toString() + PREFIX_GROUP.toString(), String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE)); } } //@@author
true
2ce48e1bcab08c2f39259d18f88c37cb167e29c3
Java
Jcateye/wechatreader
/src/main/java/com/jxlg/haoqi/wechatreader/pojo/ReadLog.java
UTF-8
1,148
2.015625
2
[]
no_license
package com.jxlg.haoqi.wechatreader.pojo; import java.io.Serializable; import java.util.Date; public class ReadLog implements Serializable { private String id; private String chapterId; private Integer length; private Date createTime; private Date updateTime; private static final long serialVersionUID = 1L; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getChapterId() { return chapterId; } public void setChapterId(String chapterId) { this.chapterId = chapterId == null ? null : chapterId.trim(); } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
true
7ff59c3d7ec78ead23747d394db09fe46ae7ee1b
Java
RaghavInfoTech/springboot
/SpringBootIgnitePoc/src/main/java/com/info/springboot/crud/service/BookService.java
UTF-8
1,215
2.515625
3
[]
no_license
package com.info.springboot.crud.service; import java.util.List; import org.apache.ignite.IgniteSpringBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.info.springboot.crud.entity.Book; import com.info.springboot.crud.repositories.BookRepository; /** * Service class , provides service to all REST APIs and calls DAO layer * * @author Raghava */ @Service public class BookService { @SuppressWarnings("unused") @Autowired private IgniteSpringBean igniteSpringBean; @Autowired @Lazy private BookRepository bookCache; public String greet() { return "Hello"; } public Book createBook(Book book) { Book save = bookCache.save(book.getId(), book); return save; } public Book getBook(Integer id) { return bookCache.findOne(id); } public List<Book> getAllBooks(){ return (List<Book>) bookCache.findAll(); } public Book updateBook(Book book) { return bookCache.save(book.getId(), book); } public void deleteBook(Integer bookId) { bookCache.delete(bookId); } }
true
3010f1259866be446c80fe776266993fa34f6978
Java
TigerChain/designpattern_javademo
/src/template/examination_page/Test.java
UTF-8
373
2.15625
2
[]
no_license
package template.examination_page; /** * Created by TigerChain */ public class Test { public static void main(String args[]){ ExaminationPage xiaoMing = new XiaoMing() ; xiaoMing.zuoTi(); System.out.println("==========华丽的分隔线==========") ; ExaminationPage xiaoZhang = new XiaoZhang() ; xiaoZhang.zuoTi(); } }
true
7b0bba4c98494d3036d986feb90ded1cbe339e31
Java
newstar123/RxJava-Android-Booking-App
/app/src/main/java/app/delivering/mvp/main/photo/facebook/presenter/RestoreFBPhotoPresenter.java
UTF-8
718
1.960938
2
[]
no_license
package app.delivering.mvp.main.photo.facebook.presenter; import android.graphics.Bitmap; import app.core.facebook.profile.interactor.RestoreFBPhotoInteractor; import app.delivering.component.BaseActivity; import app.delivering.mvp.BaseOutputPresenter; import rx.Observable; public class RestoreFBPhotoPresenter extends BaseOutputPresenter<Observable<Bitmap>> { private final RestoreFBPhotoInteractor restoreFBPhotoInteractor; public RestoreFBPhotoPresenter(BaseActivity activity) { super(activity); restoreFBPhotoInteractor = new RestoreFBPhotoInteractor(getActivity()); } @Override public Observable<Bitmap> process() { return restoreFBPhotoInteractor.process(); } }
true
e5dfe47d54aef20c3d2e1871d0a7adddf54e3ef8
Java
Harium/database-core
/src/main/java/com/harium/database/module/DatabaseModule.java
UTF-8
265
1.914063
2
[]
no_license
package com.harium.database.module; import com.harium.database.model.BaseDAO; public interface DatabaseModule<T> { void init(boolean clearDatabase); void register(BaseDAO<?, T> dao); void clear() throws Exception; BaseDAO getDAO(Class klass); }
true
b5ae13e139d454c33febd1501617ff0f0b6ff549
Java
BackupTheBerlios/unice
/sclipse/src/sclipse/toplevel/SchemeToplevelEventFilter.java
UTF-8
2,058
2.640625
3
[]
no_license
package sclipse.toplevel; /* * (c) Brent Fulgham <bfulgham@debian.org>, 2002 * All Rights Reserved. * * This software is based on examples and the source for Eclipse, which * are all copyright IBM, 2000, 2001 under the terms of the "Common * Public License Version 0.5 (CPL)". * * This package of software is also released under the terms of the CPL. */ import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.IDebugEventFilter; /** * This class serves to prevent the Launch system from throwing * a tantrum because the Goo process doesn't use a standard Eclipse * style launch protocol. * * We basically tell everything to not Show or Handle any events * from this launch. */ public class SchemeToplevelEventFilter implements IDebugEventFilter { private ILaunch fLaunch; /** * Constructor for the filter * @param launch The launch event. */ public SchemeToplevelEventFilter(final ILaunch launch) { fLaunch = launch; } /** * This routine instructs the overall Launch system to not * attempt to open a new Debug window for this process at * Launch time. * * @param launch The launch to be displayed. * @return False, since we never show the process launch. */ public final boolean showLaunch(final ILaunch launch) { return false; // We never want to show the Goo process launch } /** * Filter debug events to return Goo-relevant information. * * @param events Debug events to be filtered. * @return Null, since we don't have any debug events we understand. */ public final DebugEvent[] filterDebugEvents(final DebugEvent[] events) { return null; } /** * This routine instructs the overall Launch system to not * attempt to open a new Debug window for this process when * a Debug event is encountered. * * @param event The event to be evaluated. * @return False, since we never process debug events. */ public final boolean showDebugEvent(final DebugEvent event) { return false; // We never want to debug the Goo process } }
true
77d287ecf9966b76fa9914fca78da528a46f4987
Java
astra-zhao/softswitch-gateway
/freeswitch-xml-curl/src/main/java/com/atomscat/freeswitch/xml/constant/ConfName.java
UTF-8
449
1.96875
2
[ "Apache-2.0" ]
permissive
package com.atomscat.freeswitch.xml.constant; /** * @author th158 */ public enum ConfName { IVR("ivr.conf", "menus") ; public String confName; public String listName; public String getConfName() { return confName; } public String getListName() { return listName; } ConfName(String confName, String listName) { this.confName = confName; this.listName = listName; } }
true
70cf8014f988e79221c7eb1f6805f967f8dc4dea
Java
shb695/LChart
/app/src/main/java/com/linheimx/app/lchart/MultiLineActivity.java
UTF-8
5,271
2.46875
2
[ "Apache-2.0" ]
permissive
package com.linheimx.app.lchart; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.linheimx.app.library.adapter.IValueAdapter; import com.linheimx.app.library.charts.LineChart; import com.linheimx.app.library.data.Entry; import com.linheimx.app.library.data.Line; import com.linheimx.app.library.data.Lines; import com.linheimx.app.library.model.HightLight; import com.linheimx.app.library.model.XAxis; import com.linheimx.app.library.model.YAxis; import java.util.ArrayList; import java.util.List; import java.util.Random; public class MultiLineActivity extends AppCompatActivity { private final static int LINE_NUM = 3; LineChart _lineChart; SeekBar _SeekBar; TextView _tvLineNum; Line.CallBack_OnEntryClick onEntryClick = new Line.CallBack_OnEntryClick() { @Override public void onEntry(Line line, Entry entry) { Toast.makeText(MultiLineActivity.this, line.getName() + " \r\n" + entry.toString(), Toast.LENGTH_SHORT).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_multi_line); getSupportActionBar().setTitle("折线图:多条折线"); _lineChart = (LineChart) findViewById(R.id.chart); _SeekBar = (SeekBar) findViewById(R.id.sb_line_more); _tvLineNum = (TextView) findViewById(R.id.tv_line_nums); CheckBox cb = (CheckBox) findViewById(R.id.cb_cb); setChartData(_lineChart, LINE_NUM); // 1. 折线的数目 _tvLineNum.setText("折线的数目:" + LINE_NUM); _SeekBar.setProgress(LINE_NUM); _SeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { _tvLineNum.setText("折线的数目:" + progress); setChartData(_lineChart, progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // 2. 点击折线上的点 ,回调 cb.setChecked(true); cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Lines lines = _lineChart.getlines(); for (Line line : lines.getLines()) { if (isChecked) { line.setOnEntryClick(onEntryClick); } else { line.setOnEntryClick(null); } } } }); } private void setChartData(LineChart lineChart, int lineCount) { // 高亮 HightLight hightLight = lineChart.get_HightLight(); hightLight.setEnable(true);// 启用高亮显示 默认为启用状态,每条折线图想要获取点击回调,highlight需要启用 hightLight.setxValueAdapter(new IValueAdapter() { @Override public String value2String(double value) { return "X:" + value; } }); hightLight.setyValueAdapter(new IValueAdapter() { @Override public String value2String(double value) { return "Y:" + Math.round(value); } }); // x,y轴上的单位 XAxis xAxis = lineChart.get_XAxis(); xAxis.set_unit("s"); YAxis yAxis = lineChart.get_YAxis(); yAxis.set_unit("m"); Lines lines = new Lines(); for (int i = 0; i < lineCount; i++) { // 线的颜色 int color = Color.argb(255, (new Double(Math.random() * 256)).intValue(), (new Double(Math.random() * 256)).intValue(), (new Double(Math.random() * 256)).intValue()); Line line = createLine(i, color); lines.addLine(line); } lineChart.setLines(lines); } private Line createLine(int order, int color) { final Line line = new Line(); List<Entry> list = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 10 + order; i++) { double x = i; double y = random.nextDouble() * 100; list.add(new Entry(x, y)); } line.setEntries(list); line.setDrawLegend(true); line.setName("_line:" + order); line.setLineColor(color); line.setOnEntryClick(onEntryClick); return line; } /** * 光标左移动 */ void goLeft() { // handler.postDelayed(new Runnable() { // @Override // public void run() { // goLeft(); // } // },3000); _lineChart.highLightLeft(); } }
true
82e8efd1436ef48d4078ea4507a34be1eb730c08
Java
AmberWein/Arkanoid
/src/management/CountdownAnimation.java
UTF-8
1,960
3.109375
3
[]
no_license
//author 208783522 package management; import biuoop.DrawSurface; import biuoop.Sleeper; import java.awt.Color; /** * The type Countdown animation. * The CountdownAnimation will display the given gameScreen, * for numOfSeconds seconds, and on top of them it will show * a countdown from countFrom back to 1, where each number will * appear on the screen for (numOfSeconds / countFrom) seconds, before * it is replaced with the next one. */ public class CountdownAnimation implements Animation { private double numberOfSeconds; private int countFrom; private SpriteCollection gameScreen; private Counter timeLeftInSeconds; private boolean shouldStop; /** * Instantiates a new Countdown animation. * * @param numOfSeconds the number of seconds to count. * @param countFrom The number to count from. * @param gameScreen the game screen. */ public CountdownAnimation(double numOfSeconds, int countFrom, SpriteCollection gameScreen) { this.numberOfSeconds = numOfSeconds; this.countFrom = countFrom; this.gameScreen = gameScreen; this.timeLeftInSeconds = new Counter(); this.shouldStop = false; this.timeLeftInSeconds.increase((int) this.numberOfSeconds); } @Override public void doOneFrame(DrawSurface d) { this.gameScreen.drawAllOn(d); if (!this.shouldStop()) { d.setColor(new Color(102, 0, 0)); d.drawText(365, 380, String.valueOf(this.timeLeftInSeconds.getValue()), 120); d.setColor(new Color(250, 0, 0)); d.drawText(380, 380, String.valueOf(this.timeLeftInSeconds.getValue()), 80); } Sleeper sleeper = new Sleeper(); sleeper.sleepFor(650); timeLeftInSeconds.decrease(1); } @Override public boolean shouldStop() { return this.timeLeftInSeconds.getValue() < 0; } }
true
3718bb797ffedf2906072cf11c0559254513d1b8
Java
zcc888/Java9Source
/javafx.graphics/javafx/css/StyleClass.java
UTF-8
843
2.046875
2
[]
no_license
/* * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javafx.css; /** * * @since 9 */ public final class StyleClass { public StyleClass(String styleClassName, int index) { this.styleClassName = styleClassName; this.index = index; } /** @return the style-class */ public String getStyleClassName() { return styleClassName; } /** @return the style-class */ @Override public String toString() { return styleClassName; } public int getIndex() { return index; } private final String styleClassName; // index of this StyleClass in styleClasses list. private final int index; }
true
2e36f7078db539061b64d5fd44350eddd022243e
Java
parushisu/BatchTest
/src/jp/co/test/batch/main/BatchTest06.java
UTF-8
476
2.1875
2
[]
no_license
package jp.co.test.batch.main; import jp.co.hello.batch.main.HelloBatchMain; import jp.co.hello.batch.utils.HelloBatchLog; public class BatchTest06 extends HelloBatchMain { public int execute() { HelloBatchLog log = HelloBatchLog.getInstance(); log.debug("debug!!!"); log.info("info {}!!!", "情報"); log.warn("warn {}!!!", "警告"); log.error("error!!!"); log.fatal("fatal!!!"); log.info("BatchTest06 bye!"); return 0; } }
true
0683c91e080feb8af420a9d6de00c502329ddf44
Java
Mibizina/Java
/src/Chapitre9/TstStB.java
UTF-8
692
2.859375
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 Chapitre9; /** * TEST STRINGBUFFER * @author Mihary */ public class TstStB { public static void main (String args[]) { String ch = "la java"; StringBuffer chBuf = new StringBuffer (ch); System.out.println(chBuf); chBuf.setCharAt (3, 'J'); System.out.println(chBuf); chBuf.setCharAt(1, 'e'); System.out.println(chBuf); chBuf.append(" 2"); System.out.println(chBuf); chBuf.insert(3, " langage "); System.out.println(chBuf); } }
true
4c0bd1f42938262b89959aba736b2cf77c9854b1
Java
Mapoet/AWIPS-Test
/com.raytheon.uf.common.datadelivery.event/src/com/raytheon/uf/common/datadelivery/event/retrieval/SubscriptionRequestEvent.java
UTF-8
2,899
1.90625
2
[]
no_license
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.uf.common.datadelivery.event.retrieval; import java.util.Map; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; import com.raytheon.uf.common.stats.StatisticsEvent; /** * * Event that occurs when a subscription request is made. * * <pre> * * SOFTWARE HISTORY * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 08, 2013 1654 bgonzale Initial creation * * </pre> * * @author bgonzale * @version 1.0 */ @DynamicSerialize public class SubscriptionRequestEvent extends StatisticsEvent { private static final long serialVersionUID = -5302262650866371587L; @DynamicSerializeElement protected String owner; @DynamicSerializeElement protected String network; @DynamicSerializeElement protected String provider; @DynamicSerializeElement protected int numRecords = 1; public String getOwner() { return owner; } public String getNetwork() { return network; } public String getProvider() { return provider; } public void setOwner(String owner) { this.owner = owner; } public void setNetwork(String network) { this.network = network; } public void setProvider(String provider) { this.provider = provider; } public int getNumRecords() { return numRecords; } public void setNumRecords(int numRecords) { this.numRecords = numRecords; } public void incrementNumRecords() { ++this.numRecords; } @Override public String toString() { return super.toString() + " provider: " + provider + " owner: " + owner + " network: " + network + " numRecords: " + numRecords; } @Override protected Map<String, String> getFieldUnitMap() { // Not Implemented. return null; } @Override public void finalizeEvent() { // Not Implemented. } }
true
ab490b4483bac54a6d0b5d33b80d4214d4e1ef8d
Java
MichaelFedora/FedorasEconomy
/src/main/java/io/github/michaelfedora/fedoraseconomy/cmdexecutors/fedoraseconomy/user/FeUserResetExecutor.java
UTF-8
3,017
2.328125
2
[ "MIT" ]
permissive
package io.github.michaelfedora.fedoraseconomy.cmdexecutors.fedoraseconomy.user; import io.github.michaelfedora.fedoraseconomy.PluginInfo; import io.github.michaelfedora.fedoraseconomy.cmdexecutors.FeExecutorBase; import io.github.michaelfedora.fedoraseconomy.economy.account.FeUniqueAccount; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.service.economy.Currency; import org.spongepowered.api.service.economy.transaction.ResultType; import org.spongepowered.api.service.economy.transaction.TransactionResult; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextStyles; import java.util.*; /** * Created by Michael on 3/19/2016. */ public class FeUserResetExecutor extends FeExecutorBase { public static final List<String> ALIASES = Arrays.asList("reset", "zero"); public static final String NAME = ALIASES.get(0); public static CommandSpec create() { return CommandSpec.builder() .description(Text.of("Resets a user's balance to zero")) .permission(PluginInfo.DATA_ROOT + '.' + NAME) .arguments(GenericArguments.user(Text.of("user"))) .executor(new FeUserResetExecutor()) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { User user = args.<User>getOne("user").orElseThrow(() -> new CommandException(Text.of("Bad param [user]!"))); FeUniqueAccount account = tryGetUniqueAccount(user.getUniqueId()); Map<Currency, TransactionResult> result = account.resetBalances(Cause.of(NamedCause.of(src.getName(), src)), null, true); boolean success = false; boolean failure = false; for(Map.Entry<Currency, TransactionResult> e : result.entrySet()) { if(e.getValue().getResult() == ResultType.SUCCESS) success = true; else failure = true; } if(failure && !success) { src.sendMessage(Text.of("Could not reset ", TextColors.AQUA, user.getName(), TextColors.RESET, "'s account")); } if(failure && success) { src.sendMessage(Text.of("Could not ", TextStyles.ITALIC, "totally", TextStyles.RESET, " reset", TextColors.AQUA, user.getName(), TextColors.RESET, "'s account")); } else { src.sendMessage(Text.of("Reset ", TextColors.AQUA, user.getName(), TextColors.RESET, "'s account")); } return CommandResult.success(); } }
true
2ecc4f72251b141c70c30f7f92d29285b2208963
Java
msaifa/kasir-laundry
/src/main/java/com/komputerkit/kasirlaundry/Model/TblProduk.java
UTF-8
1,509
2.078125
2
[]
no_license
package com.komputerkit.kasirlaundry.Model; /** * Created by msaifa on 20/01/2018. */ public class TblProduk { String idproduk,produk,kategori,harga,jumlah,keterangan,flagAktif ; public TblProduk(String idproduk, String produk, String kategori, String harga) { this.idproduk = idproduk; this.produk = produk; this.kategori = kategori; this.harga = harga; } public TblProduk(String idproduk, String produk, String kategori, String harga, String jumlah, String keterangan, String flagAktif) { this.idproduk = idproduk; this.produk = produk; this.kategori = kategori; this.harga = harga; this.jumlah = jumlah; this.keterangan = keterangan ; this.flagAktif = flagAktif ; } public String getKeterangan() { return keterangan; } public void setKeterangan(String keterangan) { this.keterangan = keterangan; } public String getIdproduk() { return idproduk; } public String getProduk() { return produk; } public String getKategori() { return kategori; } public String getHarga() { return harga; } public void setJumlah(String jumlah) { this.jumlah = jumlah; } public String getJumlah() { return jumlah; } public void setFlagAktif(String flagAktif) { this.flagAktif = flagAktif; } public String getFlagAktif() { return flagAktif; } }
true
045ba974c3ae9a4c6c1c3b80056646c1ec1b59d9
Java
lostufpi/recover
/src/testeJson/InfoMunicipios.java
UTF-8
406
2.515625
3
[]
no_license
package testeJson; public class InfoMunicipios { private String UF; private String cidade; public InfoMunicipios(String uF, String cidade) { super(); UF = uF; this.cidade = cidade; } public String getUF() { return UF; } public void setUF(String uF) { UF = uF; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } }
true
f28a626302817fb485ec385183441d28f2085746
Java
miguelfoko/TimeTableCalendar
/recruitment/src/test/java/recruitment/EventTimeTableTest.java
UTF-8
3,796
2.34375
2
[]
no_license
package recruitment; import static org.junit.Assert.*; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import org.junit.Test; import com.afrinic.recruitment.EventTimeTable; public class EventTimeTableTest { EventTimeTable ett=new EventTimeTable(); // @Test public void testFileReader() { ArrayList<String> list=new ArrayList<String>(); list.add("005;IoT impact on Internet Governance Processes (Alain)"); list.add("005;Tech talk: Raiders of the lost ark (Jordi)"); list.add("030;Connecting the Unconnected in Africa (Mukom)"); list.add("180;Annual General Members Meeting (Alan)"); list.add("090;FIRE Workshop (Olatunde)"); list.add("090;Deployathon (David)"); list.add("060;Internet Governance (Patricia)"); list.add("030;Regional TTLDs (Daheda)"); list.add("045;Benefits of THD networks (Amreesh)"); list.add("045;Building registry ATI experience (Wafa)"); assertEquals(10, list.size()); } // @Test public void testFileWriter() { fail("Not yet implemented"); } // @Test public void testOrderDate() { ArrayList<String> list=new ArrayList<String>(); list.add("005;IoT impact on Internet Governance Processes (Alain)"); list.add("005;Tech talk: Raiders of the lost ark (Jordi)"); list.add("030;Connecting the Unconnected in Africa (Mukom)"); list.add("180;Annual General Members Meeting (Alan)"); list.add("090;FIRE Workshop (Olatunde)"); list.add("090;Deployathon (David)"); list.add("060;Internet Governance (Patricia)"); list.add("030;Regional TTLDs (Daheda)"); list.add("045;Benefits of THD networks (Amreesh)"); list.add("045;Building registry ATI experience (Wafa)"); list.add("120;Building registry ATI experience (Wafa)"); list.add("200;Building registry ATI experience (Wafa)"); HashMap<Integer, ArrayList<String>>map=ett.orderDate(list); assertEquals(2, map.size());//Testing the number of days for planning } @Test public void testAddDate() { ArrayList<String> list=new ArrayList<String>(); list.add("005;IoT impact on Internet Governance Processes (Alain)"); list.add("005;Tech talk: Raiders of the lost ark (Jordi)"); list.add("030;Connecting the Unconnected in Africa (Mukom)"); list.add("180;Annual General Members Meeting (Alan)"); list.add("090;FIRE Workshop (Olatunde)"); list.add("090;Deployathon (David)"); list.add("060;Internet Governance (Patricia)"); list.add("030;Regional TTLDs (Daheda)"); list.add("045;Benefits of THD networks (Amreesh)"); list.add("045;Building registry ATI experience (Wafa)"); list.add("120;Building registry ATI experience (Wafa)"); HashMap<Integer, ArrayList<String>>map1=ett.orderDate(list); HashMap<Integer, ArrayList<String>>map=ett.addDate(map1,list); assertEquals(2, map.size()); } // @Test public void testDayEvent() { ArrayList<String> list=new ArrayList<String>(); list.add("005;IoT impact on Internet Governance Processes (Alain)"); list.add("005;Tech talk: Raiders of the lost ark (Jordi)"); list.add("030;Connecting the Unconnected in Africa (Mukom)"); list.add("180;Annual General Members Meeting (Alan)"); list.add("090;FIRE Workshop (Olatunde)"); list.add("090;Deployathon (David)"); list.add("060;Internet Governance (Patricia)"); list.add("030;Regional TTLDs (Daheda)"); list.add("045;Benefits of THD networks (Amreesh)"); list.add("045;Building registry ATI experience (Wafa)"); list.add("120;Building registry ATI experience (Wafa)"); HashMap<Integer, ArrayList<String>>map1=ett.orderDate(list); HashMap<Integer, ArrayList<String>>map=ett.addDate(map1,list); ArrayList<String> liste=ett.dayEvent(map.get(0)); assertEquals(9, liste.size()); ArrayList<String> liste2=ett.dayEvent(map.get(1)); assertEquals(5, liste2.size()); } }
true
fd97de684d50d91e4b0caadeecea2976ecb1d117
Java
SaiferGit/Consumable-Management-System
/src/com/cms/controller/ArtController.java
UTF-8
1,607
2.78125
3
[]
no_license
package com.cms.controller; import com.cms.model.Art; import com.cms.view.ArtView; public class ArtController { private Art art; private ArtView artView; public ArtController(Art art, ArtView artView) { this.art = art; this.artView = artView; } public String getArtType(){ return art.getType(); } public String getArtName() { return art.getName(); } public String getArtStartingDate() { if(art.getStartingDate().equals("0")) return ""; return art.getStartingDate(); } public String getArtEndingDate() { if(art.getEndingDate().equals("0")) return ""; return art.getEndingDate(); } public double getArtTotalConsumptionHours() { return art.getTotalConsumptionHours(); } public String getArtRating() { if((int)art.getRating()== 0) return ""; return Double.toString(art.getRating()); } public int getArtTotalConsumptionDays() { return art.getTotalConsumptionDays(); } public void showDetails(){ artView.print(getArtType(), getArtName(), getArtStartingDate(), getArtEndingDate(), getArtTotalConsumptionHours(), getArtRating(), getArtTotalConsumptionDays()); } public void showSpecific(String type){ if(type.equals(getArtType())) artView.print(getArtType(), getArtName(), getArtStartingDate(), getArtEndingDate(), getArtTotalConsumptionHours(), getArtRating(), getArtTotalConsumptionDays()); else return; } }
true
1b0d4dad5b0efcfc5528725e28efd26e60457f74
Java
MarcBrejner/PokemonBattle
/src/main/java/com/mycompany/pokemonBattle/Profile.java
UTF-8
1,791
2.921875
3
[]
no_license
package com.mycompany.pokemonBattle; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Profile { public int id; private String username; private List<Pokemon> pokemons = new ArrayList<Pokemon>(); private List<Item> items = new ArrayList<Item>(); private int level, XP, requiredXP; public Profile(int id, String username, int level, int XP, int requiredXP) { this.id = id; this.username = username; this.level = level; this.XP = XP; this.requiredXP = requiredXP; } public static String toJson(Profile profile){ Gson gson = new Gson(); String json = gson.toJson(profile); return json; } public static Profile fromJson(String json){ GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); Profile gsonProfile = gson.fromJson(json, Profile.class); return gsonProfile; } public String getUsername() { return username; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getXP() { return XP; } public void setXP(int XP) { this.XP = XP; } public int getRequiredXP() { return requiredXP; } public void setRequiredXP(int XP) { requiredXP = XP; } public List<Pokemon> getPokemons() { return pokemons; } public void setPokemons(List<Pokemon> pokemons) { this.pokemons = pokemons; } public void addPokemon(Pokemon pokemon) { this.pokemons.add(pokemon); } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public void addItem(Item item) { this.items.add(item); } public void removeItem(Item item) { items.remove(item); } }
true
a87558e311dc5f90b435ab0fc61488055710e228
Java
flashscope/next-chessgame
/src/util/exceptions/EmptyPositionException.java
UTF-8
545
2.578125
3
[]
no_license
package util.exceptions; public class EmptyPositionException extends RuntimeException { private static final long serialVersionUID = -3536523914470825348L; /** * Constructs a {@code EmptyPositionException} with no detail message. */ public EmptyPositionException() { super(); } /** * Constructs a {@code EmptyPositionException} with the specified * detail message. * * @param s the detail message. */ public EmptyPositionException(String s) { super(s); } }
true
8539e5d93e3326d4290a3e3661ffdbda4c7ffa49
Java
369857519/javaExerciseSet
/src/main/java/C_ADT/CircularLinkedList.java
UTF-8
2,259
3.28125
3
[]
no_license
package C_ADT; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; /** * Created by qilianshan on 17/8/14. */ public class CircularLinkedList<T> extends B_LinkedList{ private int theSize; private int modCount=0; private Node<T> beginMarker; private Node<T> endMarker; public CircularLinkedList(){ clear(); } public void clear(){ beginMarker=new Node<T>(null,null,null); endMarker=new Node<T>(null,beginMarker,null); beginMarker.next=endMarker; theSize=0; modCount++; } public Iterator<T> iterator() { return new MyIterator(); } private T remove(Node<T> p) { p.next.prev=p.prev; p.prev.next=p.next; theSize--; modCount++; return p.data; } private class MyIterator implements Iterator<T>{ private Node<T> current=beginMarker.next; private int expectedmodCount=modCount; private boolean okToRemove=false; public boolean hasNext() { return true; } public T next() { if(modCount!=expectedmodCount) throw new ConcurrentModificationException(); if(!hasNext()) throw new NoSuchElementException(); //如果链到了最后一个,则回到第一个 if(current==endMarker){ current=beginMarker; } T nextItem=current.data; current=current.next; okToRemove=true; return nextItem; } public void remove() { if(modCount!=expectedmodCount) throw new ConcurrentModificationException(); if(!okToRemove) throw new IllegalStateException(); CircularLinkedList.this.remove(current.prev); okToRemove=false; expectedmodCount++; } } private static class Node<T> { public Node(T d,Node<T> p,Node<T> n) { data=d; prev=p; next=n; } public T data; public Node<T> prev; public Node<T> next; } }
true
8f8564b5983948cb46d819b880df6fea01d255e1
Java
vegetaz/OOP-QLDSV
/Java_Project_OOP_QLD_02/src/ltu13b/nhom05/oop/object/SinhVien.java
UTF-8
1,208
2.6875
3
[]
no_license
package ltu13b.nhom05.oop.object; import java.io.Serializable; import java.util.Date; /** * Created by Heart Of Dead on 5/19/2017. */ public class SinhVien extends ConNguoi{ private String maSinhVien; private String lop; private String khoa; public SinhVien(String ten, Date ngaySinh, boolean gioiTinh, String diaChi, int soDienThoai, String mail,String maSinhVien,String lop,String khoa) { super(ten, ngaySinh, gioiTinh, diaChi, soDienThoai, mail); this.maSinhVien=maSinhVien; this.lop=lop; this.khoa=khoa; } public String getMaSinhVien() { return maSinhVien; } public void setMaSinhVien(String maSinhVien) { this.maSinhVien = maSinhVien; } public String getLop() { return lop; } public void setLop(String lop) { this.lop = lop; } public String getKhoa() { return khoa; } public void setKhoa(String khoa) { this.khoa = khoa; } @Override public boolean equals(Object obj) { SinhVien sv = (SinhVien) obj; if (this.getMaSinhVien().equals(sv.getMaSinhVien())) { return true; } return false; } }
true
95d2a2111cf03dd3c366ca8a9e1881fe2d5104ab
Java
jianbingfang/xhf
/src/main/java/com/xthena/gcgl/web/PjRyController.java
UTF-8
10,592
1.632813
2
[ "Apache-2.0" ]
permissive
package com.xthena.gcgl.web; import com.xthena.api.user.UserConnector; import com.xthena.core.hibernate.PropertyFilter; import com.xthena.core.mapper.BeanMapper; import com.xthena.core.page.Page; import com.xthena.core.spring.MessageHelper; import com.xthena.ext.export.Exportor; import com.xthena.ext.export.TableModel; import com.xthena.gcgl.domain.PjRy; import com.xthena.gcgl.domain.PjRyRecord; import com.xthena.gcgl.manager.PjRyManager; import com.xthena.hr.domain.CommRy; import com.xthena.hr.domain.HrLz; import com.xthena.hr.manager.CommRyManager; import com.xthena.hr.manager.HrLzManager; import com.xthena.security.util.SpringSecurityUtils; import com.xthena.util.CommRyMapUtil; import com.xthena.util.JsonResponseUtil; import com.xthena.util.PjXmMapUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; import java.util.Map; @Controller @RequestMapping("gcgl") public class PjRyController { private PjRyManager pjRyManager; private Exportor exportor; private BeanMapper beanMapper = new BeanMapper(); private UserConnector userConnector; private MessageHelper messageHelper; @Autowired private CommRyManager commRyManager; @Autowired private HrLzManager hrLzManager; @RequestMapping("pjRy-info-list") public String list(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, Model model) { parameterMap.put("filter_EQS_fstatus", "在岗"); List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); page.setOrderBy("fxmid"); page = pjRyManager.pagedQuery(page, propertyFilters); model.addAttribute("page", page); model.addAttribute("xmMap", PjXmMapUtil.getXmMap()); model.addAttribute("ryMap", CommRyMapUtil.getRyMap()); return "gcgl/pjRy-info-list"; } @RequestMapping("pjRy-info-input") public String input(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "fxmid", required = false) Long fxmid, Model model) { if (id != null) { PjRy pjRy = pjRyManager.get(id); model.addAttribute("model", pjRy); } if (id == null && fxmid != null) { PjRy pjRy = new PjRy(); pjRy.setFxmid(fxmid); model.addAttribute("model", pjRy); } model.addAttribute("xmMap", PjXmMapUtil.getXmMap()); model.addAttribute("ryMap", CommRyMapUtil.getRyMap()); return "gcgl/pjRy-info-input"; } @RequestMapping("pjRy-info-add") public String add(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "fxmid", required = false) Long fxmid, Model model) { if (id != null) { PjRy pjRy = pjRyManager.get(id); model.addAttribute("model", pjRy); } if (id == null && fxmid != null) { PjRy pjRy = new PjRy(); pjRy.setFxmid(fxmid); model.addAttribute("model", pjRy); } model.addAttribute("xmMap", PjXmMapUtil.getXmMap()); return "gcgl/pjRy-info-add"; } @RequestMapping("pjRy-info-addsave") public String addsave(@ModelAttribute PjRy pjRy, @RequestParam Map<String, Object> parameterMap, RedirectAttributes redirectAttributes) { PjRy dest = null; Long id = pjRy.getFid(); if (id != null) { dest = pjRyManager.get(id); beanMapper.copy(pjRy, dest); } else { dest = pjRy; } PjRyRecord pjRyRecord = new PjRyRecord(); pjRyRecord.setFdrxm(dest.getFxmid()); pjRyRecord.setFdrgw(dest.getFgangwei()); pjRyRecord.setFjingbanrenid(Long.valueOf(SpringSecurityUtils.getCurrentUserId())); pjRyRecord.setFryid(dest.getFryid()); pjRyRecord.setFdbdate(dest.getFstartdate()); dest.setFstatus("在岗"); pjRyManager.saveAndRecord(dest, pjRyRecord); messageHelper.addFlashMessage(redirectAttributes, "core.success.save", "保存成功"); return "redirect:/gcgl/pjRyRecord-info-list.do"; } @RequestMapping("pjRy-info-sub") public String sub(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "fxmid", required = false) Long fxmid, Model model) { if (id != null) { PjRy pjRy = pjRyManager.get(id); model.addAttribute("model", pjRy); } if (id == null && fxmid != null) { PjRy pjRy = new PjRy(); pjRy.setFxmid(fxmid); model.addAttribute("model", pjRy); } model.addAttribute("xmMap", PjXmMapUtil.getXmMap()); return "gcgl/pjRy-info-sub"; } @RequestMapping("pjRy-info-subsave") public String subsave(@ModelAttribute PjRy pjRy, @RequestParam Map<String, Object> parameterMap, RedirectAttributes redirectAttributes) { PjRy dest = null; Long id = pjRy.getFid(); if (id != null) { dest = pjRyManager.get(id); beanMapper.copy(pjRy, dest); } else { dest = pjRy; } /* PjRyRecord pjRyRecord=new PjRyRecord(); pjRyRecord.setFdrxm(dest.getFxmid()); pjRyRecord.setFdrgw(dest.getFgangwei()); pjRyRecord.setFjingbanrenid(Long.valueOf(SpringSecurityUtils.getCurrentUserId())); pjRyRecord.setFryid(dest.getFryid()); pjRyRecord.setFdbdate(dest.getFstartdate());*/ pjRyManager.saveSub(dest); messageHelper.addFlashMessage(redirectAttributes, "core.success.save", "保存成功"); return "redirect:/gcgl/pjRyRecord-info-list.do"; } @RequestMapping("pjXmRy-simple-list-ajax") public void listAjax(@ModelAttribute Page page, @RequestParam(value = "fxmid", required = false) Long fxmid, @RequestParam Map<String, Object> parameterMap, Model model, HttpServletResponse response) { List<PjRy> pjRies = pjRyManager.find("select pjry from PjRy pjry where fxmid=? and fstatus='在岗'", fxmid); List<Long> ryids = new ArrayList<Long>(); for (PjRy pjRy : pjRies) { ryids.add(pjRy.getFryid()); } List<CommRy> commRies = commRyManager.findByIds(ryids); JsonResponseUtil.write(response, commRies); } @RequestMapping("hrLz-simple-list-ajax") public void listhrLzAjax(@ModelAttribute Page page, @RequestParam(value = "fxmid", required = false) Long fxmid, @RequestParam Map<String, Object> parameterMap, Model model, HttpServletResponse response) { List<HrLz> pjRies = hrLzManager.find("select hrlz from HrLz hrlz "); List<Long> ryids = new ArrayList<Long>(); for (HrLz pjRy : pjRies) { ryids.add(pjRy.getFry()); } List<CommRy> commRies = new ArrayList<CommRy>(); if (!ryids.isEmpty()) { commRies = commRyManager.findByIds(ryids); } JsonResponseUtil.write(response, commRies); } @RequestMapping("pjRy-info-save") public String save(@ModelAttribute PjRy pjRy, @RequestParam Map<String, Object> parameterMap, RedirectAttributes redirectAttributes) { PjRy dest = null; Long id = pjRy.getFid(); if (id != null) { dest = pjRyManager.get(id); beanMapper.copy(pjRy, dest); } else { dest = pjRy; } PjRyRecord pjRyRecord = new PjRyRecord(); pjRyRecord.setFdrxm(dest.getFxmid()); pjRyRecord.setFdrgw(dest.getFgangwei()); pjRyRecord.setFjingbanrenid(Long.valueOf(SpringSecurityUtils.getCurrentUserId())); pjRyRecord.setFryid(dest.getFryid()); pjRyRecord.setFdbdate(dest.getFstartdate()); dest.setFstatus("在岗"); pjRyManager.saveAndRecord(dest, pjRyRecord); messageHelper.addFlashMessage(redirectAttributes, "core.success.save", "保存成功"); return "redirect:/gcgl/jlDept-info-input.do?fxmid=" + dest.getFxmid(); } @RequestMapping("pjRy-info-remove") public String remove(@RequestParam("selectedItem") List<Long> selectedItem, RedirectAttributes redirectAttributes) { List<PjRy> pjRys = pjRyManager.findByIds(selectedItem); pjRyManager.removeAll(pjRys); messageHelper.addFlashMessage(redirectAttributes, "core.success.delete", "删除成功"); // return "redirect:/gcgl/jlDept-info-input.do?fxmid="+pjRys.get(0).getFxmid(); return "redirect:/gcgl/pjRy-info-list.do"; } @RequestMapping("pjRy-info-export") public void export(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, HttpServletResponse response) throws Exception { List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); page = pjRyManager.pagedQuery(page, propertyFilters); List<PjRy> pjRys = (List<PjRy>) page.getResult(); TableModel tableModel = new TableModel(); //tableModel.setName("pjRy info"); //tableModel.addHeaders("id", "name"); tableModel.setData(pjRys); exportor.export(response, tableModel); } // ~ ====================================================================== @Resource public void setPjRyManager(PjRyManager pjRyManager) { this.pjRyManager = pjRyManager; } @Resource public void setExportor(Exportor exportor) { this.exportor = exportor; } @Resource public void setUserConnector(UserConnector userConnector) { this.userConnector = userConnector; } @Resource public void setMessageHelper(MessageHelper messageHelper) { this.messageHelper = messageHelper; } }
true
840524d9bbc4bf84a1fb0eecf320ca9774205d32
Java
EvilCodes/ShunJianMeiManager
/src/com/wenyuankeji/spring/dao/IBaseSuggestionDao.java
UTF-8
899
2.171875
2
[]
no_license
package com.wenyuankeji.spring.dao; import java.util.List; import com.wenyuankeji.spring.model.BaseSuggestionModel; import com.wenyuankeji.spring.util.BaseException; public interface IBaseSuggestionDao { /** * 根据商户id查询建议信息 * @param sid * @return * @throws BaseException */ public BaseSuggestionModel searchBaseSuggestion(int sid)throws BaseException; /** * 查询建议 * @param startTime * @param endTime * @param page * @param rows * @return * @throws BaseException */ public List<BaseSuggestionModel> searchBaseSuggestion(String startTime,String endTime,int page, int rows) throws BaseException; /** * 查询建议Count * @param startTime 注册开始时间 * @param endTime 注册结束时间 * @return * @throws BaseException */ public int searchBaseSuggestionCount(String startTime,String endTime) throws BaseException; }
true
eb19153fbb2996a187680f930ff46b7247e9d7ac
Java
MioProject/StargazerCloudSystem
/BusResources/com/stargazerproject/bus/resources/EventBusIPublicationErrorHandler.java
UTF-8
1,426
2.1875
2
[]
no_license
package com.stargazerproject.bus.resources; import com.stargazerproject.log.LogMethod; import net.engio.mbassy.bus.error.IPublicationErrorHandler; import net.engio.mbassy.bus.error.PublicationError; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component(value="eventBusIPublicationErrorHandler") @Qualifier("eventBusIPublicationErrorHandler") @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public class EventBusIPublicationErrorHandler implements IPublicationErrorHandler { @Autowired @Qualifier("logRecord") protected LogMethod log; @Override public void handleError(PublicationError error) { System.out.println(error.getMessage()); // An error message to describe what went wrong System.out.println(error.getCause()); // The underlying exception System.out.println(error.getPublishedMessage()); // The message that was published (can be null) System.out.println(error.getListener()); // The listener that was invoked when the execption was thrown (can be null) System.out.println(error.getHandler()); // The message handler (Method) that was invoked when the execption was thrown (can be null) } }
true
ac8d486931314cc3fc4d75f7e46cd27044416d33
Java
Hester1937/practice-it
/chapter-16/split.java
UTF-8
601
3.328125
3
[]
no_license
/* * Write a method split that rearranges the elements of a list so that all * of the negative values appear before all of the non-negatives. */ public void split() { ListNode current = front; if (current != null) { while (current.next != null) { if (current.next.data < 0) { ListNode temp = current.next.next; current.next.next = front; front = current.next; current.next = temp; } else { current = current.next; } } } }
true
7e796abceba58cafaf97a101a4c30115bcafbfa4
Java
zhmaylovv/java_first_dump
/src/Hash.java
UTF-8
566
3.296875
3
[]
no_license
import java.util.*; public class Hash { public static void main(String[] args) { HashMap<String, String> hm = new HashMap(); hm.put("Заря", "Солнце"); hm.put("Приливы", "Луна"); hm.put("Динозавры", "Астероид"); hm.put("Атланты", "Геродот"); System.out.println(hm); for (Map.Entry<String, String> entry : hm.entrySet()){ String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + ":" + value); } } }
true
dd807801c093fd0a1920e45ae4b3adb272429d8d
Java
EdotJ/crappybudget
/api/src/main/java/com/budgeteer/api/controllers/ReceiptHandlingController.java
UTF-8
2,701
2.140625
2
[]
no_license
package com.budgeteer.api.controllers; import com.budgeteer.api.dto.receipts.ReceiptParseResponse; import com.budgeteer.api.exception.ServiceDisabledException; import com.budgeteer.api.receipts.OnlineReceiptParser; import com.budgeteer.api.receipts.gcp.model.response.ApiResponse; import io.micronaut.context.annotation.Property; import io.micronaut.http.HttpResponse; import io.micronaut.http.MediaType; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Post; import io.micronaut.http.annotation.QueryValue; import io.micronaut.http.multipart.CompletedFileUpload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Named; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; @Controller("${api.base-path}/receipts") public class ReceiptHandlingController { private final Logger logger = LoggerFactory.getLogger(ReceiptHandlingController.class); private final OnlineReceiptParser<InputStream, ApiResponse, ReceiptParseResponse> basicParser; private final OnlineReceiptParser<InputStream, ApiResponse, ReceiptParseResponse> advancedParser; @Property(name = "api.receipt-recognition.enabled") private Boolean isRecognitionEnabled; public ReceiptHandlingController( @Named("BasicCloudVision") OnlineReceiptParser<InputStream, ApiResponse, ReceiptParseResponse> basic, @Named("AdvancedCloudVision") OnlineReceiptParser<InputStream, ApiResponse, ReceiptParseResponse> advanced) { this.basicParser = basic; this.advancedParser = advanced; } @Post(consumes = MediaType.MULTIPART_FORM_DATA) public HttpResponse<Object> parseReceipt(CompletedFileUpload file, @QueryValue(value = "isBasic", defaultValue = "true") boolean isBasic) throws IOException, ParseException { if (!isRecognitionEnabled) { String msg = "We were unable to process your request"; String detail = "Receipt recognition is disabled"; throw new ServiceDisabledException("receipts", msg, detail); } if (logger.isDebugEnabled()) { logger.debug("Got receipt parsing request"); } InputStream is = file.getInputStream(); OnlineReceiptParser<InputStream, ApiResponse, ReceiptParseResponse> receiptParser = isBasic ? basicParser : advancedParser; ApiResponse obj = receiptParser.makeRequest(is); is.close(); ReceiptParseResponse parseResponse = receiptParser.parseReceipt(obj); return HttpResponse.ok().body(parseResponse); } }
true
553d88bd169954d02e1a618f9af4d82a78ea15bd
Java
Xenia444/QA28_XeniaK_ILCarro_v1.0
/src/main/java/application/UserHelper.java
UTF-8
1,952
2.578125
3
[ "Apache-2.0" ]
permissive
package application; import models.User; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public class UserHelper extends HelperBase{ public UserHelper(WebDriver wd) { super(wd); } public void openLoginFrom() { click(By.xpath("//a[.=' Log in ']")); } public void fillLoginForm(String email, String password) { type(By.id("email"),email); type(By.id("password"),password); } public void fillLoginForm(User user) { type(By.id("email"),user.getEmail()); type(By.id("password"), user.getPassword()); } public void clickOkButton() { click(By.xpath("//button[.='Ok']")); } public boolean isLogged() { return wd.findElements(By.xpath("//a[.=' Log in ']")).size() > 0; } public void logOut() { click(By.xpath("//a[.=' Logout ']")); } public void clickOnSignUp() { click(By.xpath("//a[.=' Sign up ']")); } public void fillRegistrationForm(User user) { type(By.id("name"), user.getName()); type(By.id("lastName"), user.getLastName()); type(By.id("email"), user.getEmail()); type(By.id("password"), user.getPassword()); } public void clickOnCheckbox() { // click(By.xpath("//div[@class='checkbox-container']")); JavascriptExecutor js =(JavascriptExecutor) wd; js.executeScript("document.querySelector('#terms-of-use').click();"); // js.executeScript("document.querySelector('#terms-of-use').checked=true;"); } public void clickOnSubmit() { click(By.xpath("//*[@type='submit']")); } public String takeTheText() { return getText(By.xpath("//div[@class='dialog-container']//h2")); } public void waitTheRegistrationInSuccess() { waitForElement(By.xpath("//div[@class='dialog-container']//h2"), 30); } }
true
1fb1de25adc612a03d8e01ec3c1db1b4920d817f
Java
sionguo/SyncFile
/src/main/java/cn/guoxy/SyncRunnable.java
UTF-8
2,800
2.703125
3
[]
no_license
package cn.guoxy; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import java.io.File; import java.util.Objects; /** * @author Guo Xiaoyong */ public class SyncRunnable implements Runnable { private static final Log log = LogFactory.get(); private File sourceFile; private File distFile; private Boolean isDebug; public SyncRunnable(String source, String dist, Boolean isDebug) { sourceFile = new File(source); distFile = new File(dist); this.isDebug = isDebug; } @Override public void run() { while (true) { File[] files = sourceFile.listFiles(); if (Objects.isNull(files)) { continue; } for (File file : files) { try { syncFile(file, distFile.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } } private void syncFile(File f, String dist) { try { if (f.isFile()) { String parpath = f.getParentFile().getAbsolutePath(); String replace = StrUtil.replace(parpath, this.sourceFile.getAbsolutePath(), "", true); log.debug("{}", parpath); log.debug("{}", replace); File distDir; if (replace.isEmpty()) { distDir = new File(dist); if (!distDir.exists()) { distDir.mkdirs(); } } else { distDir = new File(dist + replace); if (!distDir.exists()) { distDir.mkdirs(); } } File re = FileUtil.copyFilesFromDir(f, distDir, true); if (!Objects.isNull(re)) { log.info("sync {} to {}", f.getAbsolutePath(), distDir.getAbsolutePath()); boolean isDel = FileUtil.del(f); if (isDel) { log.info("delete {}", f.getAbsolutePath()); } } } else if (f.isDirectory()) { File[] files = f.listFiles(); for (File file : files) { syncFile(file, dist); } if (!isDebug) { boolean isDel = FileUtil.del(f); if (isDel) { log.info("delete {}", f.getAbsolutePath()); } } } } catch (Exception e) { log.error(e.getLocalizedMessage()); } } }
true
fde6f62553a777810833e63ea91be21559e0c07f
Java
fgarcia1401/control-password
/app/src/main/java/br/com/fernando/control_password/ui/activities/RegisterActivity.java
UTF-8
2,815
1.96875
2
[]
no_license
package br.com.fernando.control_password.ui.activities; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import javax.inject.Inject; import br.com.fernando.control_password.R; import br.com.fernando.control_password.api.ControlPasswordService; import br.com.fernando.control_password.app.ControlPasswordApplication; import br.com.fernando.control_password.component.ControlPasswordComponent; import br.com.fernando.control_password.ui.fragments.RegisterCompleteNameFragment; import br.com.fernando.control_password.util.FragmentUtil; import butterknife.BindView; import butterknife.ButterKnife; public class RegisterActivity extends AppCompatActivity { @BindView(R.id.toolbar_top) Toolbar toolbar; @Inject ControlPasswordService controlPasswordService; private ControlPasswordComponent component; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); ButterKnife.bind(this ); component = ((ControlPasswordApplication) getApplication()).getComponent(); component.inject( this ); start(); setToolbar(); } public void setToolbar() { setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); } } private void start() { FragmentUtil.addFragment(getSupportFragmentManager(), R.id.fragment_container, new RegisterCompleteNameFragment()); } public void goNext(Fragment fragment) { FragmentUtil.closeKeyboard(this); FragmentUtil.replaceFragmentWithBackStack(getSupportFragmentManager(), R.id.fragment_container, fragment); } public void reqFocus(EditText editText) { editText.requestFocus(); final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public ControlPasswordService getControlPasswordService() { return controlPasswordService; } }
true
1a4d23b6dc14e9ab24326fad90c0d69d8fc98e17
Java
mikeleonida/QueryParser
/QueryParameter.java
UTF-8
4,878
2.796875
3
[]
no_license
package com.stackroute.datamunger.query.parser; import java.util.ArrayList; import java.util.List; /* * This class will contain the elements of the parsed Query String such as conditions, * logical operators,aggregate functions, file name, fields group by fields, order by * fields, Query Type * */ public class QueryParameter { private String query = ""; public QueryParameter() { } public QueryParameter(String query) { super(); this.query = query; } public void setQuery(String query) { this.query = query; } public String getFileName() { String[] words = getBaseQuery().split(" from "); if (words.length > 1) { return words[1]; } return null; } public String getBaseQuery() { return query.split(" where ")[0].split(" order by ")[0].split(" group by ")[0]; } public List<Restriction> getRestrictions() { List<Restriction> lr = new ArrayList<Restriction>(); String[] conditionWords = query.trim().replaceAll("\\s+", " ").split(" where "); if (conditionWords.length<2) { return lr; } String conditionClause = conditionWords[1].split(" order by ")[0].split(" group by ")[0]; return getRestrictionClauses(conditionClause); } public List<String> getLogicalOperators() { return parseLogicalOps(query); } public List<String> getFields() { return getListFromArr(getBaseQuery().replaceAll("^\\s*(S|s)elect\\s+", "").split(" from ")[0] .replaceAll("\\s*,\\s*"," ").split(" ")); } public List<AggregateFunction> getAggregateFunctions() { String[] fields = getBaseQuery().replace("\\s*(Select|select)\\s+", "").split(" from ")[0] .replaceAll("\\s*,\\s*"," ").split(" "); List<AggregateFunction> laf = new ArrayList<AggregateFunction>(); for (String f : fields) { f = f.replaceAll("\\s+", ""); if (f.contains( "(") && f.contains( ")" ) && ( f.indexOf('(') < f.indexOf(')') ) ) { String fn = f.substring(0, f.indexOf('(')); if (fn.equalsIgnoreCase("min") || fn.equalsIgnoreCase("max") || fn.equalsIgnoreCase("avg") || fn.equalsIgnoreCase("count") || fn.equalsIgnoreCase("sum")) { AggregateFunction af = new AggregateFunction(f.substring(f.indexOf('(')+1, f.indexOf(')')), fn); laf.add(af); } } } return laf; } public List<String> getGroupByFields() { String[] groupByWords = query.split(" group by "); if (groupByWords.length > 1) { return getListFromArr(groupByWords[1].split(" order by ")[0].replaceAll("\\s*,\\s*"," ").split(" ")); } return null; } public List<String> getOrderByFields() { String[] orderByWords = query.split(" order by "); if (orderByWords.length > 1) { return getListFromArr(orderByWords[1].split(" group by ")[0].replaceAll("\\s*,\\s*"," ").split(" ")); } return null; } private List<String> getListFromArr(String[] sa) { ArrayList<String> gf = new ArrayList<String>(); for (String field : sa) { gf.add(field); } return gf; } private List<Restriction> getRestrictionClauses(String conditionClause) { List<Restriction> lr = new ArrayList<Restriction>(); List<String> logicalOps = parseLogicalOps(conditionClause); String newConditionClause = new String(conditionClause); for (int i=0; i<=logicalOps.size(); i++) { String op = " "; if (i!=logicalOps.size()) { op = logicalOps.get(i); } String[] words = newConditionClause.split(" " + op + " "); String currentCondition = words[0].trim().replaceAll("\\s+", ""); lr.add(parseRestriction(currentCondition)); if (words.length<2) { break; } newConditionClause = newConditionClause.substring(newConditionClause.indexOf(" " + op + " ") + op.length()+2); } return lr; } private Restriction parseRestriction(String s) { if (s.contains("<=")) { return new Restriction(s.substring(0, s.indexOf("<=")), s.substring(s.indexOf("<=")+2), "<="); } else if (s.contains(">=")) { return new Restriction(s.substring(0, s.indexOf(">=")), s.substring(s.indexOf(">=")+2), ">="); } else if (s.contains("!=")) { return new Restriction(s.substring(0, s.indexOf("!=")), s.substring(s.indexOf("!=")+2), "!="); } else if (s.contains("<")) { return new Restriction(s.substring(0, s.indexOf("<")), s.substring(s.indexOf("<")+1), "<"); } else if (s.contains(">")) { return new Restriction(s.substring(0, s.indexOf(">")), s.substring(s.indexOf(">")+1), ">"); } else if (s.contains("=")) { return new Restriction(s.substring(0, s.indexOf("=")), s.substring(s.indexOf("=")+1), "="); } return new Restriction(); } private List<String> parseLogicalOps(String q) { List<String> ls = new ArrayList<String>(); String[] queryWords = q.trim().replaceAll("\\s+", " ").split(" "); for (String s : queryWords) { if (s.compareToIgnoreCase("and") == 0 || (s.compareToIgnoreCase("or") == 0) ) { ls.add(s.toLowerCase()); } } return ls; } }
true
d63667d9c9f0905bf9ec5fe3e14d7c6b74bfa602
Java
lor6/tutorials
/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/PersonRepository.java
UTF-8
373
2.140625
2
[ "MIT" ]
permissive
package com.baeldung.spring.data.couchbase2b.repos; import java.util.List; import com.baeldung.spring.data.couchbase.model.Person; import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository<Person, String> { List<Person> findByFirstName(String firstName); List<Person> findByLastName(String lastName); }
true
466fff8da11a452f1a9811779e44371915bceab1
Java
RoyalLachinov/ACTO_Assignment_Brandon
/app/src/main/java/com/project/acto_assignment_brandon/Activities_Adapters/PhotoActivity.java
UTF-8
3,332
2.1875
2
[]
no_license
package com.project.acto_assignment_brandon.Activities_Adapters; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import com.project.acto_assignment_brandon.MyViewModel; import com.project.acto_assignment_brandon.OffLineDataBase.Photo; import com.project.acto_assignment_brandon.R; import com.project.acto_assignment_brandon.Models.PhotoHolder; import java.util.List; public class PhotoActivity extends AppCompatActivity { private RecyclerView photo_recyclerView; private PhotoAdapter adapter; private OffLinePhotoAdapter offLinePhotoAdapter; private MyViewModel viewModel; private Context context; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo); photo_recyclerView = findViewById(R.id.photo_recyclerView); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL); photo_recyclerView.setLayoutManager(layoutManager); photo_recyclerView.setHasFixedSize(true); if(isNetworkAvailable()){ viewModel = ViewModelProviders.of(this).get(MyViewModel.class); viewModel.getAllPhoto().observe(this, new Observer<List<PhotoHolder>>() { @Override public void onChanged(@Nullable List<PhotoHolder> photoHolders) { populatePhotoRecyclerView(photoHolders, context); viewModel.deleteAllPhoto(); for (int i = 0; i < photoHolders.size(); i++) { Photo photo = new Photo(photoHolders.get(i).getTitle(),photoHolders.get(i).getUrl()); viewModel.insert(photo); } } }); }else { viewModel = ViewModelProviders.of(this).get(MyViewModel.class); viewModel.getOffLinePhoto().observe(this, new Observer<List<Photo>>() { @Override public void onChanged(@Nullable List<Photo> photos) { offLinePhotoAdapter = new OffLinePhotoAdapter(photos,context); photo_recyclerView.setAdapter(offLinePhotoAdapter); } }); } } private void populatePhotoRecyclerView(List<PhotoHolder> photoHolders, Context context){ adapter = new PhotoAdapter(photoHolders, context); photo_recyclerView.setAdapter(adapter); adapter.notifyDataSetChanged(); } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = null; if (manager != null) { networkInfo = manager.getActiveNetworkInfo(); }return networkInfo != null && networkInfo.isConnected(); } }
true
dbaa3af346b3e7f3569d52f5441a1cd93a68e4a9
Java
Mm12341234/Demo
/generator/src/main/java/com/example/entity/ColumnInfo.java
UTF-8
696
2.28125
2
[]
no_license
package com.example.entity; import com.example.utils.StringUtil; import lombok.Data; import java.io.Serializable; /** * @Author Liumq * @Date 2019/05/23 */ @Data public class ColumnInfo implements Serializable { private String columnName; // 列名 private int type; // 类型代码 private String propertyName; // 属性名 private boolean isPrimaryKey; // 是否主键 public ColumnInfo() { } public ColumnInfo(String columnName, int type, boolean isPrimaryKey) { this.columnName = columnName; this.type = type; this.propertyName = StringUtil.columnName2PropertyName(columnName); this.isPrimaryKey = isPrimaryKey; } }
true
df02e3d1814420a1ceeacf36624613379501f1ff
Java
pptik/Android-RabbitMQ-Client-Test
/app/src/main/java/pptik/org/rabbitmqclienttest/MainActivity.java
UTF-8
3,212
2.0625
2
[]
no_license
package pptik.org.rabbitmqclienttest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import java.io.IOException; import pptik.org.rabbitmqclienttest.rabbit.ManagerRabbitMQ; public class MainActivity extends AppCompatActivity { ManagerRabbitMQ manage; private static final String EXCHANGE_NAME = "sabuga.chat"; private static String TAG_INCOMING = "Incoming Message"; private String TAG = getClass().getSimpleName(); private EditText boxChat; private ImageButton btnSend; private TextView chatMain; private static final String ACTION_STRING_ACTIVITY = "broadcast_event"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); boxChat = (EditText)findViewById(R.id.boxChat); btnSend = (ImageButton)findViewById(R.id.btnsend); chatMain = (TextView)findViewById(R.id.chatMain); manage = new ManagerRabbitMQ(MainActivity.this); manage.connectToRabbitMQ(); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { manage.sendMessage(boxChat.getText().toString()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver( mMessageReceiver); super.onPause(); } @Override protected void onResume() { LocalBroadcastManager.getInstance(this).registerReceiver( mMessageReceiver, new IntentFilter(ACTION_STRING_ACTIVITY)); super.onResume(); } @Override protected void onDestroy(){ manage.dispose(); super.onDestroy(); } private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("message"); chatMain.setText(chatMain.getText().toString()+"\n"+message); } }; }
true
9b2df806f3a746ad512669580d72ca5c1c2807f0
Java
rpm-house/OnlineUML
/src/main/java/org/infosys/biz/CallHierarchyVO.java
UTF-8
596
2.34375
2
[]
no_license
package org.infosys.biz; import java.util.List; public class CallHierarchyVO { String methodName; List<String> methodInvokes; public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public List<String> getMethodInvokes() { return methodInvokes; } public void setMethodInvokes(List<String> methodInvokes) { this.methodInvokes = methodInvokes; } @Override public String toString() { return "{methodName:" + methodName + ", methodInvokes:" + methodInvokes + "}"; } }
true
4a7855112be1e2b4eca010a983e2d961198631b0
Java
qinmeng110/001
/最大公约数和最小公倍数.java
GB18030
923
3.328125
3
[]
no_license
package javaϰ; import java.util.Scanner; public class ԼС { public static void main(String[] args) { Scanner in=new Scanner(System.in);//ʼ int x=in.nextInt(); int y=in.nextInt(); if(x>y){int temp; temp=x;x=y;y=temp;} int m=x; int n=y; int i; while(true){ i=y%x; y=x; x=i; if(x==0) break; } System.out.println("Լ"+y);// Լ System.out.println("-------------"); int a[] = {0}; int j=0;// for(i=2;i<=m;i++){ if(m%i==0&&n%i==0){ a[j]=i; j++; m=m/i;n=n/i;i=i-1; } } int sum=1; for(j=0;a[j]!=0;j++){ sum=sum*a[j]; } sum=sum*m*n; System.out.print("С"+sum); } }
true
7c66bf5c86fca2d370d676af41df874de1f5da2d
Java
Arun-George-Zachariah/TorcDB
/src/main/java/net/ellitron/torc/util/MeasurementClient.java
UTF-8
19,929
1.65625
2
[ "Apache-2.0", "ISC" ]
permissive
/* Copyright (c) 2015-2019 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package net.ellitron.torc.util; import static edu.stanford.ramcloud.ClientException.*; import static java.lang.Thread.sleep; import net.ellitron.torc.TorcGraph; import edu.stanford.ramcloud.*; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.io.FilenameUtils; import org.apache.tinkerpop.gremlin.structure.T; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Map; /** * * @author Jonathan Ellithorpe (jde@cs.stanford.edu) */ public class MeasurementClient { private static final Logger logger = Logger.getLogger(MeasurementClient.class.getName()); private final String coordinatorLocator; private final int numClients; private final int clientIndex; private final PrintWriter logFile; private final String logDir; private final int numMasters; private final long testDuration; private final int numSamples; private final int threads; private static final Map<String, Runnable> tests = new HashMap<>(); RAMCloud cluster; private long controlTableId; public MeasurementClient(String coordinatorLocator, int numClients, int clientIndex, PrintWriter logFile, String logDir, int numMasters, long testDuration, int numSamples, int threads) { this.coordinatorLocator = coordinatorLocator; this.numClients = numClients; this.clientIndex = clientIndex; this.logFile = logFile; this.logDir = logDir; this.numMasters = numMasters; this.testDuration = testDuration; this.numSamples = numSamples; this.threads = threads; tests.put("testAddVertexThroughput", () -> testAddVertexThroughput()); tests.put("testAddVertexLatency", () -> testAddVertexLatency()); cluster = new RAMCloud(coordinatorLocator); controlTableId = cluster.createTable("controlTable"); } private enum ControlRegister { COMMAND, ARGUMENTS, RETURN_CODE, RETURN_VALUE, } private enum CommandCode { RUN, RUN_CONTINUOUSLY, STOP, DIE, } private enum ReturnStatus { STATUS_OK, UNRECOGNIZED_COMMAND, INVALID_COMMAND, } private String getRegisterKey(int clientIndex, ControlRegister reg) { return String.format("%d:%s", clientIndex, reg.name()); } /** * Helper methods used by masters. */ private void issueCommandToSlaves(CommandCode cmd, String args, int firstSlave, int numSlaves) { // Clear status and return value registers. for (int i = 0; i < numSlaves; ++i) { String regKey = getRegisterKey(firstSlave + i, ControlRegister.RETURN_CODE); cluster.remove(controlTableId, regKey); regKey = getRegisterKey(firstSlave + i, ControlRegister.RETURN_VALUE); cluster.remove(controlTableId, regKey); } // If this command has args, first write the args. if (args != null) { for (int i = 0; i < numSlaves; ++i) { String regKey = getRegisterKey(firstSlave + i, ControlRegister.ARGUMENTS); cluster.write(controlTableId, regKey, args); } } // Finally issue the command. for (int i = 0; i < numSlaves; ++i) { String regKey = getRegisterKey(firstSlave + i, ControlRegister.COMMAND); cluster.write(controlTableId, regKey, cmd.name()); } } private void pollSlaves(int firstSlave, int numSlaves, double timeoutSeconds) throws Exception { for (int i = 0; i < numSlaves; ++i) { String regKey = getRegisterKey(firstSlave + i, ControlRegister.RETURN_CODE); long startTimeMillis = System.currentTimeMillis(); while (true) { try { RAMCloudObject obj = cluster.read(controlTableId, regKey); if (obj != null) { if (obj.getValue().equals(ReturnStatus.STATUS_OK.name())) { break; } else { throw new Exception("Slave " + (firstSlave + i) + " returned error status " + obj.getValue()); } } } catch (TableDoesntExistException e) { } double elapsedTimeSeconds = (System.currentTimeMillis() - startTimeMillis) / 1000.0; if (elapsedTimeSeconds > timeoutSeconds) { throw new Exception("Slave " + (firstSlave + i) + " did not return a status after " + timeoutSeconds + "s."); } try { sleep(10L); } catch (InterruptedException ex) { } } } } private String[] readSlavesReturnValues(int firstSlave, int numSlaves) { String[] values = new String[numSlaves]; for (int i = 0; i < numSlaves; ++i) { String regKey = getRegisterKey(firstSlave + i, ControlRegister.RETURN_VALUE); try { RAMCloudObject obj = cluster.read(controlTableId, regKey); if (obj != null) { values[i] = obj.getValue(); } else { values[i] = null; } } catch (TableDoesntExistException e) { throw new RuntimeException(e); } } return values; } /** * Helper methods used by slaves. */ private CommandCode pollForCommand() { String regKey = getRegisterKey(clientIndex, ControlRegister.COMMAND); while (true) { try { RAMCloudObject obj = cluster.read(controlTableId, regKey); if (obj != null) { return CommandCode.valueOf(obj.getValue()); } } catch (TableDoesntExistException e) { } catch (ClientException e) { throw new RuntimeException(e); } try { sleep(10L); } catch (InterruptedException ex) { } } } private CommandCode checkForCommand() { String regKey = getRegisterKey(clientIndex, ControlRegister.COMMAND); try { RAMCloudObject obj = cluster.read(controlTableId, regKey); if (obj != null) { return CommandCode.valueOf(obj.getValue()); } else { return null; } } catch (TableDoesntExistException e) { return null; } catch (ClientException e) { throw new RuntimeException(e); } } private String readCommandArguments() { String regKey = getRegisterKey(clientIndex, ControlRegister.ARGUMENTS); try { RAMCloudObject obj = cluster.read(controlTableId, regKey); if (obj != null) { return obj.getValue(); } } catch (TableDoesntExistException e) { } catch (ClientException e) { throw new RuntimeException(e); } return null; } private void setStatusAndReturnValue(ReturnStatus status, String returnValue) { // Clear command register. String regKey = getRegisterKey(clientIndex, ControlRegister.COMMAND); cluster.remove(controlTableId, regKey); // Clear command arguments register. regKey = getRegisterKey(clientIndex, ControlRegister.ARGUMENTS); cluster.remove(controlTableId, regKey); // First write out the return value string. if (returnValue != null) { regKey = getRegisterKey(clientIndex, ControlRegister.RETURN_VALUE); cluster.write(controlTableId, regKey, returnValue); } // Finally write out the return status. regKey = getRegisterKey(clientIndex, ControlRegister.RETURN_CODE); cluster.write(controlTableId, regKey, status.name()); } public void testAddVertexThroughput() { BaseConfiguration ramCloudGraphConfig = new BaseConfiguration(); ramCloudGraphConfig.setDelimiterParsingDisabled(true); ramCloudGraphConfig.setProperty(TorcGraph.CONFIG_COORD_LOCATOR, coordinatorLocator); ramCloudGraphConfig.setProperty(TorcGraph.CONFIG_NUM_MASTER_SERVERS, numMasters); TorcGraph graph = TorcGraph.open(ramCloudGraphConfig); if (clientIndex == 0) { PrintWriter dataFile; try { dataFile = new PrintWriter(logDir + "/testAddVertexThroughput.data", "UTF-8"); } catch (FileNotFoundException | UnsupportedEncodingException ex) { logger.log(Level.SEVERE, null, ex); return; } dataFile.println("## testAddVertexThroughput(): testDuration=" + testDuration + ", numMasters=" + numMasters); dataFile.println("## clients operations per second"); dataFile.println("## ----------------------------------"); for (int slaves = 1; slaves < numClients; ++slaves) { System.out.println("testAddVertexThroughput(): testDuration=" + testDuration + ", numMasters=" + numMasters + ", clients=" + slaves); try { pollSlaves(1, slaves, 10.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); issueCommandToSlaves(CommandCode.DIE, null, 1, numClients - 1); return; } long startTime = System.currentTimeMillis(); issueCommandToSlaves(CommandCode.RUN, null, 1, slaves); try { pollSlaves(1, slaves, testDuration * 2.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); issueCommandToSlaves(CommandCode.DIE, null, 1, numClients - 1); return; } long elapsedTime = (System.currentTimeMillis() - startTime) / 1000; String retVals[] = readSlavesReturnValues(1, slaves); long totalOps = 0; for (int i = 0; i < slaves; ++i) { totalOps += Long.decode(retVals[i]); } dataFile.println(String.format("%8d\t%d", slaves, totalOps / elapsedTime)); dataFile.flush(); } issueCommandToSlaves(CommandCode.DIE, null, 1, numClients - 1); try { pollSlaves(1, numClients - 1, 10.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } dataFile.flush(); dataFile.close(); graph.deleteGraph(); graph.close(); return; } else { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); while (true) { CommandCode cmd = pollForCommand(); if (cmd == CommandCode.RUN) { long opCount = 0; long startTime = System.nanoTime(); while (true) { graph.addVertex(T.label, "Person", "name", "Raggles"); opCount++; if (opCount % 1000 == 0) { if ((System.nanoTime() - startTime) / 1000000000L > testDuration) { break; } } } setStatusAndReturnValue(ReturnStatus.STATUS_OK, Long.toString(opCount)); } else if (cmd == CommandCode.DIE) { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); graph.close(); return; } else { // Don't recognize this command." setStatusAndReturnValue(ReturnStatus.UNRECOGNIZED_COMMAND, null); graph.close(); return; } } } } public void testAddVertexLatency() { BaseConfiguration ramCloudGraphConfig = new BaseConfiguration(); ramCloudGraphConfig.setDelimiterParsingDisabled(true); ramCloudGraphConfig.setProperty(TorcGraph.CONFIG_COORD_LOCATOR, coordinatorLocator); ramCloudGraphConfig.setProperty(TorcGraph.CONFIG_NUM_MASTER_SERVERS, numMasters); TorcGraph graph = TorcGraph.open(ramCloudGraphConfig); if (clientIndex == 0) { for (int slaves = 0; slaves < numClients; ++slaves) { int clients = slaves + 1; System.out.println("testAddVertexLatency(): numSamples=" + numSamples + ", numMasters=" + numMasters + ", clients=" + clients); PrintWriter dataFile; try { dataFile = new PrintWriter(logDir + "/testAddVertexLatency" + clients + ".data", "UTF-8"); } catch (FileNotFoundException | UnsupportedEncodingException ex) { logger.log(Level.SEVERE, null, ex); return; } dataFile.println("## testAddVertexLatency(): numSamples=" + numSamples + ", numMasters=" + numMasters + ", clients=" + clients); dataFile.println("## latency (us) % Samples > X"); dataFile.println("## ----------------------------------"); // Wait for slaves to be ready. try { pollSlaves(1, slaves, 10.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); issueCommandToSlaves(CommandCode.DIE, null, 1, numClients - 1); return; } issueCommandToSlaves(CommandCode.RUN_CONTINUOUSLY, null, 1, slaves); // Wait for slaves to be running. try { pollSlaves(1, slaves, 10.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); issueCommandToSlaves(CommandCode.DIE, null, 1, numClients - 1); return; } // Take measurements. List<Double> latencyTimesUs = new ArrayList<Double>(numSamples); for (int i = 0; i < numSamples; ++i) { long opStartTime = System.nanoTime(); graph.addVertex(T.label, "Person", "name", "Raggles"); long latency = System.nanoTime() - opStartTime; latencyTimesUs.add(((double) latency) / 1000.0); } issueCommandToSlaves(CommandCode.STOP, null, 1, slaves); Collections.sort(latencyTimesUs); for (int i = 0; i < numSamples; ++i) { double percentile = (double) i / (double) numSamples; dataFile.println(String.format("%8.1f\t%.6f", latencyTimesUs.get(i), 1.0 - percentile)); } dataFile.flush(); dataFile.close(); } // Wait for slaves to be stopped. try { pollSlaves(1, numClients - 1, 10.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } // Command slaves to die. issueCommandToSlaves(CommandCode.DIE, null, 1, numClients - 1); try { pollSlaves(1, numClients - 1, 10.0); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } graph.deleteGraph(); graph.close(); return; } else { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); while (true) { CommandCode cmd = pollForCommand(); if (cmd == CommandCode.RUN_CONTINUOUSLY) { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); long startTime = System.currentTimeMillis(); while (true) { graph.addVertex(T.label, "Person", "name", "Raggles"); if (System.currentTimeMillis() - startTime > 100l) { cmd = checkForCommand(); if (cmd == null) { startTime = System.currentTimeMillis(); } else if (cmd == CommandCode.DIE) { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); graph.close(); return; } else if (cmd == CommandCode.STOP) { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); break; } else { setStatusAndReturnValue(ReturnStatus.INVALID_COMMAND, null); startTime = System.currentTimeMillis(); } } } } else if (cmd == CommandCode.DIE) { setStatusAndReturnValue(ReturnStatus.STATUS_OK, null); graph.close(); return; } else { // Don't recognize this command." setStatusAndReturnValue(ReturnStatus.UNRECOGNIZED_COMMAND, null); graph.close(); return; } } } } public void executeTest(String testName) { tests.get(testName).run(); } /** * @param args the command line arguments */ public static void main(String[] args) { Options options = new Options(); String coordinatorLocator; int numClients; int clientIndex; String logFileName; int numMasters; long testDuration; int numSamples; int threads; String testName; options.addOption("C", "coordinator", true, "Service locator where the " + "coordinator can be contacted."); options.addOption(null, "numClients", true, "Total number of clients."); options.addOption(null, "clientIndex", true, "This client's index number " + "in total clients."); options.addOption(null, "logFile", true, "File to use as the log."); options.addOption(null, "numMasters", true, "Total master servers."); options.addOption(null, "testDuration", true, "Duration of each test."); options.addOption(null, "numSamples", true, "Number of samples to take."); options.addOption(null, "threads", true, "Number of threads to use."); options.addOption(null, "testName", true, "Name of the test to run."); options.addOption("h", "help", false, "Print usage."); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException ex) { logger.log(Level.SEVERE, null, ex); return; } if (cmd.hasOption("h")) { formatter.printHelp("MeasurementClient", options); return; } // Required parameters. if (cmd.hasOption("coordinator")) { coordinatorLocator = cmd.getOptionValue("coordinator"); } else { logger.log(Level.SEVERE, "Missing required argument: coordinator"); return; } if (cmd.hasOption("numMasters")) { numMasters = Integer.decode(cmd.getOptionValue("numMasters")); } else { logger.log(Level.SEVERE, "Missing required argument: numMasters"); return; } // Optional parameters. testDuration = Long.decode(cmd.getOptionValue("testDuration", "5")); numSamples = Integer.decode(cmd.getOptionValue("numSamples", "1000000")); threads = Integer.decode(cmd.getOptionValue("threads", "1")); numClients = Integer.decode(cmd.getOptionValue("numClients", "1")); clientIndex = Integer.decode(cmd.getOptionValue("clientIndex", "0")); logFileName = cmd.getOptionValue("logFile"); testName = cmd.getOptionValue("testName"); PrintWriter logFile; try { logFile = new PrintWriter(logFileName, "UTF-8"); } catch (FileNotFoundException | UnsupportedEncodingException ex) { logger.log(Level.SEVERE, null, ex); return; } String logDir = FilenameUtils.getFullPathNoEndSeparator(logFileName); MeasurementClient mc = new MeasurementClient(coordinatorLocator, numClients, clientIndex, logFile, logDir, numMasters, testDuration, numSamples, threads); mc.executeTest(testName); } }
true
1cb141efb83b81805e6c5a61375d6c2f48a71fac
Java
NullEmpty/CarlDemo
/bwgallerylibrary/src/main/java/com/royole/bwgallery/AbsGalleryLinearLayout.java
UTF-8
2,350
2.140625
2
[]
no_license
package com.royole.bwgallery; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.LinearLayout; /** * Created by pcxu on 2016/2/26. */ public class AbsGalleryLinearLayout extends LinearLayout { private static final String TAG = AbsGalleryLinearLayout.class.getSimpleName(); private String mIndex = "0"; private int mType = ItemType.ITEM_TYPE_2; private PaintFlagsDrawFilter mPaintFlagsDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); public AbsGalleryLinearLayout(Context context) { super(context); } public AbsGalleryLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public AbsGalleryLinearLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (findViewWithTag("3") != null) { mType = ItemType.ITEM_TYPE_3; } else if (findViewWithTag("1") != null) { mType = ItemType.ITEM_TYPE_1; } else { mType = ItemType.ITEM_TYPE_2; } } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { // Log.e(TAG, "onFocusChanged" + gainFocus + "," + direction + "," + previouslyFocusedRect.toString()); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); } public void setIndex(String index) { mIndex = index; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { if (mType == ItemType.ITEM_TYPE_3) { findViewWithTag(mIndex).requestFocus(direction, previouslyFocusedRect); mIndex = "0"; return true; } return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); } @Override protected void dispatchDraw(Canvas canvas) { canvas.setDrawFilter(mPaintFlagsDrawFilter); super.dispatchDraw(canvas); } }
true
8d4a3d9f31d1004bcf3746c11218b2ce838f962c
Java
Sylwester12351/Weather-App
/src/main/java/service/Properties.java
UTF-8
311
1.765625
2
[]
no_license
package service; public class Properties { public static final String DB_DRIVER = "org.postgresql.Driver"; public static final String DB_URL = "jdbc:postgresql://localhost:5432/postgres"; public static final String DB_USER = "postgres"; public static final String DB_PASSWORD = "root"; }
true
79fcd2b9fd80cb157937782959a22e870771de4f
Java
chinaliuweijie/qmdoctors
/app/src/main/java/com/qingmiao/qmdoctor/global/JSObject.java
UTF-8
3,722
2.15625
2
[]
no_license
package com.qingmiao.qmdoctor.global; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.webkit.JavascriptInterface; import android.widget.Toast; import com.qingmiao.qmdoctor.activity.WebCommentActivity; import com.qingmiao.qmdoctor.activity.WebViewCircleActivity; import com.qingmiao.qmdoctor.bean.WebShareBean; import com.qingmiao.qmdoctor.utils.GsonUtil; import com.qingmiao.qmdoctor.utils.ToastUtils; import com.umeng.socialize.ShareAction; import com.umeng.socialize.UMShareListener; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.media.UMWeb; /** * company : 青苗 * Created by 刘伟杰 on 2017/3/2. */ public class JSObject { /* * 绑定的object对象 * */ private Context context; // public ClickJs clickJs; private String id; public JSObject(Context context) { this.context = context; } // public void setClickJs(ClickJs clickJs) { // this.clickJs = clickJs; // } public void setId(String id) { this.id = id; } /* * JS调用android的方法 * @JavascriptInterface仍然必不可少 * * */ @JavascriptInterface public void postShare(String s1) { // 分享的点击 // if(clickJs!=null){ // clickJs.onClickShare(s1); // } WebShareBean webShareBean = GsonUtil.getInstance().fromJson(s1, WebShareBean.class); UMImage image = new UMImage(context, webShareBean.thumb);//网络图片 image.setThumb(image); UMWeb web = new UMWeb(UrlGlobal.SERVER_URL + webShareBean.url); web.setTitle(webShareBean.title);//标题 web.setThumb(image); //缩略图 web.setDescription(webShareBean.description);//描述 System.out.println(webShareBean.action); if (webShareBean.action.equals("qq")) { showShare(web, SHARE_MEDIA.QQ); } else if (webShareBean.action.equals("wechat")) { showShare(web, SHARE_MEDIA.WEIXIN); } else if (webShareBean.action.equals("wechat_timeline")) { showShare(web, SHARE_MEDIA.WEIXIN_CIRCLE); } else if (webShareBean.action.equals("sina")) { showShare(web, SHARE_MEDIA.SINA); } } private void showShare(UMWeb web, SHARE_MEDIA shareMedia) { new ShareAction((Activity) context) .setPlatform(shareMedia) .withMedia(web) .setCallback(new UMShareListener() { @Override public void onStart(SHARE_MEDIA share_media) { } @Override public void onResult(SHARE_MEDIA share_media) { ToastUtils.showLongToast(context, "分享成功!"); } @Override public void onError(SHARE_MEDIA share_media, Throwable throwable) { ToastUtils.showLongToast(context, throwable.getMessage()); } @Override public void onCancel(SHARE_MEDIA share_media) { ToastUtils.showLongToast(context, "分享取消!"); } }).share(); } @JavascriptInterface public void commentList() { Intent intent = new Intent(context, WebCommentActivity.class); intent.putExtra("id", id); context.startActivity(intent); } // public interface ClickJs{ // public void onClickCommentList(); // public void onClickShare(String str); // // } }
true
ee6e55e16079f29b0d91031258673785b622f498
Java
evrimulgen/Blog-Project-Files
/JAX-RS/0004-com.enesbyc-RESTful-JAXB/src/com/enesbyc/service/ProductService.java
ISO-8859-2
679
2.390625
2
[]
no_license
package com.enesbyc.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.enesbyc.model.Product; //Url kismina /rest/product geldiginde yapilacaklari belirtiyoruz. @Path("product") public class ProductService { //Url kismina /rest/product/info geldiginde yapilacaklari belirtiyoruz. //XML tipinde veri dnecegini belirtiyoruz. @GET @Path("info") @Produces(MediaType.APPLICATION_XML) public Product getProductInfo(){ Product product=new Product(); product.setProductName("Cup"); product.setProductPrice("25"); return product; } }
true
4ec51b0ba4d06f3bc70862e0d1fc7b0f6d9868b1
Java
inavangen/Clustering
/Euclidean.java
UTF-8
429
3.40625
3
[]
no_license
public class Euclidean implements DistanceMeasure { public double calculateDistance(Unit unit1, Unit unit2){ int numOfVariables = unit1.getNumOfVariables(); double sum = 0; double unit1_var = 0; double unit2_var = 0; for (int i = 0; i < numOfVariables; i++){ unit1_var = unit1.getValue(i); unit2_var = unit2.getValue(i); sum += Math.pow((unit1_var - unit2_var), 2 ); } return Math.sqrt(sum); } }
true
37f3eb4e71da8435778ad89ef0a3a251d521ccff
Java
gyjnoodle/Ioc
/src/main/java/com/gyj/ioc/annotations/MyAutowired.java
UTF-8
261
1.945313
2
[]
no_license
package com.gyj.ioc.annotations; import java.lang.annotation.*; /** * @Author noodle * @Description 自定义服务的依赖注入 */ @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAutowired { }
true
60592234e4386eca3e606055f61f7860f764a1b4
Java
denis-v-s/CSE148-HW05
/src/Person.java
UTF-8
2,177
3.90625
4
[]
no_license
/** * Person */ public class Person { private String name; private String address; private int age; private String phoneNumber; private String gender; public Person() {} public Person(String name, String address, int age, String phoneNumber, String gender) { this.name = name; this.address = address; this.age = age; this.phoneNumber = phoneNumber; this.gender = gender; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } // getters / setters for name, address, age, and phone public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getGender() { return this.gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return String.format( "My name is %S, I'm %d years old, %s", this.getName(), this.getAge(), this.getGender() ); } // equals if name, age, and gender are the same @Override public boolean equals(Object o) { Person p = (Person) o; return ( this.getName().equals(p.getName()) && this.getAge() == p.getAge() && this.getAddress().equals(p.getAddress()) && this.getPhoneNumber().equals(p.getPhoneNumber()) && this.getGender().equals(p.getGender()) ); } public static void main(String[] args) { // Write appropriate getter and setter methods. Test the program by creating two // instances (objects) and printing out the information. Person p1 = new Person(); Person p2 = new Person(); p1.setName("John Doe"); p1.setAddress("123 whatever street"); p1.setAge(21); p1.setPhoneNumber("321 456 4566"); p2.setName("Jane Doe"); p2.setAddress("456 another street"); p2.setAge(19); p2.setPhoneNumber("888 454 2221"); System.out.println(p1); System.out.println(p2); } }
true
fe612442a390a8f726a0887e6e470a873ca3463e
Java
Falldays/wsccode
/coding/src/main/java/com/qst/ssm/controller/UserController.java
UTF-8
4,925
2.328125
2
[]
no_license
package com.qst.ssm.controller; import com.qst.ssm.entity.User; import com.qst.ssm.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.DigestUtils; 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.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 处理用户业务控制器 */ @Controller @RequestMapping("user") public class UserController { @Autowired @Qualifier("userService") private IUserService userService; /*** * 查询所有用户 * @return */ @RequestMapping("cxUser") public String cxUser(Model model){ List<User> userList=userService.cxUser(); model.addAttribute("userList",userList); return "/user/query_user.jsp"; } @RequestMapping("xgUser") public String xgUser(Model model){ List<User> userList=userService.cxUser(); model.addAttribute("userList",userList); return "/user/query+update-user.jsp"; } @RequestMapping("query") public String queryUser(Model model) { List<User> userList = userService.queryUser(); model.addAttribute("userList",userList); return "/user/query_user.jsp"; } /** * 根据用户ID删除用户 * * @param userId * @return */ @RequestMapping("delete") public String deleteUser(@RequestParam("user_id") int userId) { int rows = userService.deleteUser(userId); //重定向到删除结果的页面 return "redirect:/user/delete_user_result.jsp?rows=" + rows; } /** * 查看详细信息 * * @return */ @RequestMapping("info") public String showInfo(@RequestParam("user_id") int userId, Model model) { User user = userService.getUser(userId); model.addAttribute("user", user); return "/user/info.jsp"; } /** * 添加用户 * * @param user * @return */ @RequestMapping("add") public String addUser(User user) { int rows = userService.insertUser(user); return "redirect:/user/add_user_result.jsp?rows=" + rows; } /** * 加载用户数据 * http://localhost:8080/user/load_one?user_id=4 * * @param userId * @return */ @RequestMapping(value = "load_one", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public Map<String, Object> loadUserData(@RequestParam("user_id") int userId,HttpServletRequest request) { User user = userService.getUser(userId); String username=request.getParameter("username"); // User users = userService.queryUser(username); Map<String, Object> dataMap = new HashMap<>(); dataMap.put("user", user); return dataMap; } /** * 修改用户 * * @param user * @return */ @RequestMapping("update") public String updateUser(User user) { int rows =userService.updateUser(user); return "redirect:/user/update_user_result.jsp?rows="+rows; } /** * 用户登录 * @param user * @param model * @param session * @return */ @RequestMapping(value = "login",method = RequestMethod.POST) public String login(User user, Model model, HttpSession session){ User user1 = userService.login(user); String href= null; if (user1==null){ //出现异常 model.addAttribute("msg","发生异常,请重新登录!"); return "/user/userLogin.jsp"; }else if (user1.getUserId()==null){ //不存在 model.addAttribute("msg","账号或密码错误,请重新登录!"); return "/user/userLogin.jsp"; }//else { //登录成功 session.setAttribute("user",user1); return "redirect:/userIndex.jsp"; /* } model.addAttribute("msg","用户名或密码错误,请重新登录!"); System.out.println("用户名或密码错误,请重新登录"); return href="/userLogin.jsp";*/ } /** * 用户退出 * @param session * @return * @throws Exception */ @RequestMapping(value = "/logout") public String logout(HttpSession session)throws Exception{ session.removeAttribute("userId"); session.invalidate(); return "redirect:/userIndex.jsp"; } }
true
d60b32e5141eb5084eaceb3762b88ca16d28cd3f
Java
nckmml/ANXGallery
/src/ANXGallery/sources/com/miui/gallery/loader/ProcessingMediaLoader.java
UTF-8
3,316
2.046875
2
[]
no_license
package com.miui.gallery.loader; import android.content.AsyncTaskLoader; import android.content.ContentResolver; import android.content.Context; import android.content.Loader; import android.database.ContentObserver; import com.miui.gallery.photosapi.PhotosOemApi; import com.miui.gallery.provider.ProcessingMedia; import com.miui.gallery.provider.ProcessingMediaManager; import java.util.List; public class ProcessingMediaLoader extends AsyncTaskLoader<List<ProcessingMedia>> { private static boolean sHasSpecialTypesProvider = true; private List<ProcessingMedia> mDataSet; private final ContentObserver mForceLoadContentObserver = new Loader.ForceLoadContentObserver(this); private boolean mIsObserversRegistered; public ProcessingMediaLoader(Context context) { super(context); } private void registerContentObservers() { if (!this.mIsObserversRegistered) { this.mIsObserversRegistered = true; ContentResolver contentResolver = getContext().getContentResolver(); if (sHasSpecialTypesProvider) { try { contentResolver.registerContentObserver(PhotosOemApi.getQueryProcessingUri(getContext()), true, this.mForceLoadContentObserver); } catch (Exception unused) { sHasSpecialTypesProvider = false; } } } } private void unregisterContentObservers() { if (this.mIsObserversRegistered) { this.mIsObserversRegistered = false; getContext().getContentResolver().unregisterContentObserver(this.mForceLoadContentObserver); } } public final void deliverResult(List<ProcessingMedia> list) { if (!isReset()) { List<ProcessingMedia> list2 = this.mDataSet; this.mDataSet = list; if (isStarted()) { super.deliverResult(list); } if (list2 != null && list2 != list) { list2.clear(); } } else if (list != null) { list.clear(); } } public List<ProcessingMedia> loadInBackground() { return ProcessingMediaManager.queryProcessingMedias(); } /* access modifiers changed from: protected */ public void onAbandon() { super.onAbandon(); unregisterContentObservers(); } public final void onCanceled(List<ProcessingMedia> list) { if (list != null) { list.clear(); } } /* access modifiers changed from: protected */ public final void onReset() { super.onReset(); onStopLoading(); unregisterContentObservers(); List<ProcessingMedia> list = this.mDataSet; if (list != null) { list.clear(); this.mDataSet = null; } } /* access modifiers changed from: protected */ public final void onStartLoading() { List<ProcessingMedia> list = this.mDataSet; if (list != null) { deliverResult(list); } if (takeContentChanged() || this.mDataSet == null) { forceLoad(); } registerContentObservers(); } /* access modifiers changed from: protected */ public void onStopLoading() { cancelLoad(); } }
true
eb183525899530cad97e6c8d73cd91e8495d27cd
Java
KevinMTO/ing-sw-2018-lanzillotta-marazzi-mato
/src/main/java/it/polimi/se2018/server/events/responses/SuccessColor.java
UTF-8
576
2.609375
3
[]
no_license
package it.polimi.se2018.server.events.responses; import it.polimi.se2018.server.events.tool_mex.Activate; /** * Evento laciato per indicare un successo di attivazione di una carta utensile multi fase che richieda il ripescaggio di un dado. * La classe possiede un getter per ogni attributo. * @author Kevin Mato */ public class SuccessColor extends Activate { private String value; public SuccessColor( String player,int index,String color){ super(player,index); this.value=color ; } public String getValue(){ return value; } }
true
2254d510c2f7fdeb72914073b4b3a1fe8ba097ed
Java
VadimKhom/TaskJava_TheBank
/Files/src/main/java/by/itclass/Bank/bank/value/Prices.java
UTF-8
1,291
3.171875
3
[]
no_license
package by.itclass.Bank.bank.value; import java.util.HashMap; public class Prices { private HashMap<String, Double> priceStocks = new HashMap<>(); private HashMap<Metals, Double> priceMetals = new HashMap<>(); private HashMap<Currency, Double> priceMoney = new HashMap<>(); public Prices() { fillMetals(); fillStocks(); fillMoney(); } private void fillStocks() { Stocks stocks = new Stocks(); for (String str : stocks) { priceStocks.put(str, 100d); } } private void fillMetals() { priceMetals.put(Metals.GOLD, 77.30); priceMetals.put(Metals.SILVER, 1.01); priceMetals.put(Metals.PLATINUM, 55.47); priceMetals.put(Metals.PALLADIUM, 56.18); } private void fillMoney() { priceMoney.put(Currency.BYN, 1.0); priceMoney.put(Currency.RUR, 0.033810); priceMoney.put(Currency.EUR, 2.2950); priceMoney.put(Currency.USD, 1.9900); } public double getPriceMoney(Currency currency) { return priceMoney.get(currency); } public double getPriceMetal(Metals metal) { return priceMetals.get(metal); } public double getPriceStock(String company) { return priceStocks.get(company); } }
true
5f0b21217dcaebcd6854795fa5b168c9f505715d
Java
ds0704/YZR-Search
/project/src/main/java/net/nigne/yzrproject/persistence/ActorDAOImpl.java
UHC
896
1.671875
2
[]
no_license
/** * */ package net.nigne.yzrproject.persistence; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Order; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import net.nigne.yzrproject.domain.ActorVO; import net.nigne.yzrproject.domain.Criteria; import net.nigne.yzrproject.domain.MovieVO; import net.nigne.yzrproject.domain.SearchVO; /** * @FileName : ActorDAOImpl.java * @Package : net.nigne.yzrproject.persistence * @Date : 2016. 7. 11. * @ۼ : 뼺 * @α׷ : ... */ @Repository public class ActorDAOImpl implements ActorDAO { }
true
01760035187313eb7504a9f24d4ae808b31caca7
Java
UPIC/sutuo
/upic-web-lucene/src/main/java/com/upic/lucene/utils/MySameAnalyzer.java
UTF-8
1,152
2.359375
2
[]
no_license
package com.upic.lucene.utils; import java.io.Reader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import com.chenlb.mmseg4j.Dictionary; import com.chenlb.mmseg4j.MaxWordSeg; import com.chenlb.mmseg4j.Seg; public class MySameAnalyzer extends Analyzer { private SamewordContext samewordContext; private Dictionary dic; public MySameAnalyzer(SamewordContext swc, String path) { samewordContext = swc; dic = Dictionary.getInstance(path); } protected Seg newSeg() { return new MaxWordSeg(dic); } @Override protected TokenStreamComponents createComponents(String fieldName) { final MMySegTokenizer src=new MMySegTokenizer(newSeg()); TokenStream tok = new MySameTokenFilter(src,samewordContext); return new TokenStreamComponents(src, tok) { @Override protected void setReader(final Reader reader) { super.setReader(reader); src.setInputs(reader); } }; } @Override protected TokenStream normalize(String fieldName, TokenStream in) { return new MySameTokenFilter( new MMySegTokenizer(new MaxWordSeg(dic)),samewordContext); } }
true
f9b83ff6086b4a17dab35fcafb78d791d7cd3710
Java
jiangjb/smarthome
/src/main/java/com/smarthome/imcp/util/StaticUtils.java
UTF-8
1,680
1.71875
2
[]
no_license
/* */ package com.smarthome.imcp.util; /* */ /* */ import java.util.HashMap; /* */ import java.util.Map; /* */ /* */ public class StaticUtils /* */ { /* 12 */ public static Map<String, String[]> dIdByName = new HashMap(); /* */ /* 16 */ public static Map<String, String[]> drik = new HashMap(); /* */ /* 20 */ public static Map<String, String[]> CURTAIN = new HashMap(); /* 21 */ public static Map<String, String[]> QUERYLIGHT = new HashMap(); /* 22 */ public static Map<String, String[]> VERIFICATIONCODE = new HashMap(); /* */ /* 28 */ public static Map<String, String[]> AUTHORIZATIONSENDMSG = new HashMap(); /* */ /* 33 */ public static Map<String, Integer> locks = new HashMap(); /* */ /* 38 */ public static Map<String, Integer> status = new HashMap(); /* */ /* */ public static void lockNum(String lockAddress) { /* 41 */ if (locks.get(lockAddress) == null) /* 42 */ locks.put(lockAddress, Integer.valueOf(1)); /* */ else /* 44 */ locks.put(lockAddress, Integer.valueOf(((Integer)locks.get(lockAddress)).intValue() + 1)); /* */ } /* */ /* */ public static void Status(String roomCode) /* */ { /* 50 */ if (status.get(roomCode) == null) /* 51 */ status.put(roomCode, Integer.valueOf(1)); /* */ else /* 53 */ status.put(roomCode, Integer.valueOf(((Integer)status.get(roomCode)).intValue() + 1)); /* */ } /* */ } /* Location: C:\Users\znhome\Desktop\bak\smarthome.IMCPlatform\WEB-INF\classes\ * Qualified Name: com.smarthome.imcp.util.StaticUtils * JD-Core Version: 0.6.2 */
true
048476afa5a010a10a33246881c95418565d0aa8
Java
nowodoo/MyProject
/bytecode/src/main/java/com/zach/bytecode/cglib/interf/IAnimal.java
UTF-8
98
1.828125
2
[]
no_license
package com.zach.bytecode.cglib.interf; public interface IAnimal { Object see(String see); }
true
9ef74b8dc270e5fb2a223d1d08f87fe4e6a19e01
Java
harsheelshah/Lease-Management-System
/src/lease_management_system/ManagerHome.java
UTF-8
892
2.171875
2
[]
no_license
package lease_management_system; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ManagerHome */ @WebServlet("/hw2/ManagerHome") public class ManagerHome extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.sendRedirect("ManagerHome.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true