text stringlengths 10 2.72M |
|---|
package com.san.guiTextInLanguage;
import com.san.guiText.GuiText;
import com.san.language.Language;
import com.san.textTranslated.TextTranslated;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@IdClass(GuiTextInLanguagePk.class)
public class GuiTextInLanguage {
@Id
@ManyToOne
private GuiText gui_text;
@Id
@ManyToOne
private Language language;
@ManyToOne
private TextTranslated gui_text_translated;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp gui_text_in_language_created_at;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Timestamp gui_text_in_language_updated_at;
public GuiTextInLanguage() {
}
public GuiText getGui_text() {
return gui_text;
}
public void setGui_text(GuiText gui_text) {
this.gui_text = gui_text;
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public TextTranslated getGui_text_translated() {
return gui_text_translated;
}
public void setGui_text_translated(TextTranslated gui_text_translated) {
this.gui_text_translated = gui_text_translated;
}
public Timestamp getGui_text_in_language_created_at() {
return gui_text_in_language_created_at;
}
public void setGui_text_in_language_created_at(Timestamp gui_text_in_language_created_at) {
this.gui_text_in_language_created_at = gui_text_in_language_created_at;
}
public Timestamp getGui_text_in_language_updated_at() {
return gui_text_in_language_updated_at;
}
public void setGui_text_in_language_updated_at(Timestamp gui_text_in_language_updated_at) {
this.gui_text_in_language_updated_at = gui_text_in_language_updated_at;
}
} |
package com.oaec.service;
import java.util.List;
import com.oaec.dao.StudentDao;
import com.oaec.model.Student;
public class StudentService {
public List getStudentList(int page,int row){
// page*row row
StudentDao sd = new StudentDao();
String sql = "select * from student order by sname limit "+(page*row)+","+row;
return sd.getStudentList(sql);
}
public int add(Student stu) {
StudentDao sd = new StudentDao();
//String sql =
//"insert into student(sid,sname,sage,ssex,sphone) values('"+stu.getSid()+"','"+stu.getSname()+"','"+stu.getSage()+"','"+stu.getSsex()+"','"+stu.getSphone()+"')";
String sql = "insert into student(sid,sname,sage,ssex,sphone) values(?,?,?,?,?)";
return sd.add(sql,stu);
}
public int del(String[] ids) {
StudentDao sd = new StudentDao();
int num = 0;
for(int i = 0;i<ids.length;i++){
String sql = "delete from student where sid='"+ids[i]+"'";
num += sd.del(sql);
}
return num;
}
public Student findOneStuForId(String id) {
StudentDao studao = new StudentDao();
String sql = "select * from student where sid = '"+id+"'";
return studao.findOneStuForId(sql);
}
public int update(Student stu) {
StudentDao studao = new StudentDao();
String sql = "UPDATE student SET sname='"+stu.getSname()+"',sage="+stu.getSage()+",ssex='"+stu.getSsex()+"',sphone='"+stu.getSphone()+"' where sid='"+stu.getSid()+"'";
return studao.update(sql);
}
}
|
package styleomega.cb006456.styleomega;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private String EmailHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
EmailHolder = getIntent().getStringExtra("email");
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
// Opening activity using intent on button click.
Intent intent = new Intent(this, Home.class);
intent.putExtra("email", EmailHolder);
startActivity(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_store) {
Store_Fragment fragment = new Store_Fragment();
Bundle bun = new Bundle();
bun.putString("emailholder", EmailHolder);
fragment.setArguments(bun);
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, fragment)
.commit();
} else if (id == R.id.nav_contact) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new Contact_Fragment())
.commit();
} else if (id == R.id.nav_cart) {
Cart_Fragment fragment = new Cart_Fragment();
Bundle bun = new Bundle();
bun.putString("emailholder", EmailHolder);
fragment.setArguments(bun);
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, fragment)
.commit();
} else if (id == R.id.nav_share) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new Share_Fragment())
.commit();
} else if (id == R.id.manageacc) {
ManageAcc_Fragment fragment = new ManageAcc_Fragment();
Bundle args = new Bundle();
args.putString("email",EmailHolder);
fragment.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, fragment)
.commit();
} else if (id == R.id.logout) {
finishAffinity();
startActivity(new Intent(this, Login.class));
//Finishing current DashBoard activity on button click.
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
|
package sr.hakrinbank.intranet.api.model;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.Date;
/**
* Created by clint on 4/26/17.
*/
@Entity
@Audited
public class PosMerchant {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String address;
private String contact;
private String phoneNumber;
private String terminalId;
@ManyToOne
private District district;
@Temporal(TemporalType.TIMESTAMP)
private Date date;
private Double latitude;
private Double longitude;
@Column(nullable = false, columnDefinition = "TINYINT", length = 1)
private boolean deleted;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getTerminalId() {
return terminalId;
}
public void setTerminalId(String terminalId) {
this.terminalId = terminalId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public District getDistrict() {
return district;
}
public void setDistrict(District district) {
this.district = district;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
|
HashTable:
HashSet is a set.
HashMap is <Key, Value> pair.
String common problem:
Key method: It is similar to array problem. Using two pointer.
1. Removal
a). remove particular chars from a string.
b). remove all leading/trailing/duplicate empty spaces from a string.
Method: (two pointer)
Two blocks, Three area, Same direction
i = 0, all letters to the left sides of i are processed letters that should not be removed.
j = 0, j is the current index to move, [i, j] do not care.
(j, size - 1), unknown area.
new String(arr, (offset), (length));
2. Deduplication
two pointer way.
3. SubString problem
travese is ok. |
package com.lti.test;
public class Test {
public String msg()
{
return "hi";
}
}
|
package de.cm.osm2po.snapp;
import java.util.Arrays;
import org.mapsforge.android.maps.overlay.ArrayWayOverlay;
import org.mapsforge.android.maps.overlay.OverlayWay;
import org.mapsforge.core.GeoPoint;
import android.graphics.Color;
import android.graphics.Paint;
import de.cm.osm2po.sd.routing.SdGeoUtils;
import de.cm.osm2po.sd.routing.SdGraph;
import de.cm.osm2po.sd.routing.SdPath;
public class RoutesLayer extends ArrayWayOverlay {
OverlayWay overlayWay;
public RoutesLayer() {
super(defaultFillPaint(), defaultOutlinePaint());
}
public static Paint defaultFillPaint() {
Paint fill = new Paint();
fill.setStyle(Paint.Style.STROKE);
fill.setColor(Color.BLUE);
fill.setAlpha(127);
fill.setStrokeWidth(7);
fill.setAntiAlias(true);
fill.setStrokeJoin(Paint.Join.ROUND);
return fill;
}
public static Paint defaultOutlinePaint() {
Paint outline = new Paint();
outline.setStyle(Paint.Style.STROKE);
outline.setColor(Color.BLACK);
outline.setAlpha(31);
outline.setAntiAlias(true);
outline.setStrokeWidth(11);
outline.setStrokeJoin(Paint.Join.ROUND);
return outline;
}
public void drawPath(SdGraph graph, SdPath path) {
if (overlayWay != null) removeWay(overlayWay); // remove old routes
if (path != null) {
GeoPoint[] geoPoints = new GeoPoint[0x400 /*1k*/];
int n = 0;
int nEdges = path.getNumberOfEdges();
for (int i = 0; i < nEdges; i++) {
long[] coords = path.fetchGeometry(graph, i);
int nCoords = coords.length;
int z = 0 == i ? 0 : 1;
for (int j = z; j < nCoords; j++) {
double lat = SdGeoUtils.toLat(coords[j]);
double lon = SdGeoUtils.toLon(coords[j]);
geoPoints[n++] = new GeoPoint(lat, lon);
if (geoPoints.length == n) { // ArrayOverflowCheck
geoPoints = Arrays.copyOf(geoPoints, n * 2);
}
}
}
geoPoints = Arrays.copyOf(geoPoints, n);
GeoPoint[][] geoWays = new GeoPoint[][]{geoPoints};
overlayWay = new OverlayWay(geoWays, defaultFillPaint(), defaultOutlinePaint());
addWay(overlayWay);
requestRedraw();
}
}
}
|
package Problem_4470;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for(int i = 1 ;i<=N; i++) {
sb.append(i)
.append(". ")
.append(br.readLine())
.append("\n");
}
System.out.print(sb.toString());
}
}
|
package org.reactome.web.nursa.client.details.tabs.dataset.widgets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.Stream;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.reactome.gsea.model.GseaAnalysisResult;
import org.reactome.nursa.model.DataPoint;
import org.reactome.nursa.model.Experiment;
import org.reactome.nursa.model.DisplayableDataPoint;
import org.reactome.web.analysis.client.AnalysisClient;
import org.reactome.web.analysis.client.AnalysisHandler;
import org.reactome.web.analysis.client.model.AnalysisError;
import org.reactome.web.analysis.client.model.AnalysisResult;
import org.reactome.web.analysis.client.model.AnalysisSummary;
import org.reactome.web.analysis.client.model.ExpressionSummary;
import org.reactome.web.analysis.client.model.PathwaySummary;
import org.reactome.web.analysis.client.model.ResourceSummary;
import org.reactome.web.pwp.client.common.events.AnalysisResetEvent;
import org.reactome.web.pwp.client.common.utils.Console;
import org.reactome.web.nursa.client.details.tabs.dataset.AnalysisResultFilterChangedEvent;
import org.reactome.web.nursa.client.details.tabs.dataset.GseaClient;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DoubleBox;
import com.google.gwt.user.client.ui.IntegerBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Fred Loney <loneyf@ohsu.edu>
*/
public abstract class AnalysisDisplay extends Composite {
private static final double DEF_RESULT_FILTER = 0.05;
private static final String BINOMIAL_CONFIG = "Binomial Analysis Configuration";
private static final String GSEA_CONFIG = "GSEA Configuration";
/**
* The UiBinder interface.
*/
interface Binder extends UiBinder<Widget, AnalysisDisplay> {
}
static final Binder uiBinder = GWT.create(Binder.class);
private static final String GENE_NAMES_HEADER = "#Gene names";
/** The main panel. */
@UiField()
Panel content;
/** The binomial analysis radio button. */
@UiField()
RadioButton binomialBtn;
/** The GSEA analysis radio button. */
@UiField()
RadioButton gseaBtn;
/** The launch display area. */
@UiField()
Widget launchPad;
/** The launch button. */
@UiField()
Button launchBtn;
/** The analysis running label. */
@UiField()
Label runningLbl;
/** The configuration button. */
@UiField()
Button configBtn;
/** The configuration settings text display. */
@UiField()
Label settingsLbl;
/** The results filter panel. */
@UiField()
Widget filterPanel;
/** The results filter entry box. */
@UiField()
DoubleBox filterBox;
/** The analysis result display. */
@UiField()
protected SimplePanel resultsPanel;
private BinomialConfigDisplay binomialConfig;
private GseaConfigDisplay gseaConfig;
protected EventBus eventBus;
protected Double resultFilter = DEF_RESULT_FILTER;
public AnalysisDisplay(EventBus eventBus) {
this.eventBus = eventBus;
binomialConfig = new BinomialConfigDisplay();
gseaConfig = new GseaConfigDisplay();
initWidget(uiBinder.createAndBindUi(this));
buildDisplay();
}
public double getResultFilter() {
return resultFilter == null ? DEF_RESULT_FILTER : resultFilter;
}
abstract protected void gseaAnalyse();
abstract protected void binomialAnalyse();
protected void showBinomialResult(List<PathwaySummary> results) {
Widget panel = createBinomialPanel(results);
resultsPanel.setWidget(panel);
}
protected void showGseaResult(List<GseaAnalysisResult> results) {
Widget panel = createGseaPanel(results);
resultsPanel.setWidget(panel);
}
protected void gseaAnalyse(List<DisplayableDataPoint> dataPoints, Consumer<List<GseaAnalysisResult>> consumer) {
GseaClient client = GWT.create(GseaClient.class);
// Transform the data points into the GSEA REST PUT
// payload using the Java8 list comprehension idiom.
// Only Reactome genes are included.
List<List<String>> rankedList = filterDataPoints(dataPoints).stream()
.map(AnalysisDisplay::pullRank)
.collect(Collectors.toList());
// The permutations parameter.
Integer nperms = gseaConfig.getNperms();
// The dataset size parameters.
int[] dataSetBounds = gseaConfig.getDataSetSizeBounds();
Integer dataSetSizeMinOpt = new Integer(dataSetBounds[0]);
Integer dataSetSizeMaxOpt = new Integer(dataSetBounds[1]);
// The result handler.
MethodCallback<List<GseaAnalysisResult>> callback = new MethodCallback<List<GseaAnalysisResult>>() {
@Override
public void onSuccess(Method method, List<GseaAnalysisResult> result) {
runningLbl.setVisible(false);
launchBtn.setVisible(true);
filterPanel.setVisible(true);
consumer.accept(result);
}
@Override
public void onFailure(Method method, Throwable exception) {
runningLbl.setVisible(false);
launchBtn.setVisible(true);
filterPanel.setVisible(false);
Console.error("GSEA execution unsuccessful: " + exception);
}
};
// Call the GSEA REST service.
client.analyse(rankedList, nperms, dataSetSizeMinOpt, dataSetSizeMaxOpt, callback);
}
private Collection<DisplayableDataPoint> filterDataPoints(List<DisplayableDataPoint> dataPoints) {
HashMap<String, List<DisplayableDataPoint>> geneDataPointsMap =
new HashMap<String, List<DisplayableDataPoint>>();
for (DisplayableDataPoint dataPoint: dataPoints) {
if (!dataPoint.isReactome()) {
continue;
}
String symbol = dataPoint.getSymbol();
List<DisplayableDataPoint> geneDataPoints = geneDataPointsMap.get(symbol);
if (geneDataPoints == null) {
geneDataPoints = new ArrayList<DisplayableDataPoint>();
geneDataPointsMap.put(symbol, geneDataPoints);
}
geneDataPoints.add(dataPoint);
}
return geneDataPointsMap.values().stream()
.map(AnalysisDisplay::summarize)
.collect(Collectors.toList());
}
private static DisplayableDataPoint summarize(List<DisplayableDataPoint> dataPoints) {
DisplayableDataPoint first = dataPoints.get(0);
if (dataPoints.size() == 1) {
return first;
}
DisplayableDataPoint summary = new DisplayableDataPoint();
summary.setSymbol(first.getSymbol());
summary.setReactome(first.isReactome());
// The p-value is the geometric mean of the data point p-values.
double[] pValues = dataPoints.stream()
.mapToDouble(DisplayableDataPoint::getPvalue)
.toArray();
double pValue = geometricMean(pValues);
summary.setPvalue(pValue);
// The FC is that of the most significant data point.
DisplayableDataPoint bestDataPoint = null;
for (DisplayableDataPoint dataPoint: dataPoints) {
if (bestDataPoint == null || dataPoint.getPvalue() < bestDataPoint.getPvalue()) {
bestDataPoint = dataPoint;
}
}
summary.setFoldChange(bestDataPoint.getFoldChange());
return summary;
}
private static double geometricMean(double[] values) {
double product = Arrays.stream(values)
.reduce((accum, value) -> accum * value).getAsDouble();
return Math.pow(product, 1.0 / values.length);
}
protected void binomialAnalyse(List<DisplayableDataPoint> dataPoints, Consumer<AnalysisResult> consumer) {
// The input is a table of gene symbol lines.
List<String> geneList = getBinomialGeneList(dataPoints);
if (geneList.isEmpty()) {
runningLbl.setVisible(false);
launchBtn.setVisible(true);
filterPanel.setVisible(true);
AnalysisResult result = new AnalysisResult() {
@Override
public List<String> getWarnings() {
return null;
}
@Override
public AnalysisSummary getSummary() {
return null;
}
@Override
public List<ResourceSummary> getResourceSummary() {
return null;
}
@Override
public Integer getPathwaysFound() {
return 0;
}
@Override
public List<PathwaySummary> getPathways() {
return Collections.emptyList();
}
@Override
public Integer getIdentifiersNotFound() {
return 0;
}
@Override
public ExpressionSummary getExpression() {
return null;
}
};
consumer.accept(result);
}
// Add the header required by the REST API call.
geneList.add(0, GENE_NAMES_HEADER);
// Make the REST payload text value.
String data = String.join("\n", geneList);
AnalysisClient.analyseData(data, true, false, 0, 0, new AnalysisHandler.Result() {
@Override
public void onAnalysisServerException(String message) {
runningLbl.setVisible(false);
launchBtn.setVisible(true);
filterPanel.setVisible(false);
Console.error(message);
}
@Override
public void onAnalysisResult(AnalysisResult result, long time) {
runningLbl.setVisible(false);
launchBtn.setVisible(true);
filterPanel.setVisible(true);
consumer.accept(result);
}
@Override
public void onAnalysisError(AnalysisError error) {
runningLbl.setVisible(false);
launchBtn.setVisible(true);
filterPanel.setVisible(false);
Console.error(error.getReason());
}
});
}
/**
* Filters the experiment data points based on the config.
*
* @param dataPoints the Nursa dataset experiment data points
* @return the ranked gene symbols list
*/
private List<String> getBinomialGeneList(List<DisplayableDataPoint> dataPoints) {
return filterDataPoints(dataPoints).stream()
.filter(binomialConfig.getFilter())
.map(dp -> dp.getSymbol())
.collect(Collectors.toList());
}
/**
* Pulls the gene symbol and FC from the given data point.
* The FC is formatted as a string for the REST interface.
*
* @param dataPoint the input data point.
* @return the [symbol, FC] list.
*/
private static List<String> pullRank(DataPoint dataPoint) {
return Arrays.asList(
dataPoint.getSymbol(),
Double.toString(dataPoint.getFoldChange())
);
}
private void buildDisplay() {
content.addStyleName(RESOURCES.getCSS().main());
// Note: it would be preferable to set the style for the
// widgets below in AnalysisDisplay.ui.xml, e.g.:
// <ui:style src="AnalysisDisplay.css" />
// ...
// <g:Button ui:field='sliderBtn' addStyleNames="{style.sliderBtn}">
// GWT and SO snippets suggest this is feasible and recommended, e.g.
// https://stackoverflow.com/questions/1899007/add-class-name-to-element-in-uibinder-xml-file
// However, doing so results in the following browser binding generation
// code error:
// Exception: com.google.gwt.core.client.JavaScriptException: (TypeError) :
// this.get_clientBundleFieldNameUnlikelyToCollideWithUserSpecifiedFieldOkay_4_g$(...).style_19_g$ is not a function
// The work-around is to set the style the old-fashioned verbose way with
// the CSS resource below.
launchPad.addStyleName(RESOURCES.getCSS().launchPad());
launchBtn.addStyleName(RESOURCES.getCSS().launchBtn());
gseaBtn.addStyleName(RESOURCES.getCSS().gseaBtn());
runningLbl.addStyleName(RESOURCES.getCSS().running());
configBtn.addStyleName(RESOURCES.getCSS().configBtn());
settingsLbl.addStyleName(RESOURCES.getCSS().settingsLbl());
filterPanel.addStyleName(RESOURCES.getCSS().filterPanel());
filterBox.addStyleName(RESOURCES.getCSS().filterBox());
filterBox.setValue(getResultFilter());
filterPanel.setVisible(false);
// The config button toggles the config panel display.
configBtn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// Open the configuration dialog.
showConfig();
}
});
// Per the RadioButton javadoc, the value change event is only
// triggered when the button is clicked, not when it is cleared,
// but it is good form to check the value here anyway.
binomialBtn.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
if (event.getValue()) {
settingsLbl.setText(binomialConfig.formatFilter());
}
}
});
// The default analysis is binomial.
binomialBtn.setValue(true);
settingsLbl.setText(binomialConfig.formatFilter());
gseaBtn.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
if (event.getValue()) {
settingsLbl.setText(formatGseaSettings());
}
}
});
runningLbl.setVisible(false);
launchBtn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
launchBtn.setVisible(false);
runningLbl.setVisible(true);
resultsPanel.clear();
AnalysisResetEvent resetEvent = new AnalysisResetEvent();
eventBus.fireEventFromSource(event, resetEvent);
if (gseaBtn.getValue()) {
gseaAnalyse();
} else {
binomialAnalyse();
}
}
});
filterBox.addValueChangeHandler(new ValueChangeHandler<Double>() {
@Override
public void onValueChange(ValueChangeEvent<Double> event) {
resultFilter = event.getValue();
// Redraw the tables.
AnalysisResultFilterChangedEvent changedEvent =
new AnalysisResultFilterChangedEvent(resultFilter);
eventBus.fireEventFromSource(changedEvent, this);
}
});
}
private String formatGseaSettings() {
int permutations = gseaConfig.getNperms();
int[] bounds = gseaConfig.getDataSetSizeBounds();
// Alas, GWT does not support String.format().
return Integer.toString(permutations) + " permutations, " +
Integer.toString(bounds[0]) +
" <= dataset size < " +
Integer.toString(bounds[1]);
}
private Widget createBinomialPanel(List<PathwaySummary> results) {
return new BinomialAnalysisResultPanel(results, getResultFilter(), eventBus);
}
private Widget createGseaPanel(List<GseaAnalysisResult> results) {
return new GseaAnalysisResultPanel(results, resultFilter, eventBus);
}
private void showConfig() {
DialogBox dialog = createConfigDialog();
dialog.show();
}
private DialogBox createConfigDialog() {
if (binomialBtn.getValue()) {
return createBinomialConfigDialog();
} else {
return createGseaConfigDialog();
}
}
private DialogBox createBinomialConfigDialog() {
AnalysisConfigDialog dialog =
new AnalysisConfigDialog(binomialConfig, BINOMIAL_CONFIG);
dialog.addCloseHandler(new CloseHandler<PopupPanel>() {
@Override
public void onClose(CloseEvent<PopupPanel> event) {
String settings = binomialConfig.formatFilter();
settingsLbl.setText(settings);
}
});
return dialog;
}
private DialogBox createGseaConfigDialog() {
AnalysisConfigDialog dialog =
new AnalysisConfigDialog(gseaConfig, GSEA_CONFIG);
dialog.addCloseHandler(new CloseHandler<PopupPanel>() {
@Override
public void onClose(CloseEvent<PopupPanel> event) {
settingsLbl.setText(formatGseaSettings());
}
});
return dialog;
}
private static Resources RESOURCES;
static {
RESOURCES = GWT.create(Resources.class);
RESOURCES.getCSS().ensureInjected();
}
/** A ClientBundle of resources used by this widget. */
interface Resources extends ClientBundle {
/** The styles used in this widget. */
@Source(Css.CSS)
Css getCSS();
}
/** Styles used by this widget. */
interface Css extends CssResource {
/** The path to the default CSS styles used by this resource. */
String CSS = "AnalysisDisplay.css";
String main();
String gseaBtn();
String launchPad();
String launchBtn();
String running();
String configBtn();
String settingsLbl();
String filterPanel();
String filterBox();
}
}
|
package nyc.c4q.android.ui;
public interface AuthenticationManager {
boolean validateLogin(String email, String password);
}
|
package com.mercadolibre.bootcampmelifrescos.service;
import com.mercadolibre.bootcampmelifrescos.dtos.response.WarehouseBatchResponse;
public interface WarehouseBatchService {
WarehouseBatchResponse getWarehouseBatchQuantityByProduct(Long productId) throws Exception;
}
|
package com.emmanuj.todoo.db;
/**
* Created by emmanuj on 11/12/15.
*/
public class DBConfig {
public static final String DB_NAME = "todoo.db";
public static final int DB_VERSION=1;
}
|
package garage;
public class Motorcycle extends Vehicle {
public Motorcycle(int w, int s, String c) {
//System.out.println("Motorcycle.");
super.vehicleWheels = w;
super.vehicleSpeed = s;
super.vehicleColour = c;
}
}
|
package com.memberComment.model;
import java.util.List;
public class MemberCommentService {
private MemberCommentDAO_interface dao;
public MemberCommentService() {
dao = new MemberCommentDAO();
}
public MemberCommentVO addMemberComment(MemberCommentVO memberCommentVO) {
dao.insert(memberCommentVO);
return memberCommentVO;
}
public MemberCommentVO updateMemberComment(MemberCommentVO memberCommentVO) {
dao.update(memberCommentVO);
return memberCommentVO;
}
public void deleteMemberComment(String memberCommentId) {
dao.delete(memberCommentId);
}
public MemberCommentVO getOneMemberComment(String memberCommentId) {
return dao.findByPrimaryKey(memberCommentId);
}
public List<MemberCommentVO> getAllMemberComment() {
return dao.getAll();
}
public List<MemberCommentVO> getAllMemberCommentById(String memberCommentId) {
return dao.getAllById(memberCommentId);
}
public Double getMemberRating(String memberId) {
return dao.getMemberRating(memberId);
}
}
|
package com.example.e_learning;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
public class AdminPage extends AppCompatActivity {
Button exambutton, coursebutton;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adminpage);
exambutton = findViewById(R.id.exambutton);
coursebutton = findViewById(R.id.coursebutton);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
coursebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), Course.class));
}
});
}
public void logout(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
|
package cn.tedu.reivew;
///本类用于单例饿汉式
public class Test1 {
public static void main(String[] args) {
Mysing s1 = Mysing.getmysing();
Mysing s2 = Mysing.getmysing();
System.out.println(s1==s2);
}
}
class Mysing{
private Mysing(){}
private static Mysing mysing=new Mysing();
public static Mysing getmysing(){
return mysing;
}
} |
package br.com.gestor.database.modelo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity
public class Gerente extends Usuario{
}
|
package com.leetcode.oj.list;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import com.leetcode.oj.util.ListNode;
/**
* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*
* @author flu
*
*/
public class MergeKSortedLists {
public ListNode mergeKLists(List<ListNode> lists) {
if (lists == null || lists.size() == 0)
return null;
Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
ListNode head = new ListNode(-1);
ListNode n = head;
// add the first pass of all nodes in the list
// the rest can handle directly in the heap since these are head nodes of each linked list
for (ListNode list : lists) {
if (list != null) {
heap.offer(list);
}
}
while (heap.size() > 0) {
ListNode tmp = heap.poll();
n.next = tmp;
n = n.next;
if (tmp.next != null) {
heap.offer(tmp.next);
}
}
return head.next;
}
public static void main(String[] args) {
int[] l = new int[] { 1, 3, 5, 9 };
ListNode n = new ListNode(-1);
ListNode head = n;
for (int i : l) {
ListNode d = new ListNode(i);
n.next = d;
n = n.next;
}
List<ListNode> list = new ArrayList<>();
list.add(head.next);
l = new int[] { 1, 5, 7, 10 };
n = new ListNode(-1);
head = n;
for (int i : l) {
ListNode d = new ListNode(i);
n.next = d;
n = n.next;
}
list.add(head.next);
ListNode sorted = new MergeKSortedLists().mergeKLists(list);
while (sorted != null) {
System.out.print(sorted.val + ", ");
sorted = sorted.next;
}
}
}
|
package utils;
public class Parameters {
/**
* global parameters stands for the orders status
*/
public final static String BOOKING = "booking";
public final static String ACTIVE = "active";
public final static String FINISH = "finish";
public final static String CANCEL = "cancel";
/**
* The global settings for number of retrying to reconnect the database
* if the request was rejected.
*/
public final static int num_of_retry = 3;
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.codec.multipart;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
import reactor.core.scheduler.Scheduler;
import reactor.util.context.Context;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferLimitException;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.util.FastByteArrayOutputStream;
/**
* Subscribes to a token stream (i.e. the result of
* {@link MultipartParser#parse(Flux, byte[], int, Charset)}), and produces a flux of {@link Part} objects.
*
* @author Arjen Poutsma
* @since 5.3
*/
final class PartGenerator extends BaseSubscriber<MultipartParser.Token> {
private static final Log logger = LogFactory.getLog(PartGenerator.class);
private final AtomicReference<State> state = new AtomicReference<>(new InitialState());
private final AtomicBoolean requestOutstanding = new AtomicBoolean();
private final MonoSink<Part> sink;
private final int maxInMemorySize;
private final long maxDiskUsagePerPart;
private final Mono<Path> fileStorageDirectory;
private final Scheduler blockingOperationScheduler;
private PartGenerator(MonoSink<Part> sink, int maxInMemorySize, long maxDiskUsagePerPart,
Mono<Path> fileStorageDirectory, Scheduler blockingOperationScheduler) {
this.sink = sink;
this.maxInMemorySize = maxInMemorySize;
this.maxDiskUsagePerPart = maxDiskUsagePerPart;
this.fileStorageDirectory = fileStorageDirectory;
this.blockingOperationScheduler = blockingOperationScheduler;
}
/**
* Creates parts from a given stream of tokens.
*/
public static Mono<Part> createPart(Flux<MultipartParser.Token> tokens, int maxInMemorySize,
long maxDiskUsagePerPart, Mono<Path> fileStorageDirectory, Scheduler blockingOperationScheduler) {
return Mono.create(sink -> {
PartGenerator generator = new PartGenerator(sink, maxInMemorySize, maxDiskUsagePerPart,
fileStorageDirectory, blockingOperationScheduler);
sink.onCancel(generator);
sink.onRequest(l -> generator.requestToken());
tokens.subscribe(generator);
});
}
@Override
public Context currentContext() {
return Context.of(this.sink.contextView());
}
@Override
protected void hookOnSubscribe(Subscription subscription) {
requestToken();
}
@Override
protected void hookOnNext(MultipartParser.Token token) {
this.requestOutstanding.set(false);
State state = this.state.get();
if (token instanceof MultipartParser.HeadersToken) {
newPart(state, token.headers());
}
else {
state.body(token.buffer());
}
}
private void newPart(State currentState, HttpHeaders headers) {
if (MultipartUtils.isFormField(headers)) {
changeState(currentState, new FormFieldState(headers));
requestToken();
}
else {
changeState(currentState, new InMemoryState(headers));
requestToken();
}
}
@Override
protected void hookOnComplete() {
this.state.get().onComplete();
}
@Override
protected void hookOnError(Throwable throwable) {
this.state.get().error(throwable);
changeStateInternal(DisposedState.INSTANCE);
this.sink.error(throwable);
}
@Override
public void dispose() {
changeStateInternal(DisposedState.INSTANCE);
cancel();
}
boolean changeState(State oldState, State newState) {
if (this.state.compareAndSet(oldState, newState)) {
if (logger.isTraceEnabled()) {
logger.trace("Changed state: " + oldState + " -> " + newState);
}
oldState.dispose();
return true;
}
else {
logger.warn("Could not switch from " + oldState +
" to " + newState + "; current state:"
+ this.state.get());
return false;
}
}
private void changeStateInternal(State newState) {
if (this.state.get() == DisposedState.INSTANCE) {
return;
}
State oldState = this.state.getAndSet(newState);
if (logger.isTraceEnabled()) {
logger.trace("Changed state: " + oldState + " -> " + newState);
}
oldState.dispose();
}
void emitPart(Part part) {
if (logger.isTraceEnabled()) {
logger.trace("Emitting: " + part);
}
this.sink.success(part);
}
void emitError(Throwable t) {
cancel();
this.sink.error(t);
}
void requestToken() {
if (upstream() != null &&
this.state.get().canRequest() &&
this.requestOutstanding.compareAndSet(false, true)) {
request(1);
}
}
/**
* Represents the internal state of the {@link PartGenerator} for
* creating a single {@link Part}.
* {@link State} instances are stateful, and created when a new
* {@link MultipartParser.HeadersToken} is accepted (see
* {@link #newPart(State, HttpHeaders)}).
* The following rules determine which state the creator will have:
* <ol>
* <li>If the part is a {@linkplain MultipartUtils#isFormField(HttpHeaders) form field},
* the creator will be in the {@link FormFieldState}.</li>
* <li>Otherwise, the creator will initially be in the
* {@link InMemoryState}, but will switch over to {@link CreateFileState}
* when the part byte count exceeds {@link #maxInMemorySize},
* then to {@link WritingFileState} (to write the memory contents),
* and finally {@link IdleFileState}, which switches back to
* {@link WritingFileState} when more body data comes in.</li>
* </ol>
*/
private interface State {
/**
* Invoked when a {@link MultipartParser.BodyToken} is received.
*/
void body(DataBuffer dataBuffer);
/**
* Invoked when all tokens for the part have been received.
*/
void onComplete();
/**
* Invoked when an error has been received.
*/
default void error(Throwable throwable) {
}
/**
* Indicates whether the current state is ready to accept a new token.
*/
default boolean canRequest() {
return true;
}
/**
* Cleans up any state.
*/
default void dispose() {
}
}
/**
* The initial state of the creator. Throws an exception for {@link #body(DataBuffer)}.
*/
private final class InitialState implements State {
private InitialState() {
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
@Override
public void onComplete() {
}
@Override
public String toString() {
return "INITIAL";
}
}
/**
* The creator state when a {@linkplain MultipartUtils#isFormField(HttpHeaders) form field} is received.
* Stores all body buffers in memory (up until {@link #maxInMemorySize}).
*/
private final class FormFieldState implements State {
private final FastByteArrayOutputStream value = new FastByteArrayOutputStream();
private final HttpHeaders headers;
public FormFieldState(HttpHeaders headers) {
this.headers = headers;
}
@Override
public void body(DataBuffer dataBuffer) {
int size = this.value.size() + dataBuffer.readableByteCount();
if (PartGenerator.this.maxInMemorySize == -1 ||
size < PartGenerator.this.maxInMemorySize) {
store(dataBuffer);
requestToken();
}
else {
DataBufferUtils.release(dataBuffer);
emitError(new DataBufferLimitException("Form field value exceeded the memory usage limit of " +
PartGenerator.this.maxInMemorySize + " bytes"));
}
}
private void store(DataBuffer dataBuffer) {
try {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
this.value.write(bytes);
}
catch (IOException ex) {
emitError(ex);
}
finally {
DataBufferUtils.release(dataBuffer);
}
}
@Override
public void onComplete() {
byte[] bytes = this.value.toByteArrayUnsafe();
String value = new String(bytes, MultipartUtils.charset(this.headers));
emitPart(DefaultParts.formFieldPart(this.headers, value));
}
@Override
public String toString() {
return "FORM-FIELD";
}
}
/**
* The creator state when not handling a form field.
* Stores all received buffers in a queue.
* If the byte count exceeds {@link #maxInMemorySize}, the creator state
* is changed to {@link CreateFileState}, and eventually to
* {@link WritingFileState}.
*/
private final class InMemoryState implements State {
private final AtomicLong byteCount = new AtomicLong();
private final Queue<DataBuffer> content = new ConcurrentLinkedQueue<>();
private final HttpHeaders headers;
private volatile boolean releaseOnDispose = true;
public InMemoryState(HttpHeaders headers) {
this.headers = headers;
}
@Override
public void body(DataBuffer dataBuffer) {
long prevCount = this.byteCount.get();
long count = this.byteCount.addAndGet(dataBuffer.readableByteCount());
if (PartGenerator.this.maxInMemorySize == -1 ||
count <= PartGenerator.this.maxInMemorySize) {
storeBuffer(dataBuffer);
}
else if (prevCount <= PartGenerator.this.maxInMemorySize) {
switchToFile(dataBuffer, count);
}
else {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
}
private void storeBuffer(DataBuffer dataBuffer) {
this.content.add(dataBuffer);
requestToken();
}
private void switchToFile(DataBuffer current, long byteCount) {
List<DataBuffer> content = new ArrayList<>(this.content);
content.add(current);
this.releaseOnDispose = false;
CreateFileState newState = new CreateFileState(this.headers, content, byteCount);
if (changeState(this, newState)) {
newState.createFile();
}
else {
content.forEach(DataBufferUtils::release);
}
}
@Override
public void onComplete() {
emitMemoryPart();
}
private void emitMemoryPart() {
byte[] bytes = new byte[(int) this.byteCount.get()];
int idx = 0;
for (DataBuffer buffer : this.content) {
int len = buffer.readableByteCount();
buffer.read(bytes, idx, len);
idx += len;
DataBufferUtils.release(buffer);
}
this.content.clear();
Flux<DataBuffer> content = Flux.just(DefaultDataBufferFactory.sharedInstance.wrap(bytes));
emitPart(DefaultParts.part(this.headers, content));
}
@Override
public void dispose() {
if (this.releaseOnDispose) {
this.content.forEach(DataBufferUtils::release);
}
}
@Override
public String toString() {
return "IN-MEMORY";
}
}
/**
* The creator state when waiting for a temporary file to be created.
* {@link InMemoryState} initially switches to this state when the byte
* count exceeds {@link #maxInMemorySize}, and then calls
* {@link #createFile()} to switch to {@link WritingFileState}.
*/
private final class CreateFileState implements State {
private final HttpHeaders headers;
private final Collection<DataBuffer> content;
private final long byteCount;
private volatile boolean completed;
private volatile boolean releaseOnDispose = true;
public CreateFileState(HttpHeaders headers, Collection<DataBuffer> content, long byteCount) {
this.headers = headers;
this.content = content;
this.byteCount = byteCount;
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
@Override
public void onComplete() {
this.completed = true;
}
public void createFile() {
PartGenerator.this.fileStorageDirectory
.map(this::createFileState)
.subscribeOn(PartGenerator.this.blockingOperationScheduler)
.subscribe(this::fileCreated, PartGenerator.this::emitError);
}
private WritingFileState createFileState(Path directory) {
try {
Path tempFile = Files.createTempFile(directory, null, ".multipart");
if (logger.isTraceEnabled()) {
logger.trace("Storing multipart data in file " + tempFile);
}
WritableByteChannel channel = Files.newByteChannel(tempFile, StandardOpenOption.WRITE);
return new WritingFileState(this, tempFile, channel);
}
catch (IOException ex) {
throw new UncheckedIOException("Could not create temp file in " + directory, ex);
}
}
private void fileCreated(WritingFileState newState) {
this.releaseOnDispose = false;
if (changeState(this, newState)) {
newState.writeBuffers(this.content);
if (this.completed) {
newState.onComplete();
}
}
else {
MultipartUtils.closeChannel(newState.channel);
MultipartUtils.deleteFile(newState.file);
this.content.forEach(DataBufferUtils::release);
}
}
@Override
public void dispose() {
if (this.releaseOnDispose) {
this.content.forEach(DataBufferUtils::release);
}
}
@Override
public String toString() {
return "CREATE-FILE";
}
}
private final class IdleFileState implements State {
private final HttpHeaders headers;
private final Path file;
private final WritableByteChannel channel;
private final AtomicLong byteCount;
private volatile boolean closeOnDispose = true;
private volatile boolean deleteOnDispose = true;
public IdleFileState(WritingFileState state) {
this.headers = state.headers;
this.file = state.file;
this.channel = state.channel;
this.byteCount = state.byteCount;
}
@Override
public void body(DataBuffer dataBuffer) {
long count = this.byteCount.addAndGet(dataBuffer.readableByteCount());
if (PartGenerator.this.maxDiskUsagePerPart == -1 || count <= PartGenerator.this.maxDiskUsagePerPart) {
this.closeOnDispose = false;
this.deleteOnDispose = false;
WritingFileState newState = new WritingFileState(this);
if (changeState(this, newState)) {
newState.writeBuffer(dataBuffer);
}
else {
MultipartUtils.closeChannel(this.channel);
MultipartUtils.deleteFile(this.file);
DataBufferUtils.release(dataBuffer);
}
}
else {
MultipartUtils.closeChannel(this.channel);
MultipartUtils.deleteFile(this.file);
DataBufferUtils.release(dataBuffer);
emitError(new DataBufferLimitException(
"Part exceeded the disk usage limit of " + PartGenerator.this.maxDiskUsagePerPart +
" bytes"));
}
}
@Override
public void onComplete() {
MultipartUtils.closeChannel(this.channel);
this.deleteOnDispose = false;
emitPart(DefaultParts.part(this.headers, this.file, PartGenerator.this.blockingOperationScheduler));
}
@Override
public void dispose() {
if (this.closeOnDispose) {
MultipartUtils.closeChannel(this.channel);
}
if (this.deleteOnDispose) {
MultipartUtils.deleteFile(this.file);
}
}
@Override
public String toString() {
return "IDLE-FILE";
}
}
private final class WritingFileState implements State {
private final HttpHeaders headers;
private final Path file;
private final WritableByteChannel channel;
private final AtomicLong byteCount;
private volatile boolean completed;
private volatile boolean disposed;
public WritingFileState(CreateFileState state, Path file, WritableByteChannel channel) {
this.headers = state.headers;
this.file = file;
this.channel = channel;
this.byteCount = new AtomicLong(state.byteCount);
}
public WritingFileState(IdleFileState state) {
this.headers = state.headers;
this.file = state.file;
this.channel = state.channel;
this.byteCount = state.byteCount;
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
@Override
public void onComplete() {
this.completed = true;
State state = PartGenerator.this.state.get();
// writeComplete might have changed our state to IdleFileState
if (state != this) {
state.onComplete();
}
else {
this.completed = true;
}
}
public void writeBuffer(DataBuffer dataBuffer) {
Mono.just(dataBuffer)
.flatMap(this::writeInternal)
.subscribeOn(PartGenerator.this.blockingOperationScheduler)
.subscribe(null,
PartGenerator.this::emitError,
this::writeComplete);
}
public void writeBuffers(Iterable<DataBuffer> dataBuffers) {
Flux.fromIterable(dataBuffers)
.concatMap(this::writeInternal)
.then()
.subscribeOn(PartGenerator.this.blockingOperationScheduler)
.subscribe(null,
PartGenerator.this::emitError,
this::writeComplete);
}
private void writeComplete() {
IdleFileState newState = new IdleFileState(this);
if (this.disposed) {
newState.dispose();
}
else if (changeState(this, newState)) {
if (this.completed) {
newState.onComplete();
}
else {
requestToken();
}
}
else {
MultipartUtils.closeChannel(this.channel);
MultipartUtils.deleteFile(this.file);
}
}
@SuppressWarnings("BlockingMethodInNonBlockingContext")
private Mono<Void> writeInternal(DataBuffer dataBuffer) {
try {
try (DataBuffer.ByteBufferIterator iterator = dataBuffer.readableByteBuffers()) {
while (iterator.hasNext()) {
ByteBuffer byteBuffer = iterator.next();
while (byteBuffer.hasRemaining()) {
this.channel.write(byteBuffer);
}
}
}
return Mono.empty();
}
catch (IOException ex) {
MultipartUtils.closeChannel(this.channel);
MultipartUtils.deleteFile(this.file);
return Mono.error(ex);
}
finally {
DataBufferUtils.release(dataBuffer);
}
}
@Override
public boolean canRequest() {
return false;
}
@Override
public void dispose() {
this.disposed = true;
}
@Override
public String toString() {
return "WRITE-FILE";
}
}
private static final class DisposedState implements State {
public static final DisposedState INSTANCE = new DisposedState();
private DisposedState() {
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
}
@Override
public void onComplete() {
}
@Override
public String toString() {
return "DISPOSED";
}
}
}
|
package ch.ethz.geco.t4j.internal.json.custom;
/**
* Represents a logo custom field json object.
*/
public class LogoObject {
public String logo_small;
public String logo_medium;
public String logo_large;
public String original;
}
|
package CamelWebservicePOC.client;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.8
* Generated source version: 2.0
*
*/
@WebServiceClient(name = "ReferralServiceService", targetNamespace = "http://webservice.hci.iso.com", wsdlLocation = "file:/C:/Dev/projects/CoventryIntegration/trunk/CamelWebservicePOC/src/wsdl/ReferralService.wsdl")
public class ReferralServiceService
extends Service
{
private final static URL REFERRALSERVICESERVICE_WSDL_LOCATION;
private final static WebServiceException REFERRALSERVICESERVICE_EXCEPTION;
private final static QName REFERRALSERVICESERVICE_QNAME = new QName("http://webservice.hci.iso.com", "ReferralServiceService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("file:/C:/Dev/projects/CoventryIntegration/trunk/CamelWebservicePOC/src/wsdl/ReferralService.wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
REFERRALSERVICESERVICE_WSDL_LOCATION = url;
REFERRALSERVICESERVICE_EXCEPTION = e;
}
public ReferralServiceService() {
super(__getWsdlLocation(), REFERRALSERVICESERVICE_QNAME);
}
public ReferralServiceService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
/**
*
* @return
* returns ReferralService
*/
@WebEndpoint(name = "ReferralService")
public ReferralService getReferralService() {
return super.getPort(new QName("http://webservice.hci.iso.com", "ReferralService"), ReferralService.class);
}
private static URL __getWsdlLocation() {
if (REFERRALSERVICESERVICE_EXCEPTION!= null) {
throw REFERRALSERVICESERVICE_EXCEPTION;
}
return REFERRALSERVICESERVICE_WSDL_LOCATION;
}
}
|
package com.project.personaddress.domain.service;
import com.project.personaddress.domain.model.Address;
import com.project.personaddress.repositories.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
@Service
public class AddressService extends AbstractService<Address, Long>{
@Autowired
private AddressRepository addressRepository;
@Override
JpaRepository<Address, Long> getRepository() {
return addressRepository;
}
@Override
protected Class<Address> getEntityClass() {
return Address.class;
}
}
|
import static org.junit.Assert.assertEquals;
import image.Image;
import image.Pixel;
import java.util.ArrayList;
import java.util.List;
import model.ImageUtils;
import model.PPM;
import org.junit.Test;
/**
* Test class for the ImageUtils class.
*/
public class ImageUtilsTest {
// tests readFile
@Test
public void testReadFile() {
Image im = ImageUtils.readFile("checkerboardBLUR.ppm",new PPM());
List<List<Pixel>> expectedPixels = new ArrayList<>();
expectedPixels.add(new ArrayList<>());
expectedPixels.add(new ArrayList<>());
expectedPixels.add(new ArrayList<>());
expectedPixels.get(0).add(new Pixel(64, 64, 64));
expectedPixels.get(0).add(new Pixel(96, 96, 96));
expectedPixels.get(0).add(new Pixel(64, 64, 64));
expectedPixels.get(1).add(new Pixel(96, 96, 96));
expectedPixels.get(1).add(new Pixel(128, 128, 128));
expectedPixels.get(1).add(new Pixel(96, 96, 96));
expectedPixels.get(2).add(new Pixel(64, 64, 64));
expectedPixels.get(2).add(new Pixel(96, 96, 96));
expectedPixels.get(2).add(new Pixel(64, 64, 64));
Image expectedImage = new Image(expectedPixels, 3, 3);
assertEquals(im, expectedImage);
}
// tests writeFile
@Test
public void testWriteFile() {
Image im = ImageUtils.readFile("checkerboardBLUR.ppm",new PPM());
PPM ppmtest = new PPM(new StringBuilder());
ImageUtils.writeFile("checkboardBLUR", im, ppmtest);
assertEquals("P3\n"
+ "3 3\n"
+ "255\n"
+ "64\n"
+ "64\n"
+ "64\n"
+ "96\n"
+ "96\n"
+ "96\n"
+ "64\n"
+ "64\n"
+ "64\n"
+ "96\n"
+ "96\n"
+ "96\n"
+ "128\n"
+ "128\n"
+ "128\n"
+ "96\n"
+ "96\n"
+ "96\n"
+ "64\n"
+ "64\n"
+ "64\n"
+ "96\n"
+ "96\n"
+ "96\n"
+ "64\n"
+ "64\n"
+ "64\n",ppmtest.getAp().toString());
}
}
|
package com.qumla.service.impl;
import io.katharsis.errorhandling.ErrorData;
import io.katharsis.errorhandling.ErrorResponse;
import io.katharsis.errorhandling.mapper.ExceptionMapperProvider;
import io.katharsis.errorhandling.mapper.JsonApiExceptionMapper;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import com.qumla.web.exception.BadRequest;
@ExceptionMapperProvider
public class BadRequestExceptionMapper implements JsonApiExceptionMapper<BadRequest>{
@Override
public ErrorResponse toErrorResponse(BadRequest exception) {
List l= new ArrayList();
l.add(new ErrorData(null,null,"error",exception.getMessage(),null,null,null,null,null));
return new ErrorResponse(l,HttpStatus.BAD_REQUEST.value());
}
}
|
package com.example.zad2.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@WebFilter("/login.jsp")
public class LoginFormFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) request).getSession();
Integer failedLogins = (Integer) session.getAttribute("failedLogins");
if (failedLogins != null && failedLogins == 3) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<a href=\"index.jsp\">Main page</a>");
out.println("<p>User made 3 failed login attempts. Login is locked!</p>");
out.println("</html></body>");
out.close();
return;
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
|
package bd.edu.httpdaffodilvarsity.jobtrack.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Zakaria on 05-Dec-16.
*/
public class DatabaseHelper extends SQLiteOpenHelper{
// Logcat tag
private static final String LOG = "DatabaseHelper";
static final int DATABASE_VERSION=3;
static final String DATABASE_NAME="jobtrack.db";
//common column
static final String COL_EMPLOYEE_ID="employee_id";
static final String COL_READ_FLAG="read_flag";
static final String COL_MEM_STATUS="mem_status";
static final String COL_EMAIL_WANT="email_want";
static final String COL_VISIBLE="visible";
static final String COL_CREATED_BY="created_by";
static final String COL_CREATED_TIME="created_time";
static final String COL_TASK_ID="task_id";
static final String COL_STATUS="status";
static final String COL_ROLE="role";
static final String COL_JOB_ID="COL_JOB_ID";
static final String COL_UPDATE_BY="COL_UPDCOL_UPDATED_TIME";
// Table `hrm_designation`
static final String TABLE_HRM_DESIGNATION="hrm_designation";
static final String COL_DESIGNATION_ID="desig_id";
static final String COL_DESIGNATION="designation";
static final String COL_VIEW_ORDER="view_order";
static final String COL_DESIG_CREATED_BY="created_by";
static final String COL_DESIG_CREATED_TIME="created_time";
static final String COL_DESIG_MODIFIED_BY="modified_by";
static final String COL_DESIG_MODIFIED_TIME="modified_time";
String CREATE_TABLE_HRM_DESIGNATION=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_DESIGNATION + " ( "
+ COL_DESIGNATION_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL_DESIGNATION +" TEXT ,"
+ COL_VIEW_ORDER +" INTEGER,"
+ COL_DESIG_CREATED_BY +" TEXT,"
+ COL_DESIG_CREATED_TIME +" DATETIME,"
+ COL_DESIG_MODIFIED_BY +" TEXT,"
+ COL_DESIG_MODIFIED_TIME+" DATETIME);";
public boolean insertHRMDesignation( String designation){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_DESIGNATION_ID,desig_id);
contentValues.put(COL_DESIGNATION,designation);
//contentValues.put(COL_VIEW_ORDER,view_order);
//contentValues.put(COL_DESIG_CREATED_BY, created_by);
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//contentValues.put("created_time", dateFormat.format(created_time));
//contentValues.put(COL_DESIG_MODIFIED_BY,modified_by);
//contentValues.put("modified_time", dateFormat.format(modified_time));
//contentValues.put(COL_DESIG_MODIFIED_TIME, modified_time);
long result = db.insert(TABLE_HRM_DESIGNATION,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
/*public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_HRM_DESIGNATION,null);
return res;
}
*/
static final String TABLE_DEPARTMENT_INFO="department_info";
static final String COL_DEPARTMETN_ID="dept_id";
static final String COL_DEPARTMETN_NAME="dept_name";
String CREATE_TABLE_DEPARTMENT_INFO=" CREATE TABLE IF NOT EXISTS " + TABLE_DEPARTMENT_INFO + " ( "
+ COL_DEPARTMETN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL_DEPARTMETN_NAME +" TEXT UNIQUE);";
public boolean insertHRMDepartment( String designation){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_DESIGNATION_ID,desig_id);
contentValues.put(COL_DESIGNATION,designation);
//contentValues.put(COL_VIEW_ORDER,view_order);
//contentValues.put(COL_DESIG_CREATED_BY, created_by);
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//contentValues.put("created_time", dateFormat.format(created_time));
//contentValues.put(COL_DESIG_MODIFIED_BY,modified_by);
//contentValues.put("modified_time", dateFormat.format(modified_time));
//contentValues.put(COL_DESIG_MODIFIED_TIME, modified_time);
long result = db.insert(TABLE_DEPARTMENT_INFO,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
// TABLE_HRM_EMPLOYEE
static final String TABLE_PERSON_INFO="person_info";
static final String COL_ID="id";
//static final String COL_EMPLOYEE_ID="employee_id";
static final String COL_EMP_NAME="emp_name";
//static final String COL_DESIGNATION_ID="designation_id";
static final String COL_EMP_EMAIL="emp_email";
static final String COL_CURRENT_DEPT_ID="current_dept_id";
static final String COL_CURRENT_BRANCH="current_branch";
static final String COL_REPORTS_TO="reports_to";
static final String COL_ACTIVE="active";
//static final String COL_EMP_CREATED_BY="created_by";
//static final String COL_EMP_CREATED_TIME="created_time";
static final String COL_MODIFIED_BY="modified_by";
static final String COL_MODIFIED_TIME="modified_time";
static final String COL_USER_GROUP_ID="user_group_id";
static final String COL_PASSWORD="password";
static final String COL_AUTHENTICATE_CODE="authenticate_code";
static final String COL_CURRENT_STATUS="current_status";
static final String COL_STATUS_UPDATE_TIME="status_update_time";
String CREATE_TABLE_PERSON_INFO =" CREATE TABLE IF NOT EXISTS " + TABLE_PERSON_INFO + " ( "
+ COL_ID +" INTEGER PRIMARY KEY,"
+ COL_EMPLOYEE_ID +" TEXT ,"
+ COL_EMP_NAME +" TEXT,"
+ COL_EMP_EMAIL +" TEXT,"
+ COL_DESIGNATION_ID +" INTEGER,"
+ COL_CURRENT_DEPT_ID +" INTEGER,"
+ COL_CURRENT_BRANCH +" INTEGER,"
+ COL_REPORTS_TO +" TEXT,"
+ COL_ACTIVE +" TEXT,"
+ COL_CREATED_BY +" TEXT,"
+ COL_CREATED_TIME +" DATETIME,"
+ COL_MODIFIED_BY +" TEXT,"
+ COL_MODIFIED_TIME +" DATETIME,"
+ COL_USER_GROUP_ID +" INTEGER,"
+ COL_PASSWORD +" TEXT,"
+ COL_AUTHENTICATE_CODE +" TEXT,"
+ COL_CURRENT_STATUS +" TEXT,"
+ COL_STATUS_UPDATE_TIME+" DATETIME, "
+ " FOREIGN KEY ("+COL_CURRENT_DEPT_ID+") REFERENCES "+TABLE_DEPARTMENT_INFO+"("+COL_DEPARTMENT_ID+")"
+ " FOREIGN KEY ("+COL_DESIGNATION_ID+") REFERENCES "+TABLE_HRM_DESIGNATION+"("+COL_DESIGNATION_ID+"));";
public boolean insertHRMPersonInfo(String employee_id, String emp_name, String emp_email,
String current_dept_id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_ID,id);
contentValues.put(COL_EMPLOYEE_ID,employee_id);
contentValues.put(COL_EMP_NAME, emp_name);
contentValues.put(COL_EMP_EMAIL, emp_email);
//contentValues.put(COL_DEPARTMENT_ID,designation_id);
contentValues.put(COL_CURRENT_DEPT_ID,current_dept_id);
//contentValues.put(COL_CURRENT_BRANCH, current_branch);
/*contentValues.put(COL_REPORTS_TO,reports_to);
contentValues.put(COL_ACTIVE,active);
contentValues.put(COL_CREATED_BY, created_by);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
contentValues.put("created_time", dateFormat.format(created_time));
contentValues.put(COL_DESIG_MODIFIED_BY,modified_by);
contentValues.put("modified_time", dateFormat.format(modified_time));
contentValues.put(COL_USER_GROUP_ID,user_group_id);
contentValues.put(COL_PASSWORD,password);
contentValues.put(COL_AUTHENTICATE_CODE, authenticate_code);
contentValues.put(COL_CURRENT_STATUS,current_status);
contentValues.put("status_update_time", dateFormat.format(status_update_time));*/
long result = db.insert(TABLE_PERSON_INFO,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_JOB_MEMBER
static final String TABLE_HRM_ORG_JOB_MEMBER="hrm_org_job_member";
//static final String COL_JOB_ID="job_id";
//static final String COL_EMPLOYEE_ID="employee_id";
//static final String COL_ROLE="role";
//static final String COL_READ_FLAG="read_flag";
//static final String COL_MEM_STATUS="mem_status";
//static final String COL_EMAIL_WANT="email_want";
//static final String COL_VISIBLE="visible";
String CREATE_TABLE_HRM_ORG_JOB_MEMBER =" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_JOB_MEMBER + " ( "
+ COL_JOB_ID +" INTEGER,"
+ COL_EMPLOYEE_ID+" INTEGER,"
+ COL_ROLE +" TEXT,"
+ COL_READ_FLAG +" boolean,"
+ COL_MEM_STATUS +" INTEGER,"
+ COL_EMAIL_WANT +" boolean,"
+ COL_VISIBLE+" boolean, "
+ " PRIMARY KEY ("+COL_JOB_ID+","+COL_EMPLOYEE_ID+"), "
+ " FOREIGN KEY ("+COL_ROLE+") REFERENCES "+TABLE_HRM_ROLE+"("+COL_ROLE+"));";
/* "CREATE TABLE IF NOT EXISTS " + TABLE_ATTENDEE +
" (" + COLUMN_Att_Event_ID + " TEXT," +
COLUMN_Att_Email + " TEXT, PRIMARY KEY(" + COLUMN_Att_Event_ID + "," + COLUMN_Att_Email + "))"
*/
public boolean insertHRMJobMember(int job_id, int employee_id, String role, boolean read_flag, int mem_status,
boolean email_want, boolean visible){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_JOB_ID,job_id);
contentValues.put(COL_EMPLOYEE_ID,employee_id);
contentValues.put(COL_ROLE, role);
contentValues.put(COL_READ_FLAG,read_flag);
contentValues.put(COL_MEM_STATUS, mem_status);
contentValues.put(COL_EMAIL_WANT, email_want);
contentValues.put(COL_VISIBLE, visible);
long result = db.insert(TABLE_HRM_ORG_JOB_MEMBER,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_JOB_TRACKER
static final String TABLE_HRM_ORG_JOB_TRACKER="hrm_org_job_tracker";
static final String COL_WHO="who";
static final String COL_WHOM="whom";
//static final String COL_READ_FLAG="read_flag";
//static final String COL_EMAIL_WANT="email_want";
//static final String COL_VISIBLE="visible";
//static final String COL_CREATED_BY="created_by";
//static final String COL_CREATED_TIME="created_time";
String CREATE_TABLE_HRM_ORG_JOB_TRACKER=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_JOB_TRACKER + " ( "
+ COL_WHO +" INTEGER ,"
+ COL_WHOM +" INTEGER ,"
+ COL_READ_FLAG +" TEXT,"
+ COL_EMAIL_WANT +" boolean,"
+ COL_VISIBLE +" boolean,"
+ COL_CREATED_BY +" TEXT,"
+ COL_CREATED_TIME+" DATETIME, "
+ " PRIMARY KEY (" + COL_WHO + "," + COL_WHOM + "));";
public boolean insertHRMOrgJobTracker(int who, int whom, int read_flag, boolean email_want, boolean visible,
String created_by, Date created_time){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_WHO,who);
contentValues.put(COL_WHOM,whom);
contentValues.put(COL_READ_FLAG,read_flag);
contentValues.put(COL_EMAIL_WANT,email_want);
contentValues.put(COL_VISIBLE,visible);
contentValues.put(COL_CREATED_BY, created_by);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
contentValues.put("created_time", dateFormat.format(created_time));
long result = db.insert(TABLE_HRM_ORG_JOB_TRACKER,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_PRIORITY
static final String TABLE_HRM_ORG_PRIORITY="hrm_org_priority";
static final String COL_PRIORITY_NO="priority_no";
static final String COL_PRIORITY_NAME="priority_name";
String CREATE_TABLE_HRM_ORG_PRIORITY=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_PRIORITY + " ( "
+ COL_PRIORITY_NO +" INTEGER PRIMARY KEY,"
+ COL_PRIORITY_NAME+" TEXT);";
public boolean insertHRMOrgPriority(int priority_no, String priority_name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_PRIORITY_NO,priority_no);
contentValues.put(COL_PRIORITY_NAME,priority_name);
long result = db.insert(TABLE_HRM_ORG_PRIORITY,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_TASK
static final String TABLE_HRM_ORG_TASK="hrm_org_task";
//static final String COL_TASK_ID="task_id";
static final String COL_TASK_TITLE="task_title";
static final String COL_TASK_DESCRIPTION="task_description";
static final String COL_START_DATE="startdate";
static final String COL_ESTIMATED_DATE="estimated_date";
static final String COL_ACTUAL_ENDDATE="actual_enddate";
//static final String COL_STATUS="status";
static final String COL_PERCENT_DONE="percent_done";
static final String COL_PRIORITY="priority";
static final String COL_OWNER_COMMENTS="owner_comments";
static final String COL_INCHARGE_COMMENTS="incharge_comments";
static final String COL_TASK_OWNER_ID="task_owner_id";
//static final String COL_JOB_ID="job_id";
static final String COL_ACCESIBILITY="accesibility";
static final String COL_PREV_OWNER_ID="prev_owner_id";
//static final String COL_CREATED_BY="created_by";
//static final String COL_CREATED_TIME="created_time";
//static final String COL_UPDATE_BY="update_by";
//static final String COL_UPDATE_TIME="updated_time";
String CREATE_TABLE_HRM_ORG_TASK=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_TASK + " ( "
+ COL_TASK_ID +" INTEGER PRIMARY KEY,"
+ COL_TASK_TITLE +" TEXT,"
+ COL_TASK_DESCRIPTION +" TEXT,"
+ COL_START_DATE +" DATETIME,"
+ COL_ESTIMATED_DATE +" DATETIME,"
+ COL_ACTUAL_ENDDATE +" DATETIME,"
+ COL_STATUS +" TEXT,"
+ COL_PERCENT_DONE +" TEXT,"
+ COL_PRIORITY +" TEXT,"
+ COL_OWNER_COMMENTS +" TEXT,"
+ COL_INCHARGE_COMMENTS +" TEXT,"
+ COL_TASK_OWNER_ID +" TEXT,"
+ COL_JOB_ID +" TEXT,"
+ COL_ACCESIBILITY +" TEXT,"
+ COL_PREV_OWNER_ID +" TEXT,"
+ COL_CREATED_BY +" TEXT,"
+ COL_CREATED_TIME +" DATETIME,"
+ COL_UPDATE_BY +" TEXT,"
+ COL_UPDATE_TIME+" DATETIME, "
+ " FOREIGN KEY ("+COL_STATUS+") REFERENCES "+TABLE_HRM_ORG_TASK_STATUS+"("+COL_STATUS+")"
+ " FOREIGN KEY ("+COL_PRIORITY+") REFERENCES "+TABLE_HRM_ORG_PRIORITY+"("+COL_PRIORITY+")"
+ " FOREIGN KEY ("+COL_JOB_ID+") REFERENCES "+TABLE_JOB_MANAGEMENT+"("+COL_JOB_ID+"));";
public boolean insertHRMOrgTask(int task_id, String task_title, String task_description, Date startdate, Date estimated_date,
Date actual_enddate, String status, int percent_done, int priority, String owner_comments,
String incharge_comments, int task_owner_id, int job_id, int accesibility, int prev_owner_id, int created_by,
Date created_time, int update_by, Date updated_time){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_TASK_ID,task_id);
contentValues.put(COL_TASK_TITLE,task_title);
contentValues.put(COL_TASK_DESCRIPTION,task_description);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
contentValues.put("startdate", dateFormat.format(startdate));
contentValues.put("estimated_date", dateFormat.format(estimated_date));
contentValues.put("actual_enddate", dateFormat.format(actual_enddate));
contentValues.put(COL_STATUS,status);
contentValues.put(COL_PERCENT_DONE,percent_done);
contentValues.put(COL_PRIORITY,priority);
contentValues.put(COL_OWNER_COMMENTS,owner_comments);
contentValues.put(COL_INCHARGE_COMMENTS,incharge_comments);
contentValues.put(COL_TASK_OWNER_ID,task_owner_id);
contentValues.put(COL_JOB_ID,job_id);
contentValues.put(COL_ACCESIBILITY,accesibility);
contentValues.put(COL_PREV_OWNER_ID,prev_owner_id);
contentValues.put(COL_CREATED_BY, created_by);
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
contentValues.put("created_time", dateFormat.format(created_time));
contentValues.put(COL_UPDATE_BY, update_by);
contentValues.put("updated_time", dateFormat.format(updated_time));
long result = db.insert(TABLE_HRM_ORG_TASK,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_TASK_ACTIVITIES
static final String TABLE_HRM_ORG_TASK_ACTIVITIES="hrm_org_task_activities";
static final String COL_ACTIVITY_ID="activity_id";
//static final String COL_TASK_ID="task_id";
static final String COL_DATE="date";
static final String COL_ACTIVITY_DESC="activity_desc";
static final String COL_ACTIVITY_GRADE="activity_grade";
static final String COL_ACTIVITY_GRADE_BY="activity_grade_by";
static final String COL_COMMENTATOR_ID="commentator_id";
static final String COL_PERFORMED_BY="performed_by";
static final String COL_APP="app";
static final String COL_CLIENT_IP="client_ip";
static final String COL_READERS="readers";
static final String COL_PREV_COMMENTATOR_ID="prev_commentator_id";
static final String COL_PREV_PERFORMED_BY="prev_performed_by";
String CREATE_TABLE_HRM_ORG_TASK_ACTIVITIES=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_TASK_ACTIVITIES + " ( "
+ COL_ACTIVITY_ID +" INTEGER PRIMARY KEY,"
+ COL_TASK_ID +" INTEGER,"
+ COL_DATE +" DATETIME,"
+ COL_ACTIVITY_DESC +" TEXT,"
+ COL_ACTIVITY_GRADE +" TEXT,"
+ COL_ACTIVITY_GRADE_BY +" TEXT,"
+ COL_COMMENTATOR_ID +" INTEGER,"
+ COL_PERFORMED_BY +" TEXT,"
+ COL_APP +" TEXT,"
+ COL_CLIENT_IP +" TEXT,"
+ COL_READERS +" TEXT,"
+ COL_PREV_COMMENTATOR_ID +" TEXT,"
+ COL_PREV_PERFORMED_BY +" TEXT, "
+ " FOREIGN KEY ("+COL_TASK_ID+") REFERENCES "+TABLE_HRM_ORG_TASK+"("+COL_TASK_ID+"));";
public boolean insertHRMOrgTaskActivities(int activity_id, int task_id, Date date, String activity_desc, int activity_grade,
String activity_grade_by, int commentator_id, int performed_by, String app,
String client_ip, String readers, int prev_commentator_id, int prev_performed_by){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ACTIVITY_ID,activity_id);
contentValues.put(COL_TASK_ID,task_id);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
contentValues.put("date", dateFormat.format(date));
contentValues.put(COL_ACTIVITY_DESC,activity_desc);
contentValues.put(COL_ACTIVITY_GRADE,activity_grade);
contentValues.put(COL_ACTIVITY_GRADE_BY, activity_grade_by);
contentValues.put(COL_COMMENTATOR_ID,commentator_id);
contentValues.put(COL_PERFORMED_BY,performed_by);
contentValues.put(COL_APP,app);
contentValues.put(COL_CLIENT_IP,client_ip);
contentValues.put(COL_READERS,readers);
contentValues.put(COL_PREV_COMMENTATOR_ID, prev_commentator_id);
contentValues.put(COL_PREV_PERFORMED_BY,prev_performed_by);
long result = db.insert(TABLE_HRM_ORG_TASK_ACTIVITIES,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_TASK_STATUS
static final String TABLE_HRM_ORG_TASK_STATUS="hrm_org_task_status";
//static final String COL_STATUS="status";
static final String COL_STATUS_ID="status_id";
String CREATE_TABLE_HRM_ORG_TASK_STATUS=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_TASK_STATUS + " ( "
+COL_STATUS +" TEXT PRIMARY KEY);";
/*+COL_STATUS_ID +" INTEGER );";*/
public boolean insertHRMOrgTaskStatus(int status_id, String status){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_STATUS_ID,status_id);
contentValues.put(COL_STATUS,status);
long result = db.insert(TABLE_HRM_ORG_TASK_STATUS,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ORG_TASK_TRACKER
static final String TABLE_HRM_ORG_TASK_TRACKER="hrm_org_task_tracker";
//static final String COL_TASK_ID="task_id";
//static final String COL_EMPLOYEE_ID="employee_id";
//static final String COL_ROLE="role";
//static final String COL_READ_FLAG="read_flag";
//static final String COL_MEM_STATUS="mem_status";
//static final String COL_EMAIL_WANT="email_want";
//static final String COL_VISIBLE="visible";
String CREATE_TABLE_HRM_ORG_TASK_TRACKER=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ORG_TASK_TRACKER + " ( "
+ COL_TASK_ID +" INTEGER,"
+ COL_EMPLOYEE_ID +" INTEGER ,"
+ COL_ROLE +" TEXT,"
+ COL_READ_FLAG +" TEXT,"
+ COL_MEM_STATUS +" TEXT,"
+ COL_EMAIL_WANT +" TEXT,"
+ COL_VISIBLE+" TEXT ,"
+ " PRIMARY KEY (" + COL_TASK_ID + "," + COL_EMPLOYEE_ID + "));";
public boolean insertHRMOrgTaskTracker(int task_id, int employee_id, String role, int read_flag, int mem_status, boolean email_want,
boolean visible){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_TASK_ID,task_id);
contentValues.put(COL_EMPLOYEE_ID,employee_id);
contentValues.put(COL_ROLE,role);
contentValues.put(COL_READ_FLAG,read_flag);
contentValues.put(COL_MEM_STATUS,mem_status);
contentValues.put(COL_EMAIL_WANT, email_want);
contentValues.put(COL_VISIBLE, visible);
long result = db.insert(TABLE_HRM_ORG_TASK_TRACKER,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
//TABLE_HRM_ROLE
static final String TABLE_HRM_ROLE="hrm_role";
//static final String COL_ROLE="role";
//static final String COL_ROLE_ID="role_id";
String CREATE_TABLE_HRM_ROLE=" CREATE TABLE IF NOT EXISTS " + TABLE_HRM_ROLE + " ( "
/*+ COL_ROLE_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"*/
+ COL_ROLE +" TEXT PRIMARY KEY);";
public boolean insertHRMRole(String role){
//public boolean insertHRMRole(int role_id, String role){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_ROLE_ID,role_id);
contentValues.put(COL_ROLE,role);
long result = db.insert(TABLE_HRM_ROLE,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
// TABLE_JOB_MANAGEMENT
static final String TABLE_JOB_MANAGEMENT="job_management";
//static final String COL_JOB_ID="job_id";
static final String COL_JOB_TITLE="job_title";
static final String COL_JOB_DESCRIPTION="job_description";
static final String COL_JOB_HAS_DEADLINE="job_has_deadline_";
static final String COL_JOB_STARTDATE="job_startdate";
static final String COL_JOB_ENDDATE="col_job_enddate";
static final String COL_JOB_PROGRESS="col_job_progress";
static final String COL_JOB_PRIORITY="job_priority";
static final String COL_JOB_STATUS="job_status";
static final String COL_DEPARTMENT_ID ="department_id";
//static final String COL_CREATED_BY="created_by";
//static final String COL_CREATED_TIME="created_time";
//static final String COL_UPDATE_BY="update_by";
static final String COL_UPDATE_TIME="update_time";
static final String COL_JOB_OWNER="job_owner";
String CREATE_TABLE_JOB_MANAGEMENT=" CREATE TABLE IF NOT EXISTS " + TABLE_JOB_MANAGEMENT + " ( "
+ COL_JOB_ID +" INTEGER PRIMARY KEY,"
+ COL_JOB_TITLE +" TEXT,"
+ COL_JOB_DESCRIPTION +" TEXT,"
+ COL_JOB_HAS_DEADLINE +" INTEGER,"
+ COL_JOB_STARTDATE +" DATETIME DEFAULT CURRENT_TIMESTAMP,"
+ COL_JOB_ENDDATE +" DATETIME ,"
+ COL_JOB_PROGRESS +" TEXT,"
+ COL_JOB_PRIORITY +" TEXT,"
+ COL_JOB_STATUS +" TEXT,"
+ COL_DEPARTMENT_ID +" INTEGER,"
+ COL_CREATED_BY +" TEXT,"
+ COL_CREATED_TIME +" DATETIME,"
+ COL_UPDATE_BY +" TEXT,"
+ COL_UPDATE_TIME +" DATETIME,"
+ COL_JOB_OWNER +" TEXT,"
+ " FOREIGN KEY ("+COL_DEPARTMENT_ID+") REFERENCES "+TABLE_DEPARTMENT_INFO+"("+COL_DEPARTMENT_ID+"));";
/*public boolean insertJobManagement(int job_id, String job_title, String job_description, int job_has_deadline,
Date job_startdate, Date job_enddate, int job_progress, int job_priority, String job_status,
int department_id, int created_by, Date created_time, int update_by, Date update_time,
int job_owner){*/
public boolean insertJobManagement(String job_title, String job_description, int job_has_deadline, Date job_enddate,
int job_progress, int job_priority, String job_status,
int department_id, int job_owner){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_JOB_ID, job_id);
contentValues.put(COL_JOB_TITLE, job_title);
contentValues.put(COL_JOB_DESCRIPTION,job_description);
contentValues.put(COL_JOB_HAS_DEADLINE, job_has_deadline);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//contentValues.put("job_startdate", dateFormat.format(job_startdate));
//contentValues.put(COL_JOB_STARTDATE, job_startdate);
contentValues.put("job_enddate", dateFormat.format(job_enddate));
//contentValues.put(COL_JOB_ENDDATE, job_enddate);
contentValues.put(COL_JOB_PROGRESS, job_progress);
contentValues.put(COL_JOB_PRIORITY, job_priority);
contentValues.put(COL_JOB_STATUS,job_status);
contentValues.put(COL_DEPARTMENT_ID, department_id);
//contentValues.put(COL_CREATED_BY, created_by);
//contentValues.put("created_time", dateFormat.format(created_time));
//contentValues.put(COL_JOB_ENDDATE, created_time);
//contentValues.put(COL_JOB_ID, update_by);
//contentValues.put("update_time", dateFormat.format(update_time));
//contentValues.put(COL_JOB_TITLE, update_time);
contentValues.put(COL_JOB_OWNER,job_owner);
long result = db.insert(TABLE_JOB_MANAGEMENT,null,contentValues);
if(result ==-1)
return false;
else
return true;
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_TABLE_HRM_DESIGNATION);
db.execSQL(CREATE_TABLE_DEPARTMENT_INFO);
db.execSQL(CREATE_TABLE_PERSON_INFO);
db.execSQL(CREATE_TABLE_HRM_ORG_JOB_MEMBER);
db.execSQL(CREATE_TABLE_HRM_ORG_JOB_TRACKER);
db.execSQL(CREATE_TABLE_HRM_ORG_PRIORITY);
db.execSQL(CREATE_TABLE_HRM_ORG_TASK);
db.execSQL(CREATE_TABLE_HRM_ORG_TASK_ACTIVITIES);
db.execSQL(CREATE_TABLE_HRM_ORG_TASK_STATUS);
db.execSQL(CREATE_TABLE_HRM_ORG_TASK_TRACKER);
db.execSQL(CREATE_TABLE_HRM_ROLE);
db.execSQL(CREATE_TABLE_JOB_MANAGEMENT);
};
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_DESIGNATION);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DEPARTMENT_INFO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSON_INFO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_JOB_MEMBER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_JOB_TRACKER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_PRIORITY);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_TASK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_TASK_ACTIVITIES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_TASK_STATUS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ORG_TASK_TRACKER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HRM_ROLE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_JOB_MANAGEMENT);
onCreate(db);
}
}
|
package gameData.enums;
/**
* Created by corentinl on 1/28/16.
*/
public enum VoiceState {
PROMPT_FOR_INSTRUCTIONS, INITIALIZATION, QUICK_GAME_STARTED, ADVANCED_GAME_STARTED
}
|
/**
* Copyright 2017 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yea.achieve.generator.dto.table;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.yea.achieve.generator.util.StringUtility;
/**
* 基于MybatisGenerator
* @author yiyongfei
*
*/
public class IntrospectedTable {
/** The introspected catalog. */
private String introspectedCatalog;
/** The introspected schema. */
private String introspectedSchema;
/** The introspected table name. */
private String introspectedTableName;
private String humpNamingTable;
private String introspectedfullName;
/** The primary key columns. */
protected List<IntrospectedColumn> primaryKeyColumns;
/** The base columns. */
protected List<IntrospectedColumn> baseColumns;
/** The blob columns. */
protected List<IntrospectedColumn> blobColumns;
/**
* Table remarks retrieved from database metadata
*/
protected String remarks;
/**
* Table type retrieved from database metadata
*/
protected String tableType;
/**
* Instantiates a new introspected table.
*
* @param targetRuntime
* the target runtime
*/
public IntrospectedTable(String catalog, String schema, String tableName) {
primaryKeyColumns = new ArrayList<IntrospectedColumn>();
baseColumns = new ArrayList<IntrospectedColumn>();
blobColumns = new ArrayList<IntrospectedColumn>();
this.introspectedCatalog = catalog;
this.introspectedSchema = schema;
this.introspectedTableName = tableName;
this.introspectedfullName = StringUtility.composeFullyQualifiedTableName(catalog,
schema, tableName, '.');
humpNamingTable = StringUtility.getCamelCaseString(introspectedTableName, true);
}
public String getIntrospectedCatalog() {
return introspectedCatalog;
}
public String getIntrospectedSchema() {
return introspectedSchema;
}
public String getIntrospectedTableName() {
return introspectedTableName;
}
public String getHumpNamingTable() {
return humpNamingTable;
}
/**
* Gets the column.
*
* @param columnName
* the column name
* @return the column
*/
public IntrospectedColumn getColumn(String columnName) {
if (columnName == null) {
return null;
} else {
// search primary key columns
for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {
if (introspectedColumn.isColumnNameDelimited()) {
if (introspectedColumn.getActualColumnName().equals(
columnName)) {
return introspectedColumn;
}
} else {
if (introspectedColumn.getActualColumnName()
.equalsIgnoreCase(columnName)) {
return introspectedColumn;
}
}
}
// search base columns
for (IntrospectedColumn introspectedColumn : baseColumns) {
if (introspectedColumn.isColumnNameDelimited()) {
if (introspectedColumn.getActualColumnName().equals(
columnName)) {
return introspectedColumn;
}
} else {
if (introspectedColumn.getActualColumnName()
.equalsIgnoreCase(columnName)) {
return introspectedColumn;
}
}
}
// search blob columns
for (IntrospectedColumn introspectedColumn : blobColumns) {
if (introspectedColumn.isColumnNameDelimited()) {
if (introspectedColumn.getActualColumnName().equals(
columnName)) {
return introspectedColumn;
}
} else {
if (introspectedColumn.getActualColumnName()
.equalsIgnoreCase(columnName)) {
return introspectedColumn;
}
}
}
return null;
}
}
/**
* Returns true if any of the columns in the table are JDBC Dates (as
* opposed to timestamps).
*
* @return true if the table contains DATE columns
*/
public boolean hasJDBCDateColumns() {
boolean rc = false;
for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {
if (introspectedColumn.isJDBCDateColumn()) {
rc = true;
break;
}
}
if (!rc) {
for (IntrospectedColumn introspectedColumn : baseColumns) {
if (introspectedColumn.isJDBCDateColumn()) {
rc = true;
break;
}
}
}
return rc;
}
/**
* Returns true if any of the columns in the table are JDBC Times (as
* opposed to timestamps).
*
* @return true if the table contains TIME columns
*/
public boolean hasJDBCTimeColumns() {
boolean rc = false;
for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {
if (introspectedColumn.isJDBCTimeColumn()) {
rc = true;
break;
}
}
if (!rc) {
for (IntrospectedColumn introspectedColumn : baseColumns) {
if (introspectedColumn.isJDBCTimeColumn()) {
rc = true;
break;
}
}
}
return rc;
}
/**
* Returns the columns in the primary key. If the generatePrimaryKeyClass()
* method returns false, then these columns will be iterated as the
* parameters of the selectByPrimaryKay and deleteByPrimaryKey methods
*
* @return a List of ColumnDefinition objects for columns in the primary key
*/
public List<IntrospectedColumn> getPrimaryKeyColumns() {
return primaryKeyColumns;
}
/**
* Checks for primary key columns.
*
* @return true, if successful
*/
public boolean hasPrimaryKeyColumns() {
return primaryKeyColumns.size() > 0;
}
/**
* Gets the base columns.
*
* @return the base columns
*/
public List<IntrospectedColumn> getBaseColumns() {
return baseColumns;
}
/**
* Returns all columns in the table (for use by the select by primary key and select by example with BLOBs methods).
*
* @return a List of ColumnDefinition objects for all columns in the table
*/
public List<IntrospectedColumn> getAllColumns() {
List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();
answer.addAll(primaryKeyColumns);
answer.addAll(baseColumns);
answer.addAll(blobColumns);
return answer;
}
/**
* Returns all columns except BLOBs (for use by the select by example without BLOBs method).
*
* @return a List of ColumnDefinition objects for columns in the table that are non BLOBs
*/
public List<IntrospectedColumn> getNonBLOBColumns() {
List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();
answer.addAll(primaryKeyColumns);
answer.addAll(baseColumns);
return answer;
}
/**
* Gets the non blob column count.
*
* @return the non blob column count
*/
public int getNonBLOBColumnCount() {
return primaryKeyColumns.size() + baseColumns.size();
}
/**
* Gets the non primary key columns.
*
* @return the non primary key columns
*/
public List<IntrospectedColumn> getNonPrimaryKeyColumns() {
List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();
answer.addAll(baseColumns);
answer.addAll(blobColumns);
return answer;
}
/**
* Gets the BLOB columns.
*
* @return the BLOB columns
*/
public List<IntrospectedColumn> getBLOBColumns() {
return blobColumns;
}
/**
* Checks for blob columns.
*
* @return true, if successful
*/
public boolean hasBLOBColumns() {
return blobColumns.size() > 0;
}
/**
* Checks for base columns.
*
* @return true, if successful
*/
public boolean hasBaseColumns() {
return baseColumns.size() > 0;
}
/**
* Checks for any columns.
*
* @return true, if successful
*/
public boolean hasAnyColumns() {
return primaryKeyColumns.size() > 0 || baseColumns.size() > 0
|| blobColumns.size() > 0;
}
/**
* Adds the column.
*
* @param introspectedColumn
* the introspected column
*/
public void addColumn(IntrospectedColumn introspectedColumn) {
if (introspectedColumn.isBLOBColumn()) {
blobColumns.add(introspectedColumn);
} else {
baseColumns.add(introspectedColumn);
}
}
/**
* Adds the primary key column.
*
* @param columnName
* the column name
*/
public void addPrimaryKeyColumn(String columnName) {
boolean found = false;
// first search base columns
Iterator<IntrospectedColumn> iter = baseColumns.iterator();
while (iter.hasNext()) {
IntrospectedColumn introspectedColumn = iter.next();
if (introspectedColumn.getActualColumnName().equals(columnName)) {
introspectedColumn.setPrimaryable(true);
primaryKeyColumns.add(introspectedColumn);
iter.remove();
found = true;
break;
}
}
// search blob columns in the weird event that a blob is the primary key
if (!found) {
iter = blobColumns.iterator();
while (iter.hasNext()) {
IntrospectedColumn introspectedColumn = iter.next();
if (introspectedColumn.getActualColumnName().equals(columnName)) {
introspectedColumn.setPrimaryable(true);
primaryKeyColumns.add(introspectedColumn);
iter.remove();
found = true;
break;
}
}
}
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getTableType() {
return tableType;
}
public void setTableType(String tableType) {
this.tableType = tableType;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof IntrospectedTable)) {
return false;
}
return obj.hashCode() == (this.hashCode());
}
@Override
public int hashCode() {
return this.introspectedfullName.hashCode();
}
@Override
public String toString() {
return introspectedfullName;
}
}
|
package com.blue33sun.recipe.utils;
import com.blue33sun.recipe.MainApplication;
import com.blue33sun.recipe.R;
import com.blue33sun.recipe.http.callback.ErrorInfo;
/**
* ClassName:HttpUtils
* Description:Http相关字符串的定义
* Author:lanjing
* Date:2017/10/4 21:45
*/
public class HttpUtils {
public static final int CODE_SUCCESS = 200;
public static final int CODE_EXCEPTION_ERROR = -1;
public static final int CODE_NO_DATA = 0;
public static final String MSG_NO_DATA = MainApplication.getInstance().getString(R.string.msg_empty);
public static ErrorInfo getError(int errorCode, String reason){
ErrorInfo error = new ErrorInfo(errorCode,reason);
return error;
}
public static ErrorInfo getDefaultError( ){
ErrorInfo error = new ErrorInfo(CODE_NO_DATA,MSG_NO_DATA);
return error;
}
public static ErrorInfo getExceptionError(Throwable e){
ErrorInfo error = new ErrorInfo(CODE_EXCEPTION_ERROR,e.getMessage());
return error;
}
}
|
package com.icanit.app;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.unionpay.upomp.lthj.util.PluginHelper;
public class UpompPay{
public static final String CMD_PAY_PLUGIN = "cmd_pay_plugin";
//商户包名
public static final String MERCHANT_PACKAGE = "com.lthj.gq.merchant";
public void start_upomp_pay(Activity thisActivity,String LanchPay){
byte[] to_upomp = LanchPay.getBytes();
Bundle mbundle = new Bundle();
// to_upomp为商户提交的XML
mbundle.putByteArray("xml", to_upomp);
mbundle.putString("action_cmd", CMD_PAY_PLUGIN);
//更换参数调起测试与生产插件,value为true是测试插件 ,为false是生产插件
mbundle.putBoolean("test", false);
Log.d("errorTag","@upomPay");
PluginHelper.LaunchPlugin(thisActivity, mbundle);
}
} |
package br.com.posgraduacao.revendacarros.daos;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import br.com.posgraduacao.revendacarros.models.*;
@Repository
public class TelefoneDAO {
@PersistenceContext
private EntityManager manager;
public List<Telefone> all() {
return manager.createQuery("select t from Telefone t", Telefone.class).getResultList();
}
public void save(Telefone telefone) {
manager.persist(telefone);
}
public Telefone findById(Integer id) {
return manager.find(Telefone.class, id);
}
public void remove(Telefone telefone) {
manager.remove(telefone);
}
public void update(Telefone telefone) {
manager.merge(telefone);
}
public PaginatedList paginated(int page, int max) {
return new PaginatorQueryHelper().list(manager, Telefone.class, page, max);
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package art;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.LockSupport;
import java.util.ListIterator;
import java.util.function.Consumer;
import java.util.function.Function;
public class Test1931 {
public static void printStackTrace(Throwable t) {
System.out.println("Caught exception: " + t);
for (Throwable c = t.getCause(); c != null; c = c.getCause()) {
System.out.println("\tCaused by: " +
(Test1931.class.getPackage().equals(c.getClass().getPackage())
? c.toString() : c.getClass().toString()));
}
}
public static void handleMonitorEnter(Thread thd, Object lock) {
System.out.println(thd.getName() + " contended-LOCKING " + lock);
}
public static void handleMonitorEntered(Thread thd, Object lock) {
System.out.println(thd.getName() + " LOCKED " + lock);
}
public static void handleMonitorWait(Thread thd, Object lock, long timeout) {
System.out.println(thd.getName() + " start-monitor-wait " + lock + " timeout: " + timeout);
}
public static void handleMonitorWaited(Thread thd, Object lock, boolean timed_out) {
System.out.println(thd.getName() + " monitor-waited " + lock + " timed_out: " + timed_out);
}
public static void run() throws Exception {
Monitors.setupMonitorEvents(
Test1931.class,
Test1931.class.getDeclaredMethod("handleMonitorEnter", Thread.class, Object.class),
Test1931.class.getDeclaredMethod("handleMonitorEntered", Thread.class, Object.class),
Test1931.class.getDeclaredMethod("handleMonitorWait",
Thread.class, Object.class, Long.TYPE),
Test1931.class.getDeclaredMethod("handleMonitorWaited",
Thread.class, Object.class, Boolean.TYPE),
Monitors.NamedLock.class,
null);
System.out.println("Testing contended locking.");
testLock(new Monitors.NamedLock("Lock testLock"));
System.out.println("Testing park.");
testPark(new Monitors.NamedLock("Parking blocker object"));
System.out.println("Testing monitor wait.");
testWait(new Monitors.NamedLock("Lock testWait"));
System.out.println("Testing monitor timed wait.");
testTimedWait(new Monitors.NamedLock("Lock testTimedWait"));
System.out.println("Testing monitor timed with timeout.");
testTimedWaitTimeout(new Monitors.NamedLock("Lock testTimedWaitTimeout"));
// TODO It would be good (but annoying) to do this with jasmin/smali in order to test if it's
// different without the reflection.
System.out.println("Waiting on an unlocked monitor.");
testUnlockedWait(new Monitors.NamedLock("Lock testUnlockedWait"));
System.out.println("Waiting with an illegal argument (negative timeout)");
testIllegalWait(new Monitors.NamedLock("Lock testIllegalWait"));
System.out.println("Interrupt a monitor being waited on.");
testInteruptWait(new Monitors.NamedLock("Lock testInteruptWait"));
}
public static void testPark(Object blocker) throws Exception {
Thread holder = new Thread(() -> {
LockSupport.parkNanos(blocker, 10); // Should round up to one millisecond
}, "ParkThread");
holder.start();
holder.join();
}
public static void testInteruptWait(final Monitors.NamedLock lk) throws Exception {
final Monitors.LockController controller1 = new Monitors.LockController(lk);
controller1.DoLock();
controller1.waitForLockToBeHeld();
controller1.DoWait();
controller1.waitForNotifySleep();
try {
controller1.interruptWorker();
controller1.waitForLockToBeHeld();
controller1.DoUnlock();
System.out.println("No Exception thrown!");
} catch (Monitors.TestException e) {
printStackTrace(e);
}
controller1.DoCleanup();
}
public static void testIllegalWait(final Monitors.NamedLock lk) throws Exception {
Monitors.LockController controller1 = new Monitors.LockController(lk, /*timed_wait time*/-100);
controller1.DoLock();
controller1.waitForLockToBeHeld();
try {
controller1.DoTimedWait();
controller1.waitForNotifySleep();
controller1.waitForLockToBeHeld();
controller1.DoUnlock();
System.out.println("No Exception thrown!");
} catch (Monitors.TestException e) {
printStackTrace(e);
}
controller1.DoCleanup();
}
public static void testUnlockedWait(final Monitors.NamedLock lk) throws Exception {
synchronized (lk) {
Thread thd = new Thread(() -> {
try {
Method m = Object.class.getDeclaredMethod("wait");
m.invoke(lk);
} catch (Exception e) {
printStackTrace(e);
}
}, "Unlocked wait thread:");
thd.start();
thd.join();
}
}
public static void testLock(Monitors.NamedLock lk) throws Exception {
Monitors.LockController controller1 = new Monitors.LockController(lk);
Monitors.LockController controller2 = new Monitors.LockController(lk);
controller1.DoLock();
controller1.waitForLockToBeHeld();
controller2.DoLock();
if (controller2.IsLocked()) {
throw new Exception("c2 was able to gain lock while it was held by c1");
}
controller2.waitForContendedSleep();
controller1.DoUnlock();
controller2.waitForLockToBeHeld();
controller2.DoUnlock();
}
public static void testWait(Monitors.NamedLock lk) throws Exception {
Monitors.LockController controller1 = new Monitors.LockController(lk);
Monitors.LockController controller2 = new Monitors.LockController(lk);
controller1.DoLock();
controller1.waitForLockToBeHeld();
controller1.DoWait();
controller1.waitForNotifySleep();
controller2.DoLock();
controller2.waitForLockToBeHeld();
controller2.DoNotifyAll();
controller2.DoUnlock();
controller1.waitForLockToBeHeld();
controller1.DoUnlock();
}
public static void testTimedWait(Monitors.NamedLock lk) throws Exception {
// Time to wait (1 hour). We will wake it up before timeout.
final long millis = 60l * 60l * 1000l;
Monitors.LockController controller1 = new Monitors.LockController(lk, millis);
Monitors.LockController controller2 = new Monitors.LockController(lk);
controller1.DoLock();
controller1.waitForLockToBeHeld();
controller1.DoTimedWait();
controller1.waitForNotifySleep();
controller2.DoLock();
controller2.waitForLockToBeHeld();
controller2.DoNotifyAll();
controller2.DoUnlock();
controller1.waitForLockToBeHeld();
controller1.DoUnlock();
}
public static void testTimedWaitTimeout(Monitors.NamedLock lk) throws Exception {
// Time to wait (10 seconds). We will wait for the timeout.
final long millis = 10l * 1000l;
Monitors.LockController controller1 = new Monitors.LockController(lk, millis);
controller1.DoLock();
controller1.waitForLockToBeHeld();
System.out.println("Waiting for 10 seconds.");
controller1.DoTimedWait();
controller1.waitForNotifySleep();
controller1.DoUnlock();
System.out.println("Wait finished with timeout.");
}
}
|
package com.java1.demo1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class DemoController {
@RequestMapping("/index")
public String index(){
return "a1";
}
public static void main(String args[]){
SpringApplication.run(DemoController.class, args);
}
}
|
package com.ipartek.formacion.nombreproyecto;
import static org.junit.Assert.*;
import org.junit.Test;
public class CajaRegistradoraTest {
@Test
public void test() {
CajaRegistradora caja = new CajaRegistradora();
caja.setPago(10f);
caja.setPrecio(9f);
int[] resul = caja.getaVueltas();
assertEquals("50 mal calculado", 0, resul[0] );
assertEquals( 0, resul[1] );
assertEquals( 0, resul[2] );
assertEquals( 0, resul[3] );
assertEquals( 0, resul[4] );
assertEquals( 1, resul[5] );
assertEquals( 0, resul[6] );
assertEquals( 0, resul[7] );
assertEquals( 0, resul[8] );
assertEquals( 0, resul[9] );
assertEquals( 0, resul[10] );
assertEquals( 0, resul[11] );
caja = new CajaRegistradora();
caja.setPago(2000f);
caja.setPrecio(1326.24f);
resul = caja.getaVueltas();
assertEquals( 13, resul[0] );
assertEquals( 1, resul[1] );
assertEquals( 0, resul[2] );
assertEquals( 0, resul[3] );
assertEquals( 1, resul[4] );
assertEquals( 1, resul[5] );
assertEquals( 1, resul[6] );
assertEquals( 1, resul[7] );
assertEquals( 0, resul[8] );
assertEquals( 1, resul[9] );
assertEquals( 0, resul[10] );
assertEquals( 1, resul[11] );
caja = new CajaRegistradora();
caja.setPago(1f);
caja.setPrecio(0.6f);
resul = caja.getaVueltas();
assertEquals( 0, resul[0] );
assertEquals( 0, resul[1] );
assertEquals( 0, resul[2] );
assertEquals( 0, resul[3] );
assertEquals( 0, resul[4] );
assertEquals( 0, resul[5] );
assertEquals( 0, resul[6] );
assertEquals("20Cnt mal calculado", 2, resul[7] );
assertEquals( 0, resul[8] );
assertEquals( 0, resul[9] );
assertEquals( 0, resul[10] );
assertEquals( 0, resul[11] );
}
}
|
package org.dajlab.mondialrelayapi.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Classe Java pour ret_WSI2_CreationExpedition complex type.
*
* <p>
* Le fragment de schéma suivant indique le contenu attendu figurant dans cette
* classe.
*
* <pre>
* <complexType name="ret_WSI2_CreationExpedition">
* <complexContent>
* <extension base="{http://www.mondialrelay.fr/webservice/}ret_">
* <sequence>
* <element name="ExpeditionNum" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TRI_AgenceCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TRI_Groupe" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TRI_Navette" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TRI_Agence" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TRI_TourneeCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TRI_LivraisonMode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CodesBarres" type="{http://www.mondialrelay.fr/webservice/}ArrayOfString" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ret_WSI2_CreationExpedition", propOrder = { "expeditionNum", "triAgenceCode", "triGroupe",
"triNavette", "triAgence", "triTourneeCode", "triLivraisonMode", "codesBarres" })
public class RetWSI2CreationExpedition extends Ret {
@XmlElement(name = "ExpeditionNum")
protected String expeditionNum;
@XmlElement(name = "TRI_AgenceCode")
protected String triAgenceCode;
@XmlElement(name = "TRI_Groupe")
protected String triGroupe;
@XmlElement(name = "TRI_Navette")
protected String triNavette;
@XmlElement(name = "TRI_Agence")
protected String triAgence;
@XmlElement(name = "TRI_TourneeCode")
protected String triTourneeCode;
@XmlElement(name = "TRI_LivraisonMode")
protected String triLivraisonMode;
@XmlElement(name = "CodesBarres")
protected ArrayOfString codesBarres;
/**
* Obtient la valeur de la propriété expeditionNum.
*
* @return possible object is {@link String }
*
*/
public String getExpeditionNum() {
return expeditionNum;
}
/**
* Définit la valeur de la propriété expeditionNum.
*
* @param value
* allowed object is {@link String }
*
*/
public void setExpeditionNum(String value) {
this.expeditionNum = value;
}
/**
* Obtient la valeur de la propriété triAgenceCode.
*
* @return possible object is {@link String }
*
*/
public String getTRIAgenceCode() {
return triAgenceCode;
}
/**
* Définit la valeur de la propriété triAgenceCode.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTRIAgenceCode(String value) {
this.triAgenceCode = value;
}
/**
* Obtient la valeur de la propriété triGroupe.
*
* @return possible object is {@link String }
*
*/
public String getTRIGroupe() {
return triGroupe;
}
/**
* Définit la valeur de la propriété triGroupe.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTRIGroupe(String value) {
this.triGroupe = value;
}
/**
* Obtient la valeur de la propriété triNavette.
*
* @return possible object is {@link String }
*
*/
public String getTRINavette() {
return triNavette;
}
/**
* Définit la valeur de la propriété triNavette.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTRINavette(String value) {
this.triNavette = value;
}
/**
* Obtient la valeur de la propriété triAgence.
*
* @return possible object is {@link String }
*
*/
public String getTRIAgence() {
return triAgence;
}
/**
* Définit la valeur de la propriété triAgence.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTRIAgence(String value) {
this.triAgence = value;
}
/**
* Obtient la valeur de la propriété triTourneeCode.
*
* @return possible object is {@link String }
*
*/
public String getTRITourneeCode() {
return triTourneeCode;
}
/**
* Définit la valeur de la propriété triTourneeCode.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTRITourneeCode(String value) {
this.triTourneeCode = value;
}
/**
* Obtient la valeur de la propriété triLivraisonMode.
*
* @return possible object is {@link String }
*
*/
public String getTRILivraisonMode() {
return triLivraisonMode;
}
/**
* Définit la valeur de la propriété triLivraisonMode.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTRILivraisonMode(String value) {
this.triLivraisonMode = value;
}
/**
* Obtient la valeur de la propriété codesBarres.
*
* @return possible object is {@link ArrayOfString }
*
*/
public ArrayOfString getCodesBarres() {
return codesBarres;
}
/**
* Définit la valeur de la propriété codesBarres.
*
* @param value
* allowed object is {@link ArrayOfString }
*
*/
public void setCodesBarres(ArrayOfString value) {
this.codesBarres = value;
}
}
|
package com.networks.ghosttears.adapters;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.networks.ghosttears.R;
import com.networks.ghosttears.gameplay_package.ManagingImages;
import com.networks.ghosttears.user_profiles.LeaderboardItem;
import com.networks.ghosttears.user_profiles.LevelAndExp;
import com.networks.ghosttears.user_profiles.ManagingLeaderboards;
import java.util.ArrayList;
/**
* Created by NetWorks on 9/1/2017.
*/
public class LeaderboardRecyclerAdapter extends RecyclerView.Adapter<LeaderboardRecyclerAdapter.LeaderboardHolder>{
private ArrayList<LeaderboardItem> leaderboardItemArrayList;
public LeaderboardRecyclerAdapter(ArrayList<LeaderboardItem> leaderboardItemArrayList){
this.leaderboardItemArrayList = leaderboardItemArrayList;
}
@Override
public int getItemCount() {
return leaderboardItemArrayList.size();
}
@Override
public LeaderboardRecyclerAdapter.LeaderboardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_leaderboard_recycler,parent,false);
return new LeaderboardHolder(inflatedView);
}
@Override
public void onBindViewHolder(LeaderboardRecyclerAdapter.LeaderboardHolder holder, int position) {
final LeaderboardItem leaderboardItem = leaderboardItemArrayList.get(position);
holder.bindLeaderboardItem(leaderboardItem,leaderboardItemArrayList);
}
public static class LeaderboardHolder extends RecyclerView.ViewHolder{
ManagingImages managingImages = new ManagingImages();
ManagingLeaderboards managingLeaderboards = new ManagingLeaderboards();
private ImageView mPositionImageview;
private TextView mPositionTextview;
private ImageView mAvatarImageview;
private TextView mDisplayNameTextview;
private ImageView mOnlineGoldImageview;
private ImageView mOnlineSilverImageview;
private ImageView mOnlineBronzeImageview;
private ImageView mOnlineFourthImageview;
private TextView mOnlineGoldTextview;
private TextView mOnlineSilverTextview;
private TextView mOnlineBronzeTextview;
private TextView mOnlineFourthTextview;
private ImageView mSingleplayerGoldImageview;
private ImageView mSingleplayerSilverImageview;
private TextView mSingleplayerGoldTextview;
private TextView mSingleplayerSilverTextview;
private TextView mExperienceGainedTextview;
private ImageView mExperienceGainedImageview;
private LeaderboardItem mleaderboardItem;
public LeaderboardHolder(View view){
super(view);
mPositionImageview = (ImageView) view.findViewById(R.id.leaderboard_position_imageview);
mPositionTextview = (TextView) view.findViewById(R.id.leaderboard_position_textview);
mAvatarImageview = (ImageView) view.findViewById(R.id.leaderboard_profile_pic);
mDisplayNameTextview = (TextView) view.findViewById(R.id.leaderboard_display_name);
mOnlineGoldImageview = (ImageView) view.findViewById(R.id.first_place_imageview);
mOnlineSilverImageview = (ImageView) view.findViewById(R.id.second_place_imageview);
mOnlineBronzeImageview = (ImageView) view.findViewById(R.id.third_place_imageview);
mOnlineFourthImageview = (ImageView) view.findViewById(R.id.fourth_place_imageview);
mSingleplayerGoldImageview = (ImageView) view.findViewById(R.id.singleplayer_first_place_imageview);
mSingleplayerSilverImageview = (ImageView) view.findViewById(R.id.singleplayer_second_place_imageview);
mOnlineGoldTextview = (TextView) view.findViewById(R.id.first_place_number);
mOnlineSilverTextview = (TextView) view.findViewById(R.id.second_place_number);
mOnlineBronzeTextview = (TextView) view.findViewById(R.id.third_place_number);
mOnlineFourthTextview = (TextView) view.findViewById(R.id.fourth_place_number);
mSingleplayerGoldTextview = (TextView) view.findViewById(R.id.singleplayer_first_place_number);
mSingleplayerSilverTextview = (TextView) view.findViewById(R.id.singleplayer_second_place_number);
mExperienceGainedTextview = (TextView) view.findViewById(R.id.leaderboard_exp_gained);
mExperienceGainedImageview = (ImageView) view.findViewById(R.id.leaderboard_exp_icon);
}
public void bindLeaderboardItem(LeaderboardItem leaderboardItem,ArrayList<LeaderboardItem> mleaderboardItemArrayList){
mleaderboardItem = leaderboardItem;
managingImages.loadImageIntoImageview(R.drawable.first_badge,mOnlineGoldImageview);
managingImages.loadImageIntoImageview(R.drawable.second_badge,mOnlineSilverImageview);
managingImages.loadImageIntoImageview(R.drawable.third_badge,mOnlineBronzeImageview);
managingImages.loadImageIntoImageview(R.drawable.fourth_badge,mOnlineFourthImageview);
managingImages.loadImageIntoImageview(R.drawable.first_badge,mSingleplayerGoldImageview);
managingImages.loadImageIntoImageview(R.drawable.second_badge,mSingleplayerSilverImageview);
managingImages.loadImageIntoImageview(R.drawable.level_toolbar_background,mExperienceGainedImageview);
//reverse postion since firebase ordering is ascending
if(getAdapterPosition()==mleaderboardItemArrayList.size()-1){
managingImages.loadImageIntoImageview(R.drawable.first_badge,mPositionImageview);
}else if(getAdapterPosition()==mleaderboardItemArrayList.size()-2){
managingImages.loadImageIntoImageview(R.drawable.second_badge,mPositionImageview);
}else if(getAdapterPosition()==mleaderboardItemArrayList.size()-3){
managingImages.loadImageIntoImageview(R.drawable.third_badge,mPositionImageview);
} else{
String position = (mleaderboardItemArrayList.size()- (getAdapterPosition()))+"";
mPositionTextview.setText(position);
}
LevelAndExp levelAndExp = new LevelAndExp();
managingImages.loadImageIntoImageview(levelAndExp.getLevelsGhostId(leaderboardItem.getLevel()),mAvatarImageview);
mDisplayNameTextview.setText(leaderboardItem.getDisplayName());
if(FirebaseAuth.getInstance().getCurrentUser().getUid().equalsIgnoreCase(leaderboardItem.getUserId())){
mDisplayNameTextview.setTextColor(Color.GREEN);
}
String number = leaderboardItem.getOnlineMedalsCode();
String numberString = ""+number;
mOnlineGoldTextview.setText(""+managingLeaderboards.getMedalNumber("Online",leaderboardItem.getOnlineMedalsCode(),"Gold"));
mOnlineSilverTextview.setText(""+managingLeaderboards.getMedalNumber("Online",leaderboardItem.getOnlineMedalsCode(),"Silver"));
mOnlineBronzeTextview.setText(""+managingLeaderboards.getMedalNumber("Online",leaderboardItem.getOnlineMedalsCode(),"Bronze"));
mOnlineFourthTextview.setText(""+managingLeaderboards.getMedalNumber("Online",leaderboardItem.getOnlineMedalsCode(),"Paper"));
mSingleplayerGoldTextview.setText(""+managingLeaderboards.getMedalNumber("Singleplayer",leaderboardItem.getSingleplayerMedalsCode(),"Gold"));
mSingleplayerSilverTextview.setText(""+managingLeaderboards.getMedalNumber("Singleplayer",leaderboardItem.getSingleplayerMedalsCode(),"Silver"));
String expGained = ""+leaderboardItem.getExpGained();
mExperienceGainedTextview.setText(expGained);
}
}
}
|
package com.ats.communication_admin.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ats.communication_admin.R;
import com.ats.communication_admin.adapter.NoticeAdapter;
import com.ats.communication_admin.adapter.SuggestionAdapter;
import com.ats.communication_admin.bean.SchedulerList;
import com.ats.communication_admin.bean.SuggestionData;
import com.ats.communication_admin.db.DatabaseHandler;
import com.ats.communication_admin.interfaces.NoticesInterface;
import com.google.gson.Gson;
import java.util.ArrayList;
public class NoticesFragment extends Fragment implements NoticesInterface {
private RecyclerView rvNotices;
DatabaseHandler db;
NoticeAdapter adapter;
ArrayList<SchedulerList> noticesArray;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private BroadcastReceiver mBroadcastReceiver;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notices, container, false);
rvNotices = view.findViewById(R.id.rvNotices);
db = new DatabaseHandler(getActivity());
noticesArray = db.getAllSqliteNotices();
adapter = new NoticeAdapter(noticesArray);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
rvNotices.setLayoutManager(mLayoutManager);
rvNotices.setItemAnimator(new DefaultItemAnimator());
rvNotices.setAdapter(adapter);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("NOTICE_ADMIN")) {
handlePushNotification(intent);
}
}
};
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("REFRESH_DATA")) {
handlePushNotification1(intent);
}
}
};
return view;
}
@Override
public void onPause() {
Log.e("NOTICE", " ON PAUSE");
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mRegistrationBroadcastReceiver);
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
@Override
public void onResume() {
super.onResume();
Log.e("NOTICE", " ON RESUME");
db.updateSuggestionRead();
noticesArray.clear();
noticesArray = db.getAllSqliteNotices();
adapter = new NoticeAdapter(noticesArray);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
rvNotices.setLayoutManager(mLayoutManager);
rvNotices.setItemAnimator(new DefaultItemAnimator());
rvNotices.setAdapter(adapter);
// registering the receiver for new notification
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter("NOTICE_ADMIN"));
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mBroadcastReceiver,
new IntentFilter("REFRESH_DATA"));
}
private void handlePushNotification(Intent intent) {
Log.e("handlePushNotification", "------------------------------------**********");
Gson gson = new Gson();
SchedulerList noticeData = gson.fromJson(intent.getStringExtra("message"), SchedulerList.class);
SchedulerList dbNotice = db.getNotice(noticeData.getSchId());
if (dbNotice.getSchId() == 0) {
Log.e("Msg " + noticeData, "------------------- ");
if (noticeData != null) {
noticesArray.add(0, noticeData);
adapter.notifyDataSetChanged();
}
} else {
for (int i = 0; i < noticesArray.size(); i++) {
if (dbNotice.getSchId() == noticesArray.get(i).getSchId()) {
noticesArray.set(i, noticeData);
db.updateNoticeById(noticeData);
}
}
adapter.notifyDataSetChanged();
}
/* Log.e("Msg " + noticeData, "------------------- ");
if (noticeData != null) {
noticesArray.add(0, noticeData);
adapter.notifyDataSetChanged();
}*/
}
private void handlePushNotification1(Intent intent) {
Log.e("handlePushNotification1", "------------------------------------**********");
adapter.notifyDataSetChanged();
}
@Override
public void fragmentGetVisible() {
db.updateNoticeRead();
noticesArray.clear();
noticesArray = db.getAllSqliteNotices();
adapter = new NoticeAdapter(noticesArray);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
rvNotices.setLayoutManager(mLayoutManager);
rvNotices.setItemAnimator(new DefaultItemAnimator());
rvNotices.setAdapter(adapter);
}
}
|
package br.com.silver.utils;
import java.util.ArrayList;
public interface IReaderCSV {
/**
* Function called after read file
* @param data
*/
public void lineReady(ArrayList<String> data);
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.log;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 日志注册表
*
* @author 小流氓[176543888@qq.com]
* @since 3.4.3
*/
class LoggerRegistry {
private ConcurrentMap<String, AbstractLogger> loggerMap = new ConcurrentHashMap<>();
/**
* 根据一个类来获取日志对象
*
* @param klass 类
* @return 日志对象
*/
public Logger getLogger(Class<?> klass) {
return this.getLogger(klass.getName());
}
/**
* 根据一个名称来获取日志对象
*
* @param name 名称
* @return 日志对象
*/
public Logger getLogger(String name) {
return loggerMap.computeIfAbsent(name, key -> new NoarkAsyncLogger(name));
}
/**
* 根据指定的配置更新所有Logger
*
* @param configurator 当前配置
*/
void updateLoggers(LogConfigurator configurator) {
for (AbstractLogger logger : loggerMap.values()) {
logger.updateConfiguration(configurator);
}
}
} |
package Vistas;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import Controlador.AreaAdministracion;
import Negocio.Socio;
import ViewModels.VistaSocio;
public class FormSocio extends JFrame {
private JPanel pnlContenedor;
private JPanel pnlCentro;
private JButton btnGuardar;
private JLabel lblTitulo;
private JLabel lblNombre;
private JLabel lblDomicilio;
private JLabel lblTelefono;
private JLabel lblMail;
private JTextField txtNombre;
VistaSocio entidad;
private JTextField txtDomicilio;
private JTextField txtTelefono;
private JTextField txtMail;
private int id;
private ListadoSocio lst;
FormSocio that = this;
public FormSocio(String frameTitle, int idSocio, ListadoSocio lst) {
this.id = idSocio;
this.lst = lst;
this.entidad = null;
// Establecer el titulo de la ventana
this.setTitle(frameTitle);
// Establecer la dimension de la ventana (ancho, alto)
this.setSize(400, 250);
// Establecer NO dimensionable la ventana
this.setResizable(false);
// Ubicar la ventana en el centro de la pantalla
this.setLocationRelativeTo(null);
// Agregar el panel al JFrame
this.getContentPane().add(this.getPanelContenedor());
if (idSocio != -1) {
VistaSocio socioAEditar = null;
for (VistaSocio currentVistaSocio : lst.items) {
if (currentVistaSocio.getIdSocio() == id) {
this.entidad = currentVistaSocio;
break;
}
}
bindView();
}
// Mostrar la ventana
this.setVisible(true);
}
private void bindView() {
txtNombre.setText(entidad.getNombre());
txtDomicilio.setText(entidad.getDomicilio());
txtTelefono.setText(entidad.getTelefono());
txtMail.setText(entidad.getMail());
}
private JPanel getPanelContenedor() {
pnlContenedor = new JPanel();
pnlContenedor.setLayout(new BorderLayout());
if (this.id == -1)
lblTitulo = new JLabel("Alta Socio");
else
lblTitulo = new JLabel("Editar Socio");
lblTitulo.setFont(new Font("Serif", Font.BOLD, 20));
lblTitulo.setHorizontalAlignment(JLabel.CENTER);
pnlContenedor.add(lblTitulo, BorderLayout.PAGE_START);
pnlContenedor.add(getPanelCentro(), BorderLayout.CENTER);
return pnlContenedor;
}
private JPanel getPanelCentro() {
pnlCentro = new JPanel();
pnlCentro.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
lblNombre = new JLabel("Nombre:");
lblNombre.setHorizontalAlignment(JLabel.RIGHT);
gbc.gridx = 0; // n�mero columna
gbc.gridy = 0; // n�mero fila
gbc.gridwidth = 1; // numero de columnas de ancho
gbc.gridheight = 1; // numero de filas de ancho
gbc.weightx = 0.1;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL; // rellenar la celda en ambos sentidos (horizontal y vertical)
gbc.insets = new Insets(3, 3, 3, 3); // definir el relleno exterior
pnlCentro.add(lblNombre, gbc); // agregar el label al panel contenedor
txtNombre = new JTextField();
gbc.gridx = 1; // n�mero columna
gbc.gridy = 0; // n�mero fila
gbc.weightx = 0.9;
pnlCentro.add(txtNombre, gbc); // agregar el textField al panel contenedor
lblDomicilio = new JLabel("Domicilio:");
lblDomicilio.setHorizontalAlignment(JLabel.RIGHT);
gbc.gridx = 0; // n�mero columna
gbc.gridy = 1; // n�mero fila
gbc.weightx = 0.1;
pnlCentro.add(lblDomicilio, gbc); // agregar el label al panel contenedor
txtDomicilio = new JTextField();
gbc.gridx = 1; // n�mero columna
gbc.gridy = 1; // n�mero fila
gbc.weightx = 0.9;
pnlCentro.add(txtDomicilio, gbc); // agregar el textField al panel contenedor
lblTelefono = new JLabel("Telefono:");
lblTelefono.setHorizontalAlignment(JLabel.RIGHT);
gbc.gridx = 0; // n�mero columna
gbc.gridy = 2; // n�mero fila
gbc.weightx = 0.1;
pnlCentro.add(lblTelefono, gbc); // agregar el label al panel contenedor
txtTelefono = new JTextField();
gbc.gridx = 1; // n�mero columna
gbc.gridy = 2; // n�mero fila
gbc.weightx = 0.9;
pnlCentro.add(txtTelefono, gbc); // agregar el textField al panel contenedor
lblMail = new JLabel("Mail:");
lblMail.setHorizontalAlignment(JLabel.RIGHT);
gbc.gridx = 0; // n�mero columna
gbc.gridy = 3; // n�mero fila
gbc.weightx = 0.1;
pnlCentro.add(lblMail, gbc); // agregar el label al panel contenedor
txtMail = new JTextField();
gbc.gridx = 1; // n�mero columna
gbc.gridy = 3; // n�mero fila
gbc.weightx = 0.9;
pnlCentro.add(txtMail, gbc); // agregar el textField al panel contenedor
btnGuardar = new JButton("Guardar");
btnGuardar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (txtNombre.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Por favor ingrese el nombre");
txtNombre.requestFocusInWindow();
return;
}
if (txtDomicilio.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Por favor ingrese el domicilio");
txtDomicilio.requestFocusInWindow();
return;
}
if (txtTelefono.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Por favor ingrese el tel�fono");
txtTelefono.requestFocusInWindow();
return;
}
if (txtMail.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Por favor ingrese el mail");
txtMail.requestFocusInWindow();
return;
}
if (id == -1)
AreaAdministracion.getInstancia().agregarSocio(txtNombre.getText(), txtDomicilio.getText(),
txtTelefono.getText(), txtMail.getText());
else {
try {
AreaAdministracion.getInstancia().modificarSocio(entidad.getIdSocio(), txtNombre.getText(),
txtDomicilio.getText(), txtTelefono.getText(), txtMail.getText());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
closeWin();
}
});
gbc.gridx = 0; // n�mero columna
gbc.gridy = 4; // n�mero fila
gbc.gridwidth = 2; // numero de columnas de ancho
gbc.fill = GridBagConstraints.NONE; // rellenar la celda en ambos sentidos (horizontal y vertical)
pnlCentro.add(btnGuardar, gbc); // agregar el textField al panel contenedor
return pnlCentro;
}
private void closeWin() {
this.setVisible(false);
lst.fillTable("");
this.dispose();
}
}
|
package com.my_music.Acitity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.my_music.Adapter.RecyclerViewAdapter;
import com.my_music.Beans.ThemeBean;
import com.my_music.HttpData;
import com.my_music.R;
import com.my_music.Theme.Themes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MXY on 2018/3/18.
*/
public class Fragment_tuijian extends Fragment {
private static final String TAG = "Fragment_tuijian";
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mRecyclerViewAdapter;
private ArrayList<ThemeBean> fruits;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tuijian, container, false);
mRecyclerView = rootView.findViewById(R.id.RecyclerView);
new Thread(mRunnable).start();
return rootView;
}
private Runnable mRunnable = new Runnable() {
public void run() {
String data = HttpData.Query();
try {
JSONArray jsonArray = new JSONArray(data);
fruits = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String music_zt = jsonObject.getString("music_zt");
String music_zt_title = jsonObject.getString("music_zt_title");
String music_zt_image = jsonObject.getString("music_zt_image");
String music_zt_time = jsonObject.getString("music_zt_time");
ThemeBean bean = new ThemeBean();
bean.setMusic_zt(music_zt);
bean.setMusic_zt_title(music_zt_title);
bean.setMusic_zt_image(music_zt_image);
bean.setMusic_zt_time(music_zt_time);
fruits.add(bean);
}
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putSerializable("ksy", fruits);
message.setData(bundle);
mHandler.sendMessage(message);
} catch (JSONException e) {
Log.e("错误2", e.toString());
}
}
};
private Handler mHandler = new Handler() {
public void handleMessage(Message message) {
super.handleMessage(message);
final ArrayList<ThemeBean> fruits = (ArrayList<ThemeBean>) message.getData().getSerializable("ksy");
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
mRecyclerViewAdapter = new RecyclerViewAdapter(fruits);
mRecyclerView.setAdapter(mRecyclerViewAdapter);
mRecyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
@SuppressLint("WrongConstant")
@Override
public void onClick(int position) {
Intent intent = new Intent(getActivity(), Themes.class);
Bundle bundle = new Bundle();
bundle.putSerializable("zt", fruits.get(position).getMusic_zt());
bundle.putSerializable("title", fruits.get(position).getMusic_zt_title());
bundle.putSerializable("image", fruits.get(position).getMusic_zt_image());
bundle.putSerializable("time", fruits.get(position).getMusic_zt_time());
intent.putExtras(bundle);
startActivity(intent);
}
});
}
};
}
|
package mf.fssq.mf_part_one.util;
import android.content.Context;
//import android.database.sqlite.SQLiteDatabase;
//import android.database.sqlite.SQLiteOpenHelper;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;
public class DiaryDatabaseHelper extends SQLiteOpenHelper {
private static final String CREATE_DIARY = "create table Diary("
+ "id integer primary key autoincrement, "
+ "time text, "
+ "title text, "
+"week text,"
+ "content text)";
/**
* integer:整形
* real:浮点型
* text:文本类型
* blob:二进制类型
* PRIMARY KEY将id列设置为主键
* AutoIncrement关键字表示id列是自动增长的
*/
public DiaryDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建数据库的同时创建表
db.execSQL(CREATE_DIARY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Diary");
onCreate(db);
}
} |
package net.coderodde.fun.btreemapv1;
public class BTreeMapTest {
}
|
package com.git.cloud.tenant.service;
import java.util.List;
import java.util.Map;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.request.model.vo.VirtualSupplyVo;
import com.git.cloud.tenant.model.po.QuotaPo;
import com.git.cloud.tenant.model.vo.AllQuotaCountVo;
import com.git.cloud.tenant.model.vo.QuotaCountVo;
import com.git.cloud.tenant.model.vo.QuotaVo;
import com.git.cloud.tenant.model.vo.RequestInfo;
public interface ITenantQuotaService {
/**
*获取配额指标
* @param tenantId
* @param
* @return
* @throws RollbackableBizException
*/
public Map<String, List> getQuotaConfigInfo(String tenantId) throws RollbackableBizException;
/**
*根据租户ID验证旗下是否有资源池
* @param tenantId
* @param
* @return
* @throws RollbackableBizException
*/
public String getResPoolByTenantId(String tenantId) throws RollbackableBizException;
/**
*根据租户id获取租户配额
* @param String tenantId
* @return
* @throws RollbackableBizException
*/
public List<QuotaPo> selectQuotaByTenantId(String tenantId) throws RollbackableBizException;
/**
* 添加租户配额
* @param String tenantId,List<QuotaPo> list
* @throws RollbackableBizException
*/
void addQuota(String tenantId,List<QuotaPo> list) throws Exception;
/**
* 修改租户配额
* @param tenantId
* @param List<QuotaPo> list
* @throws RollbackableBizException
*/
void updateQuota(String tenantId, List<QuotaPo> list) throws Exception;
/**
* 单独验证cpu、内存、磁盘、虚拟机数是否符合配额
* @param tenantId
* @param platformTypeCode
* @param reqValue
* @param code
* @return
* @throws RollbackableBizException
*/
public boolean validateQuota(String tenantId,String platformTypeCode,int reqValue,String code)throws RollbackableBizException;
/**
* 统计Power已用cpu、已用内存、已用存储、
* @param tenantId
* @return
*/
public AllQuotaCountVo countPowerUsedQuota(String tenantId) throws RollbackableBizException;
/**
* 统计Openstack已用cpu、已用内存、已用存储、虚机数
* @param tenantId
* @return
*/
public AllQuotaCountVo countOpenstackUsedQuota(String tenantId,String projectId) throws RollbackableBizException;
/**
* 统计Vmware已用cpu、已用内存、已用存储、虚机数
* @param tenantId
* @return
*/
public AllQuotaCountVo countVmwareUsedQuota(String tenantId) throws RollbackableBizException;
/**
* 通过租户id查询所有平台的配额
* @param tenantId
* @return
*/
public List<QuotaVo> getQuotaList(String tenantId) throws RollbackableBizException;
}
|
package db.dao;
import db.connection.DbConnection;
import db.essence.Role;
import db.essence.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserDao extends AbstractDao {
private static final String forAdd = "INSERT INTO user (First_Name, Midle_Name, Last_Name, Passwords, Email, Role) VALUES(?,?,?,?,?,?)";
private static final String forUpdate = "UPDATE user SET First_Name = ?,Midle_Name = ?, Passwords = ?, Role = ? WHERE Last_Name = ?";
private static final String forDelete = "DELETE FROM user WHERE Last_Name = ? ";
private static final String nameTable = "user";
private static final String nameIdforGetById = "id_User";
private static final String nameforDelete = "Last_Name";
public void addUserInDb(String firstname, String midleName, String lastName, String passwords, String email, String role) {
try {
PreparedStatement statement = DbConnection.getConnectionDb().prepareStatement(forAdd);
statement.setString(1, firstname);
statement.setString(2, midleName);
statement.setString(3, lastName);
statement.setString(4, passwords);
statement.setString(5, email);
statement.setString(6, role);
statement.execute();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateByName(String firstname, String midleName, String lastName, String passwords, String role) {
try {
PreparedStatement statement = DbConnection.getConnectionDb().prepareStatement(forUpdate);
statement.setString(1, firstname);
statement.setString(2, midleName);
statement.setString(3, passwords);
statement.setString(4, role);
statement.setString(5, lastName);
statement.execute();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public User getById(long id) {
DbConnection.getConnectionDb();
User user = new User();
ResultSet resultSet = getResultsById(nameTable, nameIdforGetById, id);
try {
if (resultSet != null && resultSet.next()) {
user.setFirstName(resultSet.getString("First_Name") != null ? resultSet.getString("First_Name") : null)
.setMiddleName(resultSet.getString("Midle_Name") != null ? resultSet.getString("Midle_Name") : null)
.setLastName(resultSet.getString("Last_Name")).setPasswords(resultSet.getString("Passwords"))
.setEmail(resultSet.getString("Email")).setRole(Role.valueOf(resultSet.getString("Role").toString().toUpperCase()));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public User deleteByName(String name) {
try {
PreparedStatement preparedStatement = DbConnection.getConnectionDb().prepareStatement(forDelete);
preparedStatement.setString(1, name);
preparedStatement.execute();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//написать джоин
}
|
package Tree;
public class Leaves {
private String color;
private int numberOfLeaves;
private LeafType leafType;
public Leaves(String color, int numberOfLeaves, LeafType leafType) {
this.color = color;
this.numberOfLeaves = numberOfLeaves;
this.leafType = leafType;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getNumberOfLeaves() {
return numberOfLeaves;
}
public void setNumberOfLeaves(int numberOfLeaves) {
this.numberOfLeaves = numberOfLeaves;
}
public LeafType getLeafType() {
return leafType;
}
public void setLeafType(LeafType leafType) {
this.leafType = leafType;
}
}
|
package com.ex.musicdb.web;
import com.ex.musicdb.model.binding.AlbumAddBindingModel;
import com.ex.musicdb.model.binding.CommentAddBindingModel;
import com.ex.musicdb.model.servise.CommentServiceModel;
import com.ex.musicdb.model.view.ArticleViewModel;
import com.ex.musicdb.service.AlbumService;
import com.ex.musicdb.service.CommentService;
import org.modelmapper.ModelMapper;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
@Controller
@RequestMapping("/comments")
public class CommentController {
// private final CommentService commentService;
// private final ModelMapper modelMapper;
// private final AlbumService albumService;
//
//
// public CommentController(CommentService commentService, ModelMapper modelMapper, AlbumService albumService) {
// this.commentService = commentService;
// this.modelMapper = modelMapper;
// this.albumService = albumService;
// }
//
// @ModelAttribute("commentAddBindingModel")
// public CommentAddBindingModel createBindingModel() {
// return new CommentAddBindingModel();
// }
//
// @GetMapping("/add")
// private String addComments(Model model){
// model.addAttribute("comments", commentService.findAllComments());
//
// return "redirect:/";
// }
//
//
//
// @PostMapping("/add/{id}")
// public String details(@Valid CommentAddBindingModel commentAddBindingModel,
// BindingResult bindingResult,
// RedirectAttributes redirectAttributes,
// @PathVariable Long id,
// Model model,
// @AuthenticationPrincipal UserDetails principal){
//
// if(bindingResult.hasErrors()){
// redirectAttributes.addFlashAttribute("commentAddBindingModel", commentAddBindingModel);
// redirectAttributes
// .addFlashAttribute("org.springframework.validation.BindingResult.commentAddBindingModel", bindingResult);
//
// return "redirect:add";
// }
//
// model.addAttribute("comments", commentAddBindingModel);
//
// CommentServiceModel commentServiceModel = modelMapper.map(
// commentAddBindingModel,
// CommentServiceModel.class);
//
// commentServiceModel.setUser(principal.getUsername());
// commentServiceModel.setAlbumEntity(albumService.findEntityById(id).getName());
//
// commentService.createAlbum(commentServiceModel);
//
//
// return "redirect:/home";
// }
}
|
package com.breadTravel.util;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.ResultSet;
public class WorksJson {
public JSONArray getPreviewJson(ResultSet resultSet) {
JSONArray jsonArray = new JSONArray();
try {
while (resultSet.next()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("headImg", resultSet.getString("headImg"));
jsonObject.put("nickName", resultSet.getString("nickName"));
jsonObject.put("worksId", resultSet.getString("worksId"));
jsonObject.put("userName", resultSet.getString("userName"));
jsonObject.put("title", resultSet.getString("title"));
jsonObject.put("keyWords", resultSet.getString("keyWords"));
jsonObject.put("date", resultSet.getString("date"));
jsonObject.put("day", resultSet.getLong("day"));
jsonObject.put("skim", resultSet.getLong("skim"));
jsonObject.put("region", resultSet.getString("region"));
jsonObject.put("coverImg", resultSet.getString("coverImg"));
jsonObject.put("praise", resultSet.getLong("praise"));
jsonArray.put(jsonObject);
}
}catch (Exception e){
e.printStackTrace();
}
return jsonArray;
}
public JSONArray getContentJson(ResultSet resultSet) {
JSONArray jsonArray = new JSONArray();
try {
while (resultSet.next()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("worksId", resultSet.getLong("worksId"));
jsonObject.put("date", resultSet.getString("date"));
jsonObject.put("time", resultSet.getString("time"));
jsonObject.put("location", resultSet.getString("location"));
jsonObject.put("photo", resultSet.getString("photo"));
jsonObject.put("contentText", resultSet.getString("contentText"));
jsonArray.put(jsonObject);
}
}catch (Exception e){
e.printStackTrace();
}
return jsonArray;
}
}
|
/**
* JPA domain objects.
*/
package com.broadcom.websocketsampleapp.domain;
|
package Lector15.Task15_2;
import Other.ReadFromConsole;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.LinkedList;
public class StartTask15_2 {
public void start() {
try {
FileInputStream fileInput = null;
InputStreamReader inputRead = null;
int b = 0;
LinkedList<String> linkedList = new LinkedList<>();
fileInput = new FileInputStream(ReadFromConsole.findFile());
inputRead = new InputStreamReader(fileInput, "Windows-1251");
while ((b = inputRead.read()) != -1) {
if (Character.isSpaceChar((char) b)) {
b = inputRead.read();
if (isVowels((char) b)) {
while (true) {
if ((char) b == ' ' || (char) b == '\n') {
System.out.println(" ");
break;
} else {
System.out.print((char) b);
b = inputRead.read();
}
}
}
}
}
inputRead.close();
fileInput.close();
} catch (Exception excep) {
excep.printStackTrace();
}
}
public static boolean isVowels(char a) {
String z = Character.toString(Character.toLowerCase(a));
return z.matches("a|e|u|i|o|а|у|е|ы|а|о|э|ю|и|я");
}
}
|
/*
* 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 dao;
import dto.UserDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import util.DBUtil;
/**
*
* @author hienl
*/
public class UserDAO {
private final static Logger LOG = Logger.getLogger(UserDAO.class);
public String getNameFromID(String email) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String userName = "";
try {
conn = DBUtil.getCon();
String sql = "SELECT userName FROM tblUser WHERE email = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, email);
rs = ps.executeQuery();
if (rs.next()) {
userName = rs.getString("userName");
}
} catch (SQLException ex) {
LOG.error(ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
}
return userName;
}
public UserDTO checkLogin(String email, String userPass) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
UserDTO dto = null;
try {
conn = DBUtil.getCon();
String sql = "SELECT userName, roleID, email, status FROM tblUser WHERE email = ? AND userPassword = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, email);
ps.setString(2, userPass);
rs = ps.executeQuery();
if (rs.next()) {
String userName = rs.getString("userName");
String roleID = rs.getString("roleID");
boolean status = rs.getBoolean("status");
dto = new UserDTO(email, userName, "", roleID, status);
}
} catch (SQLException ex) {
LOG.error(ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
}
return dto;
}
public void newUser(UserDTO dto) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtil.getCon();
String sql = "INSERT INTO tblUser (email , userName, roleID, userPassword, status) VALUES (?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, dto.getEmail());
ps.setString(2, dto.getUserName());
ps.setString(3, dto.getRoleID());
ps.setString(4, dto.getUserPassword());
ps.setBoolean(5, dto.isStatus());
ps.executeUpdate();
} catch (SQLException ex) {
LOG.error(ex);
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
LOG.error(ex);
}
}
}
}
}
|
package ch11;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class HashSetExam {
public static void main(String[]args) {
Object[] obj= {3,6,4,1,2,3,5,7,4,2,2,8};
Set set=new HashSet();
for(Object oo:obj) {
set.add(oo);
}
System.out.println(set);
Iterator it=set.iterator();//
while(it.hasNext()) {
System.out.println((Integer)it.next());
}
}
}
|
package shapeEx;
public class Mai {
public static void main(String[] args) {
Circle c1 = new Circle();
Square s1 = new Square();
Rectangle r = new Rectangle(2.8,2.5);
//s1=(Rectangle) r;
s1= new Square();
}
}
|
package studioproject.first.my.locationmessageapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.telephony.gsm.SmsManager;
import android.util.Log;
public class MessageReceiver extends BroadcastReceiver
{
String address;
@Override
public void onReceive(Context context, Intent intent)
{
Bundle b=intent.getExtras();
Object obj[]=(Object[])b.get("pdus");
for(int i=0;i<obj.length;i++){
SmsMessage message=SmsMessage.createFromPdu((byte[])obj[i]);
address=message.getOriginatingAddress();
String msg=message.getMessageBody();
}
SmsManager manager=SmsManager.getDefault();
manager.sendTextMessage(address,null,GPSTracker.getAddress(),null,null);
}
}
|
package Main;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
public class Window implements ItemListener {
private MemberDAO dao;
private JFrame frame;
private JTextField txtID, IDtf, PWtf, NAMEtf, m_titleTF, m_yearTF, m_starTF;
private JPanel logpanel, nextpanel_1, nextpanel_genre, nextpanel_year;
// 이미지출력---------------
ImageIcon[] GenreImage = new ImageIcon[5];
int index_g = 0;
JLabel GenreMeet = new JLabel(GenreImage[index_g]);
ImageIcon[] YearImage = new ImageIcon[2];
int index_y = 0;
JLabel YearMeet = new JLabel(YearImage[index_y]);
// jtable-----------------
private JTable tablelist, table_genreselect, table_yearSelected;
static JScrollPane scroll, scroll_genreselect, scroll_yearSelected;
static DefaultTableModel model, model_genreselect, model_yearSelected;
static String[][] tabledata, tabledata_genreselect, tabledata_yearSelected;
static JCheckBox[] checkbox = new JCheckBox[12];
String[] genre = { "판타지", "액션", "로맨스", "개그", "일상", "모험", "순정", "아이돌", "스포츠", "SF", "스릴러", "추리" };
String year[] = { "-------", "2020년", "2019년", "2018년", "2017년", "2016년", "2010년대", "2000년대", "1990년대",
"1990년대 이전" };
String Section[] = { "-------", "1분기", "2분기", "3분기", "4분기" };
String checked;
private Choice yearChoice, SectionChoice;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
dao = new MemberDAO();
frame = new JFrame("LAFTEL");
frame.setSize(650, 900);
// frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().setLayout(null);
LogIn();
}
// 로그인 화면--------------------------------------------------
public void LogIn() {
logpanel = new JPanel();
logpanel.setBounds(0, 0, 632, 853);
// panel을 frame에 추가
frame.getContentPane().add(logpanel);
logpanel.setLayout(null);
logpanel.setBackground(Color.WHITE);
JLabel IDlabel = new JLabel(" ID : ");
IDlabel.setFont(new Font("Arial Black", Font.PLAIN, 20));
IDlabel.setBounds(128, 100, 52, 37);
logpanel.add(IDlabel);
txtID = new JTextField();
txtID.setFont(new Font("굴림", Font.PLAIN, 17));
txtID.setBounds(223, 103, 175, 37);
logpanel.add(txtID);
txtID.setColumns(10);
JLabel Passwordlabel = new JLabel(" PASSWORD : ");
Passwordlabel.setFont(new Font("Arial Black", Font.PLAIN, 20));
Passwordlabel.setBounds(26, 150, 166, 39);
logpanel.add(Passwordlabel);
JPasswordField txtpsw = new JPasswordField();
txtpsw.setFont(new Font("굴림", Font.PLAIN, 17));
txtpsw.setColumns(10);
txtpsw.setBounds(223, 152, 175, 37);
logpanel.add(txtpsw);
JButton logbtn = new JButton("Log In");
logbtn.setIcon(null);
logbtn.setFont(new Font("Arial Black", Font.PLAIN, 17));
logbtn.setBounds(437, 100, 140, 89);
logpanel.add(logbtn);
// 로그인 버튼에 기능 추가-----------------------------------------------------
logbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(txtID.getText());
System.out.println(txtpsw.getText());
if (txtID.getText().equals("") || txtpsw.getText().equals("")) {
JOptionPane.showMessageDialog(null, "아이디 또는 비밀번호를 입력하세요");
} else {
ArrayList<MemberVo> list = dao.list(txtID.getText());
//txtID.setText(txtID.getText());
if (list.size() == 0) {
JOptionPane.showMessageDialog(null, "잘못된 아이디 혹은 비밀번호 입니다.");
} else {
JOptionPane.showMessageDialog(null, "로그인에 성공하였습니다.");
logpanel.setVisible(false);
nextpanel_1();
}
}
}
});
JLabel Ifyoulabel = new JLabel("아직 Laftel회원이 아니신가요?");
Ifyoulabel.setFont(new Font("맑은 고딕", Font.PLAIN, 17));
Ifyoulabel.setVerticalAlignment(SwingConstants.TOP);
Ifyoulabel.setBounds(194, 228, 244, 37);
logpanel.add(Ifyoulabel);
JButton newBtn = new JButton("Register");
newBtn.setFont(new Font("Arial Black", Font.PLAIN, 13));
newBtn.setBounds(437, 223, 140, 37);
logpanel.add(newBtn);
newBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
logpanel.setVisible(false);
Register();
}
});
JLabel LogoLabel = new JLabel();
LogoLabel.setIcon(new ImageIcon("logo_image.jpg"));
LogoLabel.setBounds(26, 26, 140, 50);
logpanel.add(LogoLabel);
JLabel ImageLabel = new JLabel(new ImageIcon("main_image.jpg"));
// ImageLabel.setBackground(new Color(255, 255, 255));
ImageLabel.setBounds(0, 325, 632, 528);
logpanel.add(ImageLabel);
JButton btnManagement = new JButton("management");
btnManagement.setFont(new Font("Arial Black", Font.PLAIN, 10));
btnManagement.setBounds(437, 271, 140, 37);
logpanel.add(btnManagement);
JLabel managerlabel = new JLabel("관리자 로그인");
managerlabel.setFont(new Font("맑은 고딕", Font.PLAIN, 17));
managerlabel.setBounds(314, 272, 124, 36);
logpanel.add(managerlabel);
btnManagement.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
logpanel.setVisible(false);
ManagerLogIn();
}
});
}
// 회원 등록-------------------------------------------------------------------
public void Register() {
JPanel RegisterPanel = new JPanel();
RegisterPanel.setBackground(Color.WHITE);
RegisterPanel.setBounds(0, 0, 632, 853);
frame.getContentPane().add(RegisterPanel);
RegisterPanel.setLayout(null);
JLabel IDregister = new JLabel("ID :");
IDregister.setBounds(182, 177, 45, 18);
IDregister.setFont(new Font("Arial Black", Font.PLAIN, 22));
RegisterPanel.add(IDregister);
IDtf = new JTextField();
IDtf.setBounds(277, 173, 153, 35);
RegisterPanel.add(IDtf);
IDtf.setColumns(10);
JLabel PWregister = new JLabel("PASSWORD :");
PWregister.setBounds(66, 246, 161, 18);
PWregister.setFont(new Font("Arial Black", Font.PLAIN, 22));
RegisterPanel.add(PWregister);
PWtf = new JTextField();
PWtf.setBounds(277, 242, 153, 35);
RegisterPanel.add(PWtf);
PWtf.setColumns(10);
JLabel NAMEregister = new JLabel("이름");
NAMEregister.setBounds(165, 303, 58, 34);
NAMEregister.setFont(new Font("맑은 고딕", Font.BOLD, 22));
RegisterPanel.add(NAMEregister);
NAMEtf = new JTextField();
NAMEtf.setColumns(10);
NAMEtf.setBounds(277, 307, 153, 35);
RegisterPanel.add(NAMEtf);
JLabel GENREregister = new JLabel("좋아하는 장르");
GENREregister.setBounds(66, 371, 161, 24);
GENREregister.setFont(new Font("맑은 고딕", Font.BOLD, 22));
RegisterPanel.add(GENREregister);
Choice GENREchoice = new Choice();
GENREchoice.setBounds(277, 371, 153, 35);
GENREchoice.setFont(new Font("맑은 고딕", Font.PLAIN, 22));
RegisterPanel.add(GENREchoice);
String[] genre = { "-------", "판타지", "액션", "로맨스", "개그", "일상", "모험", "순정", "아이돌", "스포츠", "SF", "스릴러", "추리" };
for (int i = 0; i < genre.length; i++) {
GENREchoice.add(genre[i]);
}
Button CheckBtn = new Button("중복확인");
CheckBtn.setBounds(485, 173, 96, 35);
RegisterPanel.add(CheckBtn);
CheckBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
JButton REGISTER = new JButton(new ImageIcon("joinus.png"));
REGISTER.setBounds(213, 509, 217, 217);
RegisterPanel.add(REGISTER);
JButton beforebtn = new JButton("뒤로가기");
beforebtn.setBounds(14, 12, 89, 36);
RegisterPanel.add(beforebtn);
beforebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
RegisterPanel.setVisible(false);
logpanel.setVisible(true);
}
});
REGISTER.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (IDtf.getText().equals("") || PWtf.getText().equals("")) {
JOptionPane.showMessageDialog(null, "아이디 혹은 비밀번호를 입력해주세요");
} else if (NAMEtf.getText().equals("")) {
JOptionPane.showMessageDialog(null, "이름을 입력해주세요");
} else if (GENREchoice.getSelectedItem().toString().equals("-------")) {
JOptionPane.showMessageDialog(null, "좋아하는 장르를 선택해주세요");
} else {
ArrayList<MemberVo> list_6 = dao.list_6(IDtf.getText(), PWtf.getText(), NAMEtf.getText(),
GENREchoice.getSelectedItem());
for (int i = 0; i < list_6.size(); i++) {
MemberVo data = (MemberVo) list_6.get(i);
String L_ID = IDtf.getText();
String L_PW = PWtf.getText();
String L_NAME = NAMEtf.getText();
String FAVORITE_GENRE = GENREchoice.getSelectedItem();
// String GENRE = ();
System.out.println(L_ID + " : " + L_PW + " : " + L_NAME + " : " + FAVORITE_GENRE);
}
}
}
});
}
// manager 로그인 메인 -------------------------------------------------------
public void ManagerLogIn() {
JPanel ManagerLogInPanel = new JPanel();
ManagerLogInPanel.setBounds(0, 0, 632, 853);
frame.getContentPane().add(ManagerLogInPanel);
ManagerLogInPanel.setLayout(null);
ManagerLogInPanel.setBackground(Color.WHITE);
JLabel areyoumanager = new JLabel("관리자 로그인");
areyoumanager.setFont(new Font("맑은 고딕", Font.BOLD, 23));
areyoumanager.setBounds(256, 115, 148, 60);
ManagerLogInPanel.add(areyoumanager);
JLabel M_id = new JLabel("ID :");
M_id.setFont(new Font("Arial Black", Font.PLAIN, 27));
M_id.setBounds(117, 206, 113, 47);
ManagerLogInPanel.add(M_id);
JTextField M_id_tf = new JTextField();
M_id_tf.setBounds(316, 206, 206, 47);
ManagerLogInPanel.add(M_id_tf);
M_id_tf.setColumns(10);
JLabel M_pw = new JLabel("PASSWORD :");
M_pw.setFont(new Font("Arial Black", Font.PLAIN, 22));
M_pw.setBounds(117, 299, 185, 47);
ManagerLogInPanel.add(M_pw);
JPasswordField M_pw_tf = new JPasswordField();
M_pw_tf.setColumns(10);
M_pw_tf.setBounds(316, 299, 206, 47);
ManagerLogInPanel.add(M_pw_tf);
JButton M_logbtn = new JButton("LOG IN");
M_logbtn.setFont(new Font("Arial Black", Font.PLAIN, 21));
M_logbtn.setBounds(261, 396, 128, 67);
ManagerLogInPanel.add(M_logbtn);
M_logbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println(M_id_tf.getText());
System.out.println(M_pw_tf.getText());
if (M_id_tf.getText().equals("") || M_pw_tf.getText().equals("")) {
JOptionPane.showMessageDialog(null, "아이디 또는 비밀번호를 입력하세요");
} else {
M_id_tf.setText(M_id_tf.getText());
ArrayList<MemberVo> list_7 = dao.list_7(M_id_tf.getText());
if (list_7.size() == 0) {
JOptionPane.showMessageDialog(null, "잘못된 아이디 혹은 비밀번호 입니다.");
} else {
JOptionPane.showMessageDialog(null, "로그인에 성공하였습니다.");
// M_id_tf.setText(M_id_tf.getText());
ManagerLogInPanel.setVisible(false);
Manager();
}
}
}
});
}
// manager 작품 등록---------------------------------------------------------
public void Manager() {
JPanel RegisterPanel = new JPanel();
RegisterPanel.setBounds(0, 0, 632, 853);
frame.getContentPane().add(RegisterPanel);
RegisterPanel.setLayout(null);
RegisterPanel.setBackground(Color.WHITE);
JLabel insert = new JLabel("작품 등록하기");
insert.setFont(new Font("맑은 고딕", Font.BOLD, 26));
insert.setBounds(223, 70, 197, 52);
RegisterPanel.add(insert);
JButton HomeBtn = new JButton(new ImageIcon("homebtn.png"));
HomeBtn.setBounds(509, 18, 90, 90);
RegisterPanel.add(HomeBtn);
HomeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
RegisterPanel.setVisible(false);
logpanel.setVisible(true);
}
});
JLabel m_title = new JLabel("작품명");
m_title.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
m_title.setBounds(110, 190, 76, 40);
RegisterPanel.add(m_title);
m_titleTF = new JTextField();
m_titleTF.setBounds(251, 193, 191, 40);
m_titleTF.setColumns(50);
RegisterPanel.add(m_titleTF);
JLabel m_genre = new JLabel("장르");
m_genre.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
m_genre.setBounds(110, 242, 76, 39);
RegisterPanel.add(m_genre);
Choice GENREchoice = new Choice();
GENREchoice.setBounds(251, 244, 191, 40);
GENREchoice.setFont(new Font("맑은 고딕", Font.PLAIN, 22));
RegisterPanel.add(GENREchoice);
String[] genre = { "-------", "판타지", "액션", "로맨스", "개그", "일상", "모험", "순정", "아이돌", "스포츠", "SF", "스릴러", "추리" };
for (int i = 0; i < genre.length; i++) {
GENREchoice.add(genre[i]);
}
JLabel m_year = new JLabel("연도");
m_year.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
m_year.setBounds(110, 293, 76, 40);
RegisterPanel.add(m_year);
// year choice박스--------------------------------------------------------
yearChoice = new Choice();
yearChoice.setBounds(251, 296, 122, 37);
yearChoice.setFont(new Font("맑은 고딕", Font.PLAIN, 22));
for (int i = 0; i < year.length; i++) {
yearChoice.add(year[i]);
}
RegisterPanel.add(yearChoice);
// 분기 choicebox생성---------------------------------------------------
SectionChoice = new Choice();
SectionChoice.setFont(new Font("맑은 고딕", Font.PLAIN, 22));
SectionChoice.setBounds(405, 296, 122, 37);
for (int i = 0; i < Section.length; i++) {
SectionChoice.add(Section[i]);
}
RegisterPanel.add(SectionChoice);
JLabel m_star = new JLabel("평가(별점)");
m_star.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
m_star.setBounds(110, 345, 105, 40);
RegisterPanel.add(m_star);
m_starTF = new JTextField();
m_starTF.setColumns(10);
m_starTF.setBounds(251, 347, 191, 43);
RegisterPanel.add(m_starTF);
JButton InsertBtn = new JButton("등록하기");
InsertBtn.setBounds(223, 442, 197, 90);
RegisterPanel.add(InsertBtn);
InsertBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (m_titleTF.getText().equals("")) {
JOptionPane.showMessageDialog(null, "작품명을 입력해주세요");
} else if (GENREchoice.getSelectedItem().toString().equals("-------")) {
JOptionPane.showMessageDialog(null, "장르를 선택해주세요");
} else if (m_starTF.getText().equals("")) {
JOptionPane.showMessageDialog(null, "평가 점수를 입력해주세요");
} else if (yearChoice.getSelectedItem().toString().equals("-------")
|| SectionChoice.getSelectedItem().toString().equals("-------")) {
JOptionPane.showMessageDialog(null, "연도 및 분기를 선택해주세요");
} else {
ArrayList<MemberVo> list_8 = dao.list_8(m_titleTF.getText(), GENREchoice.getSelectedItem(),
yearChoice.getSelectedItem().toString() + " " + SectionChoice.getSelectedItem().toString(), m_starTF.getText());
for (int i = 0; i < list_8.size(); i++) {
MemberVo data = (MemberVo) list_8.get(i);
String TITLE = m_titleTF.getText();
String GENRE = GENREchoice.getSelectedItem();
String L_YEAR = yearChoice.getSelectedItem().toString() + " " + SectionChoice.getSelectedItem().toString();
String STAR = m_starTF.getText();
// String GENRE = ();
System.out.println(TITLE + " : " + GENRE + " : " + L_YEAR + " : " + STAR);
}
}
}
});
}
// 로그인 성공 화면----------------------------------------------------------------
public void nextpanel_1() {
nextpanel_1 = new JPanel();
nextpanel_1.setBounds(0, 0, 632, 853);
frame.getContentPane().add(nextpanel_1);
nextpanel_1.setLayout(null);
nextpanel_1.setBackground(Color.WHITE);
JLabel welcome = new JLabel(txtID.getText() + "님 반가워요");
welcome.setFont(new Font("맑은 고딕", Font.BOLD, 26));
welcome.setBounds(31, 25, 340, 55);
nextpanel_1.add(welcome);
JButton HomeBtn = new JButton(new ImageIcon("homebtn.png"));
HomeBtn.setBounds(509, 18, 90, 90);
nextpanel_1.add(HomeBtn);
HomeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
nextpanel_1.setVisible(false);
logpanel.setVisible(true);
}
});
tablelist();
JButton searchothers = new JButton(new ImageIcon("meet.png"));
searchothers.setBounds(209, 705, 241, 110);
nextpanel_1.add(searchothers);
JLabel Hellolabel = new JLabel(txtID.getText() + "님이 좋아하실 만한 작품");
Hellolabel.setFont(new Font("굴림", Font.PLAIN, 17));
Hellolabel.setBounds(31, 89, 260, 36);
nextpanel_1.add(Hellolabel);
searchothers.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextpanel_1.setVisible(false);
nextpanel_2();
}
});
}
// 반가워요페이지(작품추천)테이블------------------------------------------------------
private void tablelist() {
ArrayList<MemberVo> list_2 = (ArrayList<MemberVo>) dao.list_2(txtID.getText());
tabledata = new String[list_2.size()][2];
for (int i = 0; i < list_2.size(); i++) {
MemberVo data = (MemberVo) list_2.get(i);
String TITLE = data.getTITLE();
String STAR = data.getSTAR();
for (int j = 0; j < 2; j++) {
if (j == 0) {
tabledata[i][j] = TITLE;
} else if (j == 1) {
tabledata[i][j] = STAR;
}
}
System.out.println(TITLE + " : " + STAR);
}
String column[] = { "제목", "별점" };
model = new DefaultTableModel(tabledata, column);
tablelist = new JTable(model);
// tablelist.getTableHeader().setReorderingAllowed(false);
tablelist.setBounds(14, 91, 454, 428);
scroll = new JScrollPane(tablelist);
scroll.setBounds(31, 137, 573, 532);
nextpanel_1.add(scroll);
}
// 장르별 or 시대별 선택 화면-------------------------------------------------
public void nextpanel_2() {
JPanel nextpanel_2 = new JPanel();
nextpanel_2.setBackground(Color.WHITE);
nextpanel_2.setBounds(0, 0, 632, 853);
frame.getContentPane().add(nextpanel_2);
nextpanel_2.setLayout(null);
JLabel GenreTag = new JLabel("장르별 인기작 만나보기");
GenreTag.setFont(new Font("맑은 고딕", Font.BOLD, 23));
GenreTag.setBounds(186, 12, 251, 39);
nextpanel_2.add(GenreTag);
JLabel YearTag = new JLabel("시대별 인기작 만나보기");
YearTag.setFont(new Font("맑은 고딕", Font.BOLD, 23));
YearTag.setBounds(186, 435, 251, 39);
nextpanel_2.add(YearTag);
JButton GenreGo = new JButton("GO!!");
GenreGo.setFont(new Font("Arial Black", Font.PLAIN, 19));
GenreGo.setBounds(500, 16, 105, 35);
nextpanel_2.add(GenreGo);
JButton YearGo = new JButton("GO!!");
YearGo.setFont(new Font("Arial Black", Font.PLAIN, 19));
YearGo.setBounds(500, 438, 105, 35);
nextpanel_2.add(YearGo);
GenreGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextpanel_2.setVisible(false);
nextpanel_genre();
}
});
YearGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextpanel_year();
nextpanel_2.setVisible(false);
}
});
// 장르 이미지 출력--------------------------------------------------------------
for (int i = 0; i < GenreImage.length; i++) {
GenreImage[i] = new ImageIcon("00" + i + ".png");
GenreMeet.setIcon(GenreImage[i]);
}
GenreMeet.setBounds(14, 61, 604, 355);
nextpanel_2.add(GenreMeet);
JButton GenreMeetBtn = new JButton("");
GenreMeetBtn.setBounds(14, 61, 604, 355);
GenreMeetBtn.setBackground(Color.WHITE);
GenreMeetBtn.setOpaque(false);
nextpanel_2.add(GenreMeetBtn);
GenreMeetBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("클릭");
if (index_g < GenreImage.length) {
GenreMeet.setIcon(GenreImage[index_g++]);
} else {
index_g = 0;
}
}
});
// 연도 이미지 출력--------------------------------------------------------------
for (int i = 0; i < YearImage.length; i++) {
YearImage[i] = new ImageIcon("0" + i + ".png");
YearMeet.setIcon(YearImage[i]);
}
YearMeet.setBounds(14, 486, 604, 355);
nextpanel_2.add(YearMeet);
JButton YearMeetBtn = new JButton("");
YearMeetBtn.setBounds(14, 486, 604, 355);
YearMeetBtn.setBackground(Color.WHITE);
YearMeetBtn.setOpaque(false);
nextpanel_2.add(YearMeetBtn);
YearMeetBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("클릭");
if (index_y < YearImage.length) {
YearMeet.setIcon(YearImage[index_y++]);
} else {
index_y = 0;
}
}
});
JButton beforebtn = new JButton("뒤로가기");
beforebtn.setBounds(14, 12, 89, 36);
nextpanel_2.add(beforebtn);
beforebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextpanel_2.setVisible(false);
nextpanel_1();
}
});
}
// 장르별 인기작 만나보기 화면-------------------------------------------------------
public void nextpanel_genre() {
nextpanel_genre = new JPanel();
nextpanel_genre.setBounds(0, 0, 632, 853);
frame.getContentPane().add(nextpanel_genre);
nextpanel_genre.setLayout(null);
nextpanel_genre.setBackground(Color.WHITE);
JLabel gernelabel = new JLabel("장르별 작품 찾아보기");
gernelabel.setFont(new Font("맑은 고딕", Font.PLAIN, 25));
gernelabel.setBounds(199, 12, 243, 37);
nextpanel_genre.add(gernelabel);
nextpanel_genre.setVisible(true);
JButton beforebtn = new JButton("뒤로가기");
beforebtn.setBounds(14, 12, 89, 36);
nextpanel_genre.add(beforebtn);
beforebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextpanel_genre.setVisible(false);
nextpanel_2();
}
});
for (int i = 0; i < checkbox.length; i++) {
checkbox[i] = new JCheckBox(genre[i]);
checkbox[i].addItemListener(this);
checkbox[i].setFont(new Font("맑은 고딕", Font.BOLD, 17));
checkbox[i].setBackground(Color.WHITE);
checkbox[i].setForeground(Color.BLACK);
nextpanel_genre.add(checkbox[i]);
}
// checkbox setBounds
checkbox[0].setBounds(10, 54, 131, 27);
checkbox[1].setBounds(10, 85, 131, 27);
checkbox[2].setBounds(10, 116, 131, 27);
checkbox[3].setBounds(248, 54, 131, 27);
checkbox[4].setBounds(487, 54, 131, 27);
checkbox[5].setBounds(248, 85, 131, 27);
checkbox[6].setBounds(248, 116, 131, 27);
checkbox[7].setBounds(487, 85, 131, 27);
checkbox[8].setBounds(487, 116, 131, 27);
checkbox[9].setBounds(10, 147, 131, 27);
checkbox[10].setBounds(248, 147, 131, 27);
checkbox[11].setBounds(487, 147, 131, 27);
}
// 테이블 세팅 메서드---------------------------------------------------------------
private void tablelist_genreselect(String checked) {
// System.out.println(checkbox[i]);
ArrayList<MemberVo> list_3 = dao.list_3();
tabledata_genreselect = new String[list_3.size()][2];
for (int i = 0; i < list_3.size(); i++) {
MemberVo data = (MemberVo) list_3.get(i);
System.out.println(checked);
// if(checked.equals(data.getGENRE())) {
// System.out.println(data.getGENRE());
// }
String TITLE = data.getTITLE();
String STAR = data.getSTAR();
for (int j = 0; j < 2; j++) {
if (j == 0) {
tabledata_genreselect[i][j] = TITLE;
} else if (j == 1) {
tabledata_genreselect[i][j] = STAR;
}
System.out.println(TITLE + " : " + STAR);
}
String col[] = { "작품명", "별점" };
model_genreselect = new DefaultTableModel(tabledata_genreselect, col);
table_genreselect = new JTable(model_genreselect);
//table_genreselect.setBounds(14, 91, 454, 428);
scroll_genreselect = new JScrollPane(table_genreselect);
scroll_genreselect.setBounds(10, 199, 608, 642);
// table_genreselect.getTableHeader().setReorderingAllowed(false);
// scroll_genreselect.setViewportView(table_genreselect);
nextpanel_genre.add(scroll_genreselect);
}
// tablelist_genreselect();
}
// 장르 checkbox 이벤트--------------------------------------------------------------
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
Object obj = e.getSource();
// System.out.println(obj + "@@@@@");
for (int i = 0; i < checkbox.length; i++) {
if (obj == checkbox[i]) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("선택ok");
checked = checkbox[i].getText();
tablelist_genreselect(checked);
} else {
System.out.println("선택해제");
checked = checkbox[i].getText();
tablelist_genreselect(checked);
}
}
}
/*
* for (int i = 0; i < checkbox.length; i++) { if (e.getStateChange() ==
* ItemEvent.SELECTED) { if (e.getItem() == checkbox[i]) {
* System.out.println(checkbox[i].getText());
*
* } } else { System.out.println(checkbox[i].getText() + "해제"); } }
*
*/
}
// 시대별 인기작 만나보기 화면--------------------------------------------------------
public void nextpanel_year() {
nextpanel_year = new JPanel();
nextpanel_year.setBounds(0, 0, 632, 853);
frame.getContentPane().add(nextpanel_year);
nextpanel_year.setBackground(Color.WHITE);
nextpanel_year.setLayout(null);
JLabel yearlabel = new JLabel("시대별 인기작 찾아보기");
yearlabel.setBounds(181, 38, 278, 37);
yearlabel.setFont(new Font("맑은 고딕", Font.PLAIN, 25));
nextpanel_year.add(yearlabel);
// 콤보박스 label--------------------------------------------
JLabel YearLabel = new JLabel("연도");
YearLabel.setBounds(61, 115, 49, 37);
YearLabel.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
nextpanel_year.add(YearLabel);
JLabel SectionLabel = new JLabel("분기");
SectionLabel.setBounds(348, 115, 49, 37);
SectionLabel.setFont(new Font("맑은 고딕", Font.PLAIN, 18));
nextpanel_year.add(SectionLabel);
JButton beforebtn = new JButton("뒤로가기");
beforebtn.setBounds(14, 12, 89, 36);
nextpanel_year.add(beforebtn);
beforebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextpanel_year.setVisible(false);
nextpanel_2();
}
});
// year choice박스--------------------------------------------------------
yearChoice = new Choice();
yearChoice.setBounds(124, 115, 144, 36);
yearChoice.setFont(new Font("맑은 고딕", Font.PLAIN, 22));
for (int i = 0; i < year.length; i++) {
yearChoice.add(year[i]);
}
yearChoice.addItemListener(new MyItemListenr_year_choice());
nextpanel_year.add(yearChoice);
// 분기 choicebox생성---------------------------------------------------
SectionChoice = new Choice();
SectionChoice.setFont(new Font("맑은 고딕", Font.PLAIN, 22));
SectionChoice.setBounds(413, 116, 144, 37);
for (int i = 0; i < Section.length; i++) {
SectionChoice.add(Section[i]);
SectionChoice.addItemListener(new MyItemListener_Section_choice());
}
nextpanel_year.add(SectionChoice);
}
// DB - JTable 생성(year)------------------------------------------------------
private void yearTable(String clicked_year) {
// dao = new MemberDAO();
ArrayList<MemberVo> list_4 = (ArrayList<MemberVo>) dao.list_4(clicked_year);
tabledata_yearSelected = new String[list_4.size()][2];
for (int i = 0; i < list_4.size(); i++) {
MemberVo data = (MemberVo) list_4.get(i);
String TITLE = data.getTITLE();
String STAR = data.getSTAR();
for (int j = 0; j < 2; j++) {
if (j == 0) {
tabledata_yearSelected[i][j] = TITLE;
} else if (j == 1) {
tabledata_yearSelected[i][j] = STAR;
}
}
// System.out.println(TITLE + " : " + STAR);
}
String col[] = { "작품명", "별점" };
model_yearSelected = new DefaultTableModel(tabledata_yearSelected, col);
table_yearSelected = new JTable(model_yearSelected);
// table_yearSelected.setBounds(14, 164, 604, 677);
scroll_yearSelected = new JScrollPane(table_yearSelected);
scroll_yearSelected.setBounds(14, 164, 604, 677);
nextpanel_year.add(scroll_yearSelected);
}
// year choice 이벤트-------------------------------------------------
public class MyItemListenr_year_choice implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
System.out.println(e);
if (e.getStateChange() == ItemEvent.SELECTED) {
// System.out.println(yearChoice.getSelectedItem());
yearTable(yearChoice.getSelectedItem());
} else {
System.out.println("해제");
}
}
}
// DB - JTable (분기)------------------------------------------------
private void SectionTable(String clicked_year, String clicked_Section) {
// dao = new MemberDAO();
ArrayList<MemberVo> list_5 = (ArrayList<MemberVo>) dao.list_5(clicked_year, clicked_Section);
tabledata_yearSelected = new String[list_5.size()][2];
for (int i = 0; i < list_5.size(); i++) {
MemberVo data = (MemberVo) list_5.get(i);
String TITLE = data.getTITLE();
String STAR = data.getSTAR();
for (int j = 0; j < 2; j++) {
if (j == 0) {
tabledata_yearSelected[i][j] = TITLE;
} else if (j == 1) {
tabledata_yearSelected[i][j] = STAR;
}
}
System.out.println(TITLE + " : " + STAR);
}
String col[] = { "작품명", "별점" };
model_yearSelected = new DefaultTableModel(tabledata_yearSelected, col);
table_yearSelected = new JTable(model_yearSelected);
// table_yearSelected.setBounds(14, 164, 604, 677);
scroll_yearSelected = new JScrollPane(table_yearSelected);
scroll_yearSelected.setBounds(14, 164, 604, 677);
nextpanel_year.add(scroll_yearSelected);
}
// 분기 choice 이벤트--------------------------------------------------
public class MyItemListener_Section_choice implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println(SectionChoice.getSelectedItem());
SectionTable(yearChoice.getSelectedItem(), SectionChoice.getSelectedItem());
} else {
System.out.println("해제");
}
}
}
}
|
public class circle extends twoDimensionalShape
{
private double radius;
public circle(double r)
{
radius = r;
}
public double getArea()
{
return (Math.PI * radius * radius);
}
@Override
public double getVolume() {
return 0;
}
}
|
package com.cinema.biz.action;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cinema.biz.model.SimLogConfig;
import com.cinema.biz.model.base.TSimLogConfig;
import com.cinema.biz.service.SimLogConfigService;
import com.cinema.sys.action.util.ActionContext;
import com.cinema.sys.action.util.Service;
import com.cinema.sys.service.LogService;
import com.cinema.sys.utils.ExceptionUtil;
import com.cinema.sys.utils.MyParam;
import com.cinema.sys.utils.MyUUID;
import com.cinema.sys.utils.TimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
/**日志记录配置模块Action层*/
@Component
@Service(name = "simLogConfigAction")
public class SimLogConfigAction {
@Autowired
private SimLogConfigService simLogConfigService;
@Autowired
private LogService logService;
/**列表*/
public JSONObject getList(ActionContext cxt) {
Map<String, Object> paraMap = new HashMap<> ();
paraMap.put("startTime", TimeUtil.stringToDate(MyParam.getString(cxt, "startTime")+" 00:00:00"));
paraMap.put("endTime", TimeUtil.stringToDate(MyParam.getString(cxt, "endTime")+" 23:59:59"));
paraMap.put("name", MyParam.getString(cxt, "name"));
paraMap.put("typeFieldId", MyParam.getString(cxt, "typeFieldId"));
paraMap.put("typeId", MyParam.getString(cxt, "typeId"));
//分页查询
PageHelper.startPage(MyParam.getInt(cxt, "page", 1),MyParam.getInt(cxt, "rows", 15));
Page<SimLogConfig> p=(Page<SimLogConfig>)simLogConfigService.getList(paraMap);
JSONObject json = new JSONObject();
json.put("list",p.getResult());
json.put("total", p.getTotal());
return json;
}
/**详情*/
public JSONObject getDetail(ActionContext cxt) {
Map<String, Object> paraMap = new HashMap<> ();
paraMap.put("typeFieldId", MyParam.getString(cxt, "typeFieldId"));
JSONObject json = new JSONObject();
json.put("model",simLogConfigService.getDetail(paraMap));
return json;
}
/**添加*/
public JSONObject insert(ActionContext cxt) {
JSONObject json = new JSONObject();
try {
TSimLogConfig t = JSON.toJavaObject(MyParam.getDataItem(cxt, "dataItem"), TSimLogConfig.class);
t.setTypeFieldId(MyUUID.getUUID());
simLogConfigService.insert(t);
json.put("success", true);
json.put("message","添加日志记录配置成功");
} catch (Exception e) {
e.printStackTrace();
json.put("message", ExceptionUtil.getInsertMessage(e, "添加日志记录配置失败"));
json.put("success", false);
}
logService.addLog("添加日志记录配置", cxt, json);
return json;
}
/**更新*/
public JSONObject update(ActionContext cxt) {
JSONObject json = new JSONObject();
try {
TSimLogConfig t = JSON.toJavaObject(MyParam.getDataItem(cxt, "dataItem"), TSimLogConfig.class);
simLogConfigService.update(t);
json.put("success", true);
json.put("message","修改日志记录配置成功");
} catch (Exception e) {
e.printStackTrace();
json.put("message", ExceptionUtil.getUpdateMessage(e, "修改日志记录配置失败"));
json.put("success", false);
}
logService.addLog("修改日志记录配置", cxt, json);
return json;
}
/**删除*/
public JSONObject delete(ActionContext cxt) {
JSONObject json = new JSONObject();
try {
JSONArray ids = JSON.parseArray(MyParam.getString(cxt, "ids"));
if (ids.size() == 0)
throw new Exception("ids不能为空");
for (int i = 0; i < ids.size(); i++)
simLogConfigService.delete(ids.getString(i));
json.put("success", true);
json.put("message","删除日志记录配置成功");
} catch (Exception ex) {
ex.printStackTrace();
json.put("message", ExceptionUtil.getDeleteMessage(ex, "删除日志记录配置失败"));
json.put("success", false);
}
logService.addLog("删除日志记录配置", cxt, json);
return json;
}
}
|
package com.dokyme.alg4.sorting.priorityqueue;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by intellij IDEA.But customed by hand of Dokyme.
* 2.4.30
*
* @author dokym
* @date 2018/5/17-10:55
* Description:
*/
public class DynamicMedian {
private MinHeap<Integer> highHeap;
private MaxHeap<Integer> lowHeap;
private int n;
public DynamicMedian() {
n = 0;
highHeap = new MinHeap<>(10);
lowHeap = new MaxHeap<>(10);
}
/**
* O(logN)
*
* @param e
*/
public void insert(Integer e) {
n++;
if (highHeap.size() == lowHeap.size()) {
if (!highHeap.isEmpty() && e > highHeap.min()) {
//e比中位数大
lowHeap.insert(highHeap.delMin());
highHeap.insert(e);
} else {
//e比中位数小
lowHeap.insert(e);
}
} else {
//小半部分元素数量大于大半部分元素数量
if (e < lowHeap.max()) {
//e比中位数小
highHeap.insert(lowHeap.delMax());
lowHeap.insert(e);
} else {
//e比中位数大
highHeap.insert(e);
}
}
}
/**
* O(N)
*
* @return
*/
public Double median() {
if (lowHeap.isEmpty()) {
return 0d;
}
if (lowHeap.size() == highHeap.size()) {
return (lowHeap.max() * 1.0 + highHeap.min()) / 2;
} else {
return lowHeap.max() * 1.0;
}
}
/**
* O(logN)
* 这里定义“删除中位数”的语义为:如果总个数为偶数,那么删除最中间的两个元素。
*
* @return
*/
public Double delMedian() {
if (lowHeap.size() == highHeap.size()) {
double mid = median();
lowHeap.delMax();
highHeap.delMin();
return mid;
} else {
//最大堆比最小堆多一个元素。
return lowHeap.delMax() * 1.0;
}
}
public static void main(String[] args) {
DynamicMedian median = new DynamicMedian();
for (int i = 0; i < 10; i++) {
median.insert(i);
}
StdOut.println(median.median());
median.insert(1);
StdOut.println(median.median());
median.insert(2);
StdOut.println(median.median());
}
}
|
package Program_Examples;
public class convert_String_to_Long {
public static void main(String[] args)
{
String str="203456";
//Conversion using parseInt method
long num = Long.parseLong(str);
//Conversion using valueOf method
long num2 = Long.valueOf(str);
//Conversion: Long(String s) constructor
long num3 = new Long(str);
//Displaying variables values
System.out.println(num);
System.out.println(num2);
System.out.println(num3);
}
}
|
package com.atguigu.lgl;
//接口与类之间的多态性
/*interface Usb{
public abstract void satrtu();
public abstract void stopu();
}
interface BlueTooth{
public abstract void satrtb();
public abstract void stopb();
}
//打印机连接鼠标和蓝牙
class Printer implements BlueTooth {
// @Override
// public void satrtu() {
// System.out.println("鼠标 开始 使用了...");
// }
//
// @Override
// public void stopu() {
// System.out.println("鼠标 停止 使用了...");
// }
@Override
public void satrtb() {
System.out.println("蓝牙已经 连接...");
}
@Override
public void stopb() {
System.out.println("蓝牙已经 断开...");
}
}
class ComputerPc{
public void runUsb(Usb usb){
usb.satrtu();
}
public void stopUsb(Usb usb){
usb.stopu();
}
public void runBlueTooth(BlueTooth bt){
bt.satrtb();
}
public void stopBlueTooth(BlueTooth bt){
bt.stopb();
}
}
public class InterfaceTest2_2 {
public static void main(String[] args) {
//方式二
Usb usb2 = new Usb() {
@Override
public void stopu() {
System.out.println("鼠标 停止 运行了");
}
@Override
public void satrtu() {
System.out.println("鼠标 开始 运行了");
}
};
new ComputerPc().runUsb(usb2);
}
}
*/ |
package xyz.javista.config.security;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import xyz.javista.web.dto.UserDTO;
import java.util.Objects;
public class CustomOAuth2Token extends DefaultOAuth2AccessToken {
private UserDTO user;
public CustomOAuth2Token(OAuth2AccessToken accessToken) {
super(accessToken);
}
public UserDTO getUser() {
return user;
}
public void setUser(UserDTO user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
CustomOAuth2Token that = (CustomOAuth2Token) o;
return Objects.equals(user, that.user);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), user);
}
}
|
package com.xixiwan.platform.sys.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xixiwan.platform.module.common.rest.RestResponse;
import com.xixiwan.platform.module.web.constant.WebConsts;
import com.xixiwan.platform.constant.CommonConsts;
import com.xixiwan.platform.exception.WebException;
import com.xixiwan.platform.exception.enums.WebEnum;
import com.xixiwan.platform.sys.entity.SysDict;
import com.xixiwan.platform.sys.form.SysDictForm;
import com.xixiwan.platform.sys.mapper.SysDictMapper;
import com.xixiwan.platform.sys.service.CommonService;
import com.xixiwan.platform.sys.service.ISysDictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 字典表 服务实现类
* </p>
*
* @author Sente
* @since 2018-11-12
*/
@Service
@Transactional
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
@Resource
private CommonService commonService;
@Resource
private SysDictMapper sysDictMapper;
@Override
public IPage<SysDict> selectPage(SysDictForm dictForm) {
dictForm.setSortNames(Lists.newArrayList("code", "num"));
dictForm.setSortOrders(WebConsts.SORTORDER_ASC);
Page<SysDict> page = commonService.getPage(dictForm);
QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
String pcode = dictForm.getPcode();
if (StringUtils.isNotBlank(pcode)) {
queryWrapper.eq("pcode", pcode);
}
String name = dictForm.getName();
if (StringUtils.isNotBlank(name)) {
queryWrapper.like("name", name);
}
IPage<SysDict> iPage = sysDictMapper.selectPage(page, queryWrapper);
if (iPage != null && iPage.getTotal() > 0) {
List<SysDict> list = iPage.getRecords();
for (SysDict sysDict : list) {
sysDict.setPname(commonService.getDictNameByCode(sysDict.getPcode(), CommonConsts.TOP_LEVEL));
}
}
return iPage;
}
@Override
public List<SysDict> selectList(SysDictForm dictForm) {
QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
String pcode = dictForm.getPcode();
if (StringUtils.isNotBlank(pcode)) {
queryWrapper.eq("pcode", pcode);
}
return sysDictMapper.selectList(queryWrapper);
}
@Override
public RestResponse<String> addDict(SysDict dict) {
if (dict == null) {
throw new WebException(WebEnum.ERROR_0002);
}
String code = dict.getCode();
if (StringUtils.isBlank(code)) {
throw new WebException(WebEnum.ERROR_0009);
}
String pcode = dict.getPcode();
if (StringUtils.isBlank(pcode)) {
throw new WebException(WebEnum.ERROR_0038);
}
if (CommonConsts.TOP_LEVEL.equals(pcode)
&& commonService.selectDictByCode(code, CommonConsts.TOP_LEVEL) != null) {
throw new WebException(WebEnum.ERROR_0010);
}
if (sysDictMapper.insert(dict) > 0) {
return RestResponse.success("保存成功");
}
return RestResponse.failure("保存失败");
}
@Override
public RestResponse<String> editDict(SysDict dict) {
if (dict == null) {
throw new WebException(WebEnum.ERROR_0002);
}
Integer id = dict.getId();
if (id == null) {
throw new WebException(WebEnum.ERROR_0011);
}
String code = dict.getCode();
if (StringUtils.isBlank(code)) {
throw new WebException(WebEnum.ERROR_0009);
}
String pcode = dict.getPcode();
if (StringUtils.isBlank(pcode)) {
throw new WebException(WebEnum.ERROR_0038);
}
SysDict sysDict = sysDictMapper.selectById(id);
if (sysDict == null) {
throw new WebException(WebEnum.ERROR_0012);
}
String originalPcode = sysDict.getCode();
if (CommonConsts.TOP_LEVEL.equals(pcode)) {
sysDict = commonService.selectDictByCode(code, CommonConsts.TOP_LEVEL);
if (sysDict != null && !sysDict.getId().equals(id)) {
throw new WebException(WebEnum.ERROR_0010);
}
}
if (sysDictMapper.updateById(dict) > 0) {
// 更新子级条件
SysDict childrenConditionDict = new SysDict();
childrenConditionDict.setPcode(originalPcode);
Wrapper<SysDict> sysDictUpdateWrapper = new QueryWrapper<>(childrenConditionDict);
// 更新子级内容
SysDict childrenContentDict = new SysDict();
childrenContentDict.setPcode(code);
sysDictMapper.update(childrenContentDict, sysDictUpdateWrapper);
return RestResponse.success("修改成功");
}
return RestResponse.failure("修改失败");
}
@Override
public RestResponse<String> deleteDict(SysDictForm dictForm) {
if (dictForm == null) {
throw new WebException(WebEnum.ERROR_0002);
}
Integer[] ids = dictForm.getIds();
if (ids == null || ids.length == 0) {
throw new WebException(WebEnum.ERROR_0011);
}
int num = 0;
for (Integer id : ids) {
SysDict sysDict = sysDictMapper.selectById(id);
if (sysDict == null) {
continue;
}
if (sysDictMapper.deleteById(id) > 0) {
num++;
// 删除子级
SysDict sysDictQuery = new SysDict();
sysDictQuery.setPcode(sysDict.getCode());
Wrapper<SysDict> sysDictQueryWrapper = new QueryWrapper<>(sysDictQuery);
sysDictMapper.delete(sysDictQueryWrapper);
}
}
if (num > 0) {
return RestResponse.success("删除成功");
}
return RestResponse.failure("删除失败");
}
}
|
package Hang.Java.Common.Helpers;
import org.junit.Test;
import static org.junit.Assert.*;
public class LogHelperTest {
@Test
public void testError() throws Exception {
}
@Test
public void testWarn() throws Exception {
}
@Test
public void testInfo() throws Exception {
}
} |
/**
* Created with IntelliJ IDEA.
* User: Boss
* Date: 05.10.13 uhui
* Time: 10:16
* To change this template use File | Settings | File Templates.
*/
public class Antonina {
}
|
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.Optional;
@RepositoryRestResource(path = "foo")
public interface FooRepository extends JpaRepository<FooEntity, Long> {
/**
* Accessible over http://localhost:8080/foo/search/getByIdToProjected?id=1
* @param id Long
* @return Optional<ProjectedFooResult>
*/
@Query(nativeQuery = true, value = "SELECT f.name as name, count(b.id) as barCount FROM foo f LEFT JOIN bar b ON b.foo_id = f.id WHERE f.id = :id")
Optional<ProjectedFooResult> getByIdToProjected(Long id);
}
|
package com.beike.common.enums.trx;
/**
* @Title: CardTopupType.java
* @Package com.beike.common.enums.trx
* @Description: 千品卡充值来源
* @author wh.cheng@sinobogroup.com
* @date May 5, 2011 2:35:06 PM
* @version V1.0
*/
public enum CardTopupChannel {
WEB, // web 网页
WAP, // WAP
IVR;// 电话
}
|
package de.fhdortmund.swt2.pruefungsmeister.Model;
/**
* Created by jonas on 22.05.17.
*/
public enum Resource {
ENERGYDRINK("Energydrink"), FASTFOOD("Fastfood"), EXTRA_POINTS("Bonuspunkte"), KNOW_HOW("Lernstoff"),
TECHNOLOGY("Technik");
private final String description;
Resource(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
|
package gmit;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
public class TestClass {
private Dictionary dc = new Dictionary();
private Map<String, ArrayList<String>> dictionary = dc.parse("dictionary.csv");
public static void main(String[] args) {
// Instantiate TestClass
TestClass tc = new TestClass();
// Scanner object to read user input
Scanner console = new Scanner(System.in);
// Store user input into choice
int choice;
// Print menu
do {
System.out.println("Welcome to the Vocabulary Learning Experience Program.");
System.out.println("Please select the book you want to check a word meaning from.");
System.out.println("1.PoblachNaHEireann.");
System.out.println("2.De Bello Gallico.");
System.out.println("3.War And Peace.");
choice = console.nextInt();
switch (choice) {
case 1:
tc.getWord("PoblachtNaHEireann.txt");
break;
case 2:
tc.getWord("DeBelloGallico.txt");
break;
case 3:
tc.getWord("WarAndPeace-LeoTolstoy.txt");
break;
case -1:
System.exit(1);
break;
default:
System.out.println("Invalid Option");
}
// Exit loop if choice is -1
} while (choice != -1);
}
/*
* getWord takes book url and ask user to input a word to search in the book
* and prints its definition if found and the pages.
*/
public void getWord(String url) {
Scanner scan = new Scanner(System.in);
String searchWord;
try {
WordEntry we = new WordEntry(dictionary);
we = we.parse(url);
do {
System.out.println("Please enter word to search:");
searchWord = scan.next();
System.out.println(we.getWordDefinition(searchWord.toUpperCase()));
System.out.println(we.getWordPages(searchWord.toUpperCase()));
} while (!(searchWord.equals("-1")));
} catch (Exception e) {
e.printStackTrace();
System.out.println("Book File not Found");
}
}
}
|
package net.birelian.poc.di.guice;
import com.google.inject.Guice;
import com.google.inject.Inject;
import net.birelian.poc.di.guice.config.GuiceConfigurationModule;
import net.birelian.poc.di.guice.model.Contact;
import net.birelian.poc.di.guice.service.ContactService;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;
/**
* Main class.
* <p>
* It contains a menu with the next options
* <p>
* 1. Print all contacts
* 2. Create a new contact
* 3. Find a contact by Id
* 4. Find contacts by surname
* 5. Modify a contact
* 6. Delete a contact
* 7. Delete all contacts
* X. Exit application.1
* <p>
* We use the DAO pattern so we can delegate operations with contacts.
*/
public class Agenda {
/** Contact service */
private final ContactService contactService;
/** Scanner for reading user options */
private final Scanner optionReader = new Scanner(System.in);
/**
* Application entry
*
* @param args User args (not used)
*/
public static void main(String[] args) {
Agenda agenda = Guice.createInjector(new GuiceConfigurationModule()).getInstance(Agenda.class);
agenda.run();
}
/**
* Constructor
*
* @param contactService Injected contact service
*/
@Inject
public Agenda(ContactService contactService) {
this.contactService = contactService;
}
/**
* Main agenda method.
*/
private void run() {
String option = "";
while (!option.equals("X")) {
printMenu();
option = optionReader.nextLine();
processOption(option);
}
}
private void printMenu() {
System.out.println("Welcome to the worst Agenda you will ever see\n");
System.out.println("Please choose an option\n");
System.out.println("1. Print all contacts");
System.out.println("2. Create a new contact");
System.out.println("3. Find a contact by Id");
System.out.println("4. Find a contact by surname");
System.out.println("5. Modify a contact");
System.out.println("6. Delete a contact");
System.out.println("7. Delete all contacts");
System.out.println("X. Exit application");
}
private void processOption(String option) {
switch (option) {
case "1":
listAllContacts();
break;
case "2":
createContact();
break;
case "3":
findContactById();
break;
case "4":
findContactsBySurname();
break;
case "5":
modifyContact();
break;
case "6":
deleteContact();
break;
case "7":
deleteAllContacts();
break;
case "X":
exitApplication();
break;
default:
System.out.println("Invalid option");
}
}
private void listAllContacts() {
Collection<Contact> contacts = contactService.findAll(); // Retrieve contacts from DAO
if (contacts.isEmpty()) {
System.out.println("There are no contacts in the database");
} else {
for (Contact contact : contacts) {
System.out.println(contact);
}
}
}
private void createContact() {
Contact contact = new Contact();
readContactInfoFromUserInput(contact);
contactService.save(contact);
System.out.println("Created contact: " + contact);
}
private void findContactById() {
Integer id = getContactIdFromUser();
Contact contact = contactService.findById(id);
if (contact == null) {
System.out.println("Contact not found on the database");
} else {
System.out.println(contact);
}
}
private void findContactsBySurname() {
String surname = getSurnameFromUser();
List<Contact> contacts = contactService.findBySurname(surname);
System.out.println(contacts);
}
private void modifyContact() {
Integer id = getContactIdFromUser();
Contact contact = contactService.findById(id);
if (contact == null) {
System.out.println("Contact not found on the database");
} else {
readContactInfoFromUserInput(contact);
contactService.save(contact);
System.out.println("Saved contact: " + contact);
}
}
private void deleteContact() {
Integer id = getContactIdFromUser();
Contact contact = contactService.findById(id);
if (contact == null) {
System.out.println("Contact not found on the database");
} else {
contactService.delete(contact);
System.out.println("Deleted contact: " + contact);
}
}
private void deleteAllContacts() {
contactService.deleteAll();
System.out.println("All contacts");
}
private void readContactInfoFromUserInput(Contact contact) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the contact name");
contact.setName(reader.nextLine());
System.out.println("Please enter the contact surname");
contact.setSurname(reader.nextLine());
System.out.println("Please enter the contact email");
contact.setEmail(reader.nextLine());
}
private Integer getContactIdFromUser() {
Scanner reader = new Scanner(System.in);
System.out.println("Contact id?: ");
return reader.nextInt();
}
private String getSurnameFromUser() {
Scanner reader = new Scanner(System.in);
System.out.println("Contact surname?: ");
return reader.nextLine();
}
private void exitApplication() {
System.exit(0);
}
}
|
package script.groovy.runtime;
import java.lang.annotation.Annotation;
import java.util.Map;
import script.groovy.runtime.GroovyRuntime.MyGroovyClassLoader;
public interface ClassAnnotationListener {
public abstract Class<? extends Annotation> handleAnnotationClass(GroovyRuntime groovyRuntime);
public abstract void handleAnnotatedClasses(Map<String, Class<?>> annotatedClassMap, MyGroovyClassLoader classLoader);
}
|
package com.sherpa.sherpa.Activites;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.sherpa.sherpa.R;
import java.util.ArrayList;
import java.util.List;
public class SearchSherpa extends AppCompatActivity {
ArrayList<String> userListString;
ArrayList<ParseUser> userlist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_sherpa);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ListView listView = (ListView) findViewById(R.id.listView);
final TextView availableNumber = (TextView) findViewById(R.id.availableNumber);
final EditText editText = (EditText) findViewById(R.id.searchText);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
handled = true;
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> list, ParseException e) {
int i = 0;
int total = 0;
userlist = new ArrayList<>();
userListString = new ArrayList<>();
for (ParseUser user : list) {
if (user.getString("gcity").toLowerCase().equals(editText.getText().toString().toLowerCase()) ||
user.getString("places").toLowerCase().contains(editText.getText().toString().toLowerCase())) {
total++;
if (user.getBoolean("available")) {
userlist.add(user);
i++;
userListString.add(user.getString("firstname") + " " + user.getString("lastname"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(SearchSherpa.this,
android.R.layout.simple_list_item_1, userListString);
listView.setAdapter(arrayAdapter);
}
}
}
if(userListString.isEmpty())
{
userListString.add("There are no Sherpas available in this city!");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(SearchSherpa.this,
android.R.layout.simple_list_item_1, userListString);
listView.setAdapter(arrayAdapter);
}
availableNumber.setText(i + " of " + total + " Sherpas available");
}
});
}
return handled;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = listView.getItemAtPosition(position).toString();
if(!name.equals("There are no Sherpas available in this city!") && !name.isEmpty())
{
Intent intent = new Intent(SearchSherpa.this, ViewSherpaProfile.class);
intent.putExtra("username", userlist.get(position).getUsername());
startActivity(intent);
}
}
});
}
}
|
/**
*
*/
package com.android.aid;
import android.content.Context;
import android.util.Log;
/**
* @author wangpeifeng
*
*/
public class StampPreferences extends MainSharedPref{
private static final int WEEKLY = 6;
private static final int DAILY = 0;
private static final int SYNCTIMER = DAILY;
private static final String PREF_KEY_CONFIG_SYNC = "config_sync";
private static final int VAL_DEF_CONFIG_SYNC = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_VERSION_SYNC = "version_sync";
private static final int VAL_DEF_VERSION_SYNC = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_GROUPS_SYNC = "groups_sync";
private static final int VAL_DEF_GROUPS_SYNC = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_CATEGORIES_SYNC = "categories_sync";
private static final int VAL_DEF_CATEGORIES_SYNC = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_APPLICATIONS_SYNC = "applications_sync";
private static final int VAL_DEF_APPLICATIONS_SYNC = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_APPLICATIONS_UPDATE = "applications_update";
private static final int VAL_DEF_APPLICATIONS_UPDATE = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_APPLICATIONS_STAMP = "applications_stamp";
public static final String VAL_DEF_APPLICATIONS_STAMP = "2013-01-01 00:00:00";
private static final String PREF_KEY_APPLICATIONS_PUUP_SYNC = "applications_puup_sync";
private static final int VAL_DEF_APPLICATIONS_PUUP_SYNC = VAL_DEF_DEV_INFO_ZERO;
private static final String PREF_KEY_APPLICATIONS_PUUP_STAMP= "applications_puup_stamp";
public static final String VAL_DEF_APPLICATIONS_PUUP_STAMP = "2013-07-01 00:00:00";
private static final String PREF_KEY_DOWNLOAD_SERVER_TEST = "download_server_test";
private static final int VAL_DEF_DOWNLOAD_SERVER_TEST = VAL_DEF_DEV_INFO_ZERO;
public StampPreferences(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
private boolean checkStamp(int stamp, int timer){
boolean bool = false;
if(StampHelper.StampToDateInt(System.currentTimeMillis()) > stamp + timer
// || (new PackageHelper(context).isRunningMe()
// && new DataConnectionHelper(context).isWLANOnline())
)
{
bool = true;
}
return bool;
}
public int getConfigSyncStamp(){
return getInt(PREF_KEY_CONFIG_SYNC,VAL_DEF_CONFIG_SYNC);
}
public void setConfigSyncStamp(){
putInt(PREF_KEY_CONFIG_SYNC, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isConfigSync(){
boolean bool = false;
int stamp = getConfigSyncStamp();
if(checkStamp(stamp,SYNCTIMER)){
bool = true;
}
return bool;
}
public int getVersionSyncStamp(){
return getInt(PREF_KEY_VERSION_SYNC,VAL_DEF_VERSION_SYNC);
}
public void setVersionSyncStamp(){
putInt(PREF_KEY_VERSION_SYNC, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isVersionSync(){
boolean bool = false;
int stamp = getVersionSyncStamp();
if(checkStamp(stamp,SYNCTIMER)){
bool = true;
}
return bool;
}
public int getGroupsSyncStamp(){
return getInt(PREF_KEY_GROUPS_SYNC,VAL_DEF_GROUPS_SYNC);
}
public void setGroupSyncStamp(){
putInt(PREF_KEY_GROUPS_SYNC, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isGroupsSync(){
boolean bool = false;
int stamp = getGroupsSyncStamp();
if(checkStamp(stamp,SYNCTIMER)){
bool = true;
}
return bool;
}
public int getCategoriesSyncStamp(){
return getInt(PREF_KEY_CATEGORIES_SYNC,VAL_DEF_CATEGORIES_SYNC);
}
public void setCategoriesSyncStamp(){
putInt(PREF_KEY_CATEGORIES_SYNC, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isCategoriesSync(){
boolean bool = false;
int stamp = getCategoriesSyncStamp();
if(checkStamp(stamp,SYNCTIMER)){
bool = true;
}
return bool;
}
public int getApplicationsSyncStamp(){
return getInt(PREF_KEY_APPLICATIONS_SYNC,VAL_DEF_APPLICATIONS_SYNC);
}
public void setApplicationsSyncStamp(){
putInt(PREF_KEY_APPLICATIONS_SYNC, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isApplicationsSync(){
boolean bool = false;
int stamp = getApplicationsSyncStamp();
if(checkStamp(stamp,SYNCTIMER)){
bool = true;
}
return bool;
}
public int getApplicationsUpdateStamp(){
int stamp = getInt(PREF_KEY_APPLICATIONS_UPDATE,VAL_DEF_APPLICATIONS_UPDATE);
return stamp;
}
public void setApplicationsUpdateStamp(){
putInt(PREF_KEY_APPLICATIONS_UPDATE, StampHelper.StampToDateMinute(System.currentTimeMillis()));
}
public boolean isApplicationsUpdate(){
boolean bool = false;
int stamplast = getApplicationsUpdateStamp();
int stampnow = StampHelper.StampToDateMinute(System.currentTimeMillis());
if(stampnow-stamplast > 10){
bool = true;
}
return bool;
}
public String getApplicationsCloudStamp(){
String stamp = getString(PREF_KEY_APPLICATIONS_STAMP, VAL_DEF_APPLICATIONS_STAMP);
return stamp;
}
public void setApplicationsCloudStamp(String stamp){
putString(PREF_KEY_APPLICATIONS_STAMP, stamp);
}
public int getApplicationsPuupSyncStamp(){
return getInt(PREF_KEY_APPLICATIONS_PUUP_SYNC,VAL_DEF_APPLICATIONS_PUUP_SYNC);
}
public void setApplicationsPuupSyncStamp(){
putInt(PREF_KEY_APPLICATIONS_PUUP_SYNC, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isApplicationsPuupSync(){
boolean bool = false;
int stamp = getApplicationsPuupSyncStamp();
if(checkStamp(stamp,SYNCTIMER)){
bool = true;
}
return bool;
}
public String getApplicationsPuupCloudStamp(){
String stamp = getString(PREF_KEY_APPLICATIONS_PUUP_STAMP, VAL_DEF_APPLICATIONS_PUUP_STAMP);
return stamp;
}
public void setApplicationsPuupCloudStamp(String stamp){
putString(PREF_KEY_APPLICATIONS_PUUP_STAMP, stamp);
}
public int getDownloadServerStamp(){
return getInt(PREF_KEY_DOWNLOAD_SERVER_TEST,VAL_DEF_DOWNLOAD_SERVER_TEST);
}
public void setDownloadServerStamp(){
putInt(PREF_KEY_DOWNLOAD_SERVER_TEST, StampHelper.StampToDateInt(System.currentTimeMillis()));
}
public boolean isDownloadServerTest(){
boolean bool = false;
int stamp = getDownloadServerStamp();
if(StampHelper.StampToDateInt(System.currentTimeMillis()) > stamp + SYNCTIMER ){
bool = true;
}
return bool;
}
@Override
protected String getPrefFileName() {
// TODO Auto-generated method stub
return "stamp_pref";
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.api;
import java.util.List;
import pl.edu.icm.unity.confirmations.ConfirmationConfiguration;
import pl.edu.icm.unity.exceptions.EngineException;
/**
* This interface allows clients to manipulate confirmation configuration.
*
* @author P. Piernik
*/
public interface ConfirmationConfigurationManagement
{
public final String ATTRIBUTE_CONFIG_TYPE = "attribute";
public final String IDENTITY_CONFIG_TYPE = "identity";
public void addConfiguration(ConfirmationConfiguration toAdd) throws EngineException;
public void removeConfiguration(String typeToConfirm, String nameToConfirm) throws EngineException;
public void updateConfiguration(ConfirmationConfiguration toUpdate) throws EngineException;
public ConfirmationConfiguration getConfiguration(String typeToConfirm, String nameToConfirm) throws EngineException;
public List<ConfirmationConfiguration> getAllConfigurations() throws EngineException;
}
|
/**
* winchance Inc.
*/
package com.sshfortress.common.util;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 天搜内部签名 签名(约定key的算法)
*
* @version $Id: SignUtils.java, v 0.1 2014-6-4 下午01:05:55 kaneiqi Exp $
*/
public class SignUtils {
private static final Log logger = LogFactory.getLog(SignUtils.class);
/** 24bit 私钥KEY: TIANSOU-golf@#160314g%(^$} */
private static String key = "TIANSOU-TS@#160314g%(^$}";
private static TripleDES tripleDES;
static {
try {
tripleDES = new TripleDES(key);
} catch (UnsupportedEncodingException e) {
logger.error("初始化签名对象异常", e);
}
}
/**
* <li>init-method 与afterPropertiesSet 都是在初始化bean的时候执行</li> <li>
* 执行顺序是afterPropertiesSet 先执行,init-method 后执行</li> <li>必须实现
* InitializingBean接口</li>
*
* @throws Exception
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
/**
* 加签
*
* @param src
* @return
*/
public static String encrypt(String src) {
try {
return tripleDES.encrypt(StringUtils.trim(src));
} catch (Exception ex) {
logger.error(src + "签名异常", ex);
}
return "";
}
/**
* 解签
*
* @param src
* @return
*/
public static String decrypt(String src) {
if(StringUtil.isNullOrEmpty(src)){
return "";
}else{
try {
return tripleDES.decrypt(StringUtils.trim(src));
} catch (Exception ex) {
logger.error(src + "解签异常", ex);
}
}
return "";
}
}
|
package com.utiitsl.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.utiitsl.entity.FinancialDetailsEntity;
/**
* @author APOORVA
*
*/
@Repository
public interface FinancialDetailsRepository extends JpaRepository<FinancialDetailsEntity,Long>{
}
|
package com.lsm.springboot.service;
import java.util.List;
import java.util.Set;
/**
* 对集合的操作
* 集合里的元素是不可重复的
* set 的内部实现是一个 value永远为null的HashMap,实际就是通过计算hash的方式来快速排重的
*/
public interface IRedisSetService {
/**
* 向集合添加一个或多个成员
*/
Long sAdd(String key, String... values);
/**
* 移除集合中一个或多个成员
*/
Long sRem(String key, String... values);
/**
* 移除并返回集合中的一个随机元素
*/
String sPop(String key);
/**
* 返回集合中一个或多个随机数, 可能重复
*/
List<String> sRandMember(String key, long count);
/**
* 返回集合中一个或多个随机数,不重复
*/
Set<String> sRandMember(long count, String key);
/**
* 将 member 元素从 sourceKey 集合移动到 destKey 集合
*/
Boolean sMove(String sourceKey, String member, String destKey);
/**
* 获取集合的成员数
*/
Long sCard(String key);
/**
* 判断 member 元素是否是集合 key 的成员
*/
Boolean sIsMember(String key, String member);
/**
* 返回给定所有集合的交集
*/
Set<String> sInter(String key, List<String> otherKeys);
/**
* 返回给定所有集合的交集并存储在 destKey 中
*/
Long sInterStore(String key, List<String> otherKeys, String destKey);
/**
* 返回所有给定集合的并集
*/
Set<String> sUnion(String key, List<String> otherKeys);
/**
* 所有给定集合的并集存储在 destKey 集合中
*/
Long sUnionStore(String key, List<String> otherKeys, String destKey);
/**
* 返回给定所有集合的差集
*/
Set<String> sDiff(String key, List<String> otherKeys);
/**
* 返回给定所有集合的差集并存储在 destKey 中
*/
Long sDiffStore(String key, List<String> otherKeys, String destKey);
/**
* 返回集合中的所有成员
*/
Set<String> sMembers(String key);
}
|
package ur.api_ur.lotto;
import ur.api_ur.URApiType;
/**
* Created by redjack on 15/11/17.
*/
public class URApiLotteryType extends URApiType {
public static URApiLotteryType LIST_LOTTERY = new URApiLotteryType(601, "/lottery/list_lottery");
public static URApiLotteryType REDEEM_LOTTERY = new URApiLotteryType(602, "/lottery/redeem_lottery");
public URApiLotteryType(int type, String method) {
super(type, method);
}
}
|
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Interface to allow for easy saving of an instance
* <p>
* When saving all objects contained by implementing class
* must also implement this interface
*/
public interface Saveable extends Serializable{
/**
* Save this class instance
* <p>
* All objects contained in this class must implement Saveable also
*/
default public void save(){
ObjectOutputStream objectOutputStream;
String fileName = this.getClass().getSimpleName() + ".svbl";
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream(fileName));
objectOutputStream.writeObject(this);
// System.out.println("Saved");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Save this class instance
* <p>
* All objects contained in this class must implement Saveable also
*
* @param fileName name of file to save to
*/
default public void save(String fileName){
ObjectOutputStream objectOutputStream;
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream(fileName));
objectOutputStream.writeObject(this);
// System.out.println("Saved");
} catch (Exception ex) {
ex.printStackTrace();
}
}
} |
package com.gxtc.huchuan.ui.live.hotlist;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUiView;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.bean.ChatInfosBean;
import com.gxtc.huchuan.bean.ClassHotBean;
import com.gxtc.huchuan.bean.ClassLike;
import com.gxtc.huchuan.bean.SearchBean;
import com.gxtc.huchuan.bean.UnifyClassBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.HashMap;
import java.util.List;
/**
* Created by Gubr on 2017/3/30.
*/
public interface HotListContract {
public interface View extends BaseUiView<Presenter> {
void showData(List<UnifyClassBean> datas);
void showLoMore(List<UnifyClassBean> datas);
void loadFinish();
}
public interface Presenter extends BasePresenter {
void getData(boolean isloadmroe, int start, String type);
}
public interface Source extends BaseSource {
void getData(HashMap<String,String> map,ApiCallBack<List<UnifyClassBean>> callBack);
void getHotData(HashMap<String,String> map,ApiCallBack<List<ClassHotBean>> callBack);
void getboutiqueData(HashMap<String,String> map,ApiCallBack<List<ClassLike>> callBack);
}
}
|
/*
* Created on 2004-05-20
*
*/
package com.esum.ebms.v2.packages.container;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.ebms.v2.packages.container.element.AckRequested;
import com.esum.ebms.v2.packages.container.element.Acknowledgment;
import com.esum.ebms.v2.packages.container.element.BodyElement;
import com.esum.ebms.v2.packages.container.element.ErrorList;
import com.esum.ebms.v2.packages.container.element.ErrorList.Error;
import com.esum.ebms.v2.packages.container.element.ExtensionElement;
import com.esum.ebms.v2.packages.container.element.HeaderElement;
import com.esum.ebms.v2.packages.container.element.Manifest;
import com.esum.ebms.v2.packages.container.element.MessageHeader;
import com.esum.ebms.v2.packages.container.element.MessageOrder;
import com.esum.ebms.v2.packages.container.element.StatusRequest;
import com.esum.ebms.v2.packages.container.element.StatusResponse;
import com.esum.ebms.v2.packages.container.element.SyncReply;
public class HeaderContainer implements java.io.Serializable
{
private static Logger log = LoggerFactory.getLogger(HeaderContainer.class.getName());
public static final String NAMESPACE_PREFIX_XSI = "xsi";
public static final String NAMESPACE_PREFIX_XLINK = "xlink";
public static final String NAMESPACE_PREFIX_XML = "xml";
private static final String NAMESPACE_URI_XSI = "http://www.w3.org/2001/XMLSchema-instance";
public static final String NAMESPACE_URI_XLINK = "http://www.w3.org/1999/xlink";
public static final String NAMESPACE_URI_XML = "http://www.w3.org/XML/1998/namespace";
public static final String SCHEMA_LOCATION_PREFIX_XSI = "schemaLocation";
private static final String SCHEMA_LOCATION_URI_XSI = ExtensionElement.NAMESPACE_URI_SOAP + " "
+ "http://www.oasis-open.org/committees/ebxml-msg/schema/envelope.xsd";
private static final String NAMESPACE_PREFIX_DS = "ds";
private static final String NAMESPACE_URI_DS = "http://www.w3.org/2000/09/xmldsig#";
private static final String ELEMENT_SIGNATURE = "Signature";
private SOAPEnvelope mSoapEnvelope = null;
private SOAPHeader mSoapHeader = null;
private SOAPBody mSoapBody = null;
private String mMessageType = null;
private MessageHeader mMessageHeaderElement = null;
private Manifest mManifestElement = null;
private ErrorList mErrorListElement = null;
private SyncReply mSyncReplyElement = null;
private MessageOrder mMessageOrderElement = null;
private StatusRequest mStatusRequestElement = null;
private StatusResponse mStatusResponseElement = null;
private List mAckRequestedList = new ArrayList();
private List mAcknowledgmentList = new ArrayList();
/** Build ebXML Message */
public HeaderContainer(SOAPEnvelope soapEnvelope, String messageType) throws SOAPException
{
mSoapEnvelope = soapEnvelope;
mMessageType = messageType;
log.debug("<> SOAPEnvelope.getHeader()");
mSoapHeader = mSoapEnvelope.getHeader();
log.debug("<> SOAPEnvelope.getBody()");
mSoapBody = mSoapEnvelope.getBody();
log.debug("=> build()");
build();
log.debug("<= build()");
}
/** Extract ebXML Message */
public HeaderContainer(SOAPEnvelope soapEnvelope) throws SOAPException
{
mSoapEnvelope = soapEnvelope;
log.debug("<> SOAPEnvelope.getHeader()");
mSoapHeader = mSoapEnvelope.getHeader();
log.debug("<> SOAPEnvelope.getBody()");
mSoapBody = mSoapEnvelope.getBody();
log.debug("=> extract()");
extract();
log.debug("<= extract()");
}
/** Build */
private void build() throws SOAPException
{
/** XSI Namespace, SchemaLocation */
mSoapEnvelope.addNamespaceDeclaration(NAMESPACE_PREFIX_XSI, NAMESPACE_URI_XSI);
Name name = mSoapEnvelope.createName(SCHEMA_LOCATION_PREFIX_XSI, NAMESPACE_PREFIX_XSI, NAMESPACE_URI_XSI);
mSoapEnvelope.addAttribute(name, SCHEMA_LOCATION_URI_XSI);
/** XLINK Namespace */
mSoapEnvelope.addNamespaceDeclaration(NAMESPACE_PREFIX_XLINK, NAMESPACE_URI_XLINK);
/** XSI Namespace, SchemaLocation for Header */
mSoapHeader.addNamespaceDeclaration(ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
name = mSoapEnvelope.createName(HeaderContainer.SCHEMA_LOCATION_PREFIX_XSI, HeaderContainer.NAMESPACE_PREFIX_XSI, NAMESPACE_URI_XSI);
mSoapHeader.addAttribute(name, ExtensionElement.SCHEMA_LOCATION_URI_EB);
/** XSI Namespace, SchemaLocation for Body */
mSoapBody.addNamespaceDeclaration(ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
name = mSoapEnvelope.createName(HeaderContainer.SCHEMA_LOCATION_PREFIX_XSI, HeaderContainer.NAMESPACE_PREFIX_XSI, NAMESPACE_URI_XSI);
mSoapBody.addAttribute(name, ExtensionElement.SCHEMA_LOCATION_URI_EB);
}
/** Extract Header Element */
private void extract() throws SOAPException
{
/** Extract Message Header Element */
Name name = mSoapEnvelope.createName(HeaderElement.ELEMENT_MESSAGE_HEADER, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
Iterator childElements = mSoapHeader.getChildElements(name);
if (childElements.hasNext())
{
log.debug("=> MessageHeader(SOAPEnvelope, SOAPElement)");
mMessageHeaderElement = new MessageHeader(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= MessageHeader(SOAPEnvelope, SOAPElement)");
}
// else
// throw new EbXMLValidationException(EbXMLValidationException.ERROR_CODE_UNKNOWN
// , EbXMLValidationException.SEVERITY_ERROR
// , "The MessageHeader Element must be included.", "Header Container");
/** Extract SyncReply Element */
name = mSoapEnvelope.createName(HeaderElement.ELEMENT_SYNC_REPLY, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapHeader.getChildElements(name);
if(childElements.hasNext())
{
log.debug("=> SyncReply(SOAPEnvelope, SOAPElement)");
mSyncReplyElement = new SyncReply(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= SyncReply(SOAPEnvelope, SOAPElement)");
}
/** Extract MessageOrder Element */
name = mSoapEnvelope.createName(HeaderElement.ELEMENT_MESSAGE_ORDER, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapHeader.getChildElements(name);
if(childElements.hasNext())
{
log.debug("=> MessageOrder(SOAPEnvelope, SOAPElement)");
mMessageOrderElement = new MessageOrder(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= MessageOrder(SOAPEnvelope, SOAPElement)");
}
/** Extract AckRequested Element */
name = mSoapEnvelope.createName(HeaderElement.ELEMENT_ACK_REQUESTED, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapHeader.getChildElements(name);
while(childElements.hasNext())
{
log.debug("=> AckRequested(SOAPEnvelope, SOAPElement)");
AckRequested ackRequestedElement = new AckRequested(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= AckRequested(SOAPEnvelope, SOAPElement)");
mAckRequestedList.add(ackRequestedElement);
}
/** Extract Acknowledgment Element */
name = mSoapEnvelope.createName(HeaderElement.ELEMENT_ACKNOWLEDGMENT, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapHeader.getChildElements(name);
while(childElements.hasNext())
{
log.debug("=> Acknowledgment(SOAPEnvelope, SOAPElement)");
Acknowledgment acknowledgmentElement = new Acknowledgment(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= Acknowledgment(SOAPEnvelope, SOAPElement)");
mAcknowledgmentList.add(acknowledgmentElement);
}
/** Extract ErrorList Element */
name = mSoapEnvelope.createName(HeaderElement.ELEMENT_ERROR_LIST, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapHeader.getChildElements(name);
if (childElements.hasNext())
{
log.debug("=> ErrorList(SOAPEnvelope, SOAPElement)");
mErrorListElement = new ErrorList(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= ErrorList(SOAPEnvelope, SOAPElement)");
}
/** Extract StatusRequest Element */
name = mSoapEnvelope.createName(BodyElement.ELEMENT_STATUS_REQUEST, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapBody.getChildElements(name);
if(childElements.hasNext())
{
log.debug("=> StatusRequest(SOAPEnvelope, SOAPElement)");
mStatusRequestElement = new StatusRequest(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= StatusRequest(SOAPEnvelope, SOAPElement)");
}
/** Extract StatusResponse Element */
name = mSoapEnvelope.createName(BodyElement.ELEMENT_STATUS_RESPONSE, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapBody.getChildElements(name);
if(childElements.hasNext())
{
log.debug("=> StatusResponse(SOAPEnvelope, SOAPElement)");
mStatusResponseElement = new StatusResponse(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= StatusResponse(SOAPEnvelope, SOAPElement)");
}
/** Extract Manifest Element */
name = mSoapEnvelope.createName(BodyElement.ELEMENT_MANIFEST, ExtensionElement.NAMESPACE_PREFIX_EB, ExtensionElement.NAMESPACE_URI_EB);
childElements = mSoapBody.getChildElements(name);
if (childElements.hasNext())
{
log.debug("=> Manifest(SOAPEnvelope, SOAPElement)");
mManifestElement = new Manifest(mSoapEnvelope, (SOAPElement)childElements.next());
log.debug("<= Manifest(SOAPEnvelope, SOAPElement)");
}
}
/** Add Message Header Element */
public void addMessageHeader(HeaderContainerInfo headerContainerInfo) throws SOAPException
{
log.debug("=> MessageHeader(SOAPEnvelope, HeaderContainerInfo)");
mMessageHeaderElement = new MessageHeader(mSoapEnvelope, headerContainerInfo);
log.debug("<= MessageHeader(SOAPEnvelope, HeaderContainerInfo)");
addExtensionElement(mMessageHeaderElement);
}
/** Add Reference Element */
public void addReference(boolean useManifestId, Payload payload) throws SOAPException
{
if (mManifestElement == null)
{
log.debug("=> Manifest(SOAPEnvelope)");
mManifestElement = new Manifest(mSoapEnvelope, useManifestId);
log.debug("<= Manifest(SOAPEnvelope)");
}
log.debug("=> Manifest.addReference(Payload)");
mManifestElement.addReference(payload);
log.debug("<= Manifest.addReference(Payload)");
}
/** Add AckRequested Element */
public void addAckRequested(Iterator ackRequestedList) throws SOAPException
{
while(ackRequestedList.hasNext())
{
log.debug("=> AckRequested(SOAPEnvelope, AckRequested)");
AckRequested ackRequestedElement = new AckRequested(mSoapEnvelope, (AckRequested)ackRequestedList.next());
log.debug("<= AckRequested(SOAPEnvelope, AckRequested)");
mAckRequestedList.add(ackRequestedElement);
addExtensionElement(ackRequestedElement);
}
}
/** Add Acknowledgment Element */
public void addAcknowledgment(Iterator acknowledgmentList) throws SOAPException
{
while(acknowledgmentList.hasNext())
{
log.debug("=> Acknowledgment(SOAPEnvelope)");
Acknowledgment acknowledgment = new Acknowledgment(mSoapEnvelope, (Acknowledgment)acknowledgmentList.next());
log.debug("<= Acknowledgment(SOAPEnvelope)");
mAcknowledgmentList.add(acknowledgment);
addExtensionElement(acknowledgment);
}
}
/** Add Error Element */
public void addError(boolean useErrorListId, Error error) throws SOAPException
{
if (mErrorListElement == null)
{
log.debug("=> ErrorList(SOAPEnvelope)");
mErrorListElement = new ErrorList(mSoapEnvelope, useErrorListId);
log.debug("<= ErrorList(SOAPEnvelope)");
}
log.debug("=> ErrorList.addError(Error)");
mErrorListElement.addError(error);
log.debug("<= ErrorList.addError(Error)");
}
/** Add Status Request RefToMessageId */
public void addStatusRequest(boolean useStatusRequestId, String refToMessageId) throws SOAPException
{
if (mStatusRequestElement == null)
{
mStatusRequestElement = new StatusRequest(mSoapEnvelope, useStatusRequestId, refToMessageId);
}
addExtensionElement(mStatusRequestElement);
}
/** Add Status Response RefToMessageId */
public void addStatusResponse(boolean useStatusResponseId, String messageStatus, String refToMessageId, String timeStamp) throws SOAPException
{
if (mStatusResponseElement == null)
{
mStatusResponseElement = new StatusResponse(mSoapEnvelope, useStatusResponseId, messageStatus, refToMessageId, timeStamp);
}
addExtensionElement(mStatusResponseElement);
}
/** Add SyncReply Element */
public void addSyncReply(boolean useSyncReplyId) throws SOAPException
{
log.debug("=> SyncReply(SOAPEnvelope)");
mSyncReplyElement = new SyncReply(mSoapEnvelope, useSyncReplyId);
log.debug("<= SyncReply(SOAPEnvelope)");
addExtensionElement(mSyncReplyElement);
}
/** Add MessageOrder Element */
public void addMessageOrder(MessageOrder messageOrder) throws SOAPException
{
log.debug("=> MessageOrder(SOAPEnvelope)");
mMessageOrderElement = new MessageOrder(mSoapEnvelope, messageOrder);
log.debug("<= MessageOrder(SOAPEnvelope)");
addExtensionElement(mMessageOrderElement);
}
/** Add Extension Element */
public void addExtensionElement(ExtensionElement element) throws SOAPException
{
if (element instanceof MessageHeader)
{
mSoapHeader.addChildElement(element.getSOAPElement());
}
else if (element instanceof Manifest)
{
mSoapBody.addChildElement(element.getSOAPElement());
}
else if (element instanceof AckRequested)
{
mSoapHeader.addChildElement(element.getSOAPElement());
}
else if (element instanceof Acknowledgment)
{
mSoapHeader.addChildElement(element.getSOAPElement());
}
else if (element instanceof ErrorList)
{
mSoapHeader.addChildElement(element.getSOAPElement());
}
else if (element instanceof SyncReply)
{
mSoapHeader.addChildElement(element.getSOAPElement());
}
else if (element instanceof MessageOrder)
{
mSoapHeader.addChildElement(element.getSOAPElement());
}
else if (element instanceof StatusRequest)
{
mSoapBody.addChildElement(element.getSOAPElement());
}
else if (element instanceof StatusResponse)
{
mSoapBody.addChildElement(element.getSOAPElement());
}
}
/** Add Manifest Element */
public void addManifest() throws SOAPException
{
if (mManifestElement != null)
{
addExtensionElement(mManifestElement);
}
}
/** Add ErrorList Element */
public void addErrorList() throws SOAPException
{
if (mErrorListElement != null)
{
log.debug("=> ErrorList.addHighestSeverity()");
mErrorListElement.addHighestSeverity();
log.debug("<= ErrorList.addHighestSeverity()");
addExtensionElement(mErrorListElement);
}
}
/** Get MessageHeader Element */
public MessageHeader getMessageHeader()
{
return mMessageHeaderElement;
}
/** Get Manifest Element */
public Manifest getMenifest()
{
return mManifestElement;
}
/** Get ErrorList Element */
public ErrorList getErrorList()
{
return mErrorListElement;
}
/** Get AckRequsted Element */
public Iterator getAckRequstedList()
{
return mAckRequestedList.iterator();
}
/** Get Acknowledgment Element */
public Iterator getAcknowledgment()
{
return mAcknowledgmentList.iterator();
}
/** Get SyncReply Element */
public SyncReply getSyncReply()
{
return mSyncReplyElement;
}
/** Get MessageOrder Element */
public MessageOrder getMessageOrder()
{
return mMessageOrderElement;
}
/** Get MessageStatus Request Element */
public StatusRequest getStatusRequest()
{
return mStatusRequestElement;
}
/** Get MessageStatus Response Element */
public StatusResponse getStatusResponse()
{
return mStatusResponseElement;
}
/** Is Message Status Request */
public boolean isMessageStatusRequest()
{
if (mMessageHeaderElement.getService().getService().equals(MessageHeader.ELEMENT_SERVICE_MESSAGE_STATUS_VALUE)
&& mMessageHeaderElement.getAction().equals(MessageHeader.ELEMENT_ACTION_MESSAGE_STATUS_REQUEST_VALUE))
return true;
else
return false;
}
/** Is Message Status Response */
public boolean isMessageStatusResponse()
{
if (mMessageHeaderElement.getService().getService().equals(MessageHeader.ELEMENT_SERVICE_MESSAGE_STATUS_VALUE)
&& mMessageHeaderElement.getAction().equals(MessageHeader.ELEMENT_ACTION_MESSAGE_STATUS_RESPONSE_VALUE))
return true;
else
return false;
}
/** Is Ping */
public boolean isPing()
{
if (mMessageHeaderElement.getService().getService().equals(MessageHeader.ELEMENT_SERVICE_PING_VALUE)
&& mMessageHeaderElement.getAction().equals(MessageHeader.ELEMENT_ACTION_PING_VALUE))
return true;
else
return false;
}
/** Is Pong */
public boolean isPong()
{
if (mMessageHeaderElement.getService().getService().equals(MessageHeader.ELEMENT_SERVICE_PONG_VALUE)
&& mMessageHeaderElement.getAction().equals(MessageHeader.ELEMENT_ACTION_PONG_VALUE))
return true;
else
return false;
}
/** Is Signed */
public boolean isSigned()
{
Name name = null;
try
{
name = mSoapEnvelope.createName(ELEMENT_SIGNATURE, NAMESPACE_PREFIX_DS, NAMESPACE_URI_DS);
}
catch (SOAPException e)
{
log.error("isSigned()", e);
}
Iterator childElements = mSoapHeader.getChildElements(name);
return childElements.hasNext();
}
}
|
package com.getkhaki.api.bff.persistence.models;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
@Accessors(chain = true)
public class GoalDao extends EntityBaseDao {
String name;
Integer greaterThanOrEqualTo;
Integer lessThanOrEqualTo;
@ManyToOne(optional = true)
OrganizationDao organization;
@ManyToOne(optional = true)
DepartmentDao department;
}
|
package com.example.words.aty;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
//import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.words.R;
import com.yydcdut.sdlv.Menu;
import com.yydcdut.sdlv.MenuItem;
import com.yydcdut.sdlv.SlideAndDragListView;
import java.util.ArrayList;
import java.util.List;
import db.ACID;
import db.Word;
public class DisplayWordsActivity extends Activity implements View.OnClickListener {
//控件
private SlideAndDragListView slideAndDragListView;
private ImageButton btnReturn;
private Button btnManage;
private TextView tvTitle;
//隐藏控件
private LinearLayout llDisplayWordsManage;
private TextView tvDeleteNumber;
private Button btnDelete;
//隐藏菜单
Menu menu;
//每一行的填充数据
Word mDraggedEntity;
private List<Word> wordslist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_words);
initDatas();
initMenus();
initViews();
initEvents();
}
//初始化数据
protected void initDatas() {
Intent intent = getIntent();
ACID acid = new ACID(DisplayWordsActivity.this);
wordslist = acid.getwordfromwb(intent.getStringExtra("wordbookName"),null);//初始化单词本
}
//初始化隐藏菜单
protected void initMenus() {
//初始化隐藏菜单
menu = new Menu(true,0);
menu.addItem(new MenuItem.Builder().setWidth(200)
.setBackground(getResources().getDrawable(R.drawable.test_btn_shape1))
.setText("删除")
.setTextColor(R.color.colorTextDark)
.setTextSize(16).setDirection(MenuItem.DIRECTION_RIGHT)
.build());
}
//初始化界面
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void initViews() {
btnReturn = (ImageButton) findViewById(R.id.btn_return);
btnManage = (Button) findViewById(R.id.btn_help);
tvTitle = (TextView) findViewById(R.id.tv_topbar_title);
System.out.println(tvTitle);
llDisplayWordsManage = (LinearLayout) findViewById(R.id.ll_display_words_manage);
tvDeleteNumber = (TextView) findViewById(R.id.tv_number_of_words_to_delete);
btnDelete = (Button) findViewById(R.id.btn_delete_words);
tvTitle.setText("单词本名字");
slideAndDragListView = (SlideAndDragListView) findViewById(R.id.sdlv);
slideAndDragListView.setMenu(menu);//设置隐藏菜单
slideAndDragListView.setAdapter(mAdapter);//设置适配器
}
//初始化事件
protected void initEvents() {
btnReturn.setOnClickListener(this);
btnManage.setOnClickListener(this);
btnDelete.setOnClickListener(this);
/*设置各种监听器*/
//隐藏菜单子项点击监听
slideAndDragListView.setOnMenuItemClickListener(new SlideAndDragListView.OnMenuItemClickListener() {
@Override
public int onMenuItemClick(View view, int itemPosition, int buttonPosition, int direction) {
switch (direction) {
//若打开左边的item
case MenuItem.DIRECTION_LEFT:
break;
//若打开右边的item
case MenuItem.DIRECTION_RIGHT:
switch (buttonPosition) {
case 0:
//从底部到顶部删除listView的子项,选择这个会调用
// setOnItemDeleteListener的onItemDelete方法
return Menu.ITEM_DELETE_FROM_BOTTOM_TO_TOP;
}
break;
default:
return Menu.ITEM_NOTHING;
}
return Menu.ITEM_NOTHING;
}
});
//设置移动控件监听
slideAndDragListView.setOnDragDropListener(new SlideAndDragListView.OnDragDropListener() {
@Override
public void onDragViewStart(int beginPosition) {
mDraggedEntity = wordslist.get(beginPosition);
}
@Override
public void onDragDropViewMoved(int fromPosition, int toPosition) {
Word movedword = wordslist.remove(fromPosition);
wordslist.add(toPosition, movedword);
}
@Override
public void onDragViewDown(int finalPosition) {
wordslist.set(finalPosition, mDraggedEntity);
}
});
//设置点击监听
slideAndDragListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(DisplayWordsActivity.this, "点击项目" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DisplayWordsActivity.this,SearchWordActivity.class);
intent.putExtra("wordToCheck",wordslist.get(position));
startActivity(intent);
}
});
//设置滑动监听
slideAndDragListView.setOnSlideListener(new SlideAndDragListView.OnSlideListener() {
@Override
public void onSlideOpen(View view, View view1, int position, int direction) {
Toast.makeText(DisplayWordsActivity.this, "滑动打开监听" + position, Toast.LENGTH_SHORT).show();
}
@Override
public void onSlideClose(View view, View view1, int position, int direction) {
Toast.makeText(DisplayWordsActivity.this, "滑动关闭监听" + position, Toast.LENGTH_SHORT).show();
}
});
//设置删除Item监听
slideAndDragListView.setOnItemDeleteListener(new SlideAndDragListView.OnItemDeleteListener() {
@Override
public void onItemDeleteAnimationFinished(View view, int position) {
Toast.makeText(DisplayWordsActivity.this, "删除" + position, Toast.LENGTH_SHORT).show();
wordslist.remove(position - slideAndDragListView.getHeaderViewsCount());
mAdapter.notifyDataSetChanged();
}
});
//设置滚动监听
slideAndDragListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
//滑动状态改变监听
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case SCROLL_STATE_IDLE:
break;
case SCROLL_STATE_TOUCH_SCROLL:
break;
case SCROLL_STATE_FLING:
break;
}
}
@Override
//当滚动的时候触发
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//会一直调用
//Toast.makeText(MainActivity.this, "正在滚动" , Toast.LENGTH_SHORT).show();
}
});
}
//适配器类
private BaseAdapter mAdapter = new BaseAdapter() {
@Override
public int getCount() {
return wordslist.size();
}
@Override
public Object getItem(int position) {
return wordslist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
//加载布局
convertView = LayoutInflater.from(DisplayWordsActivity.this).inflate(R.layout.wordlist_item,null);
//初始化控件
vh.checkBox = (CheckBox) convertView.findViewById(R.id.cb_check_word);
vh.checkBox.setVisibility(View.INVISIBLE);//初始化时cb不显示
vh.word = (TextView) convertView.findViewById(R.id.tv_wordlist_word);
//设置checkbox选中监听
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
//得到某行单词
String item = ((Word)this.getItem(position)).getSpelling().toString();
//设置控件
vh.word.setText(item);
return convertView;
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_return:
finish();
break;
case R.id.btn_help:{
if (btnManage.getText().toString().equals("管理")) {
btnManage.setText("退出管理");
//取消隐藏
showHiddenItems(new Boolean("flase"));
} else if (btnManage.getText().toString().equals("退出管理")) {
btnManage.setText("管理");
//隐藏
showHiddenItems(new Boolean("true"));
}
break;
}
case R.id.btn_delete_words:
//删除单词
break;
}
}
public void showHiddenItems(Boolean b) {
if (b) {
//取消隐藏
llDisplayWordsManage.setVisibility(View.VISIBLE);
} else {
//隐藏
llDisplayWordsManage.setVisibility(View.GONE);
}
}
private class ViewHolder {
public CheckBox checkBox;
public TextView word;
}
public class TestAdapter extends ArrayAdapter<String> {
int resource;
private LayoutInflater inflater;
private Boolean[] checks;//保存CheckBox的状态
public TestAdapter(Context context,int resource,ArrayList<String> list) {
super(context,resource,list);
checks = new Boolean[list.size()];
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
}
|
package com.sapl.retailerorderingmsdpharma.models;
/**
* Created by Sony on 13/02/2018.
*/
public class OrderDeliveryStatusModel {
String distributorId;
String OrderStatus;
String OrderDate;
String OrderID;
String Amount;
String cart_count;
String address;
String contact_no_land;
String contact_no_mob;
String address_outlet_info;
@Override
public String toString() {
return "OrderDeliveryStatusModel{" +
"distributorId='" + distributorId + '\'' +
", OrderStatus='" + OrderStatus + '\'' +
", OrderDate='" + OrderDate + '\'' +
", OrderID='" + OrderID + '\'' +
", Amount='" + Amount + '\'' +
", cart_count='" + cart_count + '\'' +
", address='" + address + '\'' +
", contact_no_land='" + contact_no_land + '\'' +
", contact_no_mob='" + contact_no_mob + '\'' +
'}';
}
public String getDistributorId() {
return distributorId;
}
public void setDistributorId(String distributorId) {
this.distributorId = distributorId;
}
public String getOrderStatus() {
return OrderStatus;
}
public void setOrderStatus(String orderStatus) {
OrderStatus = orderStatus;
}
public String getOrderDate() {
return OrderDate;
}
public void setOrderDate(String orderDate) {
OrderDate = orderDate;
}
public String getOrderID() {
return OrderID;
}
public void setOrderID(String orderID) {
OrderID = orderID;
}
public String getAmount() {
return Amount;
}
public void setAmount(String amount) {
Amount = amount;
}
public String getCart_count() {
return cart_count;
}
public void setCart_count(String cart_count) {
this.cart_count = cart_count;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact_no_land() {
return contact_no_land;
}
public void setContact_no_land(String contact_no_land) {
this.contact_no_land = contact_no_land;
}
public String getContact_no_mob() {
return contact_no_mob;
}
public void setContact_no_mob(String contact_no_mob) {
this.contact_no_mob = contact_no_mob;
}
public String getAddress_outlet_info() {
return address_outlet_info;
}
public void setAddress_outlet_info(String address_outlet_info) {
this.address_outlet_info = address_outlet_info;
}
public OrderDeliveryStatusModel(String distributorId, String OrderStatus, String OrderDate, String OrderID, String Amount, String cart_count, String address, String contact_no_land, String contact_no_mob, String address_outlet_info) {
this.distributorId = distributorId;
this.OrderStatus = OrderStatus;
this.OrderDate = OrderDate;
this.OrderID = OrderID;
this.Amount = Amount;
this.cart_count = cart_count;
this.address =address;
this.contact_no_land = contact_no_land;
this.contact_no_mob = contact_no_mob;
this.address_outlet_info = address_outlet_info;
}
} |
package custom;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Font;
public class TransparentTextField extends JTextField
{
private final int TF_WIDTH = 400;
private final int TF_HEIGHT = 27;
private final Color color = new Color(255, 255, 255, 0);
public TransparentTextField(String s)
{
super(s);
setBorder(null);
setFont(new Font("Times New Roman", Font.ITALIC, 18));
setPreferredSize(new Dimension(TF_WIDTH, TF_HEIGHT));
setEditable(false);
setComponentPopupMenu(new RightClickPopup().getMenu());
}
@Override
protected void paintComponent(Graphics g)
{
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
}
|
package com.javarush.test.level08.lesson08.task04;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/* Удалить всех людей, родившихся летом
Создать словарь (Map<String, Date>) и занести в него десять записей по принципу: «фамилия» - «дата рождения».
Удалить из словаря всех людей, родившихся летом.
*/
public class Solution
{
public static HashMap<String, Date> createMap()
{
HashMap<String, Date> map = new HashMap<String, Date>();
map.put("Сталлоне", new Date("JUNE 1 1980"));
map.put("С", new Date("APRIL 1 1980"));
map.put("Ст", new Date("JANUARY 1 1980"));
map.put("Ста", new Date("JULY 1 1980"));
map.put("Стал", new Date("AUGUST 1 1980"));
map.put("Сталл", new Date("SEPTEMBER 1 1980"));
map.put("Сталло", new Date("NOVEMBER 1 1980"));
map.put("Сталлон", new Date("MAY 1 1980"));
map.put("Сталлоне1", new Date("MAY 1 1980"));
map.put("Сталлоне2", new Date("JUNE 1 1980"));
//Напишите тут ваш код
return map;
}
public static void removeAllSummerPeople(HashMap<String, Date> map)
{
//Напишите тут ваш код
Iterator<Date> iterator = map.values().iterator();
for (int i = 0; i < map.values().size(); i++) {
while (iterator.hasNext()) {
Date n = iterator.next();
if(n.getMonth() == 5 || n.getMonth() == 6 || n.getMonth() == 7) {
iterator.remove();
}
}
}
}
}
|
/**
* Package for junior.pack2.p5.ch6 Tree.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-06-19
*/
package ru.job4j.tree;
|
package org.sayesaman.database.dao;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import com.googlecode.androidannotations.annotations.App;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EBean;
import org.sayesaman.R;
import org.sayesaman.database.DatabaseHandler;
import org.sayesaman.database.model.BuyType;
import org.sayesaman.database.model.Customer;
import org.sayesaman.database.model.Goods;
import org.sayesaman.database.model.OrderHdr;
import org.sayesaman.database.model.OrderItem;
import org.sayesaman.database.model.OrderStatus;
import org.sayesaman.database.model.reports.Report1;
import org.sayesaman.database.model.reports.Report2Hdr;
import org.sayesaman.database.model.reports.Report2Itm;
import java.util.ArrayList;
import java.util.List;
/**
* Created by meysami on 8/22/13.
* <p/>
* Please read this article asap
* Speeding up SQLite insert operations :
* http://tech.vg.no/2011/04/04/speeding-up-sqlite-insert-operations/
*/
@EBean
public class OrderDao {
@App
DatabaseHandler handler;
@Bean
CustomerDao customerDao;
@Bean
GoodsDao goodsDao;
public ArrayList<OrderHdr> getAll() {
final Cursor c;
String qry = "";
qry = handler.getResources().getString(R.string.OrderDao_getAll);
c = handler.rawQuery(qry, null);
ArrayList<OrderHdr> resultList = new ArrayList<OrderHdr>();
while (c.moveToNext()) {
try {
OrderHdr obj = new OrderHdr();
String id = c.getString(c.getColumnIndex("ID"));
Customer customer = customerDao.getCustomerSpecById(id);
obj.setCustomer(customer);
/*
For better performance we eliminated this
List<OrderItem> orderItems = new ArrayList<OrderItem>();
orderItems = getDamageItems(id);
obj.setDamageItems(orderItems);
*/
resultList.add(obj);
} catch (Exception e) {
Log.e("@sayesaman", "Error " + e.toString());
}
}
c.close();
return resultList;
}
public OrderHdr getOneOrderWithItemsById(String id) {
String qry = handler.getResources().getString(R.string.OrderDao_getOneOrderWithItemsById);
String[] args = new String[1];
args[0] = id;
final Cursor c = handler.rawQuery(qry, args);
OrderHdr obj = new OrderHdr();
while (c.moveToNext()) {
try {
String tourItmId = c.getString(c.getColumnIndex("ID"));
Customer customer = customerDao.getCustomerSpecById(tourItmId);
obj.setCustomer(customer);
List<OrderItem> orderItems = new ArrayList<OrderItem>();
orderItems = getOrderItems(id);
obj.setOrderItems(orderItems);
} catch (Exception e) {
Log.e("@sayesaman", "Error " + e.toString());
}
}
c.close();
return obj;
}
public ArrayList<OrderItem> getOrderItems(String id) {
String qry = handler.getResources().getString(R.string.OrderDao_getOrderItems);
String[] args = new String[1];
args[0] = id;
final Cursor c = handler.rawQuery(qry, args);
ArrayList<OrderItem> list = new ArrayList<OrderItem>();
int i = 0;
while (c.moveToNext()) {
OrderItem obj1 = new OrderItem();
obj1.setNo(String.valueOf(++i));
String order_itm_Id = c.getString(c.getColumnIndex("ID"));
String order_itm_qty = c.getString(c.getColumnIndex("GoodsQty"));
String goodsRef = c.getString(c.getColumnIndex("GoodsRef"));
String goodsCode = c.getString(c.getColumnIndex("GoodsCode"));
String goodsName = c.getString(c.getColumnIndex("GoodsName"));
String goodsPrice = c.getString(c.getColumnIndex("GoodsPrice"));
String cartonType = c.getString(c.getColumnIndex("CartonType"));
Goods goods = new Goods();
goods.setId(goodsRef);
goods.setCode(goodsCode);
goods.setName(goodsName);
goods.setPrice(goodsPrice);
goods.setCarton(cartonType);
double qtyD = Double.parseDouble(order_itm_qty);
double carton = Double.parseDouble(cartonType);
double unitPrice = Double.parseDouble(goodsPrice);
double sumPrice = qtyD * carton * unitPrice;
//obj1.setGoods(goodsDao.getOneById(c.getString(c.getColumnIndex("GoodsRef"))));
obj1.setId(order_itm_Id);
obj1.setQty(order_itm_qty);
obj1.setGoods(goods);
obj1.setPrice(String.valueOf(unitPrice));
obj1.setPrice_sum(String.valueOf(sumPrice));
list.add(obj1);
}
c.close();
return list;
}
public ArrayList<OrderItem> getOrderItemsForNewOrder(String id, String mainGroupId, String subGroupId) {
String qry = handler.getResources().getString(R.string.OrderDao_getOrderItemsForNewOrder);
String[] args = new String[6];
args[0] = id;
args[1] = mainGroupId;
args[2] = subGroupId;
args[3] = id;
args[4] = mainGroupId;
args[5] = subGroupId;
final Cursor c = handler.rawQuery(qry, args);
ArrayList<OrderItem> list = new ArrayList<OrderItem>();
int i = 0;
while (c.moveToNext()) {
OrderItem obj1 = new OrderItem();
obj1.setNo(String.valueOf(++i));
String goodsRef = c.getString(c.getColumnIndex("GoodsRef"));
String goodsCode = c.getString(c.getColumnIndex("GoodsCode"));
String goodsName = c.getString(c.getColumnIndex("GoodsName"));
String goodsPrice = c.getString(c.getColumnIndex("GoodsPrice"));
String cartonType = c.getString(c.getColumnIndex("CartonType"));
String order_itm_Id = c.getString(c.getColumnIndex("order_itm_Id"));
String order_itm_qty = c.getString(c.getColumnIndex("order_itm_qty"));
Goods obj2 = new Goods();
obj2.setId(goodsRef);
obj2.setCode(goodsCode);
obj2.setName(goodsName);
obj2.setPrice(goodsPrice);
obj2.setCarton(cartonType);
long qtyD = Long.parseLong(order_itm_qty);
long carton = Long.parseLong(cartonType);
long unitPrice = (Long.parseLong(goodsPrice)) * carton;
long sumPrice = qtyD * unitPrice;
obj1.setId(order_itm_Id);
obj1.setQty(order_itm_qty);
obj1.setPrice(String.valueOf(unitPrice).replace(".0", ""));
obj1.setPrice_sum(String.valueOf(sumPrice).replace(".0", ""));
obj1.setGoods(obj2);
list.add(obj1);
}
c.close();
return list;
}
public OrderStatus getOrderStatusAll() {
String qry = handler.getResources().getString(R.string.OrderDao_getOrderStatusAll);
final Cursor c = handler.rawQuery(qry, null);
OrderStatus status = new OrderStatus();
status.setOrder_qty("0");
status.setOrder_sum("0");
status.setOrder_price("0");
while (c.moveToNext()) {
status.setOrder_qty(c.getString(c.getColumnIndex("order_qty")));
status.setOrder_sum(c.getString(c.getColumnIndex("order_sum")));
status.setOrder_price(c.getString(c.getColumnIndex("order_price")));
}
c.close();
return status;
}
//=======================================================================================================================================
public ArrayList<Report1> getReport1() {
final Cursor c;
String qry = "";
qry = handler.getResources().getString(R.string.OrderDao_getReport1);
c = handler.rawQuery(qry, null);
ArrayList<Report1> resultList = new ArrayList<Report1>();
while (c.moveToNext()) {
try {
Goods objGoods = new Goods();
objGoods.setId(c.getString(c.getColumnIndex("ID")));
objGoods.setCode(c.getString(c.getColumnIndex("GoodsCode")));
objGoods.setName(c.getString(c.getColumnIndex("GoodsName")));
OrderStatus objStatus = new OrderStatus();
objStatus.setOrder_qty("0");
objStatus.setOrder_sum("0");
objStatus.setOrder_price("0");
objStatus.setOrder_qty(c.getString(c.getColumnIndex("order_qty")));
objStatus.setOrder_sum(c.getString(c.getColumnIndex("order_sum")));
objStatus.setOrder_price(c.getString(c.getColumnIndex("order_price")));
Report1 objReport1 = new Report1();
objReport1.setGoods(objGoods);
objReport1.setStatus(objStatus);
resultList.add(objReport1);
} catch (Exception e) {
Log.e("@sayesaman", "Error " + e.toString());
}
}
c.close();
return resultList;
}
//=======================================================================================================================================
public Report2Hdr getReport2(String goodsRef, OrderStatus reportStatus) {
final Cursor c;
String qry = "";
qry = handler.getResources().getString(R.string.OrderDao_getReport2);
String[] args = new String[1];
args[0] = goodsRef;
c = handler.rawQuery(qry, args);
Report2Hdr objReport2Hdr = new Report2Hdr();
Goods objGoods = goodsDao.getOneById(goodsRef);
objReport2Hdr.setGoods(objGoods);
objReport2Hdr.setReportStatus(reportStatus);
ArrayList<Report2Itm> listReport2Itms = new ArrayList<Report2Itm>();
int i = 0;
while (c.moveToNext()) {
try {
Customer objCustomer = new Customer();
objCustomer = customerDao.getCustomerSpecById(c.getString(c.getColumnIndex("ID")));
String goodsQty = c.getString(c.getColumnIndex("GoodsQty"));
Report2Itm objReport2Itm = new Report2Itm();
objReport2Itm.setNo(String.valueOf(++i));
objReport2Itm.setCustomer(objCustomer);
objReport2Itm.setGoodsQty(goodsQty);
listReport2Itms.add(objReport2Itm);
} catch (Exception e) {
Log.e("@sayesaman", "Error " + e.toString());
}
}
c.close();
objReport2Hdr.setReport2Itms(listReport2Itms);
return objReport2Hdr;
}
//=======================================================================================================================================
public String saveItem(String hdrRef, String orderItmId, String goodsRef, String newQty) {
if (newQty.equals("0") && !orderItmId.equals("0")) { //CRUD : delete
String[] args = new String[]{orderItmId};
handler.getDatabaseHandler().delete("tblOrderItm", "ID = " + orderItmId, null);
return "0";
} else if (newQty.equals("0") && orderItmId.equals("0")) { //CRUD : nothing
return "0";
} else if (!newQty.equals("0") && !orderItmId.equals("0")) { //CRUD : update
final ContentValues newValues = new ContentValues();
newValues.put("GoodsQty", newQty);
handler.getDatabaseHandler().update("tblOrderItm", newValues, "ID = ?", new String[]{orderItmId});
return orderItmId;
} else if (!newQty.equals("0") && orderItmId.equals("0")) { //CRUD : create new record
final ContentValues newValues = new ContentValues();
String newOrderItmId = newOrderItemId();
newValues.put("ID", newOrderItmId);
newValues.put("GoodsRef", goodsRef);
newValues.put("GoodsQty", newQty);
newValues.put("HdrRef", hdrRef);
handler.getDatabaseHandler().insert("tblOrderItm", null, newValues);
return newOrderItmId;
}
return null;
}
private String newOrderItemId() {
String qry = "SELECT ifnull(max(id),0) + 1 newId from tblOrderItm";
final Cursor c = handler.rawQuery(qry, null);
String newId = "";
while (c.moveToNext()) {
newId = c.getString(c.getColumnIndex("newId"));
}
c.close();
return newId;
}
public void saveBuyType(String formId, BuyType buyType) {
final ContentValues newValues = new ContentValues();
newValues.put("OrderBuyTypeID", buyType.getId());
newValues.put("OrderBuyTypeCode", buyType.getCode());
newValues.put("OrderNatijeVisitValue", 1);
handler.getDatabaseHandler().update("tblTourItm", newValues, "ID = ?", new String[]{formId});
}
//=======================================================================================================================================
}
|
int[][] minesweeper(boolean[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int[][] mines = new int[row][];
for(int i = 0; i < row; i++)
{
mines[i] = new int[col];
for(int j = 0; j < col; j++)
{
for(int bab = i-1; bab < i+2; bab++)
{
for(int puca = j-1; puca < j+2; puca++)
{
if(bab == i && puca == j)
continue;
else
{
try
{
if(matrix[bab][puca]) mines[i][j]++;
}
catch
}
}
}
}
}
}
|
package com.soft1841.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
public class PokerDemo {
public static void main(String[] args) {
//创建一个 HashMap 的集合
HashMap<Integer, String> hashMap = new HashMap<>();
//创建一个 ArrayList 的集合
ArrayList<Integer> arrayList = new ArrayList<>();
//创建一个花色与数字的数组
String[] colors = {"♥", "♦", "♠", "♣"};
String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",
"K", "A", "2"};
//从 0 开始往 HashMap 里面存储数字,同时往 ArrayList 里面存储数字
int index = 0;
for (String number : numbers
) {
for (String color : colors
) {
String Poker = color.concat(number);
hashMap.put(index, Poker);
arrayList.add(index);
index++;
}
}
hashMap.put(index, "大王");
hashMap.put(index, "小王");
arrayList.add(index);
//洗牌,将编号打乱
Collections.shuffle(arrayList);
//发牌,为了保证编号是排序的,创建一个 TreeSet 集合,获取编号
TreeSet<Integer> player1 = new TreeSet<>();
TreeSet<Integer> player2 = new TreeSet<>();
TreeSet<Integer> player3 = new TreeSet<>();
TreeSet<Integer> dipai = new TreeSet<>();
for (int x = 0; x < arrayList.size(); x++) {
if (x >= arrayList.size() - 3) {
dipai.add(arrayList.get(x));
} else if (x % 3 == 0) {
player1.add(arrayList.get(x));
} else if (x % 3 == 1) {
player2.add(arrayList.get(x));
} else if (x % 3 == 2) {
player3.add(arrayList.get(x));
}
}
//看牌,遍历编号,到 HashMap 集合找到对应的牌
lookPoker("玩家 1", player1, hashMap);
lookPoker("玩家 2", player2, hashMap);
lookPoker("玩家 3", player3, hashMap);
lookPoker("底牌", dipai, hashMap);
}
//看牌的方法
private static void lookPoker(String name, TreeSet<Integer> treeSet,
HashMap<Integer, String> hashMap) {
{
System.out.println();
System.out.println(name + "的牌是");
for (Integer key : treeSet) {
String value = hashMap.get(key);
System.out.print(value + " ");
}
}
}
}
|
package referencetype.practice;
public class Example1 {
public static void main(String[] args) {
int[] scores = null;
scores = new int[] {90, 80, 100};
System.out.println(scores[0]);
}
}
|
/*
* 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 model.ORM;
import java.text.ParseException;
import java.util.Date;
import model.Category;
/**
*
* @author PimGame
*/
public class ItemRow extends DbRow {
private int itemId;
private String name;
private String description;
private String currentPrice;
private String currentTrend;
private String todayTrend;
private String todayPriceChange;
private boolean members;
private String day30Trend;
private String day30Change;
private String day90Change;
private String day90Trend;
private String day180Trend;
private String day180Change;
private Category category;
private String lastUpdated;
private int accuratePrice;
public ItemRow() {
}
public void setItemId(int itemId) {
this.itemId = itemId;
setID(itemId);
}
public void setCurrentTrend(String currentTrend) {
this.currentTrend = currentTrend;
set("current_trend", currentTrend);
}
public void setCurrentPrice(String currentPrice) {
this.currentPrice = currentPrice;
set("current_price", currentPrice);
}
public void setAccuratePrice(int accuratePrice) {
this.accuratePrice = accuratePrice;
set("accurate_price", accuratePrice + "");
}
public void setName(String name) {
this.name = name;
set("name", name);
}
public void setDescription(String description) {
this.description = description;
set("description", description);
}
public void setTodayTrend(String todayTrend) {
this.todayTrend = todayTrend;
set("today_trend", todayTrend);
}
public void setTodayPriceChange(String todayPriceChange) {
this.todayPriceChange = todayPriceChange;
set("today_price_change", todayPriceChange + "");
}
public void setMembers(boolean members) {
this.members = members;
if (members == true) {
set("members", 1 + "");
} else {
set("members", 0 + "");
}
}
public void setDay30Trend(String day30Trend) {
this.day30Trend = day30Trend;
set("30day_trend", day30Trend);
}
public void setDay30Change(String day30Change) {
this.day30Change = day30Change;
set("30day_change", day30Change);
}
public void setDay90Trend(String day90Trend) {
this.day90Trend = day90Trend;
set("90day_trend", day90Trend);
}
public void setDay90Change(String day90Change) {
this.day90Change = day90Change;
set("90day_change", day90Change);
}
public void setDay180Trend(String day180Trend) {
this.day180Trend = day180Trend;
set("180day_trend", day180Trend);
}
public void setDay180Change(String day180Change) {
this.day180Change = day180Change;
set("180day_change", day180Change);
}
public void setCategory(Category category) {
this.category = category;
set("category", category.getCategoryNumber() + "");
}
public void setLastUpdated(String reportDate) {
this.lastUpdated = reportDate;
set("last_updated", reportDate);
}
public int getItemId() {
return getID();
//return this.itemId;
}
public String getName() {
return get("name");
//return this.name;
}
public String getDescription() {
return get("description");
//return this.description;
}
public String getPrice() {
return get("current_price");
//return this.currentPrice;
}
public String getTodayTrend() {
return get("today_trend");
// return this.todayTrend;
}
public int getAccuratePrice() {
if (get("accurate_price") != null && !get("accurate_price").isEmpty()) {
return Integer.parseInt(get("accurate_price"));
} else {
return -1;
}
}
public String getAccuratePriceString() {
if (get("accurate_price") != null && !get("accurate_price").isEmpty()) {
String str = String.format("%,d", getAccuratePrice());
return str;
}
return "-1";
}
public String getTodayPriceChange() {
return get("today_price_change");
// return this.todayPriceChange;
}
public boolean isMembers() {
if (get("members").equals("1")) {
return true;
} else {
return false;
}
//return this.members;
}
public String getDay30Trend() {
return get("30day_trend");
//return this.day30Trend;
}
public String getDay30Change() {
return get("30day_change");
//return this.day30Change;
}
public String getDay90Trend() {
return get("90day_trend");
//return this.day90Trend;
}
public String getDay90Change() {
return get("90day_change");
//return this.day90Change;
}
public String getDay180Trend() {
return get("180day_trend");
//return this.day180Trend;
}
public String getDay180Change() {
return get("180day_change");
//return this.day180Change;
}
public Category getCategory() {
return Category.getByNumber(Integer.parseInt(get("category")));
//return this.category;
}
public String getLastUpdated() {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf
= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
java.util.Date date = (Date) sdf.parse(get("last_updated"));
String currentTime = sdf.format(date);
return currentTime;
} catch (ParseException ex) {
return "";
}
// return currentTime;
}
@Override
public String toString() {
return getName();
}
}
|
package pro.likada.dao;
import pro.likada.model.Truck;
import java.util.List;
/**
* Created by abuca on 06.03.17.
*/
public interface TruckDAO {
Truck findById(long id);
void save(Truck truck);
List<Truck> findAllTrucks(String searchString);
void deleteById(long id);
Long findAmountOfVehiclesConnectedWithTruck(Truck truck);
}
|
package com.myvodafone.android.front.fixed;
import com.myvodafone.android.model.service.fixed.FxlProduct;
import java.util.List;
public class PlanListItem {
private String plan;
public PlanListItem() {
}
public PlanListItem(String plan) {
this.plan = plan;
}
public String getPlan() {
return plan;
}
public void setPlan(String plan) {
this.plan = plan;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow 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 any later version. *
* *
* Data Crow 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 net.datacrow.console.wizards.module;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.datacrow.console.wizards.IWizardPanel;
import net.datacrow.console.wizards.Wizard;
import net.datacrow.console.wizards.WizardException;
import net.datacrow.core.DataCrow;
import net.datacrow.core.DcRepository;
import net.datacrow.core.db.DcDatabase;
import net.datacrow.core.modules.DcMediaModule;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.modules.ModuleJar;
import net.datacrow.core.modules.xml.XmlField;
import net.datacrow.core.modules.xml.XmlModule;
import net.datacrow.core.objects.DcField;
import net.datacrow.core.objects.DcMediaObject;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.resources.DcResources;
import net.datacrow.settings.DcSettings;
import net.datacrow.util.DcSwingUtilities;
import org.apache.log4j.Logger;
public class DeleteModuleWizard extends Wizard {
private static Logger logger = Logger.getLogger(DcDatabase.class.getName());
public DeleteModuleWizard() {
super();
setTitle(DcResources.getText("lblModuleDeleteWizard"));
setHelpIndex("dc.modules.delete");
setSize(DcSettings.getDimension(DcRepository.Settings.stModuleWizardFormSize));
setCenteredLocation();
}
@Override
protected void initialize() {}
@Override
protected List<IWizardPanel> getWizardPanels() {
List<IWizardPanel> panels = new ArrayList<IWizardPanel>();
panels.add(new PanelSelectModuleToDelete(this));
panels.add(new PanelDeletionDetails(this));
return panels;
}
@Override
protected void saveSettings() {
DcSettings.set(DcRepository.Settings.stModuleWizardFormSize, getSize());
}
@Override
public void finish() throws WizardException {
if (!DcSwingUtilities.displayQuestion("msgDeleteModuleConfirmation"))
return;
XmlModule xmlModule = (XmlModule) getCurrent().apply();
DcModule module = DcModules.get(xmlModule.getIndex()) == null ?
DcModules.getPropertyBaseModule(xmlModule.getIndex()) :
DcModules.get(xmlModule.getIndex());
try {
module.delete();
// update the referencing modules; remove fields holding a reference to this module
Collection<XmlField> remove = new ArrayList<XmlField>();
for (DcModule reference : DcModules.getReferencingModules(xmlModule.getIndex())) {
if (reference != null && reference.getXmlModule() != null) {
for (XmlField field : reference.getXmlModule().getFields()){
if (reference.getField(field.getIndex()).getSourceModuleIdx() == xmlModule.getIndex())
remove.add(field);
}
reference.getXmlModule().getFields().removeAll(remove);
new ModuleJar(reference.getXmlModule()).save();
}
}
// parent child relation should be undone
undoParentChildRelation(module.getParent() != null ? module.getParent() : module.getChild());
// make sure the 'hasDependingModules' property is corrected for modules holding
// a referencing to this module
DcModule reference;
for (DcField field : module.getFields()) {
if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE) {
reference = DcModules.getReferencedModule(field);
if (reference.getXmlModule() == null) continue;
if (reference.hasDependingModules() && DcModules.getReferencingModules(reference.getIndex()).size() == 1)
reference.getXmlModule().setHasDependingModules(false);
new ModuleJar(reference.getXmlModule()).save();
}
}
// not needed for property base modules
if (DcModules.get(xmlModule.getIndex()) != null) {
DcModules.get(xmlModule.getIndex()).isEnabled(false);
DataCrow.mainFrame.applySettings(false);
}
close();
} catch (Exception e) {
logger.error(e, e);
throw new WizardException(DcResources.getText("msgCouldNotDeleteModule", e.getMessage()));
}
}
private void undoParentChildRelation(DcModule module) throws Exception {
if (module == null) return;
if (module.getType() == DcModule._TYPE_MEDIA_MODULE) {
module.getXmlModule().setModuleClass(DcMediaModule.class);
module.getXmlModule().setObject(DcMediaObject.class);
} else {
module.getXmlModule().setModuleClass(DcModule.class);
module.getXmlModule().setObject(DcObject.class);
}
module.getXmlModule().setChildIndex(-1);
module.getXmlModule().setParentIndex(-1);
new ModuleJar(module.getXmlModule()).save();
}
@Override
public void next() {
try {
XmlModule module = (XmlModule) getCurrent().apply();
if (module == null)
return;
current += 1;
if (current <= getStepCount()) {
ModuleWizardPanel panel;
for (int i = 0; i < getStepCount(); i++) {
panel = (ModuleWizardPanel) getWizardPanel(i);
panel.setModule(module);
panel.setVisible(i == current);
}
} else {
current -= 1;
}
applyPanel();
} catch (WizardException wzexp) {
if (wzexp.getMessage().length() > 1)
DcSwingUtilities.displayWarningMessage(wzexp.getMessage());
}
}
@Override
public void close() {
if (!isCancelled() && !isRestarted())
new RestartDataCrowDialog(this);
super.close();
}
@Override
protected String getWizardName() {
return DcResources.getText("msgModuleWizard",
new String[] {String.valueOf(current + 1), String.valueOf(getStepCount())});
}
@Override
protected void restart() {
try {
finish();
saveSettings();
CreateModuleWizard wizard = new CreateModuleWizard();
wizard.setVisible(true);
} catch (WizardException exp) {
DcSwingUtilities.displayWarningMessage(exp.getMessage());
}
}
}
|
package poiati.bobby;
public class FacebookIdAlreadyExistsException extends RuntimeException {
public FacebookIdAlreadyExistsException(final Integer facebookId) {
super(facebookId.toString());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DataAccess;
import Entity.Menu;
import Utility.SQLHelper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author TUNT
*/
public class MenuDAL {
private ResultSet objResult;
private static MenuDAL instance;
public static MenuDAL getInstance() {
if (instance == null) {
instance = new MenuDAL();
}
return instance;
}
public List<Menu> getMenuList() {
List<Menu> menuList = new ArrayList<Menu>();
try {
objResult = SQLHelper.getInstance().executeQuery("Sel_AllMenu", null);
while (objResult.next()) {
menuList.add(CreateMenuByResultSet(objResult));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return menuList;
}
public void addMenu(Menu menu) {
try {
String[] params = new String[2];
params[0] = menu.getMenuName();
params[1] = menu.getDescription();
SQLHelper.getInstance().executeUpdate("Ins_Menu", params);
} catch (Exception e) {
e.printStackTrace();
}
}
public Menu getMenuByID(int menuID) {
Menu menu = new Menu();
String[] params = new String[1];
params[0] = String.valueOf(menuID);
try {
objResult = SQLHelper.getInstance().executeQuery("Sel_MenuById", params);
while (objResult.next()) {
menu = CreateMenuByResultSet(objResult);
}
} catch (Exception ex) {
}
return menu;
}
public void editMenu(Menu menu) {
String[] params = new String[3];
params[0] = String.valueOf(menu.getMenuID());
params[1] = menu.getMenuName();
params[2] = menu.getDescription();
try {
SQLHelper.getInstance().executeQuery("Udp_MenuById", params);
} catch (Exception e) {
e.printStackTrace();
}
}
public Menu CreateMenuByResultSet(ResultSet objResult) {
Menu menu = new Menu();
try {
menu.setMenuID(objResult.getInt("MenuID"));
menu.setMenuName(objResult.getString("MenuName"));
menu.setDescription(objResult.getString("Description"));
} catch (Exception ex) {
try {
return getMenuByID(objResult.getInt("MenuID"));
} catch (SQLException ex1) {
}
}
return menu;
}
}
|
package tridoo.sigma2;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
class GameActivityTest {
private GameActivity game;
@BeforeEach
void init() {
game = new GameActivity();
Class<?> secretClass = game.getClass();
Field field;
try {
field = secretClass.getDeclaredField("levelConfig");
field.setAccessible(true);
field.set(game, generateLevelConfig());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
void getRank() {
int points = 10;
int expectedRank = 3;
int rank = game.getRank(points);
Assertions.assertEquals(expectedRank, rank);
}
@Test
void getLevelConfig() {
Level cfg = game.getLevelConfig();
Assertions.assertEquals(generateLevelConfig().getLevelNumber(), cfg.getLevelNumber());
}
private Level generateLevelConfig() {
return Level.of(1, 1, 1, 2, 4, 8, 0);
}
} |
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.converter.impl;
import org.junit.Test;
/**
* TimeRangeConverter测试.
*
* @author 小流氓[176543888@qq.com]
* @since 3.4
*/
public class TimeRangeConverterTest {
@Test
public void testConvertString() throws Exception {
TimeRangeConverter converter = new TimeRangeConverter();
converter.convert("[*][*][*][*][00:00-23:59:59:999]");
}
} |
package forms;
import java.util.Collection;
import javax.validation.Valid;
import org.hibernate.validator.constraints.URL;
import datatype.Url;
import domain.PeriodRecord;
public class PeriodRecordForm {
private int id;
private int version;
private String title;
private String description;
private Integer startYear;
private Integer endYear;
private Collection<Url> photo;
private String link;
public PeriodRecordForm(final PeriodRecord pR) {
this.id = pR.getId();
this.version = pR.getVersion();
this.title = pR.getTitle();
this.description = pR.getDescription();
this.startYear = pR.getStartYear();
this.endYear = pR.getEndYear();
this.photo = pR.getPhoto();
}
public PeriodRecordForm() {
}
public int getId() {
return this.id;
}
public int getVersion() {
return this.version;
}
public void setId(final int id) {
this.id = id;
}
public void setVersion(final int version) {
this.version = version;
}
public String getTitle() {
return this.title;
}
public String getDescription() {
return this.description;
}
public Integer getStartYear() {
return this.startYear;
}
public Integer getEndYear() {
return this.endYear;
}
public Collection<Url> getPhoto() {
return this.photo;
}
@Valid
@URL
public String getLink() {
return this.link;
}
public void setTitle(final String title) {
this.title = title;
}
public void setDescription(final String description) {
this.description = description;
}
public void setStartYear(final Integer startYear) {
this.startYear = startYear;
}
public void setEndYear(final Integer endYear) {
this.endYear = endYear;
}
public void setPhoto(final Collection<Url> photo) {
this.photo = photo;
}
public void setLink(final String link) {
this.link = link;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.