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
3f0b51483a779ded8aaace4ea3c3f696a7fa678c
Java
LJOSS/MeassurePreassure
/app/src/main/java/com/example/measurepressure/History.java
UTF-8
811
2.5625
3
[]
no_license
package com.example.measurepressure; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.List; public class History extends AppCompatActivity { TextView tvShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); List<UserDB> users = MainActivity.myAppDB.userDAO().getUsers(); String info = ""; for (UserDB usr : users) { String name = usr.getName(); String age = usr.getAge(); int weight = usr.getWeight(); info = info + "\n\n" + "\nName: " + name + "\nAge: " + age + "\nWeight: " + weight; } tvShow.setText(info); } }
true
696e54af35167180bbeafa6b8e379f1d280591f6
Java
Siarko/remote-cmd-host
/src/main/java/pl/siarko/Profiler/ProfilerCategory.java
UTF-8
351
2.84375
3
[]
no_license
package pl.siarko.Profiler; public class ProfilerCategory { private int times = 0; private int count = 0; public void update(int time){ this.times += time; this.count++; } public int getCount(){ return this.count; } public float getAvg(){ return (float)(this.times/this.count); } }
true
ffa921460285245ff938eefa3a204e12ea1edbbd
Java
LegacyofAden/emu-ungp
/commons/src/main/java/org/l2junity/commons/config/utils/ConfigLoader.java
UTF-8
9,028
2.046875
2
[]
no_license
package org.l2junity.commons.config.utils; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.StrBuilder; import org.atteo.classindex.ClassIndex; import org.l2junity.commons.config.annotation.ConfigAfterLoad; import org.l2junity.commons.config.annotation.ConfigComments; import org.l2junity.commons.config.annotation.ConfigFile; import org.l2junity.commons.config.annotation.ConfigProperty; import org.l2junity.commons.lang.management.ShutdownManager; import org.l2junity.commons.lang.management.TerminationStatus; import org.l2junity.core.startup.StartupComponent; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.*; /** * @author ANZO */ @Slf4j @StartupComponent("Configure") public final class ConfigLoader { @Getter(lazy = true) private static final ConfigLoader instance = new ConfigLoader(); private static Set<String> VAR_NAMES_CACHE = new HashSet<>(); private ConfigLoader() { loadConfigs(); } public void loadConfigs() { try { for (Class<?> clazz : ClassIndex.getAnnotated(ConfigFile.class)) { boolean loadConfig = false; ConfigFile annotation = clazz.getAnnotation(ConfigFile.class); if (annotation.loadForPackages().length > 0) { for (String classPath : annotation.loadForPackages()) { if (!StringUtils.isEmpty(classPath)) { URL url = getClass().getClassLoader().getResource(classPath.replace(".", "/")); if (url != null) { loadConfig = true; break; } } } } else { loadConfig = true; } if (!loadConfig) { continue; } final File file = new File(annotation.name()); if (!file.exists() && file.isDirectory()) { file.mkdirs(); } if (!file.exists()) { buildConfig(clazz); } else { updateConfig(clazz); } loadConfig(clazz); } } catch (Exception e) { log.error("Error while loading configs. Halting system.", e); ShutdownManager.getInstance().halt(TerminationStatus.RUNTIME_UNCAUGHT_ERROR); } } private void updateConfig(Class<?> clazz) { Properties properties = new Properties(); String fileName = clazz.getAnnotation(ConfigFile.class).name(); try (InputStream input = new FileInputStream(fileName)) { properties.load(input); } catch (IOException ex) { log.error("Error while calling loadConfig", ex); } if (properties.size() == clazz.getDeclaredFields().length) { return; } StrBuilder out = new StrBuilder(); for (Field field : clazz.getDeclaredFields()) { ConfigProperty annotation = field.getAnnotation(ConfigProperty.class); if (annotation != null) { final String propertyValue = properties.getProperty(configName(field)); if (propertyValue == null) { out.appendln("").appendln(generateFieldConfig(field)); log.info("Updated '{}' config with new field '{}'", fileName, configName(field)); } } } if (out.length() > 0) { final Path path = Paths.get(fileName); try { Files.write(path, out.toString().getBytes(), StandardOpenOption.APPEND); } catch (Exception e) { log.error("Error while writing config update", e); } } } private void buildConfig(Class<?> clazz) { String fileName = clazz.getAnnotation(ConfigFile.class).name(); Path path = Paths.get(fileName); log.info("Generated '{}'", fileName); try { Files.deleteIfExists(path); Files.createDirectories(path.getParent()); } catch (IOException ex) { log.error("Error while buildConfig()", ex); return; } StrBuilder out = new StrBuilder(); for (Field field : clazz.getDeclaredFields()) { String configFields = generateFieldConfig(field); if (configFields != null && !configFields.isEmpty()) { out.appendln(configFields); } } try { Files.write(path, out.toString().getBytes(), StandardOpenOption.CREATE); } catch (IOException ex) { log.error("Error while writing config file: " + path, ex); } } private String generateFieldConfig(Field field) { ConfigComments configComments = field.getAnnotation(ConfigComments.class); ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class); String cfgName = configName(field); if (configProperty != null) { StrBuilder out = new StrBuilder(); if (configComments != null && configComments.comment().length > 0) { for (String txt : configComments.comment()) { out.appendln("# " + txt); } } else if (configProperty.comment().length > 0) { for (String txt : configProperty.comment()) { out.appendln("# " + txt); } } if (VAR_NAMES_CACHE.contains(cfgName)) { log.warn("Config property name [{}] already defined!", cfgName); } else { VAR_NAMES_CACHE.add(cfgName); } out.appendln(cfgName + " = " + configProperty.value()); return out.toString(); } return null; } private void loadConfig(Class<?> clazz) { Properties properties = new Properties(); String fileName = clazz.getAnnotation(ConfigFile.class).name(); log.info("Loading config file: {}", fileName); try (InputStream input = new FileInputStream(fileName)) { properties.load(input); } catch (IOException ex) { log.error("Error while calling loadConfig", ex); } try { Object configObject = clazz.newInstance(); for (Field field : clazz.getFields()) { ConfigProperty annotation = field.getAnnotation(ConfigProperty.class); if (annotation == null) { continue; } if (!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) { log.warn("Invalid modifiers for {}", field); return; } setConfigValue(configObject, field, properties, annotation); } for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(ConfigAfterLoad.class)) { boolean isMethodAccessible = method.isAccessible(); method.setAccessible(true); try { method.invoke(configObject); } catch (Exception e) { log.error("Error while calling ConfigAfterLoad method", e); } finally { method.setAccessible(isMethodAccessible); } } } } catch (Exception e) { log.error("Error while initializing config object", e); } } @SuppressWarnings("unchecked") private void setConfigValue(Object object, Field field, Properties properties, ConfigProperty annotation) { final String propertyValue = properties.getProperty(configName(field), annotation.value()); if (StringUtils.isEmpty(propertyValue)) { return; } try { if (field.getType().isArray()) { Class<?> baseType = field.getType().getComponentType(); String[] values = propertyValue.split(annotation.splitter()); Object array = Array.newInstance(baseType, values.length); field.set(null, array); int index = 0; for (String arrValue : values) { Array.set(array, index, ConfigTypeCaster.cast(baseType, arrValue.trim())); ++index; } field.set(null, array); } else if (field.getType().isAssignableFrom(List.class)) { Class genericType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; String[] values = propertyValue.split(annotation.splitter()); ((List<Object>) field.get(object)).clear(); for (String value : values) { if (!value.trim().isEmpty()) { ((List<Object>) field.get(object)).add(ConfigTypeCaster.cast(genericType, value.trim())); } } } else if (field.getType().isAssignableFrom(Map.class)) { ((Map<Object, Object>) field.get(object)).clear(); Class keyType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; Class valueType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[1]; String[] values = propertyValue.split(annotation.splitter()); for (String value : values) { String[] valueDatas = value.trim().split(":"); Object keyObj = ConfigTypeCaster.cast(keyType, valueDatas[0].trim()); Object valueObj = ConfigTypeCaster.cast(valueType, valueDatas[1].trim()); ((Map<Object, Object>) field.get(object)).put(keyObj, valueObj); } } else { ConfigTypeCaster.cast(object, field, propertyValue); } } catch (IllegalAccessException e) { log.error("Invalid modifiers for field {}", field); } } private String configName(Field field) { ConfigProperty anno = field.getAnnotation(ConfigProperty.class); return anno == null || anno.name().isEmpty() ? field.getName() : anno.name(); } }
true
88c34e184177641275cf736fd82ae38cba650fd6
Java
eeveorg/GMSI
/script/names/IntVarSpace.java
UTF-8
3,446
2.4375
2
[ "MIT" ]
permissive
/* * Decompiled with CFR 0_119. */ package script.names; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import script.InternalScriptError; import script.dataObjects.DataObject; import script.dataObjects.DataType; import script.dataObjects.LastArrayIndex; import script.dataObjects.NullObject; import script.names.AlwaysTrueTest; import script.names.TypeTest; import script.names.VarSpace; public class IntVarSpace implements VarSpace { protected TreeMap<Integer, DataObject> map = new TreeMap(); private TypeTest t = AlwaysTrueTest.getTest(); @Override public boolean erase(Object key) { if (key instanceof LastArrayIndex) { if (this.map.isEmpty()) { return false; } if (this.map.remove(this.map.lastKey()) != null) { return true; } return false; } if (this.map.remove(key) != null) { return true; } return false; } @Override public DataObject get(Object key) throws InternalScriptError { if (key instanceof LastArrayIndex) { if (this.map.isEmpty()) { return new NullObject(); } return this.map.get(this.map.lastKey()); } return this.map.get(key); } @Override public void put(Object key, DataObject content) throws InternalScriptError { if (!this.t.test(content)) { throw new InternalScriptError("Trying to put a value of type " + content.getType() + " into an array that is restricted to the following types: " + this.t); } if (key instanceof LastArrayIndex) { try { this.map.put(this.map.lastKey() + 1, content); } catch (NoSuchElementException e) { this.map.put(0, content); } return; } this.map.put((Integer)key, content); } @Override public boolean hasName(Object key) { if (key instanceof LastArrayIndex) { return true; } return this.map.containsKey(key); } @Override public String toString() { StringBuilder b = new StringBuilder(); for (Map.Entry<Integer, DataObject> e : this.map.entrySet()) { b.append(e.getKey()); b.append(" => "); b.append(e.getValue()); b.append("\n"); } return b.toString(); } @Override public Set<? extends Object> getKeys() { return this.map.keySet(); } @Override public TypeTest getTypeTest() { return this.t; } private void testAll(boolean eraseNonMatching) throws InternalScriptError { for (Map.Entry<Integer, DataObject> e : this.map.entrySet()) { if (this.t.test(e.getValue())) continue; if (eraseNonMatching) { this.erase(e.getKey()); continue; } throw new InternalScriptError(e.getKey() + " => " + e.getValue() + " (type: " + e.getValue().getType() + ")"); } } @Override public void setTypeTest(TypeTest t, boolean eraseNonMatching) throws InternalScriptError { if (!this.t.isAncestorOf(t)) { this.t = t; this.testAll(eraseNonMatching); } else { this.t = t; } } }
true
e3f4efc1d97c1e2c1476d244c6788dc673c9d89a
Java
lazy-share/lazy-falcon
/lazy-falcon-core/src/main/java/com/lazy/falcon/core/model/input/ApiResponseParamItemInputModel.java
UTF-8
1,205
2.015625
2
[]
no_license
package com.lazy.falcon.core.model.input; /** * <p> * API 响应参数 Item 输入模型 * </p> * * @author laizhiyuan * @date 2018/6/2. */ public class ApiResponseParamItemInputModel { /** * 参数名称 */ private String name; /** * 参数描述 */ private String desc; /** * 参数备注 */ private String remark; /** * 类型 */ private String type; /** * 组标题 */ private String groupTitle; public String getGroupTitle() { return groupTitle; } public void setGroupTitle(String groupTitle) { this.groupTitle = groupTitle; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
true
a9f88a16b3067eca374a4ab56980dba6e80c543f
Java
tsuyo/topcoder-tsuyo
/catandrat-java/CatAndRat.java
UTF-8
376
2.828125
3
[]
no_license
import static java.util.Arrays.*; import static java.lang.Math.*; import java.util.*; public class CatAndRat { public double getTime(int R, int T, int Vrat, int Vcat) { if (Vrat >= Vcat) return -1.0; double D = Math.PI * R; double rat = Vrat * T; if (rat >= D) { return D / (Vcat - Vrat); } else { return rat / (Vcat - Vrat); } } }
true
a711256646a1ddd4f9e4301488585caa8cf98a14
Java
FantuzzoMarco/Tesina
/Fantuzzo Marco/App/app/src/main/java/com/pitteriimpiantisrl/app/AddJobDialog.java
UTF-8
7,441
2.171875
2
[]
no_license
package com.pitteriimpiantisrl.app; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.text.format.DateUtils; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.pitteriimpiantisrl.app.datastruct.Cliente; import com.pitteriimpiantisrl.app.datastruct.Lavoro; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import com.pitteriimpiantisrl.app.download.HttpDownloader; import com.pitteriimpiantisrl.app.download.HttpParamType; /** * Created by Utente on 13/05/2017. */ public class AddJobDialog extends AlertDialog.Builder { public interface OnJobAdded { void onJobAdded(Lavoro l); } private OnJobAdded onJobAdded; public void setOnJobAdded(OnJobAdded onJobAdded) { this.onJobAdded = onJobAdded; } private final Cliente cliente; public AddJobDialog(Context context, Cliente cliente) { super(context); this.cliente = cliente; } @Override public AlertDialog show() { View inflate = View.inflate(getContext(), R.layout.add_job_dialog, null); final TextView date = (TextView) inflate.findViewById(R.id.date); final Button selectDate = (Button) inflate.findViewById(R.id.selectDate); final EditText numberHours = (EditText) inflate.findViewById(R.id.numberOfHours); final EditText price = (EditText) inflate.findViewById(R.id.price); final EditText description = (EditText) inflate.findViewById(R.id.description); //Restituisce calendario con data corrente date.setTag(Calendar.getInstance()); invalidateDate(date); selectDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Calendar previousDate = (Calendar) date.getTag(); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); final DatePicker dp = new DatePicker(getContext()); dp.updateDate(previousDate.get(Calendar.YEAR), previousDate.get(Calendar.MONTH), previousDate.get(Calendar.DAY_OF_MONTH)); builder.setView(dp); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext()); final TimePicker tp = new TimePicker(getContext()); //noinspection deprecation tp.setCurrentHour(previousDate.get(Calendar.HOUR_OF_DAY)); //noinspection deprecation tp.setCurrentMinute(previousDate.get(Calendar.MINUTE)); tp.setIs24HourView(true); builder2.setView(tp); builder2.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, dp.getYear()); cal.set(Calendar.MONTH, dp.getMonth()); cal.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth()); //noinspection deprecation cal.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour()); //noinspection deprecation cal.set(Calendar.MINUTE, tp.getCurrentMinute()); date.setTag(cal); invalidateDate(date); } }); builder2.setNegativeButton(android.R.string.cancel, null); builder2.show(); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } }); setView(inflate); setTitle(R.string.add_job); setNegativeButton(android.R.string.cancel, null); setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { addJob(((Calendar) date.getTag()).getTime(), numberHours.getText().toString(), price.getText().toString(), description.getText().toString()); } }); final AlertDialog ad = super.show(); Button positiveButton = ad.getButton(AlertDialog.BUTTON_POSITIVE); positiveButton.setEnabled(false); new ButtonDisablerTextWatcher(positiveButton, new EditText[]{numberHours, price, description}); return ad; } private void invalidateDate(TextView date) { date.setText(DateUtils.formatDateTime( getContext(), ((Calendar) date.getTag()).getTime().getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR )); } private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private void addJob(final Date date, final String numberOfHours, final String price, final String description) { final ProgressDialog pd = new ProgressDialog(getContext()); pd.setMessage(getContext().getString(R.string.loading)); pd.show(); new AsyncTask<Void, Void, Lavoro>() { @Override protected Lavoro doInBackground(Void... params) { try { Object o = Utils.processHttpRequest( getContext(), new HttpDownloader(Utils.SERVER_PATH + "/addJob.php") .addParam("data", DATE_FORMAT.format(date), HttpParamType.GET) .addParam("numeroOre", numberOfHours, HttpParamType.GET) .addParam("cliente", cliente.getId(), HttpParamType.GET) .addParam("prezzo", price, HttpParamType.GET) .addParam("descrizione", description, HttpParamType.GET) ); return Lavoro.getInstance((JSONObject) o, cliente); } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(Lavoro lavoro) { pd.dismiss(); if (lavoro == null) { Toast.makeText(getContext(), R.string.error_adding_job, Toast.LENGTH_SHORT).show(); } else { if (onJobAdded != null) { onJobAdded.onJobAdded(lavoro); } } } }.execute(); } }
true
af725eb169d11e3b2c419f053e6cc426337de597
Java
yudaidang/AlgorithmTSPTW
/app/src/main/java/com/example/yudai/algorithmtsptw/Tour.java
UTF-8
193
1.9375
2
[]
no_license
package com.example.yudai.algorithmtsptw; public class Tour { public double score; public int[] tour; public Tour() { score = 0; tour = new int[TSPTW.N+1]; } }
true
7249b6ce423b666c469f72873a8d2ae8ad6e43ee
Java
tgrundtvig/EDMA
/IntelliJ/ExampleModel/DiveWithUs/src/com/cphdiving/divewithus/edma/generated/valuedomains/coursereg/BootSize.java
UTF-8
3,727
2.703125
3
[]
no_license
package com.cphdiving.divewithus.edma.generated.valuedomains.coursereg; import com.cphdiving.divewithus.edma.generated.DiveWithUs; import com.cphdiving.divewithus.edma.generated.valuedomains.coursereg.impl.BootSizeImpl; import com.cphdiving.divewithus.edma.generated.valuedomains.external.EDMA_ExternalConstraints; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.abstractica.edma.valuedomains.IMetaValueDomain; import org.abstractica.edma.valuedomains.exceptions.InvalidValueException; import org.abstractica.edma.valuedomains.userinput.ITerminal; import org.abstractica.edma.valuedomains.userinput.ValueDomainInput; /** * The representation of a value from the value domain: BootSize */ public abstract class BootSize implements Comparable<BootSize> { protected static final IMetaValueDomain edma_domain = DiveWithUs.environment.getValueDomainDefinitions().getValueDomain(22); /** * Get a value from a terminal * @param terminal The terminal to get the value from * @return The BootSize from the terminal */ public static BootSize fromTerminal(ITerminal terminal) { ValueDomainInput vdi = new ValueDomainInput(terminal, EDMA_ExternalConstraints.instance); return new BootSizeImpl(vdi.getValue(edma_domain)); } /** * Get a value from its string representation * @param s The String to parse * @return The BootSize from the string representation */ public static BootSize fromString(String s) throws InvalidValueException { Object res = edma_domain.valueFromString(s, EDMA_ExternalConstraints.instance); return new BootSizeImpl(res); } /** * Reads and validates a value from a stream * @param in A data input interface for the stream to read from * @return The BootSize read from the stream */ public static BootSize fromStream(DataInput in) throws IOException, InvalidValueException { Object res = edma_domain.readValue(in, EDMA_ExternalConstraints.instance); return new BootSizeImpl(res); } /** * Reads a value from a stream without validating the value * @param in A data input interface for the stream to read from * @return The BootSize read from the stream */ public static BootSize fromStreamNoValidate(DataInput in) throws IOException { Object res = edma_domain.readValueNoValidate(in); return new BootSizeImpl(res); } /** * Call this method to create a new BootSize value. * @param value The value of the BootSize to be created. * @return The newly created BootSize value */ public static BootSize create(Integer value) throws InvalidValueException { BootSizeImpl.edma_validate(value); return new BootSizeImpl(BootSizeImpl.edma_create(value)); } /** * Call this method to test if the provided Integer is a valid BootSize * @param value The Integer value to be tested * @return true if the provided Integer is a valid BootSize */ public static boolean isValidBootSize(Integer value) { try { BootSizeImpl.edma_validate(value); } catch(InvalidValueException e) { return false; } return true; } /** * Writes this value to a stream * @param out Interface to data output stream */ public abstract void toStream(DataOutput out) throws IOException; /** * returns the Integer value that is stored in this BootSize * @return The Integer value stored in this BootSize */ public abstract Integer value(); }
true
e570a22b0afcaa9e7057e3d02456e0ef3cc77836
Java
danyele999/progettoUtente
/BlockBuster/src/main/java/it/daniele/business/TipoRuolo.java
UTF-8
80
1.796875
2
[]
no_license
package it.daniele.business; public enum TipoRuolo { ROLE_USER, ROLE_ADMIN }
true
5b5737e3ead5ab0b885c85699da3f0dc4cae6279
Java
cristianokunas/ExpoPorto-APP
/app/src/main/java/kunas/app/expoporto/ListaProgramacaoActivity.java
UTF-8
4,743
1.921875
2
[]
no_license
package kunas.app.expoporto; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import kunas.app.expoporto.model.Programacao; public class ListaProgramacaoActivity extends AppCompatActivity{ private Toolbar appToolBarProgramacao; private ImageView banner; private RecyclerView recyclerListaProgramacao; private ProgramacaoAdapter adapter; private List<Programacao> listaProgramacao = new ArrayList<Programacao>(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = MainActivity.getFirebase(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_programacao); appToolBarProgramacao = findViewById(R.id.app_toolbar_programacao); appToolBarProgramacao.setTitle(R.string.title_activity_programacao); setSupportActionBar(appToolBarProgramacao); getSupportActionBar().setDisplayHomeAsUpEnabled(true); banner = findViewById(R.id.img_banner_programacao); // Configurando o gerenciador de layout para ser uma lista. recyclerListaProgramacao = (RecyclerView) findViewById(R.id.recyclerListaProgramacao); adapter = new ProgramacaoAdapter(listaProgramacao,this); recyclerListaProgramacao.setAdapter(adapter); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); recyclerListaProgramacao.setLayoutManager(layoutManager); recyclerListaProgramacao.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); Intent intent = getIntent(); final String dia = intent.getStringExtra("dia"); // Read from the database myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { listaProgramacao.clear(); for (DataSnapshot data : dataSnapshot.child(dia).getChildren()){ // Programacao programacao = data.getValue(Programacao.class); Long dt = (Long) data.child("data").getValue(); String h = (String) data.child("hora").getValue(); String t = (String) data.child("titulo").getValue(); String d = (String) data.child("descricao").getValue(); Programacao programacao = new Programacao(t,d,h,dt); listaProgramacao.add(programacao); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w("Error", "Failed to read value.", error.toException()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_programacao, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent in = null; switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.toolbar_programacao_shows: in = new Intent(ListaProgramacaoActivity.this, ShowsActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(in); finish(); break; case R.id.toolbar_programacao_mapa: in = new Intent(ListaProgramacaoActivity.this, MapaActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(in); finish(); break; } return super.onOptionsItemSelected(item); } }
true
223c1fc4bba8318d0e8fa3305c079645e4244efd
Java
UCLA-ECE209AS-2018W/Haoming-Liang
/Rachio_apk/sources/com/shinobicontrols/charts/cf.java
UTF-8
624
2.234375
2
[ "BSD-2-Clause" ]
permissive
package com.shinobicontrols.charts; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.view.View; class cf extends View { private final Drawable jZ; @SuppressLint({"NewApi", "ViewConstructor"}) public cf(Context context, Drawable drawable) { super(context); this.jZ = drawable; if (VERSION.SDK_INT >= 16) { setBackground(this.jZ); } else { setBackgroundDrawable(this.jZ); } } Drawable de() { return this.jZ; } }
true
7b7c5f53e4a093a63f902387ea2235914f224692
Java
l793854601/TKMHimalaya
/app/src/main/java/com/tkm/himalaya/fragments/HistoryFragment.java
UTF-8
751
2
2
[]
no_license
package com.tkm.himalaya.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tkm.himalaya.R; import com.tkm.himalaya.base.BaseFragment; /** * 历史 */ public class HistoryFragment extends BaseFragment { public static HistoryFragment newInstance() { HistoryFragment fragment = new HistoryFragment(); return fragment; } @Override protected View getContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_history, container, false); } }
true
c324d354d4f77e54f706df66e6eac8d87b6adc07
Java
BradleyKRamunas/Daely
/app/src/main/java/com/bramuna/daely/data/types/History.java
UTF-8
1,418
2.625
3
[]
no_license
package com.bramuna.daely.data.types; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class History { @SerializedName("date") @Expose private String date; @SerializedName("url") @Expose private String url; @SerializedName("data") @Expose private DataHolder data; private class DataHolder { @SerializedName("Events") @Expose private List<Event> events; @SerializedName("Births") @Expose private List<Event> births; @SerializedName("Deaths") @Expose private List<Event> deaths; } public class Event { @SerializedName("year") @Expose private String year; @SerializedName("text") @Expose private String text; public String getYear() { return year; } public String getText() { return text; } } public String getDate() { return date; } public List<Event> getTwoRandomEvents() { List<Event> allEvents = new ArrayList<>(data.events); // allEvents.addAll(data.births); // allEvents.addAll(data.deaths); Collections.shuffle(allEvents); return new ArrayList<>(allEvents.subList(0, 2)); } }
true
bcc7c6c2c240f8c0993e1c32a10a64b675291c8d
Java
maboeckmann/java-serializer
/dataformat-xml/src/main/java/io/adminshell/aas/v3/dataformat/xml/mixin/BlobMixin.java
UTF-8
756
1.851563
2
[ "Apache-2.0" ]
permissive
package io.adminshell.aas.v3.dataformat.xml.mixin; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.adminshell.aas.v3.dataformat.xml.serialization.BlobValueSerializer; @JsonPropertyOrder({ "extensions", "idShort", "displayNames", "category", "descriptions", "kind", "semanticId", "qualifiers", "dataSpecifications", "value", "mimeType" }) public interface BlobMixin { @JacksonXmlProperty(localName = "aas:mimeType") public String getMimeType(); @JacksonXmlProperty(localName = "aas:value") @JsonSerialize(using = BlobValueSerializer.class) public byte[] getValue(); }
true
15ca84be2021b233338de3861df9e1b463677f41
Java
zhx1019/leetCodeSrc
/ojTest/BalancedTree.java
UTF-8
1,279
3.5625
4
[]
no_license
package ojTest; import java.util.ArrayList; public class BalancedTree { public boolean isBalanced(TreeNode root) { if(root == null) { return true; } ArrayList<Integer> al = new ArrayList<Integer>(); traverseTree(root, al, 1); int max = al.get(0); int min = al.get(0); System.out.println(al.get(0)); for(int i = 1; i < al.size(); i++) { System.out.println(al.get(i)); if(al.get(i) < min) { min = al.get(i); } if(al.get(i) > max) { max = al.get(i); } } if(max - min >= 2) { return false; } else return true; } public void traverseTree(TreeNode root, ArrayList<Integer> al, int depth) { if(root == null) { return; } if(root.left == null && root.right == null) { al.add(depth); } traverseTree(root.right, al, depth+1); traverseTree(root.left, al, depth+1); } public static void main(String[] args) { // TODO Auto-generated method stub BalancedTree bt = new BalancedTree(); TreeNode root = new TreeNode(1); TreeNode r1 = new TreeNode(2); TreeNode r2 = new TreeNode(3); root.right = r1; r1.right = r2; System.out.println(bt.isBalanced(root)); } }
true
d106fdf043b304f8f8ca9ebe19461b7548c041e9
Java
nikowitt/3rd-party-issues
/src/test/java/IDEA_189535_Junit5SingleTestSelectionTest.java
UTF-8
782
2.203125
2
[ "Apache-2.0" ]
permissive
import static org.junit.jupiter.params.provider.Arguments.of; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IDEA_189535_Junit5SingleTestSelectionTest { private static Logger LOGGER = LoggerFactory.getLogger(IDEA_189535_Junit5SingleTestSelectionTest.class); public static Stream<Arguments> test() { return Stream.of( of("a"), of("b"), of("c") ); } @ParameterizedTest @MethodSource public void test(String arg, String arg1) throws Exception { LOGGER.error("See https://youtrack.jetbrains.com/issue/IDEA-189535#comment=27-2799619"); } }
true
699622705ebe5613fa21cbba8007af51fd2fb673
Java
TheDarkeOne/DesignPatternsRepo
/Swing-Testing/src/MainFrame.java
UTF-8
1,699
3.1875
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MainFrame extends JFrame { private Input input; private JButton btn1; private JButton btn2; private Output output; public MainFrame(){ super("Swing Testing"); setSize(200,333); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); input = new Input(); btn1 = new JButton("Copy"); btn2 = new JButton("Copy X2"); output = new Output(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; c.ipady = 0; c.ipadx = 100; c.gridwidth = 2; add(input, c); c.gridx=0; c.gridy=1; c.ipady=0; c.ipadx=0; c.gridheight=1; c.gridwidth = 1; add(btn1, c); c.gridx=1; c.gridy=1; add(btn2, c); c.gridx = 0; c.gridy = 2; c.ipady = 200; c.ipadx = 100; c.gridwidth = 2; add(output, c); btn1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { output.appendText(input.getText() + "\n"); } }); btn2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { output.appendText(input.getText() + "\n"); output.appendText(input.getText() + "\n"); } }); } }
true
156509197d2c65e238582fb324b24df49681af62
Java
weipingQin/AndroidShoppingAdProject
/goumei/src/com/www/goumei/activity/AttentionAct.java
UTF-8
1,168
1.8125
2
[]
no_license
package com.www.goumei.activity; import com.www.goumei.R; import com.www.goumei.fragment.AttentionFragment; import android.os.Bundle; /** * * @ClassName: AttentionAct * @Description: TODO * @author sunyouyi * @date 2015-6-1 下午9:17:52 * */ public class AttentionAct extends BaseFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.net_finance_goods); setiContainerID(R.id.finance_goods); initShowFragment(new AttentionFragment(),"GoodsFragment"); //lockScreen();//手势密码锁屏 } @Override public void onBackPressed() { super.onBackPressed(); this.goBackAndShowPreView(null); } /* public void gotoGoodsBijia(String gid ){ GoodsParityFragment goodsParityFragment = new GoodsParityFragment(); Bundle bundle = new Bundle(); bundle.putString("gid", gid); bundle.putString("from", "MyCollectionFragment"); goodsParityFragment.setArguments(bundle); dumpToNext(goodsParityFragment, "GoodsParityFragment"); }*/ }
true
d0121bf22c5b9d98b3a572a529db17e6986f723d
Java
aruiz69/SimpleJPA
/JavaApplication6/src/entities/Order.java
UTF-8
2,578
2.5625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; /** * * @author alvaro.ruiz */ @Entity(name="Orders") public class Order implements Serializable { public Order() { } private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ORDER_ID", nullable = false) private Long id; @Column(name="DESCRIPTION") private String description; @ManyToOne(optional=false) @JoinColumn(name="CUST_ID",referencedColumnName="PERSONA_ID") private Person person; public Order(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Order)) { return false; } Order other = (Order) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "Order{" + "id=" + id + ", description=" + description + ", person=" + person + '}'; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @param person the person to set */ public void setPerson(Person person) { this.person = person; } /** * @return the person */ public Person getPerson() { return person; } }
true
aff074b41b8975c1b0eb0de04eaf5f9d6bab12de
Java
MarkusBerthold/group311-server
/src/LongestTrain.java
UTF-8
198
2.15625
2
[]
no_license
import java.awt.image.BufferedImage; public class LongestTrain extends Card { private int points; private BufferedImage image; LongestTrain(){ this.points = 10; } }
true
0f42020fa22f8a90a1b1eee1ad3aedc6a84c2310
Java
rudy2steiner/KVEngine
/engine_java/src/main/java/com/alibabacloud/polar_race/engine/kv/event/Cell.java
UTF-8
1,506
2.40625
2
[]
no_license
package com.alibabacloud.polar_race.engine.kv.event; import com.alibabacloud.polar_race.engine.common.StoreConfig; import com.alibabacloud.polar_race.engine.common.recyclable; import java.nio.ByteBuffer; public class Cell implements recyclable { private final static int KEY_LENGTH=StoreConfig.KEY_SIZE; private byte[] key; private byte[] value; private volatile long txId; private volatile long offset; public byte[] getKey() { return key; } public Cell(byte[] key,byte[] value){ this.key=key; this.value=value; } public Cell(ByteBuffer buffer){ if(buffer.remaining()>=KEY_LENGTH){ key=new byte[KEY_LENGTH]; buffer.get(key) ; } if(buffer.hasRemaining()){ value=new byte[buffer.remaining()]; buffer.get(value); } } public void setKey(byte[] key) { this.key = key; } public byte[] getValue() { return value; } public void setValue(byte[] value) { this.value = value; } public long getTxId() { return txId; } public void setTxId(long txId) { this.txId = txId; } public int size(){ return key.length+value.length; } public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } @Override public void free() { this.key=null; this.value=null; } }
true
2b28a5579d5bf4ba1737bba49936dc7eb378d988
Java
gerixx/spring-boot
/accounts-management/src/main/java/com/smec/cc/accountsmanagement/db/entity/AccountEntityRepository.java
UTF-8
210
1.539063
2
[]
no_license
package com.smec.cc.accountsmanagement.db.entity; import org.springframework.data.jpa.repository.JpaRepository; public interface AccountEntityRepository extends JpaRepository<AccountEntity, Long> { }
true
b347f2a1519e4b1233c166f0a1d93a53016e94f9
Java
SuperHuggy/HogLab
/Temp/src/LabWork0.java
UTF-8
3,281
3.1875
3
[]
no_license
import java.io.*; import java.text.DecimalFormat; public class LabWork0 { public static void main(String[] args) { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------"); System.out.println(" № | слово | | Количество информации "); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------"); System.out.println(" | | | кол-во | байт, размер | бит, | бит, "); System.out.println(" | | палиндром | символов | в программе | по Хартли | по Шеннону "); try (BufferedReader in = new BufferedReader(new FileReader("file0"))) { String s; int i = 0, S = 0; double H = 0, Sh = 0; while ((s = in.readLine()) != null) { System.out.printf("%-4s", (i++)); S += s.length(); H += hartli(s); Sh += henon(s); System.out.print(formatedInformation(s)); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------"); } System.out.printf("%-4s%-58s%-12s%-12s%1s%14s%1s%14.2f%1s%14.9f%n", "", "|Итого", "|", "|" + S, "|", S * 2, "|", H, "|", Sh); } catch (Exception ex) { System.out.println(ex.getMessage()); } } public static String formatedInformation(String s) { int l = s.length(); return String.format("%-58s%-12s%-12s%1s%14s%1s%14.2f%1s%14.9f%n", "|" + s, "|" + isPolindrom(s), "|" + l, "|", l * 2, "|", hartli(s), "|", henon(s)); } private static double hartli(String s) { int alphPower = 0; short[] alph = new short[58]; for (int i = 0; i < s.length(); i++) { char buf = s.charAt(i); alph[buf - (buf < 'а' ? ('a' - 32) : 'а')] = 1; } for (int i = 0; i < 58; i++) alphPower += alph[i]; return s.length() * Math.log(alphPower) / Math.log(2); } private static double henon(String s) { int l = s.length(); double res = 0; short[] alph = new short[58]; for (int i = 0; i < s.length(); i++) { char buf = s.charAt(i); alph[buf - (buf < 'а' ? ('a' - 32) : 'а')]++; } for (int i = 0; i < 58; i++) res -= alph[i] == 0 ? 0 : (double) alph[i] / l * Math.log((double) alph[i] / l) / Math.log(2.0); return res; } private static char isPolindrom(String s) { int l = s.length(); for (int i = 0; i < l / 2; i++) if (s.charAt(i) != s.charAt(l - i - 1)) return '-'; return '+'; } }
true
d86b263c72a2709a1c976a4adf53247afd4d1268
Java
NightTerror1721/gow
/src/main/java/kp/gow/parser/Operator.java
UTF-8
3,989
2.671875
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 kp.gow.parser; /** * * @author mpasc */ public class Operator implements ParsedCode { private final OperatorSymbol symbol; private final ParsedCode[] operands; private Operator(OperatorSymbol symbol, ParsedCode... operands) { if(symbol == null) throw new NullPointerException(); if(operands.length < 1) throw new IllegalStateException(); for(ParsedCode operand : operands) if(operand == null) throw new NullPointerException(); this.symbol = symbol; this.operands = operands; } public final boolean isUnary() { return symbol.isUnary(); } public final boolean isBinary() { return symbol.isBinary(); } public final boolean isTernary() { return symbol.isTernary(); } public final boolean isCall() { return symbol.isCall(); } public final boolean isInvoke() { return symbol.isInvoke(); } public final boolean isNew() { return symbol.isNew(); } public final boolean isAssignation() { return symbol.isAssignation(); } public final OperatorSymbol getSymbol() { return symbol; } public final int getOperandCount() { return operands.length; } public final ParsedCode getOperand(int index) { return operands[index]; } public final void setOperand(int index, ParsedCode operand) { if(operand == null) throw new NullPointerException(); operands[index] = operand; } public final boolean isLeftOrder() { return symbol.isLeftOrder(); } public final boolean isRightOrder() { return symbol.isRightOrder(); } @Override public CodeType getCodeType() { return CodeType.OPERATOR; } @Override public final String toString() { return symbol.toString(); } public static final Operator unary(OperatorSymbol symbol, ParsedCode op0) { return new Operator(symbol, op0); } public static final Operator binary(OperatorSymbol symbol, ParsedCode op0, ParsedCode op1) { return new Operator(symbol, op0, op1); } public static final Operator ternary(OperatorSymbol symbol, ParsedCode op0, ParsedCode op1, ParsedCode op2) { return new Operator(symbol, op0, op1, op2); } public static final Operator callOperator(Identifier functionName, ArgumentList parameters) { if(functionName == null) throw new NullPointerException(); if(parameters == null) throw new NullPointerException(); ParsedCode[] code = new ParsedCode[parameters.getCodeCount() + 1]; code[0] = functionName; parameters.putInArray(code, 1); return new Operator(OperatorSymbol.CALL, code); } public static final Operator invokeOperator(ParsedCode invoker, Identifier methodName, ArgumentList parameters) { if(invoker == null) throw new NullPointerException(); if(methodName == null) throw new NullPointerException(); if(parameters == null) throw new NullPointerException(); ParsedCode[] code = new ParsedCode[parameters.getCodeCount() + 2]; code[0] = invoker; code[1] = methodName; parameters.putInArray(code, 2); return new Operator(OperatorSymbol.INVOKE, code); } public static final Operator newOperator(Identifier className, ArgumentList parameters) { if(className == null) throw new NullPointerException(); if(parameters == null) throw new NullPointerException(); ParsedCode[] code = new ParsedCode[parameters.getCodeCount() + 1]; code[0] = className; parameters.putInArray(code, 1); return new Operator(OperatorSymbol.CALL, code); } }
true
301f3a017364387cc5775274184d674e053e5971
Java
jimsush/IHN
/projects/bootstrap/src/java/com/sf/core/bootstrap/def/module/ModuleConstants.java
GB18030
943
2.390625
2
[]
no_license
package com.sf.core.bootstrap.def.module; /** * <p> * Title: ModuleConstants * </p> * <p> * Description: ģƵij࣬ģ״̬ * </p> * * modified [who date description] * check [who date description] */ public interface ModuleConstants { /** * ״̬ */ String STATUS_NONE = "NONE"; /** * ģѱʶ𲢼,δ */ String STATUS_LOADED="LOADED"; /** * */ String STATUS_STARTING = "STARTING"; /** * ʧ */ String STATUS_FAILED="FAILED"; /** * ϣṩ */ String STATUS_ACTIVE = "ACTIVE"; /** * ֹͣ */ String STATUS_STOPPING = "STOPPING"; /** * ֹͣϣdeactive״̬޷ṩ */ String STATUS_DEACTIVE = "DEACTIVE"; }
true
29e5af115b46f052c85073a869fc16335aca0964
Java
moutainhigh/agent
/agentManage/agentManageAdmin-api/src/main/java/com/ryx/credit/pojo/admin/agent/AgentQuit.java
UTF-8
6,851
1.578125
2
[]
no_license
package com.ryx.credit.pojo.admin.agent; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; public class AgentQuit implements Serializable{ private String id; private String agentId; private String agentName; private String quitPlatform; private BigDecimal capitalDebt; private BigDecimal orderDebt; private BigDecimal profitDebt; private BigDecimal agentDept; private String suppType; private BigDecimal suppDept; private BigDecimal realitySuppDept; private BigDecimal agentOweTicket; private BigDecimal suppTicket; private BigDecimal subtractAmt; private String migrationPlatform; private BigDecimal contractStatus; private BigDecimal refundAmtStatus; private BigDecimal refundAmtDeadline; private Date approveTime; private BigDecimal cloReviewStatus; private String remark; private Date cTime; private Date uTime; private String cUser; private String uUser; private BigDecimal status; private BigDecimal version; private String quitBusId; private BigDecimal appRefund; private BigDecimal platformStatus; private List<Attachment> attachments; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getAgentId() { return agentId; } public void setAgentId(String agentId) { this.agentId = agentId == null ? null : agentId.trim(); } public String getAgentName() { return agentName; } public void setAgentName(String agentName) { this.agentName = agentName == null ? null : agentName.trim(); } public String getQuitPlatform() { return quitPlatform; } public void setQuitPlatform(String quitPlatform) { this.quitPlatform = quitPlatform == null ? null : quitPlatform.trim(); } public BigDecimal getCapitalDebt() { return capitalDebt; } public void setCapitalDebt(BigDecimal capitalDebt) { this.capitalDebt = capitalDebt; } public BigDecimal getOrderDebt() { return orderDebt; } public void setOrderDebt(BigDecimal orderDebt) { this.orderDebt = orderDebt; } public BigDecimal getProfitDebt() { return profitDebt; } public void setProfitDebt(BigDecimal profitDebt) { this.profitDebt = profitDebt; } public BigDecimal getAgentDept() { return agentDept; } public void setAgentDept(BigDecimal agentDept) { this.agentDept = agentDept; } public String getSuppType() { return suppType; } public void setSuppType(String suppType) { this.suppType = suppType == null ? null : suppType.trim(); } public BigDecimal getSuppDept() { return suppDept; } public void setSuppDept(BigDecimal suppDept) { this.suppDept = suppDept; } public BigDecimal getRealitySuppDept() { return realitySuppDept; } public void setRealitySuppDept(BigDecimal realitySuppDept) { this.realitySuppDept = realitySuppDept; } public BigDecimal getAgentOweTicket() { return agentOweTicket; } public void setAgentOweTicket(BigDecimal agentOweTicket) { this.agentOweTicket = agentOweTicket; } public BigDecimal getSuppTicket() { return suppTicket; } public void setSuppTicket(BigDecimal suppTicket) { this.suppTicket = suppTicket; } public BigDecimal getSubtractAmt() { return subtractAmt; } public void setSubtractAmt(BigDecimal subtractAmt) { this.subtractAmt = subtractAmt; } public String getMigrationPlatform() { return migrationPlatform; } public void setMigrationPlatform(String migrationPlatform) { this.migrationPlatform = migrationPlatform == null ? null : migrationPlatform.trim(); } public BigDecimal getContractStatus() { return contractStatus; } public void setContractStatus(BigDecimal contractStatus) { this.contractStatus = contractStatus; } public BigDecimal getRefundAmtStatus() { return refundAmtStatus; } public void setRefundAmtStatus(BigDecimal refundAmtStatus) { this.refundAmtStatus = refundAmtStatus; } public BigDecimal getRefundAmtDeadline() { return refundAmtDeadline; } public void setRefundAmtDeadline(BigDecimal refundAmtDeadline) { this.refundAmtDeadline = refundAmtDeadline; } public Date getApproveTime() { return approveTime; } public void setApproveTime(Date approveTime) { this.approveTime = approveTime; } public BigDecimal getCloReviewStatus() { return cloReviewStatus; } public void setCloReviewStatus(BigDecimal cloReviewStatus) { this.cloReviewStatus = cloReviewStatus; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public Date getcTime() { return cTime; } public void setcTime(Date cTime) { this.cTime = cTime; } public Date getuTime() { return uTime; } public void setuTime(Date uTime) { this.uTime = uTime; } public String getcUser() { return cUser; } public void setcUser(String cUser) { this.cUser = cUser == null ? null : cUser.trim(); } public String getuUser() { return uUser; } public void setuUser(String uUser) { this.uUser = uUser == null ? null : uUser.trim(); } public BigDecimal getStatus() { return status; } public void setStatus(BigDecimal status) { this.status = status; } public BigDecimal getVersion() { return version; } public void setVersion(BigDecimal version) { this.version = version; } public String getQuitBusId() { return quitBusId; } public void setQuitBusId(String quitBusId) { this.quitBusId = quitBusId == null ? null : quitBusId.trim(); } public BigDecimal getAppRefund() { return appRefund; } public void setAppRefund(BigDecimal appRefund) { this.appRefund = appRefund; } public BigDecimal getPlatformStatus() { return platformStatus; } public void setPlatformStatus(BigDecimal platformStatus) { this.platformStatus = platformStatus; } public List<Attachment> getAttachments() { return attachments; } public void setAttachments(List<Attachment> attachments) { this.attachments = attachments; } }
true
b9553d4671fc6fea44c06ffc6cb52f020613ba45
Java
explosiveforce/HR_management
/HR_management/src/main/java/com/ndgwww/HR/management/Config/DepartConfig.java
UTF-8
2,357
2.3125
2
[]
no_license
package com.ndgwww.HR.management.Config; import com.ndgwww.HR.management.pojo.Department; import org.apache.ibatis.jdbc.SQL; public class DepartConfig { //更新 public String update(Department department) { return new SQL() {{ UPDATE("department"); if (department.getName() != null) { SET("name = #{name}"); } if (department.getType() != null) { SET("type = #{type}"); } if (department.getTelephone() != null) { SET("telephone = #{telephone}"); } if (department.getFax() != null) { SET("fax = #{fax}"); } if (department.getDescription() != null) { SET("description = #{description}"); } if (department.getPredepartment() != null) { SET("predepartment = #{predepartment}"); } if (department.getDate() != null) { SET("date = #{date}"); } WHERE("id = #{id}"); }}.toString(); } //新增 public String insert (Department department){ return new SQL() {{ INSERT_INTO("department"); if (department.getId() != null) { VALUES("id", "#{id}"); } if (department.getName() != null) { VALUES("name", "#{name}"); } if (department.getType() != null) { VALUES("type", "#{type}"); } if (department.getTelephone() != null) { VALUES("telephone", "#{telephone}"); } if (department.getFax() != null) { VALUES("fax", "#{fax}"); } if (department.getDescription() != null) { VALUES("description", "#{description}"); } if (department.getPredepartment() != null) { VALUES("predepartment", "#{predepartment}"); } if (department.getDate() != null) { VALUES("date", "#{date}"); } }}.toString(); } }
true
418584705deac3e11c940361912d68504ea62b73
Java
nativebinary/java-common
/java-common-basic/src/main/java/common/basic/events/EventChange.java
UTF-8
194
2.078125
2
[]
no_license
package common.basic.events; public class EventChange<T> { public boolean onChanging(T before, T after) { return true; } public void onChanged(T before, T after) { } }
true
c093f97ff72f14c09da1dc22cff38b001dd97a68
Java
yoojaZhang/xiaojue
/src/main/java/com/eg/mp/web/controller/LoginController.java
UTF-8
705
1.734375
2
[]
no_license
package com.eg.mp.web.controller; import com.eg.mp.web.error.OperationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; /** * @author liangjiange * @since 2017-02-07 20:46 */ @Controller public class LoginController { private static Logger logger = LoggerFactory.getLogger(LoginController.class); @RequestMapping("login") public String login() { return "login/login"; } }
true
9bfca71d5c43b3eb30358272ab354c3eae95cd2a
Java
n-ong/Monopoly
/prop.java
UTF-8
452
2.828125
3
[]
no_license
public class prop extends SquareType { private int cost; private int value; public prop(String name, String tileType, int cost, int value) { super(name, tileType); this.cost = cost; this.value = value; } public int getCost() { return cost; } public void setCost(int x) { cost = x; } public int getValue() { return value; } public void setValue(int x) { value = x; } }
true
a70d6b3d5867c6585f6b20f41270f7fbdcf3271a
Java
arpit9691/Data-Structures-and-Algorithms
/DataStructures/src/AnagramPractice.java
UTF-8
962
3.34375
3
[]
no_license
import java.util.HashMap; public class AnagramPractice { public static void main(String[] args) { // TODO Auto-generated method stub String a = "Arpot"; char[] a1 = a.toCharArray(); String b = "rpiAt"; char[] b1 = b.toCharArray(); HashMap<Character,Integer> hm = new HashMap<Character,Integer>(); if(a.length()!=b.length() || a.length()<0 || b.length()<0) { System.out.println("Not Anagram"); } for(int i=0;i<a1.length;i++) { if(hm.containsKey(a1[i])) { hm.put(a1[i], hm.get(a1[i])+1); } else { hm.put(a1[i], 1); } } for(int i=0;i<b1.length;i++) { if(hm.containsKey(b1[i])) { if(hm.get(b1[i])>0) { int value=hm.get(b1[i]); value--; hm.put(b1[i], value); } } } for(int i=0;i<a1.length;i++) { if(hm.get(a1[i])!=0) { System.out.println("False"); } else continue; } } }
true
7bffb1b4ab59170bfe93a3c84ff8fee870bccaf6
Java
LukeSAV/ProtoScape
/src/org/apollo/game/event/handler/impl/PrivateChatEventHandler.java
UTF-8
536
2.078125
2
[ "ISC" ]
permissive
package org.apollo.game.event.handler.impl; import org.apollo.game.event.handler.EventHandler; import org.apollo.game.event.handler.EventHandlerContext; import org.apollo.game.event.impl.PrivateChatEvent; import org.apollo.game.model.Player; import org.apollo.game.model.PrivateChat; public final class PrivateChatEventHandler extends EventHandler<PrivateChatEvent> { @Override public void handle(EventHandlerContext ctx, Player player, PrivateChatEvent event) { PrivateChat.getInstance().sendPrivateMessage(player, event); } }
true
872dca9b1844b5c40812bb1f29665e6d3d552aa0
Java
XY113HE/DouYu
/app/src/main/java/com/ibagou/dou/network/NetWorkManager.java
UTF-8
1,989
2.1875
2
[]
no_license
package com.ibagou.dou.network; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import com.ibagou.dou.network.api.DouYuNetApi; /** * Created by sdbean-zlh on 16/5/20. */ public class NetWorkManager { // public static final String DOUYU_URL_BASE = "http://werewolf.53site.com/ScriptKill/"; public static final String DOUYU_URL_BASE = "http://dou.ibagou.com/api/"; public static final String DOUYU_VERSION = "v1/"; private static NetWorkManager netWorkManager; private OkHttpClient okHttpClient; private DouYuNetApi douYuNetApi; private static Converter.Factory gsonConverterFactory; private static CallAdapter.Factory rxJavaCallAdapterFactory; public static NetWorkManager getInstance() { if (netWorkManager == null) { netWorkManager = new NetWorkManager(); } return netWorkManager; } private NetWorkManager() { HttpLoggingInterceptor httpLoggingInterceptor= new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE); this.okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build(); gsonConverterFactory = GsonConverterFactory.create(); rxJavaCallAdapterFactory = RxJava2CallAdapterFactory.create(); } public DouYuNetApi getDouYuNetApi() { if (douYuNetApi == null) { Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) .baseUrl(DOUYU_URL_BASE) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(rxJavaCallAdapterFactory) .build(); douYuNetApi = retrofit.create(DouYuNetApi.class); } return douYuNetApi; } }
true
7bfb2fdcc9a0429cf5bc7e44f6a0ff05a362a70d
Java
currrentbp/myGenProject
/src/main/java/com/currentbp/test/other/Java8Test.java
UTF-8
6,342
3.03125
3
[]
no_license
package com.currentbp.test.other; import com.currentbp.common.model.Course; import com.currentbp.common.model.Student; import com.currentbp.common.model.Subject; import com.currentbp.util.all.ListUtil; import org.assertj.core.util.Lists; import org.junit.Test; import java.util.*; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; /** * @author baopan * @createTime 20190823 */ public class Java8Test { @Test public void t111(){ List<Student> students =new ArrayList<>();// Lists.newArrayList(new Student(1,"1"),new Student(2,"1")); Map<String, Integer> collect = students.stream().collect(Collectors.toMap(Student::getName, Student::getId, (k1, k2) -> k1 + k2)); System.out.println(collect.get("1")); } @Test public void k1k2sum(){ List<Student> students = Lists.newArrayList(new Student(1,"b1") ,new Student(2,"b1") ,new Student(3,"b1") ,new Student(4,"b1")); Map<String, Integer> collect = students.stream().collect(Collectors.toMap(Student::getName, Student::getId, (k1, k2) -> k1 + k2)); for (Map.Entry<String, Integer> stringIntegerEntry : collect.entrySet()) { System.out.println("key111:"+stringIntegerEntry.getKey()+" value222:"+stringIntegerEntry.getValue()); } } @Test public void filter(){ List<Student> students = Lists.newArrayList(new Student(1,"s1"),new Student(2,"s2")); List<Student> collect = students.stream().filter(s -> s.getId().equals(10)).collect(toList()); ListUtil.printList(collect); } @Test public void sum(){ List<Student> students = Lists.newArrayList(new Student(1,"s1"),new Student(2,"s2")); int sum = students.stream().mapToInt(Student::getId).sum(); System.out.println(sum); List<Student> students1 = new ArrayList<>(); int sum1 = students1.stream().mapToInt(Student::getId).sum(); System.out.println(sum1); } @Test public void t6(){ List<Student> students = new ArrayList<>(); students.add(new Student(1,"1", Lists.newArrayList(new Course(1,"c1",new Subject(1,"s1")),new Course(2,"c2")))); students.add(new Student(2,"2",Lists.newArrayList(new Course(3,"c3")))); students.add(new Student(3,"3",Lists.newArrayList(new Course(4,"c4"),new Course(5,"c5")))); List<Course> allCourses = students.stream().flatMap(o -> o.getMyCourses().stream()).collect(toList()); Course course = allCourses.get(0); course.setName("ssssssssssssssssssssssssss"); course.getSubject().setName("sssfffffff"); ListUtil.printList(allCourses); ListUtil.printList(students); } @Test public void t5(){ List<Student> students = new ArrayList<>(); students.add(new Student(1,"1", Lists.newArrayList(new Course(1,"c1"),new Course(2,"c2")))); students.add(new Student(2,"2",Lists.newArrayList(new Course(3,"c3")))); students.add(new Student(3,"3",Lists.newArrayList(new Course(4,"c4"),new Course(5,"c5")))); List<Course> result = new ArrayList<>(); students.forEach(s->{result.addAll(s.getMyCourses());}); Course course = result.get(0); course.setName("ssssssssssssssssssssssssss"); ListUtil.printList(result); ListUtil.printList(students); } @Test public void t4(){ //结果:修改了,说明stream是浅拷贝 List<Student> students = new ArrayList<>(); students.add(new Student(1,"1", Lists.newArrayList(new Course(1,"c1"),new Course(2,"c2")))); students.add(new Student(2,"2",Lists.newArrayList(new Course(3,"c3")))); students.add(new Student(3,"3",Lists.newArrayList(new Course(4,"c4"),new Course(5,"c5")))); List<Course> allCourses = students.stream().flatMap(o -> o.getMyCourses().stream()).collect(toList()); Course course = allCourses.get(0); course.setName("ssssssssssssssssssssssssss"); ListUtil.printList(allCourses); ListUtil.printList(students); } @Test public void t3(){ //结果:修改了,说明stream是浅拷贝 List<Student> students = new ArrayList<>(); students.add(new Student(1,"1")); students.add(new Student(2,"2")); students.add(new Student(3,"3")); List<Student> students1 = students.stream().filter(s -> s.getId().equals(1) || s.getId().equals(2)).collect(toList()); Student student = students1.get(0); student.setName("fffffff"); ListUtil.printList(students); ListUtil.printList(students1); } @Test public void t3_1(){ List<Integer> students = new ArrayList<>(); students.add(1); students.add(2); students.add(3); students.forEach(i->{if(i==1)i++;System.out.println(i);}); ListUtil.printList(students); } @Test public void t21(){ String content = "9999,12"; System.out.println(content.substring(5)); } @Test public void t11(){ Integer num = null; int f = num - 3; System.out.println(f); } @Test public void sort(){ List<Student> students = new ArrayList<>(2); Student student1 = new Student(2,"ss"); Student student2 = new Student(3,"ff"); students.add(student1); students.add(student2); List<Student> collect = students.stream().sorted((x, y) -> { return 3 == x.getId() ? -1 : 1; }).collect(toList()); ListUtil.printList(collect); } @Test public void t2(){ List<Student> students = new ArrayList<>(2); Student student1 = new Student(2,"ss"); Student student2 = new Student(3,"ff"); students.add(student1); students.add(student2); int sum = students.stream().mapToInt(Student::getId).sum(); System.out.println(sum); } @Test public void t1(){ String[] words = new String[]{"Hello","World"}; List<String[]> a = Arrays.stream(words) .map(word -> word.split("l")) .distinct() .collect(toList()); for (String[] strings : a) { ListUtil.printList(strings); } } }
true
c47a6a46b539c400f06f347a6f485180a13b6ef1
Java
borjafg/IPS_SCRUM
/IPS_L5/src/business/impl/empaquetado/CargarProductosOT.java
ISO-8859-1
1,162
2.625
3
[]
no_license
package business.impl.empaquetado; import javax.persistence.PersistenceException; import business.exception.BusinessException; import business.impl.util.Command; import model.OrdenTrabajo; import model.Pedido; import persistence.ProductoEnOrdenTrabajoFinder; import persistence.exception.MyPersistenceException; public class CargarProductosOT implements Command { private OrdenTrabajo ordenTrabajo; private Pedido pedido; public CargarProductosOT(OrdenTrabajo ordenTrabajo, Pedido pedido) { this.ordenTrabajo = ordenTrabajo; this.pedido = pedido; } @Override public Object execute() throws BusinessException { try { // No hay productos en el paquete o no hay ningn paquete abierto if (pedido == null) { return ProductoEnOrdenTrabajoFinder.findPendientesEmpaquetar(ordenTrabajo); } // Si hay un paquete abierto buscar en la OT productos de ese pedido else { return ProductoEnOrdenTrabajoFinder.findPendientesEmpaquetarPedido(ordenTrabajo, pedido); } } catch (MyPersistenceException | PersistenceException e) { throw new BusinessException("Ha ocurrido un error al cargar los productos de una OT", e); } } }
true
89e055760fd05257faa91f019e6bd63f678e706c
Java
yetote/MP4Info
/app/src/main/java/com/yetote/mp4info/bean/Vmhd.java
UTF-8
1,957
2.09375
2
[]
no_license
package com.yetote.mp4info.bean; import android.text.SpannableStringBuilder; import android.util.Log; import com.yetote.mp4info.model.Box; import com.yetote.mp4info.model.FullBox; import com.yetote.mp4info.util.CharUtil; import com.yetote.mp4info.util.NIOReadInfo; import java.nio.channels.FileChannel; public class Vmhd extends FullBox { String describe = "视频信息头,此box包含了视频的特征信息"; private String[] key = new String[]{ "version", "flag", "graphicsmode", "opcolor", }; private String[] introductions = new String[]{ "版本号", "标志码", "视频合成模式;0为复制现有模式", "rgb值,供graphics_mode使用", }; private int graphicsmode_size = 2; private int opcolor_size = 6; private byte[] graphicsmode; private byte[] opcolor; private byte[] all; public Vmhd(int length) { graphicsmode = new byte[graphicsmode_size]; opcolor = new byte[opcolor_size]; all = new byte[length]; } @Override public void read(SpannableStringBuilder[] builders, FileChannel fileChannel, Box box) { super.read(builders, fileChannel, box); CharUtil.linkDescribe(builders[0], describe, key, introductions); String[] name = new String[]{"全部数据", "length", "type", "version", "flag", "graphicsmode", "opcolor"}; byte[][] data = new byte[][]{all, length != 1 ? length_arr : large_length_arr, type_arr, version_arr, flag_arr, graphicsmode, opcolor }; String[] value = new String[name.length]; String[] type = new String[]{"char", "int", "char", "int", "int", "char", "char" }; NIOReadInfo.readBox(builders[1], box.getPos(), length, fileChannel, name, value, data, type); } }
true
89cb83c7f769e0c8a7a6f698696746b16d55a69d
Java
Maciej-Poleski/DnDP-SVN
/trunk/DnDC/src/dndp/engine/card/bonus/Bonus.java
UTF-8
688
2.953125
3
[]
no_license
/* * To change this template, choose Tools | Templates and open the template in * the editor. */ package dndp.engine.card.bonus; /** * Modeluje zachowania premii. * * @author bambucha */ public interface Bonus { /** * Dodaje premię danego typu do pola * * @param bonus * Wartośc premi */ public void addBonus(Integer bonus); /** * Usuwa premię danego typu z danego pola * * @param bonus */ public void removeBonus(Integer bonus); /** * Zwraca premię danego typu z pola. Uwzglednia przy tym wszystkie premie. * * @return Warotśc premii. */ public Integer getBonus(); }
true
cf1d17448d1f409df7ce835f3b83db119f17ecb6
Java
MaelSantos/Veiculos-Pajeu
/src/br/com/VeiculosPajeu/Dao/DaoFuncionario.java
UTF-8
289
1.90625
2
[]
no_license
package br.com.VeiculosPajeu.Dao; import br.com.VeiculosPajeu.Dao.Interface.IDaoFuncionario; import br.com.VeiculosPajeu.Entidade.Funcionario; public class DaoFuncionario extends Dao<Funcionario> implements IDaoFuncionario { public DaoFuncionario() { super(Funcionario.class); } }
true
1bb368695762b4f66fcc51df0781b45fb5cfd7fb
Java
bhanupalsingh/Simpl
/src/com/simpl/validate/Validator.java
UTF-8
202
2.21875
2
[]
no_license
package com.simpl.validate; public class Validator { public static boolean isDiscountValid(double discount) { if(discount <0 || discount > 100) { return false; }else { return true; } } }
true
3d01b6c2399ca05595bb1377f90bfc7ad8e7474e
Java
kakeking/kra
/app/src/main/java/com/usyd/riceapp/DfRecord.java
UTF-8
2,659
2.25
2
[]
no_license
package com.usyd.riceapp; import com.google.firebase.firestore.GeoPoint; import com.google.firebase.firestore.ServerTimestamp; import java.util.ArrayList; import java.util.Date; public class DfRecord { private String recordId; private @ServerTimestamp Date plantDate; private @ServerTimestamp Date createDate; private GeoPoint location; private String location_name; private ArrayList<String> riceVariety; private ArrayList<String> nitrogenType; private int seedingRate; private int nitrogenAmount; public DfRecord(){} public DfRecord(String recordId, Date plantDate, Date createDate, GeoPoint location, ArrayList<String> riceVariety, ArrayList<String> nitrogenType, int seedingRate, int nitrogenAmount, String location_name){ this.plantDate = plantDate; this.location = location; this.riceVariety = riceVariety; this.nitrogenType = nitrogenType; this.nitrogenAmount = nitrogenAmount; this.seedingRate = seedingRate; this.createDate = createDate; this.location_name = location_name; } public Date getPlantDate() { return plantDate; } public void setPlantDate(Date plantDate) { this.plantDate = plantDate; } public GeoPoint getLocation() { return location; } public void setLocation(GeoPoint location) { this.location = location; } public ArrayList<String> getRiceVariety() { return riceVariety; } public ArrayList<String> getNitrogenType() { return nitrogenType; } public void setNitrogenType(ArrayList<String> nitrogenType) { this.nitrogenType = nitrogenType; } public String getLocation_name() { return location_name; } public void setLocation_name(String location_name) { this.location_name = location_name; } public void setRiceVariety(ArrayList<String> riceVariety) { this.riceVariety = riceVariety; } public int getSeedingRate() { return seedingRate; } public void setSeedingRate(int seedingRate) { this.seedingRate = seedingRate; } public int getNitrogenAmount() { return nitrogenAmount; } public void setNitrogenAmount(int nitrogenAmount) { this.nitrogenAmount = nitrogenAmount; } public String getRecordId() { return recordId; } public void setRecordId(String recordId) { this.recordId = recordId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } }
true
bc04ca49421ad800dc8c1fa2c188f52007b19143
Java
zhong2peng/dnight-framework
/dnight-leetcode/[0127][Word Ladder]/src/Solution.java
UTF-8
3,116
3.6875
4
[ "MIT" ]
permissive
import java.util.*; /** * @author ZHONGPENG769 * @date 2019/9/9 */ public class Solution { /** * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: * <p> * Only one letter can be changed at a time. * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. * Note: * <p> * Return 0 if there is no such transformation sequence. * All words have the same length. * All words contain only lowercase alphabetic characters. * You may assume no duplicates in the word list. * You may assume beginWord and endWord are non-empty and are not the same. * Example 1: * <p> * Input: * beginWord = "hit", * endWord = "cog", * wordList = ["hot","dot","dog","lot","log","cog"] * <p> * Output: 5 * <p> * Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", * return its length 5. * Example 2: * <p> * Input: * beginWord = "hit" * endWord = "cog" * wordList = ["hot","dot","dog","lot","log"] * <p> * Output: 0 * <p> * 题目大意: * 给定两个词(beginWord和endWord),和一个字典,查找从beginWord转型到endWord的最短长度: * - 一次只有一个字母可以被改变 * - 每个中间字必须存在于词典中 * <p> * 注意: * - 如果不存在这样的变换序列,返回0。 * - 所有单词具有相同的长度。 * - 所有单词只包含小写字母字符。 * <p> * 解题思路: * 广度优化遍历 * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. * * @param beginWord * @param endWord * @param wordList * @return */ public int ladderLength(String beginWord, String endWord, List<String> wordList) { Set<String> wordDict = new HashSet<>(wordList); char[] chars; Deque<String> deque = new LinkedList<>(); deque.addLast(beginWord); int result = 0; String s; String t; while (!deque.isEmpty()) { for (int k = deque.size(); k > 0; k--) { s = deque.removeFirst(); if (s.equalsIgnoreCase(endWord)) { return result + 1; } chars = s.toCharArray(); for (int i = 0; i < beginWord.length(); i++) { for (char j = 'a'; j <= 'z'; j++) { char temp = chars[i]; chars[i] = j; t = new String(chars); if (wordDict.contains(t) && !t.equals(s)) { deque.addLast(t); wordDict.remove(t); } chars[i] = temp; } } } result++; } return 0; } }
true
89c72606c15fa19791e9adf78485f9b579ef9bfd
Java
PalladioSimulator/Palladio-Addons-EnvironmentalDynamics
/tests/org.palladiosimulator.envdyn.api.tests/src/org/palladiosimulator/envdyn/api/tests/util/ModelLoader.java
UTF-8
5,190
1.539063
2
[]
no_license
package org.palladiosimulator.envdyn.api.tests.util; import java.io.IOException; import java.nio.file.Paths; import java.util.Collections; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import org.eclipse.gmf.runtime.notation.NotationPackage; import org.modelversioning.emfprofile.EMFProfilePackage; import org.modelversioning.emfprofile.Profile; import org.modelversioning.emfprofileapplication.EMFProfileApplicationPackage; import org.palladiosimulator.envdyn.environment.templatevariable.TemplatevariablePackage; import org.palladiosimulator.pcm.repository.RepositoryPackage; import org.palladiosimulator.pcm.system.SystemPackage; public class ModelLoader { private final static String RESOURCE_ENVIRONMENT_EXTENSION = "resourceenvironment"; private final static String DISTRIBUTION_TYPE_EXTENSION = "distributiontype"; private final static String SYSTEM_EXTENSION = "system"; private final static String TEMPLATE_DEFINITION_EXTENSION = "templatevariable"; private final static String STATIC_MODEL_EXTENSION = "staticmodel"; private final static String DYNAMIC_MODEL_EXTENSION = "dynamicmodel"; private final static String MODEL_FOLDER_NAME = "models"; private final static String RESOURCE_ENVIRONMENT_FILE = String.format("%1s.%2s", "DeltaIoTResources", RESOURCE_ENVIRONMENT_EXTENSION); private final static String DISTRIBUTION_TYPE_FILE = String.format("%1s.%2s", "DeltaIoTDistributionTypes", DISTRIBUTION_TYPE_EXTENSION); private final static String SYSTEM_FILE = String.format("%1s.%2s", "DeltaIoTSystem", SYSTEM_EXTENSION); private final static String TEMPLATES_FILE = String.format("%1s.%2s", "DeltaIoTTemplateVariables", TEMPLATE_DEFINITION_EXTENSION); private final static String BN_FILE = String.format("%1s.%2s", "DeltaIoTNonTemporalEnvironmentModel", STATIC_MODEL_EXTENSION); private final static String DBN_FILE = String.format("%1s.%2s", "DeltaIoTEnvironmentalDynamics", DYNAMIC_MODEL_EXTENSION); private final static ModelLoader LOADER_INSTANCE = new ModelLoader(); private final URI resourceEnvURI; private final URI distTypeURI; private final URI systemURI; private final URI templatesURI; private final URI bnURI; private final URI dbnURI; private final ResourceSet resourceSet; private ModelLoader() { this.resourceEnvURI = URI.createFileURI(makeAbsolute(RESOURCE_ENVIRONMENT_FILE)); this.distTypeURI = URI.createFileURI(makeAbsolute(DISTRIBUTION_TYPE_FILE)); this.systemURI = URI.createFileURI(makeAbsolute(SYSTEM_FILE)); this.templatesURI = URI.createFileURI(makeAbsolute(TEMPLATES_FILE)); this.bnURI = URI.createFileURI(makeAbsolute(BN_FILE)); this.dbnURI = URI.createFileURI(makeAbsolute(DBN_FILE)); this.resourceSet = new ResourceSetImpl(); this.resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl()); this.resourceSet.getPackageRegistry().put(TemplatevariablePackage.eNS_URI, TemplatevariablePackage.eINSTANCE); this.resourceSet.getPackageRegistry().put(RepositoryPackage.eNS_URI, RepositoryPackage.eINSTANCE); this.resourceSet.getPackageRegistry().put(SystemPackage.eNS_URI, SystemPackage.eINSTANCE); this.resourceSet.getPackageRegistry().put(EMFProfilePackage.eNS_URI, EMFProfilePackage.eINSTANCE); this.resourceSet.getPackageRegistry().put(EMFProfileApplicationPackage.eNS_URI, EMFProfileApplicationPackage.eINSTANCE); this.resourceSet.getPackageRegistry().put(NotationPackage.eNS_PREFIX, NotationPackage.eINSTANCE); Profile envTags = (Profile) this.resourceSet .getResource(URI.createFileURI(makeAbsolute("profile.emfprofile_diagram")), true).getContents().get(0); this.resourceSet.getPackageRegistry().put(envTags.getNsURI(), envTags); } private String makeAbsolute(String fileName) { return Paths.get(System.getProperty("user.dir"), Paths.get(MODEL_FOLDER_NAME, fileName).toString()).toString(); } public static ModelLoader get() { return LOADER_INSTANCE; } public Resource loadTemplates() { return resourceSet.getResource(templatesURI, true); } public Resource loadResourceEnvironment() { return resourceSet.getResource(resourceEnvURI, true); } public Resource loadSystem() { return resourceSet.getResource(systemURI, true); } public Resource loadGroundProbabilisticNetwork() { return resourceSet.getResource(bnURI, true); } public Resource loadDynamicBehaviourRepo() { return resourceSet.getResource(dbnURI, true); } public Resource loadDistributionTypes() { return resourceSet.getResource(distTypeURI, true); } public void persist(EObject eObj) { Resource resource = resourceSet.createResource(URI.createFileURI(makeAbsolute("EnvDyn.dynamicmodel"))); resource.getContents().add(eObj); try { resource.save(Collections.EMPTY_MAP); } catch (IOException e) { e.printStackTrace(); } } }
true
c495d9e3ddc244c3fd85b054acb71547fb269419
Java
sanathsaithal/Wolken
/spring/dependency_injection/loggers/shops/src/main/java/com/wolken/shops/dao/ShopsDAO.java
UTF-8
142
1.625
2
[]
no_license
package com.wolken.shops.dao; import com.wolken.shops.entity.ShopsEntity; public interface ShopsDAO { String save(ShopsEntity entity); }
true
3373ad55eb63e7f08cd2cbfc991639990adda85b
Java
cckmit/mimosaframework
/mimosa-orm/src/main/java/org/mimosaframework/orm/sql/WhereItem.java
UTF-8
1,935
2.484375
2
[ "Apache-2.0" ]
permissive
package org.mimosaframework.orm.sql; import org.mimosaframework.orm.criteria.CriteriaLogic; public class WhereItem { private Class tableLeft; private Object field; private SymbolType symbol = SymbolType.EQ; private Class tableRight; /** * 如果tableRight存在则value肯定是字段 * 如果tableRight不存在则value可能是值 * 如果value类型是SelectBuilder则属于子查询 */ private Object value; private CriteriaLogic logic = CriteriaLogic.AND; public WhereItem() { } public WhereItem(CriteriaLogic logic) { this.logic = logic; } public void set(Class table, Object field, Object value) { this.tableLeft = table; this.field = field; this.value = value; } public void set(Class table1, Object field1, Class table2, Object field2) { this.tableLeft = table1; this.field = field1; this.tableRight = table2; this.value = field2; } public void set(Class table, Object field, SymbolType symbol, Object value) { this.tableLeft = table; this.field = field; this.symbol = symbol; this.value = value; } public void set(Class table1, Object field1, SymbolType symbol, Class table2, Object field2) { this.tableLeft = table1; this.field = field1; this.symbol = symbol; this.tableRight = table2; this.value = field2; } public void setLogic(CriteriaLogic logic) { this.logic = logic; } public Class getTableLeft() { return tableLeft; } public Object getField() { return field; } public SymbolType getSymbol() { return symbol; } public Class getTableRight() { return tableRight; } public Object getValue() { return value; } public CriteriaLogic getLogic() { return logic; } }
true
6fb40541d06afa8c1ec230c58eaeab2f755a7e46
Java
jasonkim4201/tasktrackv0
/src/main/java/com/tasktrack/tasktrackv0/repository/TodosRepo.java
UTF-8
276
1.507813
2
[]
no_license
package com.tasktrack.tasktrackv0.repository; import com.tasktrack.tasktrackv0.model.Todos; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface TodosRepo extends JpaRepository<Todos, Long> { }
true
cbd3c4c053140c9e72f9b30ebd5d9ac800b2488c
Java
Pavan18/intuit_assignment
/Primenumber.java
UTF-8
1,872
3.828125
4
[]
no_license
/* * * Input : Number of prime numbers to be found and the numbers itself * Output: Prime number associated with the input numbers * Description: Finds the prime number based on the input using Sieve of Eratosthenes in O(nlog(log(n))) * * */ import java.util.HashMap; import java.util.Scanner; public class Primenumber { public static void main(String[] args) { int N = 0, k = 0, max = 0, numb; HashMap<Integer, Integer> PrimeIndices = new HashMap<Integer, Integer>(); Scanner in = new Scanner(System.in); System.out.println("Number of Prime Indices to be searched for:\n"); int num = in.nextInt(); if (num <= 0) { System.out.println("Please enter positive integer"); return; } System.out.println("Enter the numbers to be searched"); for (int i = 1; i <= num; i++) { numb = in.nextInt(); if(numb<=0) { System.out.println("Re enter a positive number"); i--; continue; } if(PrimeIndices.containsKey(numb)==true) { System.out.println("Re enter a distinct number"); i--; continue; } if (max < numb) { max = numb; } PrimeIndices.put(numb, numb); if (i == num) { N = max * max; } } // initially assume all integers are prime boolean[] isPrime = new boolean[N + 1]; for (int i = 2; i <= N; i++) { isPrime[i] = true; } // mark non-primes <= N using Sieve of Eratosthenes for (int i = 2; i * i <= N; i++) { // if i is prime, then mark multiples of i as nonprime if (isPrime[i]) { for (int j = i; i * j <= N; j++) { isPrime[i * j] = false; } } } // count primes int primes = 0; for (int i = 2; i <= N; i++) { if (isPrime[i]) { primes++; if (PrimeIndices.containsKey(primes)) { System.out.println("Index: " + primes + " --> " + i); } } } } }
true
9f40f4b3193746a132618f63a6a0fc3fd590d922
Java
kevinmingtarja/kattis-solutions
/conformity.java
UTF-8
2,026
3.109375
3
[]
no_license
import java.io.*; import java.util.HashMap; import java.util.HashSet; public class conformity { // Kevin Nathanael Mingtarja // A0219748N public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); HashMap<HashSet<Integer>, Integer> combinations = new HashMap<HashSet<Integer>, Integer>(); int n = 0; try { n = Integer.parseInt(br.readLine()); } catch (IOException e) { System.out.println("Error"); } int maxCounter = 0; for (int i = 0; i < n; i++) { HashSet<Integer> currCombination = new HashSet<Integer>(); String[] currLine = new String[5]; try { currLine = br.readLine().split(" "); } catch (IOException e) { System.out.println("Error"); } currCombination.add(Integer.parseInt(currLine[0])); currCombination.add(Integer.parseInt(currLine[1])); currCombination.add(Integer.parseInt(currLine[2])); currCombination.add(Integer.parseInt(currLine[3])); currCombination.add(Integer.parseInt(currLine[4])); if (combinations.get(currCombination) == null) { combinations.put(currCombination, 1); } else { int currCount = combinations.get(currCombination); combinations.put(currCombination, currCount + 1); if (currCount + 1 > maxCounter) { maxCounter = currCount + 1; } } } int counter = 0; for (int value : combinations.values()) { if (value == maxCounter) { counter++; } } if (maxCounter == 0) { pw.print(n); } else { pw.print(maxCounter * counter); } pw.close(); } }
true
e50602e711cd87d0e99cbbc0ca791d8dc3c35195
Java
ruynzhang/shanxing
/pay/src/main/java/com/dimeng/p2p/pay/job/TestJob.java
UTF-8
789
2.078125
2
[]
no_license
package com.dimeng.p2p.pay.job; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.CronTrigger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.dimeng.p2p.pay.util.QuDateUtil; /** * 测试Job * * @author ice * */ public class TestJob implements Job { protected static Log logger = LogFactory.getLog(AutoHkJob.class); public void execute(JobExecutionContext context) throws JobExecutionException { CronTrigger cronTrigger = (CronTrigger) context.getTrigger(); logger.debug("[测试Job]已执行完一次Job,下次执行Job时间为:" + QuDateUtil.getDateStr(cronTrigger.getNextFireTime()) + "(" + "表达式:" + cronTrigger.getCronExpression() + ")"); } }
true
5c8bc9d653b765bce55daa4c4ea015568430fedb
Java
Leclaire1941/Transport
/src/main/java/by/epam/classes/transport/util/Calculator.java
UTF-8
2,118
2.75
3
[]
no_license
package by.epam.classes.transport.util; import by.epam.classes.transport.entity.AbstractWagon; import by.epam.classes.transport.entity.CargoWagon; import by.epam.classes.transport.entity.CoachWagon; import by.epam.classes.transport.entity.Train; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; public class Calculator { private final static Logger LOGGER = Logger.getLogger(Calculator.class); /*package*/ List<CoachWagon> defineCoachWagonsList(Train train) { List<CoachWagon> coachWagons = new ArrayList<>(); for (AbstractWagon wagon : train.getWagonList()) { if (wagon.getClass() == CoachWagon.class) { coachWagons.add((CoachWagon) wagon); } } return coachWagons; } private List<CargoWagon> defineCargoWagonsList(Train train) { List<CargoWagon> cargoWagons = new ArrayList<>(); for (AbstractWagon wagon : train.getWagonList()) { if (wagon.getClass() == CargoWagon.class) { cargoWagons.add((CargoWagon) wagon); } } return cargoWagons; } public int calculatePassengersAmount(Train train) { if (train == null) { throw new IllegalArgumentException("Train is null"); } List<CoachWagon> coachWagons = defineCoachWagonsList(train); int passengerAmount = 0; for (CoachWagon wagon : coachWagons) { passengerAmount += wagon.getPeopleCapacity(); } LOGGER.debug("Passenger amount calculated - " + passengerAmount); return passengerAmount; } public int calculateBaggageAmount(Train train) { if (train == null) { throw new IllegalArgumentException("Train is null"); } List<CargoWagon> cargoWagons = defineCargoWagonsList(train); int baggageAmount = 0; for (CargoWagon wagon : cargoWagons) { baggageAmount += wagon.getBaggageCapacity(); } LOGGER.debug("Baggage amount calculated - " + baggageAmount); return baggageAmount; } }
true
f0caedfe2fbd8ea72d29b9e89b3d9415f0415d65
Java
probaby/cloud
/spring-service1/src/main/java/com/example/springcontrol/dispatch/DispatchControl.java
UTF-8
804
2.078125
2
[ "MIT" ]
permissive
package com.example.springcontrol.dispatch; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author huangbiaof * @data 创建时间:2019/8/7 13:24 */ @RestController(value="hello") public class DispatchControl { private DiscoveryClient discoveryClient; // private Registration client; @RequestMapping(value = "/hello") public String hello(){ ServiceInstance service = discoveryClient.getLocalServiceInstance(); // client.getHost(); System.out.println(service.getHost()+"\nserviceId"+service.getServiceId()); return "hello word"; } }
true
8cedfe9ee3cd2bf07636d5ac16fa8b77e7805080
Java
AccaEmme/DemoJerseyRESTAPI
/src/main/java/it/accaemme/spring/demo/DemoApplication.java
UTF-8
605
1.960938
2
[]
no_license
package it.accaemme.spring.demo; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication extends ResourceConfig { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } public DemoApplication() { // register( GreetingsBean.class ); alternativa registrazione register( new GreetingsAPI() ); System.out.println("To test: http://localhost:8080/rest/greets/lang/it/user/AccaEmme"); } }
true
310f68ef5e4dc8b8ccdb68da5dd751c2820e4c24
Java
Aniz/EvDSL
/splcc/data/Author.java
UTF-8
2,315
2.4375
2
[]
no_license
//#if ${InsertAuthors} == "T" package {{systemName|lower}}.ev.data; public class Author { private int idAuthor; private String name; private String filiation; private String email; {% if data.option.properties|length > 0 %} //generated By DSL {% for property in data.option.properties %} private {{property.type|javatype}} {{property.name}}; {% endfor %} // {% endif %} {% if data.option.categories|length > 0 %} //generated By DSL private Type{{data.option.entity}} type{{data.option.entity}}; public enum Type{{data.option.entity}}{ {% for category in data.option.categories %} {% if loop.last %} {{category.name}} {% else %} {{category.name}}, {% endif %} {% endfor %} } // //generated By DSL public Type{{data.option.entity}} getType{{data.option.entity}}(){ return this.type{{data.option.entity}}; } public void setType{{data.option.entity|capitalize}}(Type{{data.option.entity}} new_value){ this.type{{data.option.entity}} = new_value; } // {% endif %} {% if data.option.properties|length > 0 %} //generated By DSL {% for property in data.option.properties %} public {{property.type|javatype}} get{{property.name|capitalize}}(){ return this.{{property.name}}; } public void set{{property.name|capitalize}}({{property.type|javatype}} new_value){ this.{{property.name}} = new_value; } {% endfor %} // {% endif %} public int getIdAuthor() { return idAuthor; } public void setIdAuthor(int idAuthor) { this.idAuthor = idAuthor; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFiliation() { return filiation; } public void setFiliation(String filiation) { this.filiation = filiation; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String toString(){ return "Author Id:"+ idAuthor + "\nName:" + name + "\nFiliation:" + filiation + "\nEmail:" + email {% if data.option.properties|length > 0 %} //generated By DSL {% for property in data.option.properties %} + "{{property.name|capitalize}}:" + {{property.name}} {% endfor %} {% endif %} {% if data.option.categories|length > 0 %} + "Type{{data.option.entity}}:" + type{{data.option.entity}} {% endif %} ; } } //#endif
true
eb89ff6665e26a879a3b58aa71ceabb590c1b3f8
Java
mrizkymunggaran/moten-util
/markup/trunk/src/main/java/moten/david/markup/CurrentStudy.java
UTF-8
1,578
2.546875
3
[]
no_license
package moten.david.markup; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import moten.david.markup.xml.study.Document; import moten.david.markup.xml.study.Study; import org.apache.commons.io.IOUtils; import com.google.inject.Inject; import com.google.inject.Provider; public class CurrentStudy implements Provider<Study> { private static final String STUDY_PATH = "src/test/resources/study1/study1.study"; private final Study study; private final StudyLoader studyFolder; @Inject public CurrentStudy(StudyLoader studyLoader) { this.studyFolder = studyLoader; study = studyLoader.getStudy(STUDY_PATH); } @Override public Study get() { return study; } public void save() { studyFolder.writeStudy(study, STUDY_PATH); } public String getText(String filename) { File parent = new File(STUDY_PATH).getParentFile(); for (Document document : study.getDocument()) if (document.getName().equals(filename)) { File file = new File(parent, filename); try { String text = IOUtils.toString(new FileInputStream(file)); return text; } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } throw new RuntimeException(filename + " not found"); } }
true
aad03fe1c5d43ac0b516bbeb26f1fd023cd947cf
Java
Zhornovyi/flowershop
/FlowerShop.java
UTF-8
1,580
2.578125
3
[]
no_license
package flowershop; import flowershop.Flower.Flower; import flowershop.Flower.FreshFlower; import java.io.File; import java.io.FileNotFoundException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.Scanner; public class FlowerShop { private ArrayList<Flower> allFlowers = new ArrayList<>(); private ArrayList<Decoration> allDecoration = new ArrayList<>(); private ArrayList<Bouquet> allBouquets = new ArrayList<>(); public File getFileReport() { return fileReport; } private File fileReport = new File("/Users/yehorzhornovyi/IdeaProjects/FlowerShop 2.0/Report"+this.getClass().getSimpleName()+".txt"); public ArrayList<Decoration> getAllDecoration() { return allDecoration; } public ArrayList<Flower> getAllFlowers() { return allFlowers; } public ArrayList<Bouquet> getAllBouquets() { return allBouquets; } public static class SortByPrice implements Comparator<Flower> { public int compare(Flower a, Flower b) { if (a.getPrice() < b.getPrice()) return -1; else if (a.getPrice() == b.getPrice()) return 0; else return 1; } } public static class SortByLength implements Comparator<Flower> { public int compare(Flower a, Flower b) { if (a.getLength() < b.getLength()) return -1; else if (a.getLength() == b.getLength()) return 0; else return 1; } } }
true
73a8d2e30183af2732be22688696d4b243fd3897
Java
eric-lanita/BigRoadTruckingLogbookApp_v21.0.12_source_from_JADX
/com/bigroad/shared/at.java
UTF-8
12,915
1.835938
2
[]
no_license
package com.bigroad.shared; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class at { private static final byte[] f2644a = new byte[]{(byte) 8, (byte) 7, (byte) 6, (byte) 5, (byte) 4, (byte) 3, (byte) 2, (byte) 10, (byte) 0, (byte) 9, (byte) 8, (byte) 7, (byte) 6, (byte) 5, (byte) 4, (byte) 3, (byte) 2}; private static final Map<String, String> f2645b = new HashMap(); private final String f2646c; private final boolean f2647d; static { f2645b.put("1A4", "Chrysler"); f2645b.put("1A8", "Chrysler"); f2645b.put("1B4", "Dodge"); f2645b.put("1B5", "Dodge"); f2645b.put("1B6", "Dodge"); f2645b.put("1B7", "Dodge"); f2645b.put("1B8", "Dodge"); f2645b.put("1C4", "Chrysler"); f2645b.put("1C6", "Dodge"); f2645b.put("1C8", "Chrysler"); f2645b.put("1CA", "Chrysler"); f2645b.put("1D3", "Dodge"); f2645b.put("1D4", "Dodge"); f2645b.put("1D7", "Dodge"); f2645b.put("1D8", "Dodge"); f2645b.put("1E5", "Dodge"); f2645b.put("1E6", "Dodge"); f2645b.put("1E7", "Dodge"); f2645b.put("1F4", "Ford"); f2645b.put("1F6", "Ford"); f2645b.put("1FA", "Ford"); f2645b.put("1FB", "Ford"); f2645b.put("1FC", "Ford"); f2645b.put("1FD", "Ford"); f2645b.put("1FF", "Ford"); f2645b.put("1FM", "Ford"); f2645b.put("1FT", "Ford"); f2645b.put("1FU", "Freightliner"); f2645b.put("1FV", "Freightliner"); f2645b.put("1G0", "GMC"); f2645b.put("1G5", "GMC"); f2645b.put("1GB", "GMC"); f2645b.put("1GC", "GMC"); f2645b.put("1GD", "GMC"); f2645b.put("1GJ", "GMC"); f2645b.put("1GK", "GMC"); f2645b.put("1GT", "GMC"); f2645b.put("1HP", "International"); f2645b.put("1HS", "International"); f2645b.put("1HT", "International"); f2645b.put("1HV", "International"); f2645b.put("1M1", "Mack"); f2645b.put("1M2", "Mack"); f2645b.put("1M3", "Mack"); f2645b.put("1M4", "Mack"); f2645b.put("1ND", "Peterbilt"); f2645b.put("1NK", "Kenworth"); f2645b.put("1NP", "Peterbilt"); f2645b.put("1X1", "Peterbilt"); f2645b.put("1X2", "Peterbilt"); f2645b.put("1XD", "Peterbilt"); f2645b.put("1XK", "Kenworth"); f2645b.put("1XP", "Peterbilt"); f2645b.put("2A4", "Chrysler"); f2645b.put("2A8", "Chrysler"); f2645b.put("2AY", "Hino"); f2645b.put("2B4", "Dodge"); f2645b.put("2B5", "Dodge"); f2645b.put("2B6", "Dodge"); f2645b.put("2B7", "Dodge"); f2645b.put("2B8", "Dodge"); f2645b.put("2C4", "Chrysler"); f2645b.put("2C8", "Chrysler"); f2645b.put("2CA", "Chrysler"); f2645b.put("2CT", "GMC"); f2645b.put("2D3", "Dodge"); f2645b.put("2D4", "Dodge"); f2645b.put("2D6", "Dodge"); f2645b.put("2D7", "Dodge"); f2645b.put("2D8", "Dodge"); f2645b.put("2E5", "Dodge"); f2645b.put("2E6", "Dodge"); f2645b.put("2E7", "Dodge"); f2645b.put("2FB", "Ford"); f2645b.put("2FC", "Ford"); f2645b.put("2FD", "Ford"); f2645b.put("2FF", "Ford"); f2645b.put("2FM", "Ford"); f2645b.put("2FT", "Ford"); f2645b.put("2FU", "Freightliner"); f2645b.put("2FV", "Freightliner"); f2645b.put("2FW", "Freightliner"); f2645b.put("2FZ", "Sterling"); f2645b.put("2G0", "GMC"); f2645b.put("2G5", "GMC"); f2645b.put("2GD", "GMC"); f2645b.put("2GJ", "GMC"); f2645b.put("2GK", "GMC"); f2645b.put("2GT", "GMC"); f2645b.put("2HP", "International"); f2645b.put("2HS", "International"); f2645b.put("2HT", "International"); f2645b.put("2HV", "International"); f2645b.put("2M1", "Mack"); f2645b.put("2M2", "Mack"); f2645b.put("2M3", "Mack"); f2645b.put("2M4", "Mack"); f2645b.put("2MA", "Mack"); f2645b.put("2MC", "Mack"); f2645b.put("2MG", "Motor Coach Industries"); f2645b.put("2MK", "Mack"); f2645b.put("2NK", "Kenworth"); f2645b.put("2NP", "Peterbilt"); f2645b.put("2P9", "Prevost"); f2645b.put("2PC", "Prevost"); f2645b.put("2WK", "Western Star"); f2645b.put("2WL", "Western Star"); f2645b.put("2WM", "Western Star"); f2645b.put("2XK", "Kenworth"); f2645b.put("2XP", "Peterbilt"); f2645b.put("3AK", "Freightliner"); f2645b.put("3AL", "Freightliner"); f2645b.put("3B3", "Dodge"); f2645b.put("3B4", "Dodge"); f2645b.put("3B5", "Dodge"); f2645b.put("3B6", "Dodge"); f2645b.put("3B7", "Dodge"); f2645b.put("3B8", "Dodge"); f2645b.put("3BK", "Kenworth"); f2645b.put("3BP", "Peterbilt"); f2645b.put("3C4", "Chrysler"); f2645b.put("3C6", "Dodge"); f2645b.put("3C7", "Dodge"); f2645b.put("3CE", "Volvo"); f2645b.put("3D3", "Dodge"); f2645b.put("3D4", "Dodge"); f2645b.put("3D6", "Dodge"); f2645b.put("3D7", "Dodge"); f2645b.put("3E4", "Dodge"); f2645b.put("3E5", "Dodge"); f2645b.put("3E6", "Dodge"); f2645b.put("3E7", "Dodge"); f2645b.put("3FB", "Ford"); f2645b.put("3FC", "Ford"); f2645b.put("3FD", "Ford"); f2645b.put("3FE", "Ford"); f2645b.put("3FF", "Ford"); f2645b.put("3FN", "Kenworth"); f2645b.put("3FR", "Ford"); f2645b.put("3FT", "Ford"); f2645b.put("3GD", "GMC"); f2645b.put("3GJ", "GMC"); f2645b.put("3GK", "GMC"); f2645b.put("3GT", "GMC"); f2645b.put("3HA", "International"); f2645b.put("3HB", "International"); f2645b.put("3HC", "International"); f2645b.put("3HS", "International"); f2645b.put("3HT", "International"); f2645b.put("3HV", "International"); f2645b.put("3NK", "Kenworth"); f2645b.put("3NM", "Kenworth"); f2645b.put("3WK", "Kenworth"); f2645b.put("3WM", "Kenworth"); f2645b.put("3WP", "Peterbilt"); f2645b.put("4DR", "International"); f2645b.put("4GT", "Isuzu"); f2645b.put("4KA", "International"); f2645b.put("4UZ", "Freightliner"); f2645b.put("4V1", "Volvo"); f2645b.put("4V2", "Volvo"); f2645b.put("4V3", "Volvo"); f2645b.put("4V4", "Volvo"); f2645b.put("4V5", "Volvo"); f2645b.put("4V6", "Volvo"); f2645b.put("4VA", "Volvo"); f2645b.put("4VG", "Volvo"); f2645b.put("4VH", "Volvo"); f2645b.put("4VJ", "Volvo"); f2645b.put("4VK", "Volvo"); f2645b.put("4VL", "Volvo"); f2645b.put("4VM", "Volvo"); f2645b.put("4VZ", "Volvo"); f2645b.put("52U", "International"); f2645b.put("52V", "International"); f2645b.put("54D", "Isuzu"); f2645b.put("5CJ", "Western Star"); f2645b.put("5CK", "Western Star"); f2645b.put("5KJ", "Western Star"); f2645b.put("5KK", "Western Star"); f2645b.put("5PV", "Hino"); f2645b.put("5RJ", "International"); f2645b.put("5WE", "International"); f2645b.put("9BF", "Ford"); f2645b.put("9DW", "Peterbilt"); f2645b.put("9F1", "GMC"); f2645b.put("9F4", "GMC"); f2645b.put("AFV", "Freightliner"); f2645b.put("J8D", "GMC"); f2645b.put("J8T", "GMC"); f2645b.put("JAL", "Isuzu"); f2645b.put("JB4", "Dodge"); f2645b.put("JB5", "Dodge"); f2645b.put("JB6", "Dodge"); f2645b.put("JB7", "Dodge"); f2645b.put("JH6", "Hino"); f2645b.put("JH7", "Hino"); f2645b.put("JH8", "Hino"); f2645b.put("JHA", "Hino"); f2645b.put("JHB", "Hino"); f2645b.put("JHC", "Hino"); f2645b.put("JHH", "Hino"); f2645b.put("JNA", "Nissan"); f2645b.put("JPA", "International"); f2645b.put("JPB", "International"); f2645b.put("JPE", "International"); f2645b.put("KFB", "Freightliner"); f2645b.put("NLT", "Temsa"); f2645b.put("NM0", "Ford"); f2645b.put("RSA", "Freightliner"); f2645b.put("RSB", "Freightliner"); f2645b.put("SBV", "Kenworth"); f2645b.put("VG6", "Mack"); f2645b.put("VG7", "Mack"); f2645b.put("WCD", "Freightliner"); f2645b.put("WDA", "Mercedes-Benz"); f2645b.put("WD0", "Dodge"); f2645b.put("WD1", "Dodge"); f2645b.put("WD2", "Dodge"); f2645b.put("WD3", "Mercedes-Benz"); f2645b.put("WD5", "Dodge"); f2645b.put("WD8", "Dodge"); f2645b.put("WDP", "Freightliner"); f2645b.put("WDR", "Freightliner"); f2645b.put("WDW", "Dodge"); f2645b.put("WDX", "Dodge"); f2645b.put("WDY", "Freightliner"); f2645b.put("WDZ", "Mercedes-Benz"); f2645b.put("YB3", "Volvo"); f2645b.put("YE2", "Van Hool"); f2645b.put("YV1", "Volvo"); f2645b.put("YV2", "Volvo"); f2645b.put("YV4", "Volvo"); f2645b.put("YV5", "Volvo"); } private static int m4247a(char c) { if (c >= '0' && c <= '9') { return c - 48; } switch (c) { case 'A': return 1; case 'B': case 'K': case 'S': return 2; case 'C': return 3; case 'D': return 4; case 'E': return 5; case 'F': return 6; case 'G': return 7; case 'H': return 8; case 'J': return 1; case 'L': return 3; case 'M': return 4; case 'N': return 5; case 'P': return 7; case 'R': return 9; case 'T': return 3; case 'U': return 4; case 'V': return 5; case 'W': return 6; case 'X': return 7; case 'Y': return 8; case 'Z': return 9; default: return 0; } } private static boolean m4249b(char c) { if (c != '0' && m4247a(c) == 0) { return false; } return true; } private static boolean m4248a(String str) { if (str.length() != 17) { return false; } boolean z = true; for (char c : str.toCharArray()) { if (!m4249b(c)) { return false; } if (c != '0') { z = false; } } if (z) { return false; } return true; } private char m4250f() { int i = 0; if (!m4251a()) { return '\u0000'; } int i2 = 0; while (i < 17) { i2 += m4247a(this.f2646c.charAt(i)) * f2644a[i]; i++; } i = i2 % 11; return i == 10 ? 'X' : (char) (i + 48); } public boolean m4251a() { return this.f2647d; } public at(String str) { if (str == null) { this.f2646c = null; this.f2647d = false; return; } String replaceAll = str.replaceAll("^\\s*", ""); if (replaceAll.length() > 17) { replaceAll = replaceAll.substring(0, 17); } this.f2646c = replaceAll.toUpperCase(Locale.ENGLISH); this.f2647d = m4248a(this.f2646c); } public String m4252b() { if (!m4251a()) { return null; } int indexOf = "ABCDEFGHJKLMNPRSTVWXY123456789".indexOf(this.f2646c.charAt(9)); if (indexOf < 0) { return null; } indexOf += 1980; return Integer.toString(Math.max(0, aa.m4138b((Calendar.getInstance().get(1) + 1) - indexOf, "ABCDEFGHJKLMNPRSTVWXY123456789".length())) + indexOf); } public String m4253c() { if (m4251a() && this.f2646c.length() > 3) { return (String) f2645b.get(this.f2646c.substring(0, 3)); } return null; } public boolean m4254d() { char f = m4250f(); return f != '\u0000' && this.f2646c.charAt(8) == f; } public String m4255e() { return this.f2646c; } public String toString() { return this.f2646c == null ? "VinDecoder [m_vin=null]" : this.f2646c; } }
true
d06198836f60044d24ba628d38422dd3825d881b
Java
aghyles/Anek08
/src/main/java/com/popov/t04jh/service/impl/DosageServiceImpl.java
UTF-8
1,932
2.5
2
[]
no_license
package com.popov.t04jh.service.impl; import com.popov.t04jh.service.DosageService; import com.popov.t04jh.domain.Dosage; import com.popov.t04jh.repository.DosageRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; /** * Service Implementation for managing {@link Dosage}. */ @Service @Transactional public class DosageServiceImpl implements DosageService { private final Logger log = LoggerFactory.getLogger(DosageServiceImpl.class); private final DosageRepository dosageRepository; public DosageServiceImpl(DosageRepository dosageRepository) { this.dosageRepository = dosageRepository; } /** * Save a dosage. * * @param dosage the entity to save. * @return the persisted entity. */ @Override public Dosage save(Dosage dosage) { log.debug("Request to save Dosage : {}", dosage); return dosageRepository.save(dosage); } /** * Get all the dosages. * * @return the list of entities. */ @Override @Transactional(readOnly = true) public List<Dosage> findAll() { log.debug("Request to get all Dosages"); return dosageRepository.findAll(); } /** * Get one dosage by id. * * @param id the id of the entity. * @return the entity. */ @Override @Transactional(readOnly = true) public Optional<Dosage> findOne(Long id) { log.debug("Request to get Dosage : {}", id); return dosageRepository.findById(id); } /** * Delete the dosage by id. * * @param id the id of the entity. */ @Override public void delete(Long id) { log.debug("Request to delete Dosage : {}", id); dosageRepository.deleteById(id); } }
true
e370f53aced3487abb0129bd12240d0c124cb5ca
Java
MissakaI/Institute-Administration-System
/src/lk/ijse/gdse41/ias/dao/custom/QueryDAO.java
UTF-8
2,079
2.0625
2
[ "Apache-2.0" ]
permissive
/* * 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 lk.ijse.gdse41.ias.dao.custom; import java.util.ArrayList; import lk.ijse.gdse41.ias.dao.SuperDAO; import lk.ijse.gdse41.ias.dto.AttendanceDTO; import lk.ijse.gdse41.ias.dto.ClassScheduleDTO; import lk.ijse.gdse41.ias.dto.PaymentDTO; import lk.ijse.gdse41.ias.dto.StudentDTO; import lk.ijse.gdse41.ias.dto.SubjectDTO; import lk.ijse.gdse41.ias.dto.SuperDTO; import lk.ijse.gdse41.ias.dto.TutorDTO; import lk.ijse.gdse41.ias.dto.TutorSubjectDTO; /** * * @author midda */ public interface QueryDAO extends SuperDAO<SuperDTO>{ public ArrayList<StudentDTO> getStudentsInClass(String cid) throws Exception; public ArrayList<AttendanceDTO> getAttendanceToClass(String cid, String date) throws Exception; public ArrayList<ClassScheduleDTO> getCSandStudentCount(ClassScheduleDTO dto) throws Exception; public ArrayList<ClassScheduleDTO> getHallSchedule(ClassScheduleDTO dto) throws Exception; public PaymentDTO getTutorsMonthlyPayment(String cid, int month) throws Exception; public ArrayList<SubjectDTO> getSubjectsOfBatch(String bid) throws Exception; public ArrayList<TutorDTO> getTutorsTeachingSubjectForBatch(TutorDTO dto) throws Exception; public ArrayList<TutorSubjectDTO> getSubjectWithTutor(String tid) throws Exception; @Override public default boolean add(SuperDTO dto) throws Exception {return false;} @Override public default boolean update(SuperDTO dto) throws Exception {return false;} @Override public default boolean delete(SuperDTO dto) throws Exception {return false;} @Override public default SuperDTO search(SuperDTO dto) throws Exception {return null;} @Override public default ArrayList<SuperDTO> get(SuperDTO dto) throws Exception {return null;} @Override public default ArrayList<SuperDTO> getAll() throws Exception {return null;} }
true
b1450983eed045206bbcfa4c95e68241118b7c31
Java
BelegCuthalion/utanks
/src/GamePanel.java
UTF-8
3,662
2.890625
3
[]
no_license
import things.*; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; public class GamePanel extends JPanel implements BombArena { private Tank player1; private Tank player2; private List<Thing> thingsToDraw = new ArrayList<>(10); private List<Wall> walls = new ArrayList<>(10); private List<Bomb> onTheAir = new ArrayList<>(10); private boolean p1Left = false; private boolean p1Right = false; private boolean p1Up = false; private boolean p2Left = false; private boolean p2Right = false; private boolean p2Up = false; private boolean quitPressed = false; GamePanel() { this.player1 = new Tank(100, 100, Tank.TankSize.NORMAL, this); this.player2 = new Tank(400, 400, Tank.TankSize.BIG, this); this.thingsToDraw.add(this.player1); this.thingsToDraw.add(this.player2); Wall leftEdge = new Wall(20, 20, 600, Wall.Orientation.VERTICAL); Wall topEdge = new Wall(20, 20, 600, Wall.Orientation.HORIZONTAL); Wall rightEdge = new Wall(620, 20, 600, Wall.Orientation.VERTICAL); Wall bottomEdge = new Wall(20, 620, 600, Wall.Orientation.HORIZONTAL); Wall center = new Wall(320, 220, 200, Wall.Orientation.VERTICAL); this.walls.add(leftEdge); this.walls.add(topEdge); this.walls.add(rightEdge); this.walls.add(bottomEdge); this.walls.add(center); this.thingsToDraw.add(leftEdge); this.thingsToDraw.add(topEdge); this.thingsToDraw.add(rightEdge); this.thingsToDraw.add(bottomEdge); this.thingsToDraw.add(center); } /** * State of the affairs. * This could be a function of time. */ void updateState() { this.onTheAir.forEach(Bomb::step); this.onTheAir.forEach(Bomb::growOld); this.onTheAir.removeIf(Bomb::isDead); this.onTheAir.forEach(bomb -> this.walls.forEach(wall -> { if (wall.hit(bomb)) bomb.bounce(wall.getOrientation()); })); if (this.p1Left) { this.player1.turnLeft(); } if (this.p1Right) { this.player1.turnRight(); } if (this.p1Up) { if (this.walls.stream().anyMatch(wall -> wall.hit(this.player1))) { this.player1.bounce(null); } else { this.player1.step(); } } if (this.p2Left) { this.player2.turnLeft(); } if (this.p2Right) { this.player2.turnRight(); } if (this.p2Up) { this.player2.step(); } } protected void paintComponent(Graphics graphics) { super.paintComponent(graphics); for (Thing thingy : this.thingsToDraw) thingy.draw((Graphics2D) graphics); for (Bomb fatMan : this.onTheAir) fatMan.draw((Graphics2D) graphics); } void setP1Left(boolean p1Left) { this.p1Left = p1Left; } void setP1Right(boolean p1Right) { this.p1Right = p1Right; } void setP1Up(boolean p1Up) { this.p1Up = p1Up; } void p1Fire() { this.player1.fire(); } void setP2Left(boolean p2Left) { this.p2Left = p2Left; } void setP2Right(boolean p2Right) { this.p2Right = p2Right; } void setP2Up(boolean p2Up) { this.p2Up = p2Up; } void p2Fire() { this.player2.fire(); } void setQuitPressed(boolean quitPressed) { this.quitPressed = quitPressed; } public void fired(Bomb bomb) { this.onTheAir.add(bomb); } }
true
e37569ab6c96bd899d0eef2a26df18c2f66f0e89
Java
slvrookie/sea-of-ql
/DannyKop/QLJava/src/org/uva/sea/ql/parser/test/form/TestQuestions.java
UTF-8
1,166
2.546875
3
[]
no_license
package org.uva.sea.ql.parser.test.form; import static org.junit.Assert.*; import org.junit.Test; import org.uva.sea.ql.ast.form.*; import org.uva.sea.ql.ast.types.BoolType; import org.uva.sea.ql.ast.types.IntType; import org.uva.sea.ql.ast.types.StrType; import org.uva.sea.ql.parser.test.ParseError; import org.uva.sea.ql.parser.test.TestParser; public class TestQuestions extends TestParser { @Test public void acceptsCorrectInputTypeBool() throws ParseError { FormElement q = parseFormElement("isOk: \"Is it ok?\" boolean"); assertEquals(Question.class, q.getClass()); assertEquals(((Question)q).getType().getClass(), BoolType.class); } @Test public void acceptsCorrectInputTypeInt() throws ParseError { FormElement q = parseFormElement("age: \"Enter you age\" int"); assertEquals(Question.class, q.getClass()); assertEquals(((Question)q).getType().getClass(), IntType.class); } @Test public void acceptsCorrectInputTypeString() throws ParseError { FormElement q = parseFormElement("name: \"Enter you name\" string"); assertEquals(Question.class, q.getClass()); assertEquals(((Question)q).getType().getClass(), StrType.class); } }
true
4fa8e41c95293069dbf86bc4c711459a9c58452d
Java
lhirsu/Algorithms
/src/main/java/problems/maximum_subarray/MaximumSubArrayAlgo.java
UTF-8
151
1.929688
2
[]
no_license
package problems.maximum_subarray; public interface MaximumSubArrayAlgo { String getName(); MaximumSubArray findMaxSubArray(int[] array); }
true
a788d3b801a2bd66095ccc254e08b7444cf3c307
Java
quochuy190/BabuMart
/app/src/main/java/com/vn/babumart/activity/notify/ActivityDetailNotify.java
UTF-8
2,340
1.929688
2
[]
no_license
package com.vn.babumart.activity.notify; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView; import com.vn.babumart.R; import com.vn.babumart.base.BaseActivity; import com.vn.babumart.config.Constants; import com.vn.babumart.models.ErrorApi; import com.vn.babumart.models.ObjNotify; import com.vn.babumart.models.respon_api.ResponGetnotify; import com.vn.babumart.untils.SharedPrefs; import com.vn.babumart.untils.StringUtil; import butterknife.BindView; /** * Created by: Neo Company. * Developer: HuyNQ2 * Date: 11-September-2019 * Time: 17:10 * Version: 1.0 */ public class ActivityDetailNotify extends BaseActivity implements InterfaceNotify.View { @BindView(R.id.txt_notify_time) TextView txt_notify_time; @BindView(R.id.webview_content) WebView webview_content; PresenterNotify mPresenter; @Override public int setContentViewId() { return R.layout.activity_notify_detail; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = new PresenterNotify(this); initAppbar(); initData(); } private void initData() { String sUserName = SharedPrefs.getInstance().get(Constants.KEY_SAVE_USERNAME, String.class); ObjNotify objNotify = (ObjNotify) getIntent().getSerializableExtra(Constants.KEY_SEND_NOTIFY); if (objNotify != null) { mPresenter.api_update_notify(sUserName, objNotify.getID()); txt_notify_time.setText(objNotify.getSENT_TIME()); StringUtil.initWebview(objNotify.getCONTENT(), webview_content); } } private void initAppbar() { ImageView img_back = findViewById(R.id.img_back); TextView txt_title = findViewById(R.id.txt_title); img_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); txt_title.setText("Chi tiết thông báo"); } @Override public void show_error_api() { } @Override public void show_update_notify(ErrorApi objError) { } @Override public void show_get_notify(ResponGetnotify obj) { } }
true
1c37c242fc46598a5043e51619ee64fe7db8ece3
Java
shoadowboy/algorithm
/src/main/java/com/demo/algorithm/array/ReversePairs.java
UTF-8
617
3.75
4
[ "Apache-2.0" ]
permissive
package com.demo.algorithm.array; /** * 在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。 * 给你一个数组,求出这个数组中逆序对的总数。概括 * :如果a[i] > a[j] 且 i < j, a[i] 和 a[j] 构成一个逆序对。 * * @author peichunle * */ public class ReversePairs { public long reversePairs(int[] A) { //复杂度o(n^2) 后续优化 long count = 0; for (int i = 0; i < A.length - 1; i++) { for (int j = i; j < A.length; j++) { if (A[i] > A[j]) { count++; } } } return count; } }
true
e9a71927e23988f55edbc45dd52d46d96cd24e52
Java
chaetodontidae/Glimmer-small-task
/src/main/java/com/example/demo/util/JsonTransfer.java
UTF-8
705
2.59375
3
[]
no_license
package com.example.demo.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonTransfer { public static String ObjectToJason(Object object){ ObjectMapper mapper=new ObjectMapper(); String json=null; try{ json= mapper.writeValueAsString(object); }catch(Exception e){ e.printStackTrace(); return null; } return json; } public static Object readJSONString(String json,Class<?> clazz)throws JsonProcessingException { ObjectMapper objectMapper=new ObjectMapper(); return objectMapper.readValue(json,clazz); } }
true
ab29ce674f9a53a4a2cf2a02b22b0688f63debc1
Java
ChuZiHang/H5.skstravel.com
/src/main/java/com/skstravel/common/mapper/sksports2/SkCartMapper.java
UTF-8
1,111
1.859375
2
[]
no_license
package com.skstravel.common.mapper.sksports2; import com.skstravel.common.model.sksports2.SkCart; import com.skstravel.common.model.sksports2.SkCartExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface SkCartMapper { long countByExample(SkCartExample example); int deleteByExample(SkCartExample example); int deleteByPrimaryKey(Integer recId); int insert(SkCart record); int insertSelective(SkCart record); List<SkCart> selectByExampleWithBLOBs(SkCartExample example); List<SkCart> selectByExample(SkCartExample example); SkCart selectByPrimaryKey(Integer recId); int updateByExampleSelective(@Param("record") SkCart record, @Param("example") SkCartExample example); int updateByExampleWithBLOBs(@Param("record") SkCart record, @Param("example") SkCartExample example); int updateByExample(@Param("record") SkCart record, @Param("example") SkCartExample example); int updateByPrimaryKeySelective(SkCart record); int updateByPrimaryKeyWithBLOBs(SkCart record); int updateByPrimaryKey(SkCart record); }
true
4b30cc7e2d93dbbfd801c57119689cafe9f88a21
Java
sriramprasad4u/shopping
/ManuVastra/app/src/main/java/com/manuvastra/Store.java
UTF-8
4,664
2.5625
3
[]
no_license
package com.manuvastra; import android.app.Activity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * Created by sriram on 20/06/17. */ /** * An utility class for EasyShopping Application to capture all required data members in a single Object. * */ public class Store extends Activity { private static Store store; private static final String TAG = Store.class.getSimpleName(); private List<Item> items = new ArrayList<>(); private Map<String, String> departments = new HashMap<String, String>(); public String getDepName() { return depName; } private void setDepName(String depName) { this.depName = depName; } private String depName; public Boolean getFeatured() { return featured; } private void setFeatured(Boolean featured) { this.featured = featured; } private Boolean featured; public static Store getStore(){ if(store == null){ store = new Store(); } return store; } private Store(){ depName = ""; featured = false; } public void setItems(List<Item> items){ this.items = items; } public void setDepartments(Map<String, String> departments){ this.departments = departments; } //load file into items array list private void readItems(){ String string = ""; Scanner scan = new Scanner(getApplicationContext().getResources().openRawResource(R.raw.products)); while (scan.hasNextLine()) { string += scan.nextLine(); } ObjectMapper objectMapper = new ObjectMapper(); JSONArray products = null; try { products = new JSONArray(string); for (int i = 0 ; i <products.length(); i++) { items.add(objectMapper.readValue(products.get(i).toString(),Item.class)); } } catch (JSONException e) { e.printStackTrace(); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } string = ""; scan = new Scanner(getResources().openRawResource(R.raw.departments)); while (scan.hasNextLine()) { string += scan.nextLine(); } JSONArray departs; try { Department department; departs = new JSONArray(string); for (int i = 0 ; i <departs.length(); i++) { department = objectMapper.readValue(departs.get(i).toString(),Department.class); departments.put(department.getId(),department.getTitle()); } } catch (JSONException e) { e.printStackTrace(); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public List<Item> getProducts(String deptName, boolean featured) { String depId =""; for (String key : departments.keySet()){ if(departments.get(key).equals(deptName)){ depId = key; break; } } List<Item> itemsToDisplay = new ArrayList<Item>(); if(!depId.isEmpty()) { for (int i = 0; i < items.size(); i++) { if (items.get(i).getDepId().equals(depId)) itemsToDisplay.add(items.get(i)); } } else if(featured){ for (int i = 0; i < items.size(); i++) { if (items.get(i).isFeatured()) itemsToDisplay.add(items.get(i)); } }else{ itemsToDisplay = items; } setDepName(deptName); setFeatured(featured); return itemsToDisplay; } /** * Returns name for the corresponding depId * @param depId * @return String */ public String getDepartmentName(String depId) { return departments.get(depId); } /** * Returns cxaAnalyticsObject * @return CxaAnalytics */ public Map<String, String> getDepartments(){ return departments; } }
true
20a96466537c890759c1643b3f5a4140f6af9376
Java
Nabiarov/Java_pirma
/src/main/java/Klientas.java
UTF-8
877
2.578125
3
[]
no_license
public class Klientas { private String vardas; private String pavarde; private String pavadinimas; private int kiekis; public Klientas(){ } public Klientas(String vardas,String pavarde,String pavadinimas,int kiekis) { this.vardas = vardas; this.pavarde = pavarde; this.pavadinimas = pavadinimas; this.kiekis = kiekis; } public String getVardas() { return vardas;} public void setVardas(String vardas){this.vardas = vardas; } public String getPavarde() { return pavarde;} public void setPavarde(String pavarde){ this.pavarde = pavarde;} public String getPavadinimas() { return pavadinimas;} public void setPavadinimas(String pavadinimas) {this.pavadinimas = pavadinimas;} public int getKiekis() { return kiekis;} public void setKiekis(int kiekis) {this.kiekis = kiekis;} }
true
7177742f5605fc3fadb8a36c514fffc7f5157871
Java
JauneWhale/JW-Mini3D
/Mmath/Mbasic.java
UTF-8
672
2.921875
3
[]
no_license
package Mmath; public final class Mbasic { public static int Isinclude(int x, int min, int max){ return (x < min)? min : ((x > max)? max : x); } public static float Isinclude(float x, float min, float max){ return (x < min)? min : ((x > max)? max : x); } public static float Interp(float x1, float x2, float t){ return x1 + (x2 - x1)*t; } public static Mvector3 Vector_Interp(Mvector3 v1,Mvector3 v2,float t){ Mvector3 x1 = v1.Mclone(); Mvector3 x2 = v2.Mclone(); x1.Mreset(); x2.Mreset(); Mvector3 res = new Mvector3( Interp(x1.x,x2.x,t), Interp(x1.y,x2.y,t), Interp(x1.z,x2.z,t), 1.0f); return res; } }
true
e7ffae0f11fa22003f04554ad93ac16e1cb71844
Java
AppSecAI-TEST/UIView2
/valley/src/main/java/com/hn/d/valley/main/other/SearchPOIUIView.java
UTF-8
7,868
1.703125
2
[]
no_license
package com.hn.d.valley.main.other; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.widget.LinearLayout; import android.widget.TextView; import com.amap.api.maps.model.LatLng; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.poisearch.PoiResult; import com.amap.api.services.poisearch.PoiSearch; import com.angcyo.uiview.container.ContentLayout; import com.angcyo.uiview.model.TitleBarPattern; import com.angcyo.uiview.recycler.RRecyclerView; import com.angcyo.uiview.skin.SkinHelper; import com.angcyo.uiview.widget.ExEditText; import com.angcyo.uiview.widget.RSoftInputLayout; import com.hn.d.valley.R; import com.hn.d.valley.base.BaseUIView; import com.hn.d.valley.base.constant.Constant; import com.hn.d.valley.bean.realm.AmapBean; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.concurrent.TimeUnit; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import static com.hn.d.valley.control.AmapControl.POI_TYPE; /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:搜索添加好友 * 创建人员:Robi * 创建时间:2016/12/26 9:04 * 修改人员:Robi * 修改时间:2016/12/26 9:04 * 修改备注: * Version: 1.0.0 */ public class SearchPOIUIView extends BaseUIView<IPOISearchPresenter> implements IPOISearchView { //view ExEditText mSearchInputView; TextView mSearchTipView; LinearLayout mSearchControlLayout; RRecyclerView mRecyclerView; TextView mEmptyTipView; //adapter private PoiItemAdapter mPoiAdapter; //latlng private LatLng latLng; AmapBean mLastBean, mTargetBean; //onDataLoadListener private PoiSearch.OnPoiSearchListener onPoiSearchListener; //action private Action1<AmapBean> action; //str private String query; private String type = POI_TYPE; private int mCurrentPage = 1; public SearchPOIUIView(Action1<AmapBean> action,LatLng latLng){ this.latLng = latLng; this.action = action; } @Override protected void inflateContentLayout(ContentLayout baseContentLayout, LayoutInflater inflater) { inflate(R.layout.view_search_layout); } @Override protected TitleBarPattern getTitleBar() { return null; } @Override public Animation loadLayoutAnimation() { return null; } @Override protected void initOnShowContentLayout() { super.initOnShowContentLayout(); mSearchInputView = v(R.id.edit_text_view); mSearchTipView = v(R.id.search_tip_view); mSearchControlLayout = v(R.id.search_control_layout); mRecyclerView = v(R.id.recycler_view); mEmptyTipView = v(R.id.empty_tip_view); click(R.id.search_tip_view, new View.OnClickListener() { @Override public void onClick(View v) { onSearchTipClick(); } }); bindPresenter(new SearchPOIPresenter()); mPoiAdapter = new PoiItemAdapter(mActivity, new PoiItemAdapter.OnPoiItemListener() { @Override public void onPoiItemSelector(com.amap.api.services.core.PoiItem item) { // 选中 AmapBean amapBean = new AmapBean(); LatLonPoint latLonPoint = item.getLatLonPoint(); amapBean.title = item.getTitle(); amapBean.latitude = latLonPoint.getLatitude(); amapBean.longitude = latLonPoint.getLongitude(); amapBean.address = PoiItemAdapter.getAddress(item); amapBean.city = item.getCityName(); amapBean.province = item.getProvinceName(); amapBean.district = item.getAdName(); mTargetBean = amapBean; //销毁uiview finishIView(); // 销毁ampauiview mILayout.finishIView(AmapUIView.class); if (action != null) { action.call(mTargetBean); } } @Override public void onPoiLoadMore() { mCurrentPage ++; mPresenter.onSearch(latLng,mCurrentPage,onPoiSearchListener,query,type); } }); mPoiAdapter.setEnableLoadMore(false); onPoiSearchListener = new PoiSearch.OnPoiSearchListener() { @Override public void onPoiSearched(PoiResult poiResult, int code) { if (code != 1000) { return; } if (mCurrentPage == 1) { mPoiAdapter.unSelectorAll(false); mPoiAdapter.resetData(poiResult.getPois()); } else { mPoiAdapter.appendData(poiResult.getPois()); } mPoiAdapter.setLoadMoreEnd(); mEmptyTipView.setVisibility(View.GONE); if (poiResult.getPois().size() == 0) { mPoiAdapter.setEnableLoadMore(false); mEmptyTipView.setVisibility(View.VISIBLE); mEmptyTipView.setText("该地点不存在"); } } @Override public void onPoiItemSearched(com.amap.api.services.core.PoiItem poiItem, int i) { } }; mRecyclerView.setAdapter(mPoiAdapter); mViewHolder.v(R.id.title_bar_layout).setBackgroundColor(SkinHelper.getSkin().getThemeColor()); mViewHolder.v(R.id.cancel_view).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finishIView(); } }); mSearchInputView.setHint(R.string.text_search_place); RSoftInputLayout.showSoftInput(mSearchInputView); RxTextView.textChanges(mSearchInputView) .debounce(Constant.DEBOUNCE_TIME_700, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { if (TextUtils.isEmpty(charSequence)) { mEmptyTipView.setText(""); } else { query = charSequence.toString(); mCurrentPage = 1; mPresenter.onSearch(latLng,mCurrentPage,onPoiSearchListener,charSequence.toString(),type); } } }); } @Override public int getDefaultBackgroundColor() { return mActivity.getResources().getColor(R.color.default_base_bg_dark2); } @NonNull @Override protected LayoutState getDefaultLayoutState() { return LayoutState.CONTENT; } @Override public void onRequestStart() { super.onRequestStart(); mEmptyTipView.setText(""); } /** * 开始搜索地点 */ public void onSearchTipClick() { mPresenter.onSearch(latLng,1,onPoiSearchListener,query,type); } // @Override // public void onSearchSuccess(@NotNull List<? extends PoiItem> result) { // if (bean == null) { // mEmptyTipView.setText("该地点不存在"); // } else { // mEmptyTipView.setText(""); // } // } }
true
130c5f9921b018c556acb0634213d82c253e69de
Java
ahowe442/java-web-dev-exercises
/src/exercises/Triangle.java
UTF-8
497
3.578125
4
[]
no_license
package exercises; import java.util.Scanner; public class Triangle { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("What is your Triangle's height?: "); int triHeight = input.nextInt(); System.out.println("What is your Triangle's length?: "); int triLength = input.nextInt(); int area = (triHeight*triLength)/2; System.out.println("Your triangle has an area of: " + area); } }
true
1c2c1602f369b5f20310d2bc95e5bda469ab5681
Java
RaulSong/java_study
/CH19_Exception/src/throwing_exception/Thermostat.java
UHC
467
3.53125
4
[ "MIT" ]
permissive
package throwing_exception; public class Thermostat { public void setTemperature(double temperature) throws Exception { if(temperature < 0 || temperature > 35) { //µ ó . throw ϴ ܸ ߿ ó( ޼ҵ带 ȣ ó) throw new Exception("µ Դϴ."); } System.out.println("µ : " + temperature); //µ } }
true
0dddf3e34d1a791ce82c00c9a59dab0b3e0a1f2b
Java
zann1x/ProjectEuler
/src/Problem005.java
UTF-8
642
3.265625
3
[]
no_license
/* * Find the smallest positive number that is evenly divisible by all numbers from 1 to 20 * Answer: 232792560 */ public class Problem005 { public static void main(String[] args) { long num = 20; while (true) { if (num % 2 == 0 && num % 3 == 0 && num % 4 == 0 && num % 5 == 0 && num % 6 == 0 && num % 7 == 0 && num % 8 == 0 && num % 9 == 0 && num % 10 == 0 && num % 11 == 0 && num % 12 == 0 && num % 13 == 0 && num % 14 == 0 && num % 15 == 0 && num % 16 == 0 && num % 17 == 0 && num % 18 == 0 && num % 19 == 0 && num % 20 == 0) { System.out.println(num); break; } else { num++; } } } }
true
648cea118dd0efbb3536f84210cc4816ba38c62b
Java
SMugallimov/SynergyProject
/src/main/java/block3/homework3_1/EmployeeRunner.java
UTF-8
2,175
3.8125
4
[]
no_license
package block3.homework3_1; import java.util.*; public class EmployeeRunner { static Scanner in = new Scanner(System.in); public static void main(String[] args) { List<Employee> employees = new ArrayList<>(); int qtyEmployees = 15; int workAges; int workAge = 0; Random rnd = new Random(); for(int i = 1; i <= qtyEmployees; i++){ workAges = rnd.nextInt(30)+1; employees.add(new Employee("#" + i + " Employee - Work Age: ", workAges)); } for(Iterator<Employee> employeeIterator = employees.iterator(); employeeIterator.hasNext();){ Employee newEmpl = employeeIterator.next(); System.out.println(newEmpl.getFio() + newEmpl.getWorkAge()); } System.out.println(); workAge = adviseWorkAge(); printEmployee(employees, workAge); System.out.println(); ListIterator<Employee> employeeListIterator = employees.listIterator(); for (int i = 0; employeeListIterator.hasNext(); i++){ employeeListIterator.next(); if (i % 2 ==0) { employeeListIterator.remove(); } } for(int i = 0; employeeListIterator.hasPrevious(); i++){ Employee reverseEmployee = employeeListIterator.previous(); System.out.println(reverseEmployee.getFio() + reverseEmployee.getWorkAge()); } } public static void printEmployee(Collection<Employee> employees, int workAge){ for(Iterator<Employee> employeeIterator = employees.iterator(); employeeIterator.hasNext();){ Employee newEmpl = employeeIterator.next(); if(workAge == newEmpl.getWorkAge()) { System.out.println(newEmpl.getFio() + newEmpl.getWorkAge()); } } } public static int adviseWorkAge(){ System.out.println("Advise work age: "); int num; if (in.hasNextInt()) { num = in.nextInt(); } else { System.out.println("Input error! Try again!"); in.next(); num = adviseWorkAge(); } return num; } }
true
4245bbd63b8d04fab2255dd72123ed961785ed3c
Java
caprice/myAndroidCommLib
/Git/GMProjects/driverGuard/src/main/java/com/gm/driverGuard/util/ConfigManager.java
UTF-8
2,059
2.625
3
[]
no_license
package com.gm.driverGuard.util; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.helpers.Loader; /** * <li><li>File Name: ConfigManager.java <li>Title: ConfigManager * <li>Description: * 可以处理文件在系统运行期间的改动。 * * String propValue=ConfigManager.getInstance().getConfigItem(key,null); * */ public class ConfigManager { private static ConfigManager m_instance; private static String PFILE; synchronized public static ConfigManager getInstance() { if (m_instance == null) { if (PFILE == null) { URL url = Loader.getResource("./prop/infobus.properties"); PFILE = url.getPath(); PFILE = StringUtils.replace(PFILE, "%20", " "); } m_instance = new ConfigManager(); } return m_instance; } private File m_file = null; private long m_lastModifiedTime = 0; private Properties m_props = null; private ConfigManager() { m_file = new File(PFILE); m_lastModifiedTime = m_file.lastModified(); if (m_lastModifiedTime == 0) { System.err.println(PFILE + " file does not exist!"); } m_props = new Properties(); try { m_props.load(new FileInputStream(PFILE)); } catch (Exception e) { e.printStackTrace(); } } final public String getConfigItem(String name, String defaultVal) { long newTime = m_file.lastModified(); if (newTime == 0) { if (m_lastModifiedTime == 0) { System.err.println(PFILE + " file does not exist!"); } else { System.err.println(PFILE + " file was deleted!!"); } return defaultVal; } else if (newTime > m_lastModifiedTime) { m_props.clear(); try { m_props.load(new FileInputStream(PFILE)); } catch (Exception e) { e.printStackTrace(); } } m_lastModifiedTime = newTime; String val = m_props.getProperty(name); if (val == null) { return defaultVal; } else { return val; } } }
true
fd7822ebc51fd379404801c1e8e0a14424ccde34
Java
SignV/BlogSSM
/src/main/java/ssm/blog/controller/BlogTypeAdminController.java
UTF-8
3,499
2.515625
3
[]
no_license
package ssm.blog.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import ssm.blog.entity.BlogType; import ssm.blog.entity.PageBean; import ssm.blog.service.BlogTypeService; import ssm.blog.util.ResponseUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("admin/blogType") public class BlogTypeAdminController { @Resource private BlogTypeService blogTypeService; // 分页查询博客类别 @RequestMapping("/list") public String listBlogType(@RequestParam(value = "page",required = false) String page, @RequestParam(value = "rows",required = false) String rows, HttpServletResponse response) throws Exception{ //定义分页bean PageBean<BlogType> pageBean = new PageBean<BlogType>(Integer.parseInt(page),Integer.parseInt(rows)); //拿到分页结果以及记录总数的pageBean pageBean = blogTypeService.listByPage(pageBean); //使用阿里巴巴的fastJson创建JSONObject JSONObject result = new JSONObject(); //通过fastJson序列化list为jsonArray String jsonArray = JSON.toJSONString(pageBean.getResult()); JSONArray array = JSONArray.parseArray(jsonArray); //将序列化结果放入json对象中 result.put("rows",array); result.put("total",pageBean.getTotal()); //使用自定义工具类向response中写入数据 ResponseUtil.write(response,result); return null; } //添加或修改博客类别 @RequestMapping("/save") public String save(BlogType blogType,HttpServletResponse response) throws Exception { //resultToal记录返回结果的记录数 int resultToal = 0; if(blogType.getId() == null){ // 说明是第一次插入,为添加操作 resultToal = blogTypeService.addBlogType(blogType); }else { // 有id,为修改操作 resultToal = blogTypeService.updateBlogType(blogType); } JSONObject result = new JSONObject(); if(resultToal > 0){ result.put("success",true); }else { result.put("success",false); } ResponseUtil.write(response,result); return null; } // 博客类别信息删除 @RequestMapping("/delete") public String delete(@RequestParam("ids") String ids,HttpServletResponse response) throws Exception{ //分割字符串得到id数组 String[] idsStr = ids.split(","); for(int i = 0;i < idsStr.length;i++){ int id = Integer.parseInt(idsStr[i]); //其实在这里我们要判断该博客类别下面是否有博客 如果有就禁止删除博客类别 ,等我们完成博客对应的操作再来完善 blogTypeService.deleteBlogType(id); //当删除类型是外键是需要在数据库指定好 进行级联更新以及级联删除 //外键指定级联更新、删除:on update cascade on delete cascade } JSONObject result = new JSONObject(); result.put("success",true); ResponseUtil.write(response,result); return null; } }
true
8bda24e871fb272c0fc22a34b970b4b478d2d0d8
Java
deepexpert-gaohz/sa-d
/jnnsBank/system-api/src/main/java/com/ideatech/ams/system/trace/dto/UserTraceDTO.java
UTF-8
1,444
1.898438
2
[]
no_license
package com.ideatech.ams.system.trace.dto; import com.ideatech.ams.system.trace.enums.OperateModule; import com.ideatech.ams.system.trace.enums.OperateType; import com.ideatech.common.dto.BaseMaintainableDto; import lombok.Data; import java.util.Date; /** * @author jzh * @date 2019-10-30. */ @Data public class UserTraceDTO extends BaseMaintainableDto { private Long id; /** * 用户名 */ private String username; /** * 操作人(机构+中文名) */ private String operateName; /** * 机构fullId */ private String organFullId; /** * 操作时间 */ private Date operateDate; /** * 调用类 */ private String className; /** * 调用方法 */ private String methodName; /** * 操作模块 */ private OperateModule operateModule; /** * 操作类型 */ private OperateType operateType; /** * 操作结果 */ private Boolean operateResult; /** * 操作内容 */ private String operateContent; /** * 操作详情(具体参数)备用 */ private String operateDetail; /** * 异常详情 */ private String exceptionDetail; /** * 请求地址 */ private String url; /** * 是否覆盖,在生成操作内容时使用,不进行存储。 */ private Boolean cover; }
true
62308edf7134ac1424733609ce14530a5f47e359
Java
Almubn/basic-testing-project
/src/test/java/com/examples/CreateTable.java
UTF-8
1,227
2.390625
2
[]
no_license
package com.examples; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Arrays; /** * Unit test for simple App. */ public class CreateTable { private static WebDriver driver; private static SQLEditor sqlEditorPage; private String statement1 = "SELECT * FROM [Categories]"; @BeforeClass public static void setUp(){ System.setProperty("webdriver.chrome.driver", "src/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("excludeSwitches", Arrays.asList("ignore-certificate-errors")); driver = new ChromeDriver(options); sqlEditorPage = new SQLEditor(driver); } @AfterClass public static void tearDown(){ driver.quit(); } @Test(description = "Run a simple sql statement", groups = {"simple","checklist critico"}) public void testMethod() throws InterruptedException{ sqlEditorPage.runSQL(statement1); } }
true
8661cbda677c7adbfaad4ea340f5384c38dde267
Java
wocaishiliuke/study-datastructure
/src/com/baicai/tree/Tree.java
UTF-8
762
3.234375
3
[]
no_license
package com.baicai.tree; /** * 树 * @Author yuzhou * @Date 18-12-14 */ public interface Tree { /** * 查找节点 * @param value * @return Node */ Node find(int value); /** * 查找最大值 * @return Node */ Node findMax(); /** * 查找最小值 * @return Node */ Node findMin(); /** * 添加节点 * @param value * @return boolean */ boolean add(int value); /** * (先、中、后序)遍历 * @return void */ void iterate(); /** * 层次遍历 * @return void */ void levelIterate(); /** * 删除节点 * @param value * @return boolean */ boolean delete(int value); }
true
071231e7d5ec487f3d29dbde0c19f743b74a5cec
Java
edgd1er/M1S2_CAR
/TP2/src/com/restgateway/services/FTPService.java
UTF-8
12,782
2.640625
3
[]
no_license
package com.restgateway.services; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.springframework.stereotype.Service; import com.restgateway.exceptions.FTPClientNotFound; import com.restgateway.exceptions.FileNotFoundException; import com.restgateway.exceptions.FileNotUploadedException; import com.restgateway.exceptions.IncorrectPathException; import com.restgateway.exceptions.NoLoginPasswordException; import com.restgateway.services.HTMLGenerator; /** * Class that will process all FTP operations towards FTP server. * @author Salomon Emmeline & Dubiez François. */ @Service public class FTPService { /** * @uml.property name="ftpClient" */ FTPClient ftpClient = null; /** * @return * @uml.property name="ftpClient" */ public FTPClient getFtpClient() { return ftpClient; } /** * @param ftpClient * @uml.property name="ftpClient" */ public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; } /** * Get the welcome message from server * * @param ftpHostName * IP or name of the server. * @param ftpPort * Port of the server * @return Array of string containing the welcome message. */ public List<String> getWelcomeMsg(String ftpHostName, int ftpPort, boolean isPASV) { String[] AString = null; List<String> myreturn = new ArrayList<String>(); if (ftpClient == null) { this.ftpClient = new FTPClient(); } try { if (isPASV) { ftpClient.enterLocalPassiveMode(); } ftpClient.connect(ftpHostName, ftpPort); AString = ftpClient.getReplyStrings(); for (String i : AString) { myreturn.add(i); } ftpClient.disconnect(); } catch (IOException ex) { myreturn.add("Error " + ex.getMessage()); } return myreturn; } /** * Public method to login in FTP server * * @param ftpHostName * FTP server name or IP * @param ftpPort * FTP IP * @param login * FTP username * @param passwd * FTP login * @param isPASV * Passive mode = true * @return Status of the logged user */ public String loginToFtp(String ftpHostName, int ftpPort, String login, String passwd, boolean isPASV) { String res = "Error, login and/or password are incorrects. Please login again."; try { if (intloginToFtp(null, ftpHostName, ftpPort, login, passwd, isPASV)) { res = this.getFtpClient().printWorkingDirectory(); } if (isPASV) { ftpClient.enterLocalPassiveMode(); } return HTMLGenerator.getInstance().getFTPLoggedContent(res); } catch (SocketException sex) { return HTMLGenerator.getInstance().getFtpErrorConnectionContent( "Error " + sex.getMessage()); } catch (IOException e) { return HTMLGenerator.getInstance().getFtpErrorConnectionContent( "Error " + e.getMessage()); } } /** * Return the welcome Message from FTP Server * * @param login * userLogin * @param ftpPort * @param passwd * user password * @param string * @return welcome message from Server */ public String listFiles(String ftpHostName, int ftpPort, String login, String passwd, String path, boolean isPASV) { String res = ""; try { if (intloginToFtp(this.ftpClient, ftpHostName, ftpPort, login, passwd, isPASV)) { String cwd = this.ftpClient.printWorkingDirectory(); path = path.length() > 0 ? checkPath(path) : cwd; this.ftpClient.changeWorkingDirectory(path); FTPFile[] files = this.ftpClient.listFiles(); this.ftpClient.disconnect(); res = HTMLGenerator.getInstance().getFileListWith(cwd, files); } else { res = HTMLGenerator .getInstance() .getFtpErrorConnectionContent( "error no correct login/password given. Try again to login."); } return res; } catch (IOException ex) { return HTMLGenerator.getInstance().getFtpErrorConnectionContent( ex.getMessage()); } } public Response getFileList(String ftpHostName, int ftpPort, String loginName, String passwd, String path, boolean isPASV) { Response response = null; path = checkPath(path); try { if (checkClient()) { ftpClient.connect(ftpHostName, ftpPort); if (ftpClient.login(loginName, passwd)) { if (isPASV) { ftpClient.enterLocalPassiveMode(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (path.length() > 0) { ftpClient.changeWorkingDirectory(path); } else { path = ftpClient.printWorkingDirectory(); } FTPFile[] fileList = ftpClient.listFiles(path); response = Response.ok( HTMLGenerator.getInstance().getFileListWith(path, fileList)).build(); } disconnectClient(); } } catch (IOException ex) { return Response .status(Status.NOT_FOUND) .entity(HTMLGenerator.getInstance().getError( ex.getMessage())).build(); } catch (FTPClientNotFound | IncorrectPathException | NoLoginPasswordException e) { return e.getResponse(); } return response; } /** * Download file to Rest client * * @param ftpHostName * @param ftpPort * @param loginName * @param passwd * @param path * @param name * @param isPASV * @return */ public Response getFile(String ftpHostName, int ftpPort, String loginName, String passwd, String path, String name, boolean isPASV) { String msg = "Error, user not logged in. Please log before"; Response response = Response.status(Status.PRECONDITION_FAILED) .entity(msg).build(); path = checkPath(path); try { if (checkClient()) { ftpClient.connect(ftpHostName, ftpPort); if (ftpClient.login(loginName, passwd)) { if (isPASV) { ftpClient.enterLocalPassiveMode(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(path); InputStream in = ftpClient.retrieveFileStream(name); response = Response .ok(in, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"" + name + "\"") .build(); if (!ftpClient.completePendingCommand() || ftpClient.getReplyCode() != 226) { response = new FileNotFoundException( ftpClient.getReplyString() + path + name) .getResponse(); } else { } disconnectClient(); } else { response = new NoLoginPasswordException().getResponse(); } } } catch (IOException ex) { response = new FileNotFoundException(path + name).getResponse(); } catch (FTPClientNotFound ex) { response = new FTPClientNotFound().getResponse(); } return response; } /** * File upload knowing filename and filepath * * @param ftpHostName * @param ftpPort * @param login * @param password * @param string * @param filePath * @param isPASV * @return */ public Response postFile(String ftpHostName, int ftpPort, String login, String password, String string, String filePath, boolean isPASV) { Response response = null; File file = null; InputStream in = null; try { file = new File(filePath); in = new FileInputStream(file); } catch (IOException ex) { response = new FileNotFoundException(filePath).getResponse(); } catch (FTPClientNotFound ex) { response = new FTPClientNotFound().getResponse(); } response = postFile(ftpHostName, ftpPort, login, password, file.getPath(), file.getName(), in, isPASV); return response; } /** * File upload knowing the fileInpustream * * @param ftpHostName * @param ftpPort * @param login * @param password * @param remotePath * @param fname * @param in * @param isPASV * @return */ public Response postFile(String ftpHostName, int ftpPort, String login, String password, String remotePath, String fname, InputStream in, boolean isPASV) { Response response = null; remotePath = checkPath(remotePath); try { if (checkClient()) { ftpClient.connect(ftpHostName, ftpPort); if (ftpClient.login(login, password)) { if (isPASV) { ftpClient.enterLocalPassiveMode(); } if (remotePath.length() < 1) { remotePath = ftpClient.printWorkingDirectory(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(remotePath); if (ftpClient.storeFile(remotePath + File.separatorChar+ fname, in)) { response = HTMLGenerator.getInstance().getFileUploadedContent(); } else { response = new FileNotUploadedException(remotePath + File.separator+ fname).getResponse(); System.err.println(ftpClient.getReplyString()); } disconnectClient(); } else { response = new NoLoginPasswordException().getResponse(); } } } catch (IOException ex) { response = new FileNotFoundException(remotePath + fname) .getResponse(); } catch (FTPClientNotFound ex) { response = new FTPClientNotFound().getResponse(); } return response; } /** * delete a File from the server. * * @param path * @param file */ public Response deleteFile(String ftpHostName, int ftpPort, String login, String password, String path, String file) { String msg = "Error, user not logged in. Please log before"; try { if (checkClient()) { path = checkPath(path); msg = "error, file " + path + file + " not deleted."; ftpClient.connect(ftpHostName, ftpPort); ftpClient.changeWorkingDirectory(path); if (ftpClient.login(login, password)) { if (ftpClient.deleteFile(file)) { msg = "Ok, file " + path + file + " deleted."; } } } } catch (IOException e) { msg += e.getMessage(); } if (msg.toLowerCase().contains("error")) { return Response.status(Status.ACCEPTED).entity(msg).build(); } return Response.status(Status.OK).entity(msg).build(); } public boolean changeWorkingDirectory(String ftpHostName, int ftpPort, String login, String password, String path, String file) { String msg = "Error, user not logged in. Please log before"; try { if (checkClient()) { path = checkPath(path); msg = "error, file " + path + " not changed."; ftpClient.connect(ftpHostName, ftpPort); if (ftpClient.changeWorkingDirectory(path)) { return true; } else { throw new IncorrectPathException(ftpClient.getReplyString()); } } } catch (IOException | FTPClientNotFound e) { msg += e.getMessage(); throw new FTPClientNotFound(); } catch (IncorrectPathException e) { msg = e.getMessage(); throw new IncorrectPathException(msg); } catch (NoLoginPasswordException e) { msg += e.getMessage(); throw new NoLoginPasswordException(); } return false; } private String checkPath(String path) { String properPath = ""; if (path == null) { return properPath; } if (path.length() > 0) { path = path.endsWith(File.separator) ? path : path + File.separator; path = path.startsWith(File.separator) ? path : File.separator + path; properPath = path; } return properPath; } /** * Check if the client is initialized with proper credentials. * * @return True Throw exception */ private boolean checkClient() throws FTPClientNotFound { if (this.getFtpClient() == null) { throw new FTPClientNotFound(); } return true; } /** * internal method for FTP Connection using then internal FTPClient * * @param client * instance of Apache client * @param ftpHostName * FTP Name or IP * @param ftpPort * FTP Port * @param login * User login name * @param passwd * User Password * @return current directory path * @throws IOException * @throws SocketException */ private boolean intloginToFtp(FTPClient _client, String ftpHostName, int ftpPort, String login, String passwd, boolean isPASV) throws SocketException, IOException { boolean res = false; if (ftpClient == null) { this.ftpClient = new FTPClient(); } if (_client != null) { this.ftpClient = _client; } ftpClient.connect(ftpHostName, ftpPort); res = ftpClient.login(login, passwd); if (isPASV) { ftpClient.enterLocalPassiveMode(); } return res; } /** * Disconnect ftpClient on request * */ public void disconnectClient() { try { if (this.getFtpClient() != null) { this.getFtpClient().disconnect(); } } catch (IOException e) { // nothing to be done } } }
true
94e705daa32ab6d36040cfd4860c7832a0db21cc
Java
huanghaixiang/FirstGitTest
/src/main/java/com/noah/manage/controller/BaseController.java
UTF-8
1,981
2.34375
2
[]
no_license
package com.noah.manage.controller; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.ExceptionHandler; public class BaseController { public String messageurl = "/common/message"; public String message = "message"; public String redirect = "redirect:"; public String forward = "forward:"; @ExceptionHandler public String exp(HttpServletRequest request, Exception e) { e.printStackTrace(); request.setAttribute("e", e); return "/error"; } /** * 公共下载方法 * * @param response * @param file * 下载的文件 * @param fileName * 下载时显示的文件名 * @return * @throws Exception */ public HttpServletResponse downFile(HttpServletResponse response, File file, String fileName, boolean delFile) throws Exception { response.setContentType("application/x-download"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); OutputStream out = null; InputStream in = null; // 下面一步不可少 fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1"); response.addHeader("Content-disposition", "attachment;filename=" + fileName);// 设定输出文件头 try { out = response.getOutputStream(); in = new FileInputStream(file); int len = in.available(); byte[] b = new byte[len]; in.read(b); out.write(b); out.flush(); } catch (Exception e) { // logger.error(e.getMessage(), e); throw new Exception("下载失败!"); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (delFile) { file.delete(); } } return response; } }
true
683b746fe2c2d4f0df17feee00c4ebd8208c2ce7
Java
Thief007/x9pro
/Settings/com/mediatek/settings/PDebug.java
UTF-8
892
2.09375
2
[]
no_license
package com.mediatek.settings; import android.os.SystemProperties; import android.os.Trace; public class PDebug { private static Boolean DEBUG; private static long TRACE_TAG; static { boolean z = true; DEBUG = Boolean.valueOf(true); TRACE_TAG = 0; if (SystemProperties.get("ap.performance.debug", "0").equals("0")) { z = false; } DEBUG = Boolean.valueOf(z); if (DEBUG.booleanValue()) { TRACE_TAG = 1 << ((int) Long.parseLong(SystemProperties.get("ap.performance.debug"))); } } public static void Start(String msg) { if (DEBUG.booleanValue()) { Trace.traceCounter(TRACE_TAG, "P$" + msg, 1); } } public static void End(String msg) { if (DEBUG.booleanValue()) { Trace.traceCounter(TRACE_TAG, "P$" + msg, 0); } } }
true
1cbf9f2bb77ea9b3ed6cf30187dfd442f27ea36a
Java
neeeekoooo/boubei-tss
/src/main/java/com/boubei/tssx/wx/gzh/GetGZHOpenId.java
UTF-8
2,453
2.078125
2
[ "Apache-2.0" ]
permissive
/* ================================================================== * Created [2018-03-14] by Jon.King * ================================================================== * TSS * ================================================================== * mailTo:boubei@163.com * Copyright (c) boubei.com, 2015-2018 * ================================================================== */ package com.boubei.tssx.wx.gzh; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import com.boubei.tss.framework.Global; import com.boubei.tss.util.EasyUtils; import com.boubei.tssx.wx.WXUtil; /** * 公众号注册登记 */ @WebServlet(urlPatterns = "/gzh_reg.in") @SuppressWarnings("unchecked") public class GetGZHOpenId extends HttpServlet { private static final long serialVersionUID = -740569423483772472L; Logger log = Logger.getLogger(this.getClass()); public void init() { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String code = request.getParameter("code"); String appId = request.getParameter("appId"); String ret = WXUtil.getOpenId4GZH(code, appId); Map<String, String> map = (new ObjectMapper()).readValue(ret, Map.class); log.info(map); if ( !EasyUtils.isNullOrEmpty(map.get("errmsg")) ) { response.getWriter().println("获取openid出错"); return; } // 获取openId String openId = map.get("openid"); // 判断该 微信号是否已经绑定手机号 String hql = "from GZHPhone where openid = ? and appid = ?"; List<?> bindPhones = Global.getCommonService().getList(hql, openId, appId); if (bindPhones.size() == 1) { response.getWriter().println("已绑定"); } else { response.getWriter().println(openId); } // 尝试获取微信个人信息 String access_token = map.get("access_token"); ret = WXUtil.getUserInfo4GZH(access_token, openId); log.info(ret); } }
true
be77b4d4f408bb6b7604a3cf8aa2aef32203924b
Java
ruupusensei/BellmanFord
/Vertex.java
UTF-8
142
2.421875
2
[]
no_license
public class Vertex { int label; Vertex predecessor; public Vertex(int label) { this.label = label; this.predecessor = null; } }
true
9a33de965b3ad5eaa03b5730e408b168ede4ae07
Java
burningrain/libGDX-book-gameDelopmentByExample
/chapter4/ecs-simple/src/com/github/br/ecs/simple/engine/debug/data/ImageData.java
UTF-8
169
1.523438
2
[ "MIT" ]
permissive
package com.github.br.ecs.simple.engine.debug.data; /** * Created by user on 07.04.2018. */ public class ImageData implements DebugData { private float x, y; }
true
d987c1b2c7838038ca1e18ffc4ec9fe1bb6ad2a5
Java
Rea2/UT
/src/test/java/triangle/TestMethod_getSquare.java
UTF-8
4,976
2.84375
3
[]
no_license
package triangle; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.*; /** * Created by Raik Yauheni on 23.11.2018. */ public class TestMethod_getSquare { @DataProvider(name = "dP_Squares") public Object[][] create() { return new Object[][]{ {new double[]{0.5, 0.4, 0.3}, 0.06}, {new double[]{0.4, 0.5, 0.3}, 0.06}, {new double[]{0.4, 0.5, 0.3}, 0.06}, {new double[]{3.0, 4.0, 5.0}, 6.0}, {new double[]{4.0, 3.0, 5.0}, 6.0}, {new double[]{4.0, 5, 3.0}, 6.0}, {new double[]{3, 4, 5}, 6}, {new double[]{4, 3, 5}, 6}, {new double[]{4, 5, 3}, 6}, {new double[]{3E76, 4E76, 5E76}, 6E152}, {new double[]{4E76, 3E76, 5E76}, 6E152}, {new double[]{4E76, 5E76, 3E76}, 6E152}, }; } /** positive test*/ @Test(dataProvider = "dP_Squares", groups = "smoke") public void testCalcSquarePositive(double[] sides , double expecrtedResult) { double actualResult = new Triangle(sides[0], sides[1], sides[2]).getSquare(); Assert.assertEquals(actualResult , expecrtedResult, "incorrect square's calculation"); } @DataProvider(name = "dP_IllegalTriangle") public Iterator<Object[]> dataIllegalTriangle() { return Arrays.asList(new Object[][] { /** negative parameter */ { new ArrayList<Double>(Arrays.asList(-1.0, 1.0, 1.0)) }, { new ArrayList<Double>(Arrays.asList(1.0, -1.0, 1.0)) }, { new ArrayList<Double>(Arrays.asList(1.0, 1.0, -1.0)) }, { new ArrayList<Double>(Arrays.asList(1.0, -1.0, -1.0)) }, /** side equals zero */ { new ArrayList<Double>(Arrays.asList(0.0, 1.1, 1.2)) }, { new ArrayList<Double>(Arrays.asList(1.2, 0.0, 1.1)) }, { new ArrayList<Double>(Arrays.asList(1.1, 1.2, 0.0)) }, { new ArrayList<Double>(Arrays.asList(0.0, 0.0, 0.0)) }, /** sides equal zero and negative number */ { new ArrayList<Double>(Arrays.asList(-1.0, 1.0, 0.0)) }, { new ArrayList<Double>(Arrays.asList(-1.1, -1.2, -1.3)) }, /** the sum of the two sides is less than the third one */ { new ArrayList<Double>(Arrays.asList(1.0, 2.0, 4.0)) }, { new ArrayList<Double>(Arrays.asList(2.0, 4.0, 1.0)) }, { new ArrayList<Double>(Arrays.asList(4.0, 1.0, 2.0)) }, }).iterator(); } /** negative test. Exception is expected, if: * - detection triangle is performed for incorrect parameters */ @Test(dataProvider = "dP_IllegalTriangle", expectedExceptions = Exception.class, groups = "smoke") public void testProhibitionGetSquareIllegalTriangle(ArrayList<Double> sizes){ new Triangle(sizes.get(0),sizes.get(1), sizes.get(2)).getSquare(); } @DataProvider(name = "dP_lackDoublePrecision") public Iterator<Object[]> lackDoublePreciseness() { return Arrays.asList(new Object[][] { { new ArrayList<Double>(Arrays.asList(1E1, 1E18, 1E18)) }, { new ArrayList<Double>(Arrays.asList(1E18, 1E18, 1E1)) }, { new ArrayList<Double>(Arrays.asList(1E18, 1E1, 1E18)) }, { new ArrayList<Double>(Arrays.asList(1E58, 1E75, 1E75)) }, { new ArrayList<Double>(Arrays.asList(1E75, 1E58, 1E75)) }, { new ArrayList<Double>(Arrays.asList(1E75, 1E75, 1E58)) }, }).iterator(); } /** negative test. Exception is expected, if: * - difference between two sizes of triangle is more than 1E17, because double has limited precision */ @Test(dataProvider = "dP_lackDoublePrecision",expectedExceptions=Exception.class) public void testTooBigParams (ArrayList<Double> sizes) { new Triangle(sizes.get(0),sizes.get(1), sizes.get(2)).getSquare(); } @DataProvider(name = "dP_doubleOverflow") public Iterator<Object[]> doubleOverflow() { return Arrays.asList(new Object[][] { { new ArrayList<Double>(Arrays.asList(3E77, 4E77, 5E77)) }, { new ArrayList<Double>(Arrays.asList(4E77, 5E77, 3E77)) }, { new ArrayList<Double>(Arrays.asList(5E77, 3E77, 4E77)) }, }).iterator(); } /** negative test (double overflow). Exception is expected, if: * p(p-a)(p-b)(p-c) >= Double.MaxValue(); */ @Test(dataProvider = "dP_doubleOverflow",expectedExceptions=Exception.class) public void testDoubleOverflow (ArrayList<Double> sizes) { new Triangle(sizes.get(0),sizes.get(1), sizes.get(2)).getSquare(); } }
true
d9c6b3cf1054e5284b238006afaa32a3ab754c26
Java
elingsudo/NikiLaundry
/src/controller/master/MasterLayananController.java
UTF-8
2,513
2.0625
2
[]
no_license
/* * Copyright (C) 2017 triastowo * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package controller.master; import helper.GeneralHelper; import implementation.master.MasterLayananServiceImpl; import java.math.BigDecimal; import java.util.List; import model.master.MasterLayananModel; import org.jdesktop.swingx.prompt.PromptSupport; import service.master.MasterLayananService; import tablemodel.master.MasterLayananTableModel; import view.internal.MasterInternalFrame; /** * * @author triastowo */ public class MasterLayananController { private final MasterLayananService masterLayananService; private final MasterLayananTableModel masterLayananTableModel; public MasterLayananController() { masterLayananService = new MasterLayananServiceImpl(MasterLayananModel.class); masterLayananTableModel = new MasterLayananTableModel(); } public void loadMasterLayananData(MasterInternalFrame view) { List<MasterLayananModel> findAll = masterLayananService.findAll(); masterLayananTableModel.setList(findAll); view.getTabelLayanan().setModel(masterLayananTableModel); // Pengganti Textfield Placeholder PromptSupport.setPrompt("ID Pewangi", view.getTxtIdLayanan()); PromptSupport.setPrompt("Nama Pewangi", view.getTxtNamaLayanan()); PromptSupport.setPrompt("Harga Pewangi", view.getTxtHargaLayanan()); } public void save(MasterInternalFrame view) { String id = GeneralHelper.validasiNullString(view.getTxtIdLayanan().getText()); String nama = GeneralHelper.validasiNullString(view.getTxtNamaLayanan().getText()); String harga = GeneralHelper.validasiNullBigDecimal(view.getTxtHargaLayanan().getText()); MasterLayananModel model = new MasterLayananModel(); model.setIdLayanan(id); model.setNamaLayanan(nama); model.setHarga(new BigDecimal(harga)); masterLayananService.save(model); loadMasterLayananData(view); } }
true
def62701cabe375432dd1d88c1788eef97474269
Java
Carln-66/JavaNotebook
/JavaSenior/Reflection/src/NewInstanceTest.java
UTF-8
2,420
3.796875
4
[]
no_license
import org.junit.Test; import reflection.Person; import java.util.Random; /** * @Auther: Carl * @Date: 2021/02/20/18:50 * @Description: * 通过反射创建对应的运行时类对象 */ public class NewInstanceTest { @Test public void test1() throws IllegalAccessException, InstantiationException { Class<Person> aClass = Person.class; /* newInstance(): 调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参的构造器 要想此方法能够正常创建运行时类的对象,要求: 1. 运行时类必须提供空参的构造器 2. 提供满足条件的空参构造器权限修饰符。通常置为public。 在javabean种要求提供一个public的空参构造器。原因: 1。 便于通过反射创建运行时类的对象 2. 便于子类继承此运行类时,默认调用super()时,保证父类有此构造器 */ Person p1 = aClass.newInstance(); //造运行时类的对象绝大多数情况都是调用此方法 System.out.println(p1); } //体会反射的动态性 @Test public void test2() { for (int i = 0; i < 100; i++) { int num = new Random().nextInt(3); //0,1,2 String classPath = ""; switch (num) { case 0: classPath = "java.util.Date"; break; case 1: classPath = "java.lang.Object"; break; case 2: classPath = "reflection.Person"; break; } Object instance = null; try { instance = getInstance(classPath); System.out.println("i---" + i + " " + instance); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } } //创建一个指定类的对象 public Object getInstance(String classPath) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class aClass = Class.forName(classPath); return aClass.newInstance(); } }
true
516fb510c540e0441206c9c857c85d5e892e9477
Java
deepexpert-gaohz/sa-d
/jnnsBank/pbc-service/src/main/java/com/ideatech/ams/pbc/spi/syncValidater/AmsLinshiOpenSyncValidater.java
UTF-8
5,287
2.390625
2
[]
no_license
package com.ideatech.ams.pbc.spi.syncValidater; import com.ideatech.ams.pbc.dto.AllAcct; import com.ideatech.ams.pbc.exception.SyncException; import com.ideatech.common.utils.StringUtils; import org.apache.commons.lang.ArrayUtils; import org.springframework.stereotype.Component; /** * 人行账管系统临时户开户报备校验器 * * @author zoulang * */ @Component public class AmsLinshiOpenSyncValidater extends AbstractSyncValidater { @Override protected void doValidater(AllAcct allAcct) throws SyncException, Exception { super.validateCustomerInfoCommonOpen(allAcct); super.validateEffectiveDate(allAcct); //法人类型值判断 String[] legalType = new String[] { "1", "2"}; if(StringUtils.isNotBlank(allAcct.getLegalType())){ if (!ArrayUtils.contains(legalType, allAcct.getLegalType())) { logger.info("临时户法人类型当前值:" + allAcct.getLegalType()); logger.info("临时户法人类型值应为:\"1\", \"2\""); throw new SyncException("临时户法人类型值不正确"); } } //上级法人类型值判断 if(StringUtils.isNotBlank(allAcct.getParLegalType())){ if (!ArrayUtils.contains(legalType, allAcct.getParLegalType())) { logger.info("临时户上级法人类型当前值:" + allAcct.getLegalType()); logger.info("临时户上级法人类型值应为:\"1\", \"2\""); throw new SyncException("临时户上级法人类型值不正确"); } } //法人证件类型值判断 String[] legalIdcardTypeAms = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9"}; if(StringUtils.isNotBlank(allAcct.getLegalIdcardTypeAms())){ if (!ArrayUtils.contains(legalIdcardTypeAms, allAcct.getLegalIdcardTypeAms())) { logger.info("临时户法人证件类型当前值:" + allAcct.getLegalIdcardTypeAms()); logger.info("临时户法人证件类型值应为:\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\""); throw new SyncException("临时户法人证件类型值不正确"); } } //上级法人证件类型值判断 if(StringUtils.isNotBlank(allAcct.getParLegalIdcardType())){ if (!ArrayUtils.contains(legalIdcardTypeAms, allAcct.getParLegalIdcardType())) { logger.info("临时户上级法人证件类型当前值:" + allAcct.getParLegalIdcardType()); logger.info("临时户上级法人证件类型值应为:\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\""); throw new SyncException("临时户上级法人证件类型值不正确"); } } //证明文件种类1类型值判断 String[] fileType = new String[] { "01", "09"}; if(StringUtils.isNotBlank(allAcct.getFileType())){ if (!ArrayUtils.contains(fileType, allAcct.getFileType())) { logger.info("临时户证明文件种类1证件类型当前值:" + allAcct.getParLegalIdcardType()); logger.info("临时户证明文件种类1证件类型值应为:\"01\", \"09\""); throw new SyncException("临时户证明文件种类1证件类型值不正确"); } } //临时户币种类型值判断 String[] regCurrencyTypeAms = new String[] { "1","2","3","4","5","A","B","C","D","E","F"}; if(StringUtils.isNotBlank(allAcct.getRegCurrencyTypeAms())){ if (!ArrayUtils.contains(regCurrencyTypeAms, allAcct.getRegCurrencyTypeAms())) { logger.info("临时户币种类型当前值:" + allAcct.getRegCurrencyTypeAms()); logger.info("临时户币种类型值应为:\"1\",\"2\",\"3\",\"4\",\"5\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\""); throw new SyncException("临时户币种类型值不正确"); } } //临时户行业归属类型值判断 String[] industryCode = new String[] { "A$$农、林、牧、渔业$$第一产业 $$1", "B$$采矿业$$第二产业 $$2", "C$$制造业$$第二产业 $$2", "D$$电力、煤气及水的生产和供应业$$第二产业 $$2", "E$$建筑业$$第二产业 $$2", "F$$交通运输、仓储及邮政业$$第一层次 $$3", "G$$信息传输、计算机服务和软件业$$第二层次 $$4", "H$$批发和零售业$$第二层次 $$4", "I$$住宿和餐饮业$$第二层次 $$4", "J$$金融业$$第二层次 $$4", "K$$房地产业$$第二层次 $$4", "L$$租赁和商务服务业$$第二层次 $$4", "M$$科学研究、技术服务和地质勘查业$$第三层次 $$5", "N$$水利、环境和公共设施管理业$$第三层次 $$5", "O$$居民服务和其他服务业$$第三层次 $$5", "P$$教育$$第三层次 $$5", "Q$$卫生、社会保障和社会福利业$$第三层次 $$5", "R$$文化、体育和娱乐业$$第三层次 $$5", "S$$公共管理和社会组织$$第四层次 $$6", "T$$国际组织(其他行业)$$第四层次 $$6", "U$$其他$$第一层次 $$3" }; if(StringUtils.isNotBlank(allAcct.getIndustryCode())){ if (!ArrayUtils.contains(industryCode, allAcct.getIndustryCode())) { throw new SyncException("临时户行业归属类型值不正确"); } } } }
true
f46a8d25c336f60f71bbfde20b3ffda9a708d094
Java
AlejandroDaneri/AlgoMon
/src/vista/contenedores/ZonaDeEleccionParaJugador.java
UTF-8
1,087
2.296875
2
[]
no_license
package vista.contenedores; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; public class ZonaDeEleccionParaJugador extends BorderPane { public ZonaDeEleccionParaJugador(Button botonCambiarIzquierda, Button botonCambiarDerecha, Button botonSeleccion, HBox seleccionados, ImagenDeAlgomonAElegir seleccionJugador, TablaDeAlgomon tabla) { this.setTop(seleccionados); this.setLeft(botonCambiarIzquierda); this.setRight(botonCambiarDerecha); this.setCenter(seleccionJugador); BorderPane.setAlignment(botonCambiarIzquierda, Pos.CENTER); BorderPane.setAlignment(botonCambiarDerecha,Pos.CENTER); this.setPadding(new Insets(0,0,0,10)); VBox zonaInferior = new VBox(); zonaInferior.getChildren().addAll(tabla,botonSeleccion); zonaInferior.setAlignment(Pos.CENTER); this.setBottom(zonaInferior); } }
true
9d9cb7349a02383139715e012a53e1ddfdd4f797
Java
dinesh0307/Stockader
/ShareMarket/src/main/java/com/dinesh/share/market/dao/StockHistoryDataDao.java
UTF-8
1,021
2.65625
3
[]
no_license
package com.dinesh.share.market.dao; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * * @author Dinesh S * */ public class StockHistoryDataDao { private Connection connection; public StockHistoryDataDao( Connection connection ) { this.connection = connection; } public void insertData( String insertQuery ) throws SQLException { Statement insertStatement = null; try { insertStatement = connection.createStatement(); insertStatement.executeUpdate( insertQuery ); } catch( SQLException e ) { throw new SQLException( "Problem during inserting data in db." + e.getMessage() + " . Error code: " + e.getErrorCode() + " . SQl State : " + e.getSQLState(), e ); } finally { if( insertStatement != null ) { insertStatement.close(); } } } }
true
3b34992bb3ea09e6f673adc17573a61b3d228418
Java
suyash-capiot/operations
/src/main/java/com/coxandkings/travel/operations/service/prepaymenttosupplier/paymentadvice/PaymentAdviceLoaderService.java
UTF-8
866
2
2
[]
no_license
package com.coxandkings.travel.operations.service.prepaymenttosupplier.paymentadvice; import com.coxandkings.travel.operations.exceptions.OperationException; import com.coxandkings.travel.operations.model.prepaymenttosupplier.paymentadvice.PaymentAdvice; import com.coxandkings.travel.operations.resource.prepaymenttosupplier.paymentadvice.SupplierPaymentResource; import java.math.BigDecimal; import java.util.List; public interface PaymentAdviceLoaderService { public SupplierPaymentResource loadSupplierDetails(String bookingReferenceId, String orderId, String supplierReferenceId, String paymentAdviceNumber) throws OperationException; public List<PaymentAdvice> getAllPaymentAdvices(String bookingID, String orderID ,String supplierId) throws OperationException; public BigDecimal getNetPayableToSupplier(String bookingID, String orderID); }
true
76c1b3225da2c0547d2aba3198529087f978a14d
Java
ZRich97/SpeedGame
/src/Card.java
UTF-8
2,698
3.90625
4
[]
no_license
import java.awt.Image; public class Card{ private int value; private String suit; private Image image; int x; int y; /** Default constructor for Card class. */ public Card(){ suit = ""; value = 0; image = null; x = 30; y = 30; } /** In-depth constructor for Card class. @param val The integer value of the card (2-14). @param su The "suit" of the card. @param image The .jpg of the card. */ public Card(int val, String su, Image image){ suit = su; // 2-10 are 2-10 // Joker == 11 // Queen == 12 // King == 13 // ACE == 14 OR 1 value = val; this.image = image; x = 30; y = 30; } /** Checks if the current Card is a valid Card. @return True if valid, False if not. */ public boolean isValid(){ if(image != null && suit != "" && value != 0) return true; return false; } /** Sets the x offset of Card. @param n New X. */ public void setX(int n){ x = n; } /** Sets the y offset of Card. @param n New Y. */ public void setY(int n){ y = n; } /** Returns the x offset of Card. @return the X offset. */ public int getX(){ return x; } /** Returns the y offset of Card. @return the y offset. */ public int getY(){ return y; } /** Returns the .jpg of Card. @return the .jpg. */ public Image getCardImage(){ return image; } /** Returns the integer value of the Card. @return The integer value of the card (2-14). */ public int value(){ return value; } /** Returns the "suit" of the Card. @return su The "suit" of the card. */ public String suit(){ return suit; } /** Returns a String representation of a Card. @return Card's details. */ public String toString(){ return "Suit="+suit+" Val=" + value; } /** Compares this Card to another Card, and decides whether or not it is a valid placement by Speed rules. @param other The Card that this Card will be placed onto. @return Whether or not the placement is valid. */ public boolean isValidPlacement(Card other){ if(other==null){ return false; } if((this.value==(other.value-1))||(this.value==(other.value+1))){ return true; } if(this.value==2){ if(other.value==14){ return true; } } if(this.value==14){ if((1==(other.value-1))||(14==(other.value+1))){ return true; } } return false; } }
true
5de3f02f7f6f22a11dab01c73de07bd8d036f49b
Java
lyn-hub/CodingPractice
/Implement PriorityQueue/src/heap/PriorityQueue.java
UTF-8
2,516
3.671875
4
[]
no_license
package heap; import java.util.Arrays; public class PriorityQueue { //Fields //For easy to test, I set the fields are public. public int[] array; public int size; private static final int[] DEFAULT_ARRAY = new int[16]; // Constructors public PriorityQueue(int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException("input array can not be null or empty"); } this.array = array; size = array.length; heapify(); } public PriorityQueue (int cap) { if (cap <= 0) { throw new IllegalArgumentException("capacity can not be <= 0"); } array = new int[cap]; size = 0; } public PriorityQueue() { this.array = DEFAULT_ARRAY; this.size = 0; } //Methods private void heapify() { for (int i = size / 2 - 1; i >= 0; i--) { percolateDown(i); } } public int size() { return size; } public boolean isEmpty() { return size == 0; } private void percolateUp(int index) { while(index > 0) { int parentIndex = (index - 1) /2; if (array[parentIndex] > array[index]) { swap(array, parentIndex, index); } else { break; } index = parentIndex; } } private void percolateDown(int index) { // check if index is legal?(The last legal one is the last leaf node's parent) while(index <= size / 2 - 1) { int leftChildIndex = index * 2 + 1; int rightChildIndex = index * 2 + 2; //find the smaller one between leftChild and rightChild, if the rightChild exists int swapCandidate = leftChildIndex; if (rightChildIndex <= size - 1 && array[leftChildIndex] >= array[rightChildIndex]) { swapCandidate = rightChildIndex; } //swap if necessary if (array[index] > array[swapCandidate]) { swap(array, index, swapCandidate); } else { break; } index = swapCandidate; } } private void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public Integer peek() { if (size == 0) { return null; } return array[0]; } public Integer poll() { if (size == 0) { return null; } int result = array[0]; array[0] = array[size - 1]; size--; percolateDown(0); return result; } public void offer (int element) { if (size == array.length) { array = Arrays.copyOf(array, (int)(1.5 * array.length)); } array[size] = element; size++; percolateUp(size - 1); } }
true
2c2c7e27093e3d3034bf37c9276d40fd3a403eb9
Java
RedHotChiliBots/FRC4453_2020_PROJ
/src/main/java/frc/robot/commands/AutonDriveJoystick.java
UTF-8
2,226
2.390625
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import java.util.function.DoubleSupplier; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Chassis; public class AutonDriveJoystick extends CommandBase { private DoubleSupplier spd; private DoubleSupplier rot; private final Chassis chassis; private final ShuffleboardTab visionTab = Shuffleboard.getTab("Vision"); private NetworkTableEntry sbLimeSpd2 = visionTab.addPersistent("Lime Spd2", 0).getEntry(); private NetworkTableEntry sbLimeRot2 = visionTab.addPersistent("Lime Rot2", 0).getEntry(); public AutonDriveJoystick(DoubleSupplier spd, DoubleSupplier rot, Chassis chassis) { this.spd = spd; this.rot = rot; this.chassis = chassis; addRequirements(chassis); } // Called just before this Command runs the first time @Override public void initialize() { } // Called repeatedly when this Command is scheduled to run @Override public void execute() { double xSpeed = spd.getAsDouble();// * ChassisConstants.kMaxSpeedMPS; double xRot = rot.getAsDouble();// * ChassisConstants.kMaxAngularSpeed; xSpeed = Math.abs(xSpeed) < 0.1 ? 0.0 : xSpeed; xRot = Math.abs(xRot) < 0.1 ? 0.0 : xRot; sbLimeSpd2.setDouble(xSpeed); sbLimeRot2.setDouble(xRot); chassis.drive(xSpeed, xRot); } // Make this return true when this Command no longer needs to run execute() @Override public boolean isFinished() { return false; } // Called once after isFinished returns true @Override public void end(boolean interrupted) { } }
true
b93b0b37b1be46ed88523107dfd5e25eaaf224b4
Java
ishche/zgis
/GeoTech/src/org/mati/geotech/app/ApplicationWorkbenchAdvisor.java
UTF-8
651
1.921875
2
[]
no_license
package org.mati.geotech.app; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { @Override public String getInitialWindowPerspectiveId() { return PerspectiveFactory.ID; } @Override public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) { configurer.setShowCoolBar(false); return super.createWorkbenchWindowAdvisor(configurer); } }
true
0831e1d5448aeb3c8a439c07e75c3fb1027e9e53
Java
AlaricLightin/S1000D-PM-Viewer
/src/test/java/ru/biderman/s1000dpmviewer/rest/SecurityPublicationTest.java
UTF-8
3,634
2.078125
2
[]
no_license
package ru.biderman.s1000dpmviewer.rest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.mock.web.MockMultipartFile; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import ru.biderman.s1000dpmviewer.rest.dto.ContentDtoService; import ru.biderman.s1000dpmviewer.services.PublicationDetailsService; import ru.biderman.s1000dpmviewer.services.PublicationService; import java.util.stream.Stream; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static ru.biderman.s1000dpmviewer.rest.ControllerTestUtils.createTestMultipartFile; @WebMvcTest(PublicationController.class) @DisplayName("Проверка безопасности работы с публикациями ") @Import(ControllerTestConfiguration.class) public class SecurityPublicationTest { @Autowired MockMvc mockMvc; @MockBean PublicationDetailsService detailsService; @MockBean PublicationService publicationService; @MockBean ContentDtoService contentDtoService; private static final long PUB_ID = 101; @Nested @WithMockUser @DisplayName("должна блокировать при отсутствии прав ") class BlockNonAuthorizedUser { @DisplayName("при попытке добавить публикацию") @Test void shouldForbidUpload() throws Exception { final String content = "Test stream"; MockMultipartFile multipartFile = createTestMultipartFile(content); mockMvc.perform(multipart("/publication").file(multipartFile).with(csrf())) .andExpect(status().isForbidden()) .andReturn(); } @DisplayName("при попытке удалить публикацию") @ParameterizedTest @ArgumentsSource(Users.class) void shouldForbidDeletePublication(RequestPostProcessor user) throws Exception{ mockMvc.perform(delete("/publication/{id}", PUB_ID).with(user).with(csrf())) .andExpect(status().isForbidden()) .andReturn(); } } static class Users implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) { return Stream.of( Arguments.of(user("user")), Arguments.of(user("user").roles("EDITOR")) ); } } }
true
6902b959444880b4117c3004c3612ea7db08b392
Java
paulzhouuu/clean-android-java
/app/src/main/java/com/mconnect/mobile/imageviewer/ui/internal/di/modules/DataModule.java
UTF-8
4,091
1.914063
2
[]
no_license
package com.mconnect.mobile.imageviewer.ui.internal.di.modules; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mconnect.mobile.imageviewer.data.db.SqliteDbHelper; import com.mconnect.mobile.imageviewer.data.file.FileManager; import com.mconnect.mobile.imageviewer.data.repository.AlbumDataRepository; import com.mconnect.mobile.imageviewer.data.repository.ImageDataRepository; import com.mconnect.mobile.imageviewer.data.rest.FileApi; import com.mconnect.mobile.imageviewer.data.rest.FileApiInterceptor; import com.mconnect.mobile.imageviewer.data.rest.ImgurApi; import com.mconnect.mobile.imageviewer.data.rest.ImgurApiInterceptor; import com.mconnect.mobile.imageviewer.domain.repository.AlbumRepository; import com.mconnect.mobile.imageviewer.domain.repository.ImageRepository; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory; @Module public class DataModule { @Provides @Singleton public AlbumRepository provideAlbumRepository(AlbumDataRepository factory) { return factory; } @Provides @Singleton public ImageRepository provideItemRepository(ImageDataRepository repository) { return repository; } @Provides public Gson provideGson() { return new GsonBuilder() .create(); } @Provides @Singleton @Named("FileApi") public OkHttpClient provideFileApiHttpClient() { OkHttpClient okClient = new OkHttpClient(); okClient.interceptors().add(new FileApiInterceptor()); return okClient; } @Provides @Singleton @Named("FileApi") public Retrofit provideFileApiRetrofit(@Named("FileApi")OkHttpClient okHttpClient) { return new Retrofit.Builder() .client(okHttpClient) .baseUrl("https://toremove.com/") .addConverterFactory(GsonConverterFactory.create()) //can add more Converters. *ORDER MATTERS* .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } @Provides @Singleton public FileApi provideFileApi(@Named("FileApi")Retrofit retrofit) { return retrofit.create(FileApi.class); } @Provides @Singleton public OkHttpClient provideRestApiHttpClient() { OkHttpClient okClient = new OkHttpClient(); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okClient.interceptors().add(loggingInterceptor); okClient.interceptors().add(new ImgurApiInterceptor()); return okClient; } @Provides @Singleton public Retrofit provideRestApiRetrofit( OkHttpClient okHttpClient /*Gson gson*/) { return new Retrofit.Builder() .baseUrl("https://api.imgur.com/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) //can add more Converters. *ORDER MATTERS* .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } @Provides @Singleton public ImgurApi provideRestApi(Retrofit retrofit) { return retrofit.create(ImgurApi.class); } @Provides @Singleton public SharedPreferences provideDefaultSharedPreferences(Context context) { return PreferenceManager.getDefaultSharedPreferences(context); } @Provides @Singleton public FileManager provideFileManager(Context context) { return new FileManager(context); } @Provides @Singleton public SqliteDbHelper provideSqliteDbHelper(Context context) { return new SqliteDbHelper(context); } }
true
a2afcb95fcd505fc3449fe2d19e91aecc120ff14
Java
stanvanrooy/decompiled-instagram
/decompiled/instagram/sources/p000X/C45171xP.java
UTF-8
325
1.5625
2
[]
no_license
package p000X; /* renamed from: X.1xP reason: invalid class name and case insensitive filesystem */ public abstract class C45171xP extends C12380ge { public final boolean A00; public final int AGu() { return 1; } public C45171xP(int i, boolean z) { super(i); this.A00 = z; } }
true
69f47e81ba6c80ddce32a53fbf6b33ca4ec9d8ed
Java
illandril/CableModemStatus
/src/net/illandril/cableModem/status/ArrisSB6141.java
UTF-8
5,871
2.359375
2
[ "MIT" ]
permissive
package net.illandril.cableModem.status; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrisSB6141 extends StatusPageParser { @Override public StatusPageData parse( ZonedDateTime statusPageRequestTime, String statusPageHTML ) { StatusPageData pageData = new StatusPageData(); boolean inDownstream = false; boolean inUpstream = false; StringBuilder upstreamTable = new StringBuilder(); StringBuilder downstreamTable = new StringBuilder(); for ( String line : statusPageHTML.split( "\n" ) ) { if ( line.indexOf( "<FONT color=#ffffff>Downstream" ) != -1 ) { inDownstream = true; inUpstream = false; } else if ( line.indexOf( "<FONT color=#ffffff>Upstream" ) != -1 ) { inDownstream = false; inUpstream = true; } else if ( inDownstream || inUpstream ){ if ( line.indexOf( "Bonding Channel Value" ) != -1 ) { // ignore the line } else if ( line.indexOf( "</TABLE></CENTER>" ) != -1 ) { inDownstream = false; inUpstream = false; } else { line = line.replace( "<TABLE border=0 cellPadding=0 cellSpacing=0 width=300> <TBODY><TR> <TD align=left><SMALL>The Downstream Power Level reading is a snapshot taken at the time this page was requested. Please Reload/Refresh this Page for a new reading </SMALL></TD></TR></TBODY></TABLE>", "" ); line = line.replace( "&nbsp;", "" ).replace( " ", "" ).replace( "</TD>", "" ).replace( "<TD>", "|" ).replace( "</TR>", "" ).replace( "<TR>", ";" ); if ( inUpstream ) { upstreamTable.append( line ); } else { downstreamTable.append( line ); } } } } List<DownstreamData> dDataRows = new ArrayList<DownstreamData>( 8 ); for ( int i = 1; i <= 8; i++ ) { dDataRows.add( new DownstreamData( statusPageRequestTime, i ) ); } for ( String row : downstreamTable.toString().split( ";" ) ) { Iterator<DownstreamData> dDataRowsIterator = dDataRows.iterator(); for ( String col : row.split( "\\|" ) ) { if ( col.equals( "" ) ) { continue; } if ( row.indexOf( "ChannelID" ) != -1 ) { if ( col.indexOf( "ChannelID" ) == -1 ) { DownstreamData data = dDataRowsIterator.next(); data.setChannelID( Integer.parseInt( col.trim() ) ); } } else if ( row.indexOf( "Frequency" ) != -1 ) { if ( col.indexOf( "Frequency" ) == -1 ) { DownstreamData data = dDataRowsIterator.next(); data.setFrequency( col ); } } else if ( row.indexOf( "SignaltoNoiseRatio" ) != -1 ) { if ( col.indexOf( "SignaltoNoiseRatio" ) == -1 ) { DownstreamData data = dDataRowsIterator.next(); data.setSNR( col ); } } else if ( row.indexOf( "DownstreamModulation" ) != -1 ) { if ( col.indexOf( "DownstreamModulation" ) == -1 ) { DownstreamData data = dDataRowsIterator.next(); data.setModulation( col ); } } else if ( row.indexOf( "PowerLevel" ) != -1 ) { if ( col.indexOf( "PowerLevel" ) == -1 ) { DownstreamData data = dDataRowsIterator.next(); data.setPower( col ); } } } } for ( DownstreamData dData : dDataRows ) { pageData.add( dData ); } List<UpstreamData> uDataRows = new ArrayList<UpstreamData>( 4 ); for ( int i = 1; i <= 4; i++ ) { uDataRows.add( new UpstreamData( statusPageRequestTime, i ) ); } for ( String row : upstreamTable.toString().split( ";" ) ) { Iterator<UpstreamData> uDataRowsIterator = uDataRows.iterator(); for ( String col : row.split( "\\|" ) ) { if ( col.equals( "" ) ) { continue; } if ( row.indexOf( "ChannelID" ) != -1 ) { if ( col.indexOf( "ChannelID" ) == -1 ) { UpstreamData data = uDataRowsIterator.next(); data.setChannelID( Integer.parseInt( col.trim() ) ); } } else if ( row.indexOf( "Frequency" ) != -1 ) { if ( col.indexOf( "Frequency" ) == -1 ) { UpstreamData data = uDataRowsIterator.next(); data.setFrequency( col ); } } else if ( row.indexOf( "SymbolRate" ) != -1 ) { if ( col.indexOf( "SymbolRate" ) == -1 ) { UpstreamData data = uDataRowsIterator.next(); data.setSymbolRate( col ); } } else if ( row.indexOf( "PowerLevel" ) != -1 ) { if ( col.indexOf( "PowerLevel" ) == -1 ) { UpstreamData data = uDataRowsIterator.next(); data.setPower( col ); } } } } for ( UpstreamData uData : uDataRows ) { pageData.add( uData ); } return pageData; } }
true
96988387df4a17c8fe14e02ceb232439e71131b2
Java
tonyg-performio/tg-java
/src/test/java/com/tony/java/lambda/PersonalDetailsTest.java
UTF-8
392
3.125
3
[]
no_license
package com.tony.java.lambda; public class PersonalDetailsTest { public static void main(String[] args) { PersonalDetails personalDetails = ((FirstName, SecondName, Age) -> { System.out.println("My name is " + FirstName + " " + SecondName); System.out.println("Age " + Age); }); personalDetails.details("Tony", "George", 32); } }
true