text stringlengths 10 2.72M |
|---|
package com.freejavaman;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class UI_EditText extends Activity {
EditText edit;
TextView txt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView)this.findViewById(R.id.txt1);
edit = (EditText)this.findViewById(R.id.edit1);
edit.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
txt.setText(edit.getText());
return false;
}
});
//Editable editAble = edit.getText();
//Log.v("UI_EditText", editAble.toString());
//edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
//edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
} |
package com.rastiehaiev.notebook.test;
import com.rastiehaiev.notebook.test.condition.ICondition;
import com.rastiehaiev.notebook.test.handler.IParameterHandler;
import org.apache.commons.collections4.CollectionUtils;
import java.util.List;
import java.util.Map;
/**
* @author Roman Rastiehaiev
* Created on 12.10.15.
*/
public class ValidationObject {
private final Map<ICondition, List<IParameterHandler>> handlers;
public ValidationObject(Map<ICondition, List<IParameterHandler>> handlers) {
this.handlers = handlers;
}
public void validate() throws ParameterException {
for (Map.Entry<ICondition, List<IParameterHandler>> handlersEntry : handlers.entrySet()) {
ICondition condition = handlersEntry.getKey();
List<IParameterHandler> handlers = handlersEntry.getValue();
if (condition.isTrue()) {
if (CollectionUtils.isEmpty(handlers)) {
return;
}
for (IParameterHandler handler : handlers) {
handler.handle();
}
return;
}
}
}
}
|
package workstarter.service.impl;
import workstarter.service.ProfessionService;
import workstarter.domain.Profession;
import workstarter.repository.ProfessionRepository;
import workstarter.repository.search.ProfessionSearchRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* Service Implementation for managing Profession.
*/
@Service
@Transactional
public class ProfessionServiceImpl implements ProfessionService{
private final Logger log = LoggerFactory.getLogger(ProfessionServiceImpl.class);
private final ProfessionRepository professionRepository;
private final ProfessionSearchRepository professionSearchRepository;
public ProfessionServiceImpl(ProfessionRepository professionRepository, ProfessionSearchRepository professionSearchRepository) {
this.professionRepository = professionRepository;
this.professionSearchRepository = professionSearchRepository;
}
/**
* Save a profession.
*
* @param profession the entity to save
* @return the persisted entity
*/
@Override
public Profession save(Profession profession) {
log.debug("Request to save Profession : {}", profession);
Profession result = professionRepository.save(profession);
professionSearchRepository.save(result);
return result;
}
/**
* Get all the professions.
*
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public List<Profession> findAll() {
log.debug("Request to get all Professions");
List<Profession> result = professionRepository.findAll();
return result;
}
/**
* Get one profession by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public Profession findOne(Long id) {
log.debug("Request to get Profession : {}", id);
Profession profession = professionRepository.findOne(id);
return profession;
}
/**
* Delete the profession by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Profession : {}", id);
professionRepository.delete(id);
professionSearchRepository.delete(id);
}
/**
* Search for the profession corresponding to the query.
*
* @param query the query of the search
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public List<Profession> search(String query) {
log.debug("Request to search Professions for query {}", query);
return StreamSupport
.stream(professionSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
}
|
package org.gbif.rest.client.geocode.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Scanner;
import java.util.StringJoiner;
/**
* Tests utility class that loads test data for Geocode reverse lookups.
* Uses a file taken from: https://developers.google.com/public-data/docs/canonical/countries_csv.
* This class should be used for test cases only!
*/
public class CountryCentroids {
//Test file
private static final String COUNTRIES_FILE = "country_centroids.csv";
//Column separator of the test file
private static final String SEPARATOR = "\t";
//Maker to ignore lines in the test data file
private static final String IGNORE_MARKER = "#";
//List of loaded countries
private final List<Country> countries;
/**
* Creates a new instance using the default test file.
*/
public CountryCentroids() {
countries = loadCountriesData(CountryCentroids.class.getClassLoader().getResource(COUNTRIES_FILE).getFile());
}
/**
*
* @return the list of loaded countries
*/
public List<Country> getCountries() {
return countries;
}
/**
* Finds a country byt its ISO country code.
* @param countryCode ISO country code
* @return found country, Optional.empty() otherwise
*/
public Optional<Country> findByCountryCode(String countryCode) {
return countries.stream().filter(country -> country.getIsoCode().equals(countryCode)).findFirst();
}
/**
* Finds a country byt its coordinate centroid.
* @param latitude decimal latitude
* @param longitude decimal longitude
* @return found country, Optional.empty() otherwise
*/
public Optional<Country> findByCoordinate(Double latitude, Double longitude) {
return countries.stream().filter(country -> country.getLatitude().equals(latitude) &&
country.getLongitude().equals(longitude)).findFirst();
}
/**
* Loads the list of countries form a test data file.
* @param dataFile test file
* @return the list of countries
*/
private static List<Country> loadCountriesData(String dataFile) {
try {
List<Country> records = new ArrayList<>();
try (Scanner scanner = new Scanner(new File(dataFile), StandardCharsets.UTF_8.name())) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!line.startsWith(IGNORE_MARKER)) {
records.add(fromLine(line, SEPARATOR));
}
}
}
return records;
} catch (FileNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
}
/**
* Converts a String, split by a separator, into a Country instance.
* @param line to read
* @param separator column separator
* @return a Country parsed from the line
*/
private static Country fromLine(String line, String separator) {
String[] lineData = line.split(separator);
return new Country(lineData[0], Double.parseDouble(lineData[1]), Double.parseDouble(lineData[2]), lineData[3]);
}
/**
* Class to abstract the content of the test data file.
*/
public static class Country {
private final String isoCode;
private final Double latitude;
private final Double longitude;
private final String name;
public Country(String isoCode, Double latitude, Double longitude, String name) {
this.isoCode = isoCode;
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
}
public String getIsoCode() {
return isoCode;
}
public Double getLatitude() {
return latitude;
}
public Double getLongitude() {
return longitude;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Country country = (Country) o;
return Objects.equals(isoCode, country.isoCode) &&
Objects.equals(latitude, country.latitude) &&
Objects.equals(longitude, country.longitude) &&
Objects.equals(name, country.name);
}
@Override
public int hashCode() {
return Objects.hash(isoCode, latitude, longitude, name);
}
@Override
public String toString() {
return new StringJoiner(", ", Country.class.getSimpleName() + "[", "]")
.add("isoCode='" + isoCode + "'")
.add("latitude=" + latitude)
.add("longitude=" + longitude)
.add("name='" + name + "'")
.toString();
}
}
}
|
package commandline.language.parser.specific.list;
import commandline.language.parser.specific.DoubleArgumentParser;
/*
* This class is aimed to be used in the @CliAnnotation
*/
/**
* User: gno, Date: 18.02.2015 - 14:44
*/
public class DoubleListArgumentParser extends ListArgumentParser<Double> {
public DoubleListArgumentParser() {
super(new DoubleArgumentParser());
}
}
|
package org.addressbook.textutils;
import java.util.Scanner;
/**
* A utility class with (so far) one static method for getting
* values from the user, using standard out and standard in for
* communication.
*/
public class TextUtils{
private static Scanner in = new Scanner(System.in);
/* We don't want client code to instantiate this class */
private TextUtils(){}
/**
* Asks the user a question and returns the result.
* Note, this method doesn't check a user reply of NULL,
* the empty String "". Nor does it trim the user's reply.
*
* These limitations are topics for the next assignment!
* @param prompt The question to ask the user, e.g. "Name: "
* @return The user's reply as a reference to a String
*
*/
public static String askFor(String prompt){
String result;
System.out.print(prompt + ": ");
if(System.console() == null){
result = in.nextLine();
}else{
result = System.console().readLine();
}
return result;
}
}
|
package com.meta.db;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LibraryController {
@Autowired LibraryRepository libRepository;
@Autowired LibraryService libService;
@RequestMapping(value="/library/search", method=RequestMethod.GET)
public String libraryConfirm(Model model) {
LibraryDto libraryDto = libService.service();
libRepository.deleteAll();
for(int i = 0 ; i < libraryDto.getResults().size(); i++ ) {
//System.out.println(libraryDto.getResults().get(i).getId());
//IDをループで自動連番
libraryDto.getResults().get(i).setId(i + 1);
libRepository.saveAndFlush(libraryDto.getResults().get(i));
}
List<LibraryApi> libList = libRepository.findAll();
for (int i = 0; i < libList.size() ; i++) {
//
String geocode = libList.get(i).getGeocode();
String[] geo = geocode.split(",");
libList.get(i).setLat(geo[0]);
libList.get(i).setLng(geo[1]);
}
libRepository.saveAll(libList);
libRepository.flush();
model.addAttribute("libList",libraryDto.getResults());
return "library";
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.form;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTWorkspace;
import com.openkm.frontend.client.constants.ui.UIDesktopConstants;
import com.openkm.frontend.client.widget.searchin.HasPropertyHandler;
/**
* FolderSelectPopup
*
* @author jllort
*
*/
public class FolderSelectPopup extends DialogBox {
private ListBox contextListBox;
private VerticalPanel vPanel;
private HorizontalPanel hPanel;
private HorizontalPanel hListPanel;
private HorizontalPanel hContextPanel;
private HTML contextTxt;
private ScrollPanel scrollDirectoryPanel;
private VerticalPanel verticalDirectoryPanel;
private FolderSelectTree folderSelectTree;
private Button cancelButton;
private Button actionButton;
private TextBox textBox;
private HasPropertyHandler propertyHandler;
private boolean categoriesVisible = false;
private boolean thesaurusVisible = false;
private boolean templatesVisible = false;
private boolean personalVisible = false;
private boolean mailVisible = false;
/**
* FolderSelectPopup
*/
public FolderSelectPopup() {
// Establishes auto-close when click outside
super(false,true);
vPanel = new VerticalPanel();
vPanel.setWidth("300px");
vPanel.setHeight("200px");
hPanel = new HorizontalPanel();
hListPanel = new HorizontalPanel();
hContextPanel = new HorizontalPanel();
contextTxt = new HTML(Main.i18n("search.context"));
contextListBox = new ListBox();
contextListBox.setStyleName("okm-Select");
contextListBox.addChangeHandler(new ChangeHandler(){
@Override
public void onChange(ChangeEvent event) {
folderSelectTree.changeView(Integer.parseInt(contextListBox.getValue(contextListBox.getSelectedIndex())));
}
}
);
hContextPanel.add(contextTxt);
hContextPanel.add(new HTML(" "));
hContextPanel.add(contextListBox);
hContextPanel.setCellVerticalAlignment(contextTxt, HasVerticalAlignment.ALIGN_MIDDLE);
hListPanel.add(hContextPanel);
hListPanel.setWidth("290px");
setText(Main.i18n("search.folder.filter"));
scrollDirectoryPanel = new ScrollPanel();
scrollDirectoryPanel.setSize("290px", "150px");
scrollDirectoryPanel.setStyleName("okm-Popup-text");
verticalDirectoryPanel = new VerticalPanel();
verticalDirectoryPanel.setSize("100%", "100%");
folderSelectTree = new FolderSelectTree();
folderSelectTree.setSize("100%", "100%");
verticalDirectoryPanel.add(folderSelectTree);
scrollDirectoryPanel.add(verticalDirectoryPanel);
cancelButton = new Button(Main.i18n("button.cancel"), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
actionButton = new Button(Main.i18n("button.select"), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
textBox.setValue(folderSelectTree.getActualPath());
if (propertyHandler!=null) {
propertyHandler.metadataValueChanged();
}
hide();
}
});
vPanel.add(new HTML("<br>"));
vPanel.add(hListPanel);
vPanel.add(new HTML("<br>"));
vPanel.add(scrollDirectoryPanel);
vPanel.add(new HTML("<br>"));
hPanel.add(cancelButton);
HTML space = new HTML();
space.setWidth("50px");
hPanel.add(space);
hPanel.add(actionButton);
vPanel.add(hPanel);
vPanel.add(new HTML("<br>"));
vPanel.setCellHorizontalAlignment(hListPanel, HasAlignment.ALIGN_CENTER);
vPanel.setCellHorizontalAlignment(scrollDirectoryPanel, HasAlignment.ALIGN_CENTER);
vPanel.setCellHorizontalAlignment(hPanel, HasAlignment.ALIGN_CENTER);
vPanel.setCellHeight(scrollDirectoryPanel, "150px");
cancelButton.setStyleName("okm-Input");
actionButton.setStyleName("okm-Input");
super.hide();
setWidget(vPanel);
}
/**
* Language refresh
*/
public void langRefresh() {
contextTxt.setHTML(Main.i18n("search.context"));
setText(Main.i18n("search.folder.filter"));
cancelButton.setText(Main.i18n("button.cancel"));
actionButton.setText(Main.i18n("button.select"));
removeAllContextListItems();
int count = 0;
contextListBox.setItemText(count++,Main.i18n("leftpanel.label.taxonomy"));
if (categoriesVisible) {
contextListBox.setItemText(count++,Main.i18n("leftpanel.label.categories"));
}
if (thesaurusVisible) {
contextListBox.setItemText(count++,Main.i18n("leftpanel.label.thesaurus"));
}
if (templatesVisible) {
contextListBox.setItemText(count++,Main.i18n("leftpanel.label.templates"));
}
if (personalVisible) {
contextListBox.setItemText(count++,Main.i18n("leftpanel.label.my.documents"));
}
if (mailVisible) {
contextListBox.setItemText(count++,Main.i18n("leftpanel.label.mail"));
}
}
/**
* Shows the popup
*/
public void show(TextBox textBox, HasPropertyHandler propertyHandler) {
this.textBox = textBox;
this.propertyHandler = propertyHandler;
int left = (Window.getClientWidth()-300) / 2;
int top = (Window.getClientHeight()-200) / 2;
setPopupPosition(left, top);
// Resets to initial tree value
folderSelectTree.reset();
GWTWorkspace workspace = Main.get().workspaceUserProperties.getWorkspace();
categoriesVisible = workspace.isStackCategoriesVisible();
thesaurusVisible = workspace.isStackThesaurusVisible();
templatesVisible = workspace.isStackTemplatesVisible();
personalVisible = workspace.isStackPersonalVisible();
mailVisible = workspace.isStackMailVisible();
removeAllContextListItems();
contextListBox.addItem(Main.i18n("leftpanel.label.taxonomy"),""+UIDesktopConstants.NAVIGATOR_TAXONOMY);
if (categoriesVisible) {
contextListBox.addItem(Main.i18n("leftpanel.label.categories"),""+UIDesktopConstants.NAVIGATOR_CATEGORIES);
}
if (thesaurusVisible) {
contextListBox.addItem(Main.i18n("leftpanel.label.thesaurus"),""+UIDesktopConstants.NAVIGATOR_THESAURUS);
}
if (templatesVisible) {
contextListBox.addItem(Main.i18n("leftpanel.label.templates"),""+UIDesktopConstants.NAVIGATOR_TEMPLATES);
}
if (personalVisible) {
contextListBox.addItem(Main.i18n("leftpanel.label.my.documents"),""+UIDesktopConstants.NAVIGATOR_PERSONAL);
}
if (mailVisible) {
contextListBox.addItem(Main.i18n("leftpanel.label.mail"),""+UIDesktopConstants.NAVIGATOR_MAIL);
}
super.show();
}
/**
* Enables or disables move button
*
* @param enable
*/
public void enable(boolean enable) {
actionButton.setEnabled(enable);
}
/**
* removeAllContextListItems
*/
private void removeAllContextListItems() {
while (contextListBox.getItemCount()>0) {
contextListBox.removeItem(0);
}
}
} |
package ch24.ex24_03;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class MyDateParse {
private static final int[] styles = {
DateFormat.FULL,
DateFormat.LONG,
DateFormat.MEDIUM,
DateFormat.SHORT
};
private static final String[] styleStrs = {
"FULL",
"LONG",
"MEDIUM",
"SHORT"
};
private static final DateFormat[] dateFomatters;
private static final DateFormat[] timeFomatters;
private static final DateFormat[] dateTimeFomatters;
static {
dateFomatters = new DateFormat[styles.length];
for (int i = 0; i < styles.length; i++) {
dateFomatters[i] = DateFormat.getDateInstance(styles[i]);
}
timeFomatters = new DateFormat[styles.length];
for (int i = 0; i < styles.length; i++) {
timeFomatters[i] = DateFormat.getTimeInstance(styles[i]);
}
dateTimeFomatters = new DateFormat[styles.length * styles.length];
for (int i = 0; i < styles.length; i++) {
for (int j = 0; j < styles.length; j++) {
int index = i * styles.length + j;
dateTimeFomatters[index] = DateFormat.getDateTimeInstance(styles[i], styles[j]);
}
}
}
public static void main(String[] args) {
printAllDateFormat("2012/12/01 10:10");
for (String dateStr : args) {
printAllDateFormat(dateStr);
}
}
private static void printAllDateFormat(String dateStr) {
for (int i = 0; i < dateFomatters.length; i++) {
try {
printDate(dateStr, dateFomatters[i]);
} catch (ParseException e) {
System.out.println("invalid date format: " + dateStr + " (style: " + styleStrs[i] + ")");
}
}
System.out.println();
for (int i = 0; i < timeFomatters.length; i++) {
try {
printDate(dateStr, timeFomatters[i]);
} catch (ParseException e) {
System.out.println("invalid date format: " + dateStr + " (style: " + styleStrs[i] + ")");
}
}
System.out.println();
for (int i = 0; i < dateTimeFomatters.length; i++) {
try {
printDate(dateStr, dateTimeFomatters[i]);
} catch (ParseException e) {
System.out.println("invalid date format: " + dateStr + " (style: " + styleStrs[i / 4] + " + " + styleStrs[i % 4] + ")");
}
}
}
private static void printDate(String dateStr, DateFormat formatter) throws ParseException {
Date date = formatter.parse(dateStr);
System.out.println(formatter.format(date));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mytest.serialize;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.mytest.common.utils.KyroSerializationUtils;
/**
* @author liqingyu
* @since 2018/12/27
*/
public class SerializationUtilsTest {
private final static Logger LOGGER = LoggerFactory.getLogger(SerializationUtilsTest.class);
@Test
public void test() throws FileNotFoundException {
System.out.println("asdf");
Kryo kryo = new Kryo();
kryo.register(SomeClass.class);
SomeClass object = new SomeClass();
object.value = "Hello Kryo!";
Output output = new Output(new FileOutputStream("file.bin"));
kryo.writeObject(output, object);
output.close();
Input input = new Input(new FileInputStream("file.bin"));
SomeClass object2 = kryo.readObject(input, SomeClass.class);
input.close();
}
@Test
public void test2() {
SomeClass object = new SomeClass();
object.value = "Hello Kryo!";
byte[] bytes = KyroSerializationUtils.writeObject(object, SomeClass.class);
System.out.println(new String(bytes));
Object object2 = KyroSerializationUtils.readObject(bytes, SomeClass.class);
if (object2 instanceof SomeClass) {
SomeClass someClass2 = (SomeClass) object2;
LOGGER.warn("Y" + someClass2);
} else {
LOGGER.warn("N");
}
}
static public class SomeClass {
String value;
}
}
|
/*
* Copyright 2008 Eckhart Arnold (eckhart_arnold@hotmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package tddd24.ajgallery.client.gwtphotoalbum;
import java.util.HashSet;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
//import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Displays a row of thumbnail images as if
* on a film strip.
*
* @author ecki
*
*/
public class Filmstrip extends Composite implements ResizeListener {
/**
* An interface that encapsulates a callback method which is called when
* the user clicks on an image of the film strip.
*/
public interface IPickImage {
/**
* Called when the user clicks on a certain image on the film strip.
* @param imageNr the number of the image that has been clicked on by
* the user.
*/
void onPickImage(int imageNr);
}
private class Sliding extends Animation {
private int displacement, current;
public boolean isComplete() {
return current == 0;
}
public void onComplete() {
if (current != 0) {
current = 0;
redraw(0);
}
thumbnails.get(cursor).setStylePrimaryName("filmstripHighlighted");
}
public void onUpdate(double progress) {
int pos = (int)((1.0-progress) * displacement);
if (Math.abs(pos - current) >= 10) { // do not take every small step!
current = pos;
redraw(current);
}
}
public void setDisplacement(int displacement) {
cancel();
current = -1;
this.displacement = displacement;
}
}
private int width, height = -1;
private int borderSize = 2; // should be the same as specified in the css-file!!!
private int cursor = 0;
private int filmstripBorderSize = 0; // should be the same as specified in the css-file!!!
private boolean isLoaded = false; // true, if the filmstrip is visible
private int slidingDuration = 200;
private HashSet<Image> visible;
private IPickImage pickImageCallback;
private final SimplePanel envelope;
private final AbsolutePanel panel;
private final Sliding sliding = new Sliding();
private final Thumbnails thumbnails;
/**
* The constructor of class <code>Filmstrip</code>
* @param collection the image collection info from which to construct the
* film strip
*/
public Filmstrip(ImageCollectionInfo collection) {
this(new Thumbnails(collection));
}
/**
* The constructor of class <code>Filmstrip</code>
* @param thumbnailImages the thumb nail images to be displayed on the
* film strip
*/
public Filmstrip(Thumbnails thumbnailImages) {
this.thumbnails = thumbnailImages;
envelope = new SimplePanel();
envelope.addStyleName("filmstripEnvelope");
panel = new AbsolutePanel();
panel.addStyleName("filmstripPanel");
envelope.setWidget(panel);
initWidget(envelope);
// sinkEvents(Event.ONMOUSEWHEEL);
ClickHandler imageClickHandler = new ClickHandler() {
public void onClick(ClickEvent event) {
Widget sender = (Widget) event.getSource();
if (pickImageCallback != null) {
pickImageCallback.onPickImage(thumbnails.indexOf((Image) sender));
}
}
};
MouseDownHandler imageMouseDownHandler = new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event) {
Widget sender = (Widget) event.getSource();
if (pickImageCallback != null && sender != thumbnails.get(cursor)) {
sender.addStyleName("filmstripPressed");
}
}
};
MouseOverHandler imageMouseOverHandler = new MouseOverHandler() {
public void onMouseOver(MouseOverEvent event) {
Widget sender = (Widget) event.getSource();
if (pickImageCallback != null && sender != thumbnails.get(cursor)) {
sender.addStyleName("filmstripTouched");
}
}
};
MouseOutHandler imageMouseOutHandler = new MouseOutHandler() {
public void onMouseOut(MouseOutEvent event) {
Widget sender = (Widget) event.getSource();
if (pickImageCallback != null && sender != thumbnails.get(cursor)) {
sender.removeStyleName("filmstripTouched");
sender.removeStyleName("filmstripPressed");
}
}
};
MouseUpHandler imageMouseUpHandler = new MouseUpHandler() {
public void onMouseUp(MouseUpEvent event) {
Widget sender = (Widget) event.getSource();
if (pickImageCallback != null && sender != thumbnails.get(cursor)) {
sender.removeStyleName("filmstripPressed");
}
}
};
for (int i = 0; i < thumbnails.size(); i++) {
Image img = thumbnails.get(i);
if (i == cursor) img.setStyleName("filmstripHighlighted");
else img.setStyleName("filmstrip");
img.addClickHandler(imageClickHandler);
img.addMouseDownHandler(imageMouseDownHandler);
img.addMouseOverHandler(imageMouseOverHandler);
img.addMouseOutHandler(imageMouseOutHandler);
img.addMouseUpHandler(imageMouseUpHandler);
}
visible = new HashSet<Image>();
}
/**
* Returns the duration in milliseconds for sliding from one image
* to the next.
* @return Duration in milliseconds
*/
public int getSlidingDuration() {
return slidingDuration;
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt.user.client.Event)
*/
/* @Override
public void onBrowserEvent(Event event) {
switch (event.getTypeInt()) {
case Event.ONMOUSEWHEEL:
}
}*/
/* (non-Javadoc)
* @see de.eckhartarnold.client.ResizeListener#onResized()
*/
public void onResized() {
//if (!loaded) return;
// envelope.clear();
assert envelope.getWidget() == null : "prepareResized() must be called before onResized()!";
int height = Toolbox.getOffsetHeight(envelope);
int width = envelope.getOffsetWidth();
GWT.log("FilmStrip.onResized: new dimensions: "+String.valueOf(width)+"x"+String.valueOf(height));
envelope.setWidget(panel);
if (width == this.width && height == this.height) return;
panel.setPixelSize(width-filmstripBorderSize*2, height);
if (width != this.width) this.width = width;
if (height != this.height && height != 0) {
this.height = height;
thumbnails.adjustToHeight(height-2*borderSize);
}
redraw(0);
}
/**
* Removes the {@link AbsolutePanel} so that the image panels size
* can be determined correctly by the browser before calling
* <code>onResized</code>. The <code>AbsolutePanel</code>
* is restored by method <code>onResized</code>. This method therefore
* should always be used in conjunction with the method
* <code>onResized</code>.
*/
public void prepareResized() {
panel.setSize("100%", "100%"); // required for Internet Explorer 7 compatibility!
envelope.clear();
}
/**
* Puts the focus on the given image, i.e. the film strip will be
* scrolled so that the focused image appears in the center. It's
* frame will be highlighted.
*
* @param imageNr
*/
public void focusImage(int imageNr) {
assert imageNr >= 0 && imageNr < thumbnails.size();
if (imageNr != cursor || !sliding.isComplete()) {
sliding.cancel();
thumbnails.get(cursor).setStylePrimaryName("filmstrip");
if (slidingDuration > 0 && isLoaded) {
sliding.setDisplacement(displacement(imageNr));
int duration = slidingDuration*Math.min(10, Math.abs(imageNr-cursor));
cursor = imageNr;
sliding.run(duration);
} else {
cursor = imageNr;
thumbnails.get(cursor).setStylePrimaryName("filmstripHighlighted");
if (height > 0 && isLoaded) redraw(0);
}
}
}
/**
* Sets the callback that is called when the user selects an image by
* clicking on a thumbnail or by turning the mouse wheel while the mouse
* pointer is located over the preview filmstrip.
*
* @param callback an Interface of the respective "callback" interface
* or <code>null</code>.
*/
public void setPickImageCallback(IPickImage callback) {
pickImageCallback = callback;
if (callback != null) {
for (int i = 0; i < thumbnails.size(); i++) {
Image img = thumbnails.get(i);
img.addStyleDependentName("selectable");
}
} else {
for (int i = 0; i < thumbnails.size(); i++) {
Image img = thumbnails.get(i);
img.removeStyleDependentName("selectable");
}
}
}
/**
* Sets the duration in milliseconds for sliding from one image
* to the next.
* @param duration Duration in milliseconds
*/
public void setSlidingDuration(int duration) {
slidingDuration = duration;
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.Widget#onLoad()
*/
@Override
protected void onLoad() {
if (envelope.getWidget() != null) {
prepareResized();
onResized();
} // else prepare resize has already been called!
isLoaded = true;
redraw(0);
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.Widget#onUnload()
*/
@Override
protected void onUnload() {
isLoaded = false;
}
/**
* Moves a thumbnail image to the given position within the widget's
* absolute panel. Automatically adds an image to the widget's panel
* if it was not visible before, or removes it, if it is not visible
* any more (due to its position lying outside the panel's boundaries).
*
* @param imgIndex the index number of the thumbnail image
* @param left the position of the image on the absolute panel
*/
private void move(int imgIndex, int left) {
Image img = thumbnails.get(imgIndex);
int imgWidth = thumbnails.imageSize(imgIndex)[0];
if (visible.contains(img)) {
if (left < this.width && left+imgWidth > 0) {
panel.setWidgetPosition(img, left, 0);
} else {
panel.remove(img);
visible.remove(img);
}
img.removeStyleName("filmstripTouched");
img.removeStyleName("filmstripPressed");
} else {
if (left < this.width && left+imgWidth > 0) {
panel.add(img, left, 0);
visible.add(img);
}
}
}
/**
* Determines the displacement of the currently focused slide to the
* given slide.
* @param slideNr the number of the slide in relation to which the
* displacement shall be calculated, if the slide
* <code>slideNr</code> were focused and the focused
* slide somewhere either to the left or to the
* right of it.
* @return the displacement
*/
private int displacement(int slideNr) {
if (slideNr == cursor) return 0;
int delta = 0;
delta += thumbnails.imageSize(cursor)[0] / 2;
delta += thumbnails.imageSize(slideNr)[0] / 2;
if (slideNr > cursor) {
for (int i = cursor + 1; i < slideNr; i++) {
delta += thumbnails.imageSize(i)[0];
}
return delta;
} else {
for (int i = slideNr + 1; i < cursor; i++) {
delta += thumbnails.imageSize(i)[0];
}
return -delta;
}
}
/**
* Redraws the film strip. if parameter <code>displacement</code> is
* unequal zero, the row of images will be displaced by a certain number of
* pixels. This is used to implement an animated change of the selected
* image changes.
*
* @param displacement the number of pixels by which the thumbnails shall be
* displaced. (0 means no displacement, a negative
* number results in a displacement to the left a
* positive number in a displacement to the right.)
*/
private void redraw(int displacement) {
int c1, c2;
int left, right;
int center = width/2 + displacement;
int w = thumbnails.imageSize(cursor)[0];
move(cursor, center - w/2);
c1 = cursor-1;
c2 = cursor+1;
left = center - w/2 - borderSize;
right = center + w/2 + borderSize;
// while ((right < width && c2 < thumbnails.size()) ||
// (left >= 0 && c1 >= 0)) {
while (c1 >= 0 || c2 < thumbnails.size()) {
if (c1 >= 0) {
left -= thumbnails.imageSize(c1)[0] + 2*borderSize;
move(c1, left + borderSize);
c1--;
}
if (c2 < thumbnails.size()) {
move(c2, right + borderSize);
right += thumbnails.imageSize(c2)[0] + 2*borderSize;
c2++;
}
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.media.validator;
import de.hybris.platform.cmsfacades.constants.CmsfacadesConstants;
import de.hybris.platform.cmsfacades.data.MediaData;
import de.hybris.platform.cmsfacades.media.validator.predicate.MediaCodeExistsPredicate;
import java.util.Objects;
import java.util.function.Predicate;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Validates DTO for creating a new media.
*
* <p>
* Rules:</br>
* <ul>
* <li>code not null</li>
* <li>code length not exceeded</li>
* <li>code does not exist: {@link MediaCodeExistsPredicate}</li>
* <li>description not null</li>
* <li>description length not exceeded</li>
* <li>altText not null</li>
* <li>altText length not exceeded</li>
* </ul>
* </p>
*/
public class CreateMediaValidator implements Validator
{
protected static final String DESCRIPTION = "description";
protected static final String CODE = "code";
protected static final String ALT_TEXT = "altText";
private Predicate<String> validStringLengthPredicate;
private Predicate<String> mediaCodeExistsPredicate;
@Override
public boolean supports(final Class<?> clazz)
{
return MediaData.class.isAssignableFrom(clazz);
}
@Override
public void validate(final Object obj, final Errors errors)
{
final MediaData target = (MediaData) obj;
ValidationUtils.rejectIfEmpty(errors, CODE, CmsfacadesConstants.FIELD_REQUIRED);
ValidationUtils.rejectIfEmpty(errors, DESCRIPTION, CmsfacadesConstants.FIELD_REQUIRED);
ValidationUtils.rejectIfEmpty(errors, ALT_TEXT, CmsfacadesConstants.FIELD_REQUIRED);
if (!Objects.isNull(target.getCode()) && !getValidStringLengthPredicate().test(target.getCode()))
{
errors.rejectValue(CODE, CmsfacadesConstants.FIELD_LENGTH_EXCEEDED);
}
else if (!Objects.isNull(target.getCode()) && getMediaCodeExistsPredicate().test(target.getCode()))
{
errors.rejectValue(CODE, CmsfacadesConstants.FIELD_ALREADY_EXIST);
}
if (!Objects.isNull(target.getDescription()) && !getValidStringLengthPredicate().test(target.getDescription()))
{
errors.rejectValue(DESCRIPTION, CmsfacadesConstants.FIELD_LENGTH_EXCEEDED);
}
if (!Objects.isNull(target.getAltText()) && !getValidStringLengthPredicate().test(target.getAltText()))
{
errors.rejectValue(ALT_TEXT, CmsfacadesConstants.FIELD_LENGTH_EXCEEDED);
}
}
protected Predicate<String> getValidStringLengthPredicate()
{
return validStringLengthPredicate;
}
@Required
public void setValidStringLengthPredicate(final Predicate<String> validStringLengthPredicate)
{
this.validStringLengthPredicate = validStringLengthPredicate;
}
protected Predicate<String> getMediaCodeExistsPredicate()
{
return mediaCodeExistsPredicate;
}
@Required
public void setMediaCodeExistsPredicate(final Predicate<String> mediaCodeExistsPredicate)
{
this.mediaCodeExistsPredicate = mediaCodeExistsPredicate;
}
}
|
package org.mengyun.tcctransaction.support;
/**
* Bean 容器的公共接口
* <p>从 1.2.X 版本中复制过来</p>
* Created by changmingxie on 11/20/15.
*/
public interface BeanFactory {
/**
* 根据 Class 对象获取对应的实例
*
* @param var1 Class 对象
* @param <T> Class 的类型
* @return Class 对象的实例
*/
<T> T getBean(Class<T> var1);
/**
* 判断 Class 对象 是否存在于容器中
*
* @param clazz Class 对象
* @param <T> Class 的类型
* @return true 存在,false 不存在
*/
<T> boolean isFactoryOf(Class<T> clazz);
}
|
package shared;
/** NominalAttrValue is a class which stores the vlaues of nominal attributes. The
* values can only be accessed through AttrInfo functions.
*/
public class NominalAttrValue extends AttrValue {
/** Creates a deep copy clone of this object.
* @throws CloneNotSupportedException if the AttrValue cloning process encounters an Exception.
* @return A deep copy of this NominalAttrValue.
*/
public Object clone() throws CloneNotSupportedException {
Object navClone = super.clone();
return navClone;
}
/**
* @param r */
private NominalAttrValue(RealAttrValue r) {
Error.err("NominalAttrValue::NominalAttrValue"
+"(RealAttrValue):Cannot construct Nominal from Real"
+ "-->fatal_error ");
}
/** Constructor. The value will be set to unknown.
*/
public NominalAttrValue() {
intVal = Globals.UNKNOWN_NOMINAL_VAL; //host_to_net(UNKNOWN_NOMINAL_VAL+NOMINAL_OFFSET);
type = AttrInfo.nominal;
}
/** Copy constructor. The AttrValue passed in is checked for compatibility with this
* NominalAttrValue.
* @param src The AttrValue to be copied.
*/
public NominalAttrValue(AttrValue src) {
if( src.type != AttrInfo.nominal)
Error.err("NominalAttrValue::NominalAttrValue"
+"(AttrValue): cannot construct a nominal from a "
+ AttrInfo.attr_type_to_string(src.type) + "--> fatal_error");
type = AttrInfo.nominal;
intVal = src.intVal;
realVal = src.realVal;
}
/** Copy constructor.
* @param src The NominalAttrValue to be copied.
*/
public NominalAttrValue(NominalAttrValue src) {
//ASSERT(src.type == nominal);
gets(src);
}
/** Assigns a RealAttrValue to this NominalAttrValue. Displays an error message and
* does nothing.
* @param r The RealAttrValue to be assigned to this NominalAttrValue.
*/
public void gets(RealAttrValue r) {
Error.err("Nominal::gets(RealAttrValue): cannot "
+"assign a Real to a Nominal -->fatal_error");
}
/** Assigns a AttrValue to this NominalAttrValue. If the AttrValue is not compatible
* with this NominalAttrValue then an error message is displayed and nothing else
* is done.
* @param src The AttrValue to be assigned to this NominalAttrValue.
*/
public void gets(AttrValue src) {
if(src != this) {
if(src.type != AttrInfo.nominal)
Error.err("NominalAttrValue::gets: cannot "
+"assign a "+AttrInfo.attr_type_to_string(src.type)
+"(AttrInfo attrType) to a "
+"NominalAttrValue -->fatal_error");
gets(src);
}
}
/** Checks if this NominalAttrValue is equivalent to the given NominalAttrValue.
* @param source The NominalAttrValue this NominalAttrValue is compared to.
* @return TRUE if the values are the same, FALSE otherwise.
*/
public boolean equals(NominalAttrValue source) {
//ASSERT(source.type == nominal);
//ASSERT(type===nominal);
return intVal == source.intVal;
}
/** Checks if this NominalAttrValue is equivalent to the given AttrValue.
* @param a The AttrValue this NominalAttrValue is compared to.
* @return TRUE if the values are the same, FALSE otherwise.
*/
public boolean equals(AttrValue a) {
Error.err("NominalAttrValue::equals: cannot compare"
+ " against base class -->fatal_error ");
return false;
}
}
|
package com.company;
public class Main {
public static void main(String[] args) {
System.out.println(getDurationString(365));
}
public static String getDurationString(int min, int sec){
if (min< 0 || (sec<0 || sec>59)){
return "invalid duration";
}
int hours = (min/60);
int minutes = (min %60);
return hours + "h " + minutes + "m " + sec +"s " ;
}
public static String getDurationString(int seconds) {
if (seconds <0 ){
return "invalid Value";
}
int sec = (seconds % 60);
int min = (seconds/60);
return getDurationString(min, sec);
}
}
|
public enum PastryTypeIngredient {
Plain, Oatmeal, Variety, ChocoNut;
}
|
package prova;
import propis.*;
import empresa.*;
public class test{
public static void main(String[] args) {
Propi bocadillo=new Entrepa(102,(float)5.2,(float)8.0,"Bocadillo de Albondigas",1,true);
try{
bocadillo.addIngredients(new Ingredient(1,1,"Pa"),(float)1.0);
bocadillo.addIngredients(new Ingredient(2,1,"Formatge"),(float)3.0);
bocadillo.addIngredients(new Ingredient(3,1,"Albondigas"),(float)4.0);
bocadillo.addIngredients(new Ingredient(4,1,"Lechuga"),(float)2.0);
bocadillo.addIngredients(new Ingredient(5,1,"Arroz"),(float)2.0);
bocadillo.addIngredients(new Ingredient(6,1,"Patatas"),(float)12.0);
bocadillo.addIngredients(new Ingredient(7,1,"Jamon"),(float)1.0);
bocadillo.addIngredients(new Ingredient(8,1,"Bacon"),(float)5.0);
}
catch(Exception e){e.printStackTrace();}
bocadillo.visualitzarIngredients();
System.out.println("");
try{bocadillo.ingredientsMesQuantitat();
}
catch(Exception e) {e.printStackTrace();}
System.out.println("");
Ingredient arroz=new Ingredient(5,1,"Arroz");
if(bocadillo.teIngredient(new Ingredient(5,1,"Arroz"))){ // Si hay arroz, lo eliminamos
bocadillo.remIngredient(arroz);
if(!(bocadillo.teIngredient(new Ingredient(5,1,"Arroz"))))System.out.println("Arroz Eliminado"); // Volvemos a comprobar si hay arroz y se ha eliminado con éxito
}
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.fun_apps_repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.fun_apps_models.DailyAgenda;
@Repository
public interface DailyAgendaRepository extends JpaRepository<DailyAgenda,Integer> {
@Query(value = "SELECT NAME FROM DAILY_AGENDA", nativeQuery=true)
List<String> getAllDailyAgendaItemNames();
@Query(value = "SELECT * FROM DAILY_AGENDA WHERE COMPLETE = TRUE", nativeQuery=true)
List<DailyAgenda> getAllFinishedTasks();
}
|
/**
* Support for deployment -a utomates the process of loading knowledge bases, compiling them
* into source code, byte code and loading the generated classes.
*/
package nz.org.take.deployment; |
package com.appdear.client.utility;
import android.util.Log;
/**
* 获得中文的汉语拼音
* @author jindan
*
*/
public class ChineseConvert {
static final String include="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
*
* @param str 字符串
* @param isfirstC 是否显示首字符
* @return 返回汉语拼音
*/
public static String ChineseToPing(String str,boolean isfirstC){
if(str==null)return "";
str=str.trim();
int t0=str.length();
String t2 = CnToSpell.getFirstSpell(str);
if(t2==null||t2.equals("")){
if(isfirstC==true){
return "其他";
}
}else{
if(isfirstC==true){
t2=t2.toUpperCase();
return String.valueOf(includeS(t2.charAt(0))?t2.charAt(0):"其他").toUpperCase();
}
}
return String.valueOf(t2.charAt(0)).toUpperCase();
}
private static boolean includeS(char a){
char[] chars=include.toCharArray();
for(char c:chars){
if(a==c)return true;
}
return false;
}
}
|
package frc.robot.commands;
import frc.robot.Robot;
import frc.robot.RobotMap;
import frc.robot.old.RobotOld;
import com.ctre.phoenix.motorcontrol.ControlMode;
import edu.wpi.first.wpilibj.DoubleSolenoid;
public class ElevatorCommand extends CommandBase
{
public enum Direction{
STAGEZERO, STAGEONE, STAGETWO, STOP
}
Direction direction;
public ElevatorCommand(Direction direction)
{
super("ElevatorCommand");
this.direction = direction;
}
@Override
protected void initialize()
{
// ???
}
@Override
protected void execute()
{
switch (direction)
{
case STAGEZERO:
RobotMap.stageOneDoubleSolenoid.set(DoubleSolenoid.Value.kForward);
RobotMap.stageTwoDoubleSolenoid.set(DoubleSolenoid.Value.kForward);
break;
case STAGEONE:
RobotMap.stageOneDoubleSolenoid.set(DoubleSolenoid.Value.kReverse);
RobotMap.stageTwoDoubleSolenoid.set(DoubleSolenoid.Value.kForward);
break;
case STAGETWO:
RobotMap.stageOneDoubleSolenoid.set(DoubleSolenoid.Value.kReverse);
RobotMap.stageTwoDoubleSolenoid.set(DoubleSolenoid.Value.kReverse);
break;
case STOP:
RobotMap.stageOneDoubleSolenoid.set(DoubleSolenoid.Value.kOff);
RobotMap.stageTwoDoubleSolenoid.set(DoubleSolenoid.Value.kOff);
break;
}
}
@Override
protected boolean isFinished()
{
return false;
}
@Override
protected void end()
{
super.end();
}
@Override
protected void interrupted()
{
super.interrupted();
}
public void enableControl()
{
}
public void disableControl()
{
//Set elevator to lowest position when disabled
RobotMap.stageOneDoubleSolenoid.set(DoubleSolenoid.Value.kForward);
RobotMap.stageTwoDoubleSolenoid.set(DoubleSolenoid.Value.kForward);
}
}
|
package kodlama.io.hrms.api.controllers;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import kodlama.io.hrms.business.abstracts.JobExperienceService;
import kodlama.io.hrms.core.utilities.results.DataResult;
import kodlama.io.hrms.core.utilities.results.Result;
import kodlama.io.hrms.entities.concretes.JobExperience;
@RestController
@RequestMapping("/app/jobexperience")
public class JobExperiencesController {
private JobExperienceService jobExperienceService;
@Autowired
public JobExperiencesController(JobExperienceService jobExperienceService) {
super();
this.jobExperienceService = jobExperienceService;
}
@GetMapping("/getall")
public DataResult<List<JobExperience>> getAll(){
return this.jobExperienceService.getAll();
}
// @GetMapping("/getById")
// public DataResult<JobExperience> getById(@RequestParam int id) {
// return this.jobExperienceService.getById(id);
// }
//
// @GetMapping("/getAllByCandidate_idOrderByEndingDateDesc")
// public DataResult<List<JobExperience>>getAllByCandidate_idOrderByEndingDateDesc(@RequestParam int id) {
// return this.jobExperienceService.getAllByCandidate_idOrderByEndingDateDesc(id);
// }
//
// @GetMapping("/getAllByCandidate_id")
// public DataResult<List<JobExperience>> getAllByCandidate_id(@RequestParam int id) {
// return this.jobExperienceService.getAllByCandidate_id(id);
// }
//
@PostMapping("/add")
public Result add(@Valid @RequestBody JobExperience jobExperience){
return this.jobExperienceService.add(jobExperience);
}
}
|
package com.youthchina.domain.Qinghong;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.sql.Timestamp;
import java.util.List;
public class Resume {
private Integer resume_id;
private String resume_url;
private Timestamp resume_upload_time;
private Integer stu_id;
private Integer is_delete;
private Timestamp is_delete_time;
public Integer getResume_id() {
return resume_id;
}
public void setResume_id(Integer resume_id) {
this.resume_id = resume_id;
}
public String getResume_url() {
return resume_url;
}
public void setResume_url(String resume_url) {
this.resume_url = resume_url;
}
public Timestamp getResume_upload_time() {
return resume_upload_time;
}
public void setResume_upload_time(Timestamp resume_upload_time) {
this.resume_upload_time = resume_upload_time;
}
public Integer getStu_id() {
return stu_id;
}
public void setStu_id(Integer stu_id) {
this.stu_id = stu_id;
}
public Integer getIs_delete() {
return is_delete;
}
public void setIs_delete(Integer is_delete) {
this.is_delete = is_delete;
}
public Timestamp getIs_delete_time() {
return is_delete_time;
}
public void setIs_delete_time(Timestamp is_delete_time) {
this.is_delete_time = is_delete_time;
}
}
|
package com.xzkj.xzkjproject.request;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.lzy.okhttputils.model.HttpParams;
import com.xzkj.xzkjproject.interfaces.IRequestLisenter;
import com.xzkj.xzkjproject.model.RequestDto;
import com.xzkj.xzkjproject.utils.LogsUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Response;
/**
* Created by sunqi on 2018/2/27.
*/
public class OkGoUtil<T> {
private HttpParams params;
private Class<T> clazz;
private int JsonType;
public static final int TYPE_ARRAY = 1001;
public static final int TYPE_DATA = 1002;
public static final int TYPE_STRING = 1003;
private static final int RESULT_CODE_DATANULL = 10001;//数据null
private static final int RESULT_CODE_ERRER = 10002;//返回异常信息
private static final int RESULT_CODE_CALLBACK = 10003;//mCallback是null
private static final int RESULT_CODE_NULL = 10004;//code是null
private IRequestLisenter<T> mCallback;
private Gson gson = new Gson();
public OkGoUtil(Class<T> clazz, int JsonType, IRequestLisenter<T> callback) {
this.clazz = clazz;
this.JsonType = JsonType;
this.mCallback = callback;
initHttpHeaders();
}
public OkGoUtil() {
initHttpHeaders();
}
/**
* Get请求
*
* @param url
*/
public void requestGet(String url) {
OkHttpUtils.get(addTelMsgByGet(url)).params(params).execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
if (s != null && !s.isEmpty()) {
analysisData(s);
} else {
if (mCallback != null) {
mCallback.onErrer(RESULT_CODE_DATANULL, "s == null");
}
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
if (mCallback != null && response != null) {
mCallback.onErrer(response.code(), response.message());
}
}
});
}
/**
* Post请求
*
* @param url
*/
public void requestPost(String url) {
OkHttpUtils.post(addTelMsgByGet(url)).params(params).execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
if (s != null && !s.isEmpty()) {
analysisData(s);
} else {
if (mCallback != null) {
mCallback.onErrer(RESULT_CODE_DATANULL, "s == null");
}
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
}
});
}
private void analysisData(String content) {
LogsUtil.d("----------content---------" + content);
try {
JSONObject object = new JSONObject(content);
RequestDto dto = new RequestDto();
if (object.has("code")) {
int code = object.getInt("code");
dto.setErrCode(code);
if (200 == code) {
switch (JsonType) {
case TYPE_ARRAY:
try {
String data = object.getString("data");
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
T date = gson.fromJson(obj.toString(), clazz);
dto.getList().add(date);
}
if (mCallback != null) {
mCallback.onSuccessData(dto);
}
} catch (JSONException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
if (mCallback != null) {
mCallback.onErrer(RESULT_CODE_ERRER, e.getMessage());
} else {
mCallback.onErrer(RESULT_CODE_CALLBACK, "mCallback == null");
}
}
break;
case TYPE_DATA:
try {
String data = object.getString("data");
if (gson != null) {
dto.setData(gson.fromJson(data, clazz));
}
if (mCallback != null) {
mCallback.onSuccessData(dto);
} else {
mCallback.onErrer(RESULT_CODE_CALLBACK, "mCallback == null");
}
} catch (JSONException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
if (mCallback != null) {
mCallback.onErrer(RESULT_CODE_ERRER, e.getMessage());
}
}
break;
case TYPE_STRING:
if (mCallback != null) {
dto.setResult(content);
mCallback.onSuccessData(dto);
} else {
if (mCallback != null) {
mCallback.onErrer(RESULT_CODE_CALLBACK, "mCallback == null");
}
}
break;
}
} else {
mCallback.onErrer(code, "");
}
} else {
mCallback.onErrer(RESULT_CODE_NULL, "code = null");
}
} catch (JSONException e) {
e.printStackTrace();
if (mCallback != null) {
mCallback.onErrer(RESULT_CODE_ERRER, e.getMessage());
}
}
}
public void params(String key, String value) {
params.put(key, value);
}
/*** 添加手机信息(Get) ***/
private static String addTelMsgByGet(String url) {
return url;
}
public void initHttpHeaders() {
params = new HttpParams();
HttpHeaders headers = new HttpHeaders();
OkHttpUtils.getInstance().addCommonHeaders(headers);
}
}
|
package com.tencent.mm.openim.b;
import com.tencent.mm.aa.f;
import com.tencent.mm.aa.j;
import com.tencent.mm.aa.q;
import com.tencent.mm.kernel.g;
import com.tencent.mm.protocal.c.axq;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
public final class i {
public static ab a(axq axq) {
ab Yg = ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().Yg(axq.eup);
if (Yg == null) {
Yg = new ab();
}
Yg.setUsername(axq.eup);
Yg.dx(axq.nickname);
Yg.setType(axq.type);
Yg.dv(axq.fky);
Yg.setSource(axq.source);
Yg.dy(axq.saN);
Yg.dz(axq.saO);
Yg.dC(axq.saP);
Yg.dB(axq.saQ);
Yg.eb(axq.saR == null ? "" : axq.saR.jQf);
Yg.eT(axq.saR == null ? 0 : axq.saR.saT);
Yg.ea(axq.rcw);
Yg.dG(axq.hva);
Yg.eJ(axq.sex);
Yg.dF(axq.saS);
Yg.eQ((int) bi.VE());
return Yg;
}
public static void b(axq axq) {
boolean z;
boolean z2 = true;
Object obj = "";
Object obj2 = "";
j kc = q.KH().kc(axq.eup);
if (kc != null) {
obj = kc.Kx();
obj2 = kc.Ky();
}
kc = new j();
kc.bWA = -1;
kc.username = axq.eup;
kc.dHQ = axq.saM;
kc.dHR = axq.saL;
x.i("MicroMsg.OpenIMContactLogic", "dealwithAvatarFromModContact contact %s b[%s] s[%s]", kc.getUsername(), kc.Kx(), kc.Ky());
if (kc.Kx().equals(obj)) {
z = false;
} else {
q.Kp();
f.B(axq.eup, true);
z = true;
}
if (kc.Ky().equals(obj2)) {
z2 = z;
} else {
q.Kp();
f.B(axq.eup, false);
}
if (z2) {
q.KJ().jO(axq.eup);
q.KH().a(kc);
}
}
}
|
package array.week_1;
import java.util.HashMap;
/**
* @program: leetcode_practise
* @description: LeetCode 类型:数组; 题号:1; 难度:简单;
*
* 题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
* 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
* 链接:https://leetcode-cn.com/problems/two-sum
*
* @author: fanyuexiang
* @create: 2019-12-17 13:09
**/
public class TwoSum_1 {
public int[] twoSum(int[] nums, int target) {
/**
* 解题思路:
* 1. 使用HashMap作为临时数据存储结构;
* 2. 遍历数组,将数组元素作为Map集合的Key,target-nums[i]作为Value;
* 3. 在遍历过程中如果,出现Value与Key相等的情况则跳出循环,返回结果
*/
int[] result = new int[2];
Integer length = nums.length;
HashMap<Integer, Integer> temp = new HashMap<Integer, Integer>();
if (length <= 0){
return null;
}
for (int i = 0 ; i < length; i++){
int num = nums[i];
if (temp.containsKey(num)){
result[0] = i;
result[1] = temp.get(num);
}else {
int subtraction = target - num;
temp.put(subtraction, i);
}
}
return result;
}
}
|
package cn.gzcc.feibao.controller;
import cn.gzcc.feibao.entity.Order_N;
import cn.gzcc.feibao.repository.NorderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class NorderController {
@Autowired
private NorderRepository norderRepository;
@RequestMapping("/nrders")
@ResponseBody
public List<Order_N> getAll(){
List<Order_N> order_n=(List<Order_N>) norderRepository.findAll();
return order_n;
}
@RequestMapping("/nrders/delete/{id}")
@ResponseBody
public boolean deletById(@PathVariable int id){
norderRepository.deleteById(id);
return true;
}
@RequestMapping("/nrders/create")
@ResponseBody
public String create(Order_N order_a){
norderRepository.save(order_a);
return "success";
}
}
|
package com.test.xiaojian.simple_reader.ui.adapter;
import com.test.xiaojian.simple_reader.model.bean.BillBookBean;
import com.test.xiaojian.simple_reader.ui.adapter.view.BillBookHolder;
import com.test.xiaojian.simple_reader.ui.base.adapter.BaseListAdapter;
import com.test.xiaojian.simple_reader.ui.base.adapter.IViewHolder;
/**
* Created by xiaojian on 17-5-3.
*/
public class BillBookAdapter extends BaseListAdapter<BillBookBean> {
@Override
protected IViewHolder<BillBookBean> createViewHolder(int viewType) {
return new BillBookHolder();
}
}
|
package com.z3pipe.z3location.model;
/**
* Created with IntelliJ IDEA.
* Description: ${TODO}
* Date: 2019-04-15
* Time: 09:40
* Copyright © 2018 ZiZhengzhuan. All rights reserved.
* https://www.z3pipe.com
*
* @author zhengzhuanzi
*/
public enum ELocationQuality {
/**
* GPS GPS状态正常
*/
GPS_STATUS_OK(0, "GPS状态正常"),
/**
* GPS NOGPSPROVIDER
*/
GPS_STATUS_NOGPSPROVIDER(1, "手机中没有GPS Provider,无法进行GPS定位"),
/**
* GPS OFF
*/
GPS_STATUS_OFF(2, "GPS关闭,建议开启GPS,提高定位质量"),
/**
* GPS SAVING
*/
GPS_STATUS_MODE_SAVING(3, "选择的定位模式中不包含GPS定位,建议选择包含GPS定位的模式,提高定位质量"),
/**
* GPS NOGPSPERMISSION
*/
GPS_STATUS_NOGPSPERMISSION(4, "没有GPS定位权限,建议开启gps定位权限");
private final int value;
private final String name;
public int getValue() {
return value;
}
public String getName() {
return name;
}
ELocationQuality(int value, String name) {
this.value = value;
this.name = name;
}
public static ELocationQuality getTypeByValue(int type) {
for (ELocationQuality e : values()) {
if (e.getValue() == type) {
return e;
}
}
return null;
}
}
|
package sorting;
import java.util.Arrays;
import sorting.NumberGenerator;
import sorting.Sorter;
public class Main {
NumberGenerator num;
Sorter sort;
public static void main(String[] args) {
/*
* In this for loop we append the k value by 2 and compare with increasing n
* we run the code twice to get the average time.
*/
for(int k = 2; k <= 20; k = k + 2) {
startSort(5000, k);
System.out.println("---");
startSort(10000, k);
System.out.println("---");
startSort(15000, k);
System.out.println("---");
startSort(20000, k);
System.out.println("---");
startSort(25000, k);
System.out.println("---");
startSort(30000, k);
System.out.println("---");
startSort(35000, k);
System.out.println("---");
startSort(40000, k);
System.out.println("---");
startSort(45000, k);
System.out.println("---");
startSort(50000, k);
System.out.println("---");
}
}
public static void startSort(int numbers, int kvalue) {
int n = numbers;
int k = kvalue;
long time, timeB;
long test, testB;
NumberGenerator num = new NumberGenerator(n);
Sorter sort = new Sorter();
long startTime = System.nanoTime();
sort.sortInsertion(num, k);
time = (long) ((System.nanoTime() - startTime)/100000.0);
test = time;
startTime = System.nanoTime();
sort.sortInsertion(num, k);
time = (long) ((System.nanoTime() - startTime)/100000.0);
test += time;
startTime = System.nanoTime();
sort.sortInsertion(num, k);
time = (long) ((System.nanoTime() - startTime)/100000.0);
test += time;
startTime = System.nanoTime();
sort.sortInsertion(num, k);
time = (long) ((System.nanoTime() - startTime)/100000.0);
test += time;
sort.sortInsertion(num, k);
time = (long) ((System.nanoTime() - startTime)/100000.0);
test += time;
test = test / 5;
System.out.println("Insert: n, k, t: " + n + "," + k + "," + test);
//System.out.println("Insertion sort takes: " + (System.nanoTime() - startTime)/1000000.0 + " Milliseconds for n = " + num.unsorted.size() + " and k = " + k );
long startTimeB = System.nanoTime();
sort.sortBinsertion(num, k);
timeB = (long) ((System.nanoTime() - startTimeB)/100000.0);
testB = timeB;
startTimeB = System.nanoTime();
sort.sortBinsertion(num, k);
testB += (long) ((System.nanoTime() - startTimeB)/100000.0);
startTimeB = System.nanoTime();
sort.sortBinsertion(num, k);
testB += (long) ((System.nanoTime() - startTimeB)/100000.0);
startTimeB = System.nanoTime();
sort.sortBinsertion(num, k);
testB += (long) ((System.nanoTime() - startTimeB)/100000.0);
startTimeB = System.nanoTime();
sort.sortBinsertion(num, k);
testB += (long) ((System.nanoTime() - startTimeB)/100000.0);
testB = testB / 5;
System.out.println("bInsert: n, k, t: " + n + "," + k + "," + testB);
}
}
|
package com.zp.stream.channel;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
public interface TestChannel {
@Output("output")
MessageChannel output();
}
|
package sarong;
import sarong.util.CrossHash;
import java.util.Arrays;
/**
* This is a port of the public domain Isaac (cryptographic) random number generator to Java, by Bob Jenkins.
* It is a RandomnessSource here, so it should generally be used to make an RNG, which has more features.
* Isaac32RNG is slower than the non-cryptographic RNGs in Sarong, but much faster than cryptographic RNGs
* that need SecureRandom, and it's compatible with GWT and Android to boot! Isaac32RNG should perform better
* than IsaacRNG on GWT, or when you specifically need a large amount of int values to be set using
* {@link #fillBlock(int[])}. If you don't need GWT support, then {@link IsaacRNG} will have better properties.
* Created by Tommy Ettinger on 8/1/2016.
*/
public final class Isaac32RNG implements RandomnessSource {
private int count; /* count through the results in results[] */
private int results[]; /* the results given to the user */
private int mem[]; /* the internal state */
private int a; /* accumulator */
private int b; /* the last result */
private int c; /* counter, guarantees cycle is at least 2^^40 */
/* no seed, equivalent to randinit(ctx,FALSE) in C */
public Isaac32RNG() {
mem = new int[256];
results = new int[256];
init(false);
}
/* equivalent to randinit(ctx, TRUE) after putting seed in randctx in C */
public Isaac32RNG(final int seed[]) {
mem = new int[256];
results = new int[256];
if(seed == null)
init(false);
else {
System.arraycopy(seed, 0, results, 0, Math.min(256, seed.length));
init(true);
}
}
/**
* Constructs an IsaacRNG with its state filled by the value of seed, run through the LightRNG algorithm.
* @param seed any long; will have equal influence on all bits of state
*/
public Isaac32RNG(long seed) {
mem = new int[256];
results = new int[256];
long z;
for (int i = 0; i < 256; i++) {
z = seed += 0x9E3779B97F4A7C15L;
z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
results[i++] = (int) ((z ^ (z >>> 31)) & 0xffffffffL);
results[i] = (int) ((z ^ (z >>> 31)) >>> 32);
}
init(true);
}
/**
* Constructs an IsaacRNG with its state filled by repeated hashing of seed.
* @param seed a String that should be exceptionally long to get the best results.
*/
public Isaac32RNG(String seed) {
mem = new int[256];
results = new int[256];
if(seed == null)
init(false);
else {
char[] chars = seed.toCharArray();
int slen = chars.length, i = 0;
for (; i < 256 && i < slen; i++) {
results[i] = CrossHash.hash(chars, i, slen);
}
for (; i < 256; i++) {
results[i] = CrossHash.hash(results);
}
init(true);
}
}
private Isaac32RNG(Isaac32RNG other)
{
this(other.results);
}
/**
* Generates 256 results to be used by later calls to next() or nextLong().
* This is a fast (not small) implementation.
*/
public final void regen() {
int i, j, x, y;
b += ++c;
for (i = 0, j = 128; i < 128; ) {
x = mem[i];
a = (a ^ a << 13) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
x = mem[i];
a = (a ^ a >>> 6) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
x = mem[i];
a = (a ^ a << 2) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
x = mem[i];
a = (a ^ a >>> 16) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
}
for (j = 0; j < 128; ) {
x = mem[i];
a = (a ^ a << 13) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
x = mem[i];
a = (a ^ a >>> 6) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
x = mem[i];
a = (a ^ a << 2) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
x = mem[i];
a = (a ^ a >>> 16) + mem[j++];
mem[i] = y = mem[x >> 2 & 255] + a + b;
results[i++] = b = mem[y >> 10 & 255] + x;
}
}
/**
* Initializes this IsaacRNG; typically used from the constructor but can be called externally.
*
* @param flag if true, use data from seed; if false, initializes this to unseeded random state
*/
public final void init(boolean flag) {
int i;
int a, b, c, d, e, f, g, h;
a = b = c = d = e = f = g = h = 0x9e3779b9; /* the golden ratio */
for (i = 0; i < 4; ++i) {
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
}
for (i = 0; i < 256; i += 8) { /* fill in mem[] with messy stuff */
if (flag) {
a += results[i];
b += results[i + 1];
c += results[i + 2];
d += results[i + 3];
e += results[i + 4];
f += results[i + 5];
g += results[i + 6];
h += results[i + 7];
}
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
mem[i] = a;
mem[i + 1] = b;
mem[i + 2] = c;
mem[i + 3] = d;
mem[i + 4] = e;
mem[i + 5] = f;
mem[i + 6] = g;
mem[i + 7] = h;
}
if (flag) { /* second pass makes all of seed affect all of mem */
for (i = 0; i < 256; i += 8) {
a += mem[i];
b += mem[i + 1];
c += mem[i + 2];
d += mem[i + 3];
e += mem[i + 4];
f += mem[i + 5];
g += mem[i + 6];
h += mem[i + 7];
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
mem[i] = a;
mem[i + 1] = b;
mem[i + 2] = c;
mem[i + 3] = d;
mem[i + 4] = e;
mem[i + 5] = f;
mem[i + 6] = g;
mem[i + 7] = h;
}
}
regen();
count = 256;
}
public final int nextInt() {
if (0 == count--) {
regen();
count = 255;
}
return results[count];
}
/**
* Generates and returns a block of 256 pseudo-random int values.
* @return a freshly-allocated array of 256 pseudo-random ints, with all bits possible
*/
public final int[] nextBlock()
{
regen();
final int[] block = new int[256];
System.arraycopy(results, 0, block, 0, 256);
count = 0;
return block;
}
/**
* Generates enough pseudo-random int values to fill {@code data} and assigns them to it.
*/
public final void fillBlock(final int[] data)
{
int len, i;
if(data == null || (len = data.length) == 0) return;
for (i = 0; len > 256; i += 256, len -= 256) {
regen();
System.arraycopy(results, 0, data, i, 256);
}
regen();
System.arraycopy(results, 0, data, i, len);
count = len & 255;
}
/**
* Generates enough pseudo-random float values between 0f and 1f to fill {@code data} and assigns them to it.
* Inclusive on 0f, exclusive on 1f. Intended for cases where you need some large source of randomness to be checked
* later repeatedly, such as how permutation tables are used in Simplex noise.
*/
public final void fillFloats(final float[] data)
{
int len, n;
if(data == null || (len = data.length) == 0) return;
for (int i = 0; i < len; i++) {
data[i] = NumberTools.intBitsToFloat(((n = nextInt()) >>> 9 ^ (n & 0x7fffff)) | 0x3f800000) - 1f;
}
}
/**
* Generates enough pseudo-random float values between -1f and 1f to fill {@code data} and assigns them to it.
* Inclusive on -1f, exclusive on 1f. Intended for cases where you need some large source of randomness to be
* checked later repeatedly, such as how permutation tables are used in Simplex noise.
*/
public final void fillSignedFloats(final float[] data)
{
int len, n;
if(data == null || (len = data.length) == 0) return;
for (int i = 0; i < len; i++) {
data[i] = NumberTools.intBitsToFloat(((n = nextInt()) >>> 9 ^ (n & 0x7fffff)) | 0x40000000) - 3f;
}
}
@Override
public final int next( int bits ) {
return nextInt() >>> 32 - bits;
}
/**
* Using this method, any algorithm that needs to efficiently generate more
* than 32 bits of random data can interface with this randomness source.
* <p>
* Get a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive).
*
* @return a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive)
*/
@Override
public long nextLong() {
return (nextInt() & 0xffffffffL) | (nextInt() & 0xffffffffL) << 32;
}
/**
* Produces another RandomnessSource, but the new one will not produce the same data as this one.
* This is meant to be a "more-secure" generator, so this helps reduce the ability to guess future
* results from a given sequence of output.
* @return another RandomnessSource with the same implementation but no guarantees as to generation
*/
@Override
public final Isaac32RNG copy() {
return new Isaac32RNG(results);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Isaac32RNG isaac32RNG = (Isaac32RNG) o;
if (count != isaac32RNG.count) return false;
if (a != isaac32RNG.a) return false;
if (b != isaac32RNG.b) return false;
if (c != isaac32RNG.c) return false;
if (!Arrays.equals(results, isaac32RNG.results)) return false;
return Arrays.equals(mem, isaac32RNG.mem);
}
@Override
public int hashCode() {
int result = count;
result = 31 * result + CrossHash.hash(results);
result = 31 * result + CrossHash.hash(mem);
result = 31 * result + a;
result = 31 * result + b;
result = 31 * result + c;
return result;
}
@Override
public String toString()
{
return "Isaac32RNG with a hidden state (id is " + System.identityHashCode(this) + ')';
}
} |
package temakereso.restcontroller;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import temakereso.entity.Category;
import temakereso.entity.Department;
import temakereso.helper.SupervisorDto;
import temakereso.helper.TopicStatus;
import temakereso.helper.TopicType;
import temakereso.service.CategoryService;
import temakereso.service.DepartmentService;
import temakereso.service.SupervisorService;
import java.util.Arrays;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/api/constants")
public class ConstantController {
private final CategoryService categoryService;
private final SupervisorService supervisorService;
private final DepartmentService departmentService;
// ------------------------ GET -------------------------- //
@GetMapping(path = "/types")
public List<TopicType> getTypes() {
return Arrays.asList(TopicType.values());
}
@GetMapping(path = "/statuses")
public List<TopicStatus> getStatuses() {
return Arrays.asList(TopicStatus.values());
}
@GetMapping(path = "/categories")
public List<Category> getCategories() {
return categoryService.getAll();
}
@GetMapping(path = "/departments")
public List<Department> getDepartments() {
return departmentService.getAll();
}
@GetMapping(path = "/supervisors")
public List<SupervisorDto> getSupervisors() {
return supervisorService.getAll();
}
// ------------------------ POST -------------------------- //
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping(path = "/categories")
public void createCategory(@RequestBody Category category) {
categoryService.createCategory(category);
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping(path = "/departments")
public void createDepartment(@RequestBody Department department) {
departmentService.createDepartment(department);
}
// ------------------------ PUT -------------------------- //
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PutMapping(path = "/categories")
public void modifyCategory(@RequestBody Category category) {
categoryService.modifyCategory(category);
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PutMapping(path = "/departments")
public void modifyDepartment(@RequestBody Department department) {
departmentService.modifyDepartment(department);
}
}
|
package kodlama.io.hrms.dataAccess.abstracts;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import kodlama.io.hrms.entities.concretes.JobAdvert;
public interface JobAdvertDao extends JpaRepository<JobAdvert, Integer>{
//@Query("From JobAdvert where isActive = true")
List<JobAdvert> getByIsActiveTrue();
//@Query("From JobAdvert where isActive = true and Order By publishedDate=: published Desc ")
List<JobAdvert> getByIsActiveTrueOrderByPublishedDateDesc();
//@Query("From JobAdvert where isActive = true and employer_id =: id")
List<JobAdvert> getByEmployer_IdAndIsActiveTrue(int employerId);
//@Query("From JobAdvert where deadline =: deadline and employerId =: employerId")
List<JobAdvert> getByDeadline(LocalDate deadline);
JobAdvert findAllByIdAndIsActiveTrue(int id);
}
|
package com.serenskye.flickrpaper.model;
import android.graphics.Point;
import android.util.Log;
import com.serenskye.flickrpaper.enums.ImageSize;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: seren
* Date: 14/08/12
* Time: 13:29
*/
public class ApplicationState {
private static final String TAG = "flickerpaper::ApplicationState" ;
private static ApplicationState instance = null;
private Boolean m_restrictedMode = false;
private Boolean roamingRestricted = false;
private Boolean m_gestureEnabled = false;
private Point m_applicationDimensions;
private String m_tags;
private Stack<PhotoVO> m_photos;
private int m_failedAttempts = 0;
private int m_totalPages;
private int m_currentPage;
private long m_updateFrequency = 90000;
private ImageSize[] m_preferedImageSizes;
private PhotoVO m_currentPhoto;
private float scalingRatio;
protected ApplicationState() {
m_applicationDimensions = new Point(0,0);
m_photos = new Stack<PhotoVO>();
m_currentPage = -1;
m_totalPages = 1;
}
public static ApplicationState getInstance() {
if(instance == null) {
instance = new ApplicationState();
}
return instance;
}
public void updateBufferFromVO(PhotosVO photos) {
setTotalPages(photos.getTotalPages());
setCurrentPage(photos.getPage());
addToBuffer(photos.getUrls());
}
public int incrementFailedAttempts() {
m_failedAttempts = m_failedAttempts + 1;
return m_failedAttempts;
}
public void resetFailedAttempts(){
m_failedAttempts = 0;
}
public void clearBuffer() {
m_photos.clear();
}
public String popURLFromBuffer(){
if(m_photos.size() >= 1){
m_currentPhoto = m_photos.pop();
return m_currentPhoto.getUrl();
}
return "";
}
public int getTotalPages() {
return m_totalPages;
}
public int getCurrentPage() {
return m_currentPage;
}
public Boolean isWifiRestricted() {
return m_restrictedMode;
}
public void setWifiRestricted(Boolean isRestricted) {
m_restrictedMode = isRestricted;
}
public Point getApplicationDimensions() {
return m_applicationDimensions;
}
public boolean setApplicationDimensions(int x, int y) {
Boolean changed = m_applicationDimensions.equals(x, y);
this.m_applicationDimensions = new Point(x, y);
m_preferedImageSizes = ImageSize .getImageSizeFromDimensions(x, y);
return changed;
}
public String getTags() {
return m_tags;
}
public void setTags(String tags) {
try{
m_tags = URLEncoder.encode(tags, "UTF-8");
} catch (UnsupportedEncodingException error){
Log.d(TAG, "problem encoding tags, will keep as default");
}
}
public int bufferSize() {
return m_photos.size();
}
/**
* Adds given URL's to url buffer
* @param photos
*/
private void addToBuffer(List<PhotoVO> photos) {
Iterator<PhotoVO> photoData = photos.iterator();
while (photoData.hasNext()){
m_photos.add(photoData.next());
}
}
public void setCurrentPage(int _currentPages) {
m_currentPage = _currentPages;
}
public void setTotalPages(int _totalPages) {
m_totalPages = _totalPages;
}
public long getUpdateFrequency() {
return m_updateFrequency;
}
public void setUpdateFrequency(long frequency){
m_updateFrequency = frequency;
}
public Boolean getGestureEnabled() {
return m_gestureEnabled;
}
public void setGestureEnabled(Boolean enabled){
m_gestureEnabled = enabled;
}
public ImageSize[] getPreferedImageSizes() {
return m_preferedImageSizes;
}
public long getUid() {
return m_currentPhoto.getUid();
}
public PhotoVO getCurrentPhotoData(){
return m_currentPhoto;
}
public void setCurrentPhotoData(PhotoVO data){
if(data != null){
m_currentPhoto = data;
}
}
public void setRoamingRestricted(boolean roamingRestricted) {
this.roamingRestricted = roamingRestricted;
}
public Boolean getRoamingRestricted() {
return roamingRestricted;
}
public void setScalingRatio(float scalingRatio) {
this.scalingRatio = scalingRatio;
}
public float getScalingRatio() {
return scalingRatio;
}
}
|
/**
* Copyright (c) 2016, 润柒 All Rights Reserved.
*
*/
package com.richer.jsms.thread.base.coll011;
import java.util.Vector;
/**
* 同步类容器:
* 同步类容器都是线程安全的,但在某些场景下可能需要加锁来保护复合操作,复合类操作
* 如:迭代(反复的访问元素,遍历完容器中的所有元素)、跳转(根据指定的顺序找到当前
* 元素的下一个元素)、以及条件运算。这写复合操作在多线程并发地修改容器时,可能会表现
* 出意外的行为,最为经典的是ConcurrentModificationException,原因是当容器迭代的过程中
* 被并发的修改了内容,这是由于早期迭代器设计的时候并没有考虑并发修改的问题。
*
* 同步类容器:如古老的Vector、HashTable.这些容器的同步功能其实都是JDK的Collections.synchronized***
* 等工厂方法创建实现的。其底层的机制无非就是用传统的synchronized关键字对每一个公用的方法都进行同步,
* 使得每次只能一个线程访问容器的状态。这很明显不满足我们今天高并发的要求,在保证线程安全的同时,
* 也需要高性能。
*
*
* @author <a href="mailto:sunline360@sina.com">润柒</a>
* @since JDK 1.7
* @version 0.0.1
*/
public class Tickets {
public static void main(String[] args) {
//初始化火车票池并添加火车票:避免线程同步可采用Vector替代ArrayList HashTable替代HashMap
final Vector<String> tickets = new Vector<String>();
//Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
for(int i = 1; i<= 1000; i++){
tickets.add("火车票"+i);
}
// for (Iterator iterator = tickets.iterator(); iterator.hasNext();) {
// String string = (String) iterator.next();
// tickets.remove(20);
// }
for(int i = 1; i <=10; i ++){
new Thread("线程"+i){
public void run(){
while(true){
if(tickets.isEmpty()) break;
System.out.println(Thread.currentThread().getName() + "---" + tickets.remove(0));
}
}
}.start();
}
}
}
|
package com.ebupt.portal.canyon.common.enums;
/**
* 日志类型枚举
*
* @author chy
* @date 2019-03-08 15:27
*/
public enum LogEnum {
/**
* 普通日志,自动添加操作用户
*/
LOG,
/**
* 自定义日志,不添加任何信息
*/
CUSTOME,
/**
* 无权限日志
*/
NO_AUTH,
/**
* 未登录日志
*/
NO_LOGIN,
/**
* 退出登录日志
*/
LOGOUT
}
|
package beanfactory;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/***
*
*@Author ChenjunWang
*@Description:
*@Date: Created in 22:01 2020/3/7
*@Modified By:
*
*/
final class PostProcessorRegistrationDelegate {
public static void registerBeanPostProcessors(BeanFactory beanFactory) {
List<String> postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class);
List<BeanPostProcessor> postProcessors = new LinkedList<>();
for (String ppName : postProcessorNames) {
BeanPostProcessor bean = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
if (bean != null) {
postProcessors.add(bean);
}
}
registerBeanPostProcessors(beanFactory, postProcessors);
}
/**
* Register the given BeanPostProcessor beans.
*/
private static void registerBeanPostProcessors(
BeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
}
|
package layout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class LayoutInputDialog {
static String selectedText = "";
static StyledText keywordText;
static String keyword;
static Button button;
public static String show(Shell shell, final StyledText styledText) {
final Shell childShellDlg = new Shell(shell, SWT.DIALOG_TRIM);
childShellDlg.setText("Find Text");
childShellDlg.setSize(250, 150);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
childShellDlg.setLayout(layout);
childShellDlg.addShellListener(new ShellAdapter() {
public void shellClosed(ShellEvent e) {
// don't dispose of the shell, just hide it for later use
e.doit = false;
childShellDlg.setVisible(false);
}
});
Display display = childShellDlg.getDisplay();
childShellDlg.setLayout(new GridLayout(1, false));
// styledText = new StyledText(shell, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = 2;
keywordText = new StyledText(childShellDlg, SWT.SINGLE | SWT.BORDER);
keywordText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Font font = new Font(shell.getDisplay(), "Courier New", 12, SWT.NORMAL);
button = new Button(childShellDlg, SWT.PUSH);
button.setText("Find");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
keyword = keywordText.getText();
styledText.redraw();
}
});
/*styledText.addLineStyleListener(new LineStyleListener() {
public void lineGetStyle(LineStyleEvent event) {
if(keyword == null || keyword.length() == 0) {
event.styles = new StyleRange[0];
return;
}
String line = event.lineText;
int cursor = -1;
LinkedList list = new LinkedList();
while( (cursor = line.indexOf(keyword, cursor+1)) >= 0) {
list.add(getHighlightStyle(event.lineOffset+cursor, keyword.length(), childShellDlg));
System.out.println("cursor = " + cursor + " " + keyword );
}
event.styles = (StyleRange[]) list.toArray(new StyleRange[list.size()]);
}
});
*/
childShellDlg.open();
while (!childShellDlg.isDisposed() ) {
if (!display.readAndDispatch() ) {
display.sleep();
}
}
return selectedText;
}
} |
package com.jovin.config;
import com.jovin.utils.Response;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by hexad3cimal on 9/4/17.
*/
@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
AuthenticationFailureHandler handler = new AuthFailureHandler();
response.getWriter().print(
"{\"data\": \"error\"}");
response.getWriter().flush();
handler.onAuthenticationFailure(request, response, exception);
}
}
|
package tech.ibit.httpclient.utils;
import org.junit.Ignore;
import org.junit.Test;
import tech.ibit.httpclient.utils.request.Request;
import tech.ibit.httpclient.utils.response.Response;
/**
* HttpClient工具类测试
*
* @author 小ben马
*/
public class HttpClientUtilsTest {
@Test
@Ignore
public void doResponse() throws Exception {
String url = "https://www.douban.com/doubanapp/dispatch?uri=/group/topic/191568149";
//String url = "https://www.douban.com/group/topic/191568149/";
Request request = new Request(url);
String userAgent = UserAgentUtils.getRandomUserAgent();
request.addHeader("User-Agent", userAgent);
request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
request.addHeader("Accept-Encoding", "gzip, deflate");
request.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
//ssl
request.setSecured(true);
Response response = HttpClientUtils.doRequest(request, true);
//System.out.println(response.getContent()); //response text
System.out.println(response.getCode()); //response code
System.out.println(response.getRealUri().getUri());
System.out.println(response.getRealUri().isRedirect());
}
} |
package com.sales.service;
import com.github.pagehelper.PageHelper;
import com.sales.entity.SalesPlanDetailEntity;
import com.sales.mapper.SalesPlanDetailMapper;
import com.system.util.BusinessException;
import com.system.util.PagerInfo;
import com.system.util.ServiceResult;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.List;
import java.util.Map;
@Service("salesPlanDetailService")
public class SalesPlanDetailService {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(SalesPlanDetailService.class);
@Autowired
private SalesPlanDetailMapper salesPlanDetailMapper;
/**
* find list
*
* @Author chenxichao
* @Date 2019-05-20 16:55
* @Param [params, pagerInfo]
**/
public ServiceResult<List<SalesPlanDetailEntity>> findList(Map<String, Object> params, PagerInfo<?> pagerInfo) {
Assert.notNull(this.salesPlanDetailMapper, "Property 'salesPlanDetailMapper' is required.");
ServiceResult<List<SalesPlanDetailEntity>> result = new ServiceResult<List<SalesPlanDetailEntity>>();
try {
if (pagerInfo != null) {
PageHelper.startPage(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
}
result.setResult(this.salesPlanDetailMapper.findList(params));
} catch (BusinessException be) {
result.setSuccess(false);
result.setMessage(be.getMessage());
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("Unknown error!");
LOGGER.error("[SalesPlanDetailService][findList]:query findList occur exception", e);
}
return result;
}
/**
* find info
*
* @Author chenxichao
* @Date 2019-05-20 16:56
* @Param [params]
**/
public ServiceResult<SalesPlanDetailEntity> findInfo(Map<String, Object> params) {
Assert.notNull(this.salesPlanDetailMapper, "Property 'salesPlanDetailMapper' is required.");
ServiceResult<SalesPlanDetailEntity> result = new ServiceResult<SalesPlanDetailEntity>();
try {
result.setResult(this.salesPlanDetailMapper.findInfo(params));
} catch (BusinessException be) {
result.setSuccess(false);
result.setMessage(be.getMessage());
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("Unknown error!");
LOGGER.error("[SalesPlanDetailService][findInfo]:query findInfo by param occur exception", e);
}
return result;
}
/**
* do insert
*
* @Author chenxichao
* @Date 2019-05-20 16:56
* @Param [salesPlanDetailEntity]
**/
public ServiceResult<Integer> doInsert(SalesPlanDetailEntity salesPlanDetailEntity) {
Assert.notNull(this.salesPlanDetailMapper, "Property 'salesPlanDetailMapper' is required.");
ServiceResult<Integer> result = new ServiceResult<Integer>();
int id = 0;
try {
int success = this.salesPlanDetailMapper.doInsert(salesPlanDetailEntity);
if (success > 0) {
id = salesPlanDetailEntity.getSalesPlanDetailId();
}
result.setResult(id);
} catch (BusinessException be) {
result.setSuccess(false);
result.setMessage(be.getMessage());
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("Unknown error!");
LOGGER.error("[SalesPlanDetailService][doInsert]:query doInsert by id occur exception", e);
}
return result;
}
/**
* do update
*
* @Author chenxichao
* @Date 2019-05-20 16:56
* @Param [salesPlanDetailEntity]
**/
public ServiceResult<Integer> doUpdate(SalesPlanDetailEntity salesPlanDetailEntity) {
Assert.notNull(this.salesPlanDetailMapper, "Property 'salesPlanDetailMapper' is required.");
ServiceResult<Integer> result = new ServiceResult<Integer>();
Integer id = 0;
try {
Integer success = this.salesPlanDetailMapper.doUpdate(salesPlanDetailEntity);
if (success > 0) {
id = salesPlanDetailEntity.getSalesPlanDetailId();
}
result.setResult(id);
} catch (BusinessException be) {
result.setSuccess(false);
result.setMessage(be.getMessage());
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("Unknown error!");
LOGGER.error("[SalesPlanDetailService][doUpdate]:query doInsert by id occur exception", e);
}
return result;
}
/**
* do delete
*
* @Author chenxichao
* @Date 2019-05-20 16:56
* @Param [salesPlanDetailId]
**/
public ServiceResult<Boolean> doDelete(int salesPlanDetailId) {
Assert.notNull(this.salesPlanDetailMapper, "Property 'salesPlanDetailMapper' is required.");
ServiceResult<Boolean> result = new ServiceResult<Boolean>();
boolean flag = false;
try {
int id = this.salesPlanDetailMapper.doDelete(salesPlanDetailId);
if (id > 0) {
flag = true;
}
result.setResult(flag);
} catch (BusinessException be) {
result.setSuccess(false);
result.setMessage(be.getMessage());
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("Unknown error!");
LOGGER.error("[SalesPlanDetailService][doDelete]:query doDelete by id occur exception", e);
}
return result;
}
} |
package it.univpm.Progetto_Programmazione.GestioneDati;
import java.util.List;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Classe per la restituzione dei metadata(le macrocategorie presenti)
*/
public class Metadata {
private List<Map> metadata = new ArrayList<>();
public Metadata()
{
Field[] fields = Energy.class.getDeclaredFields();//estrae gli attributi della classe EuropeanUn
for ( Field f : fields )
{
Map<String, String> map = new HashMap<String,String>();
//andiamo ad inserire le coppie chiave/valore
map.put("alias", f.getName());
map.put("sourceField", f.getName());//nome del campo in tsv
map.put("type", "double");
metadata.add(map);
}
}
/**
* Metodo che ritorna la lista di mappe contenente i metadati
* @return lista dei metadati
*/
public List<Map> getMetadata()
{
return metadata;
}
}
|
package com.kh.efp.band.model.vo;
import java.io.Serializable;
import java.sql.Date;
import org.springframework.stereotype.Repository;
@Repository
public class Member_Band implements Serializable{
private int mbid;
private int bid;
private int mid;
private Date idate;
private String istatus;
private String mlevel;
private String mname;
public Member_Band(){}
public Member_Band(int mbid, int bid, int mid, Date idate, String istatus, String mlevel, String mname) {
super();
this.mbid = mbid;
this.bid = bid;
this.mid = mid;
this.idate = idate;
this.istatus = istatus;
this.mlevel = mlevel;
this.mname = mname;
}
public int getMbid() {
return mbid;
}
public void setMbid(int mbid) {
this.mbid = mbid;
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public int getMid() {
return mid;
}
public void setMid(int mid) {
this.mid = mid;
}
public Date getIdate() {
return idate;
}
public void setIdate(Date idate) {
this.idate = idate;
}
public String getIstatus() {
return istatus;
}
public void setIstatus(String istatus) {
this.istatus = istatus;
}
public String getMlevel() {
return mlevel;
}
public void setMlevel(String mlevel) {
this.mlevel = mlevel;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
@Override
public String toString() {
return "Member_Band [mbid=" + mbid + ", bid=" + bid + ", mid=" + mid + ", idate=" + idate + ", istatus="
+ istatus + ", mlevel=" + mlevel + ", mname=" + mname + "]";
}
}
|
package com.selesgames.weave.ui.onboarding;
interface OnboardingController {
void finished();
} |
/**
* Copyright 2007 Jens Dietrich 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 nz.org.take.deployment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import nz.org.take.KnowledgeBase;
import nz.org.take.KnowledgeSource;
import nz.org.take.TakeException;
import nz.org.take.compiler.Location;
import nz.org.take.compiler.reference.DefaultCompiler;
import nz.org.take.compiler.util.DefaultLocation;
import nz.org.take.compiler.util.DefaultNameGenerator;
import nz.org.take.compiler.util.Logging;
import nz.org.take.compiler.util.jalopy.JalopyCodeFormatter;
import nz.org.take.deployment.ant.ANTCompilerAdapter;
/**
* Utility class used to instantiate the generated interface with an instance of the
* generated class.
* @author <a href="http://www-ist.massey.ac.nz/JBDietrich/">Jens Dietrich</a>
*/
public class KnowledgeBaseManager<I> implements Logging {
// data format used in generated class names
private DateFormat dateFormat = new SimpleDateFormat("yyMMdd_HHmmss");
// the folder where files are stored
private String workingDirRoot = null;
// the name of the kb class
private String className = "KBImpl";
// whether to check bindings
private boolean checkBindingsForCompleteness = true;
// the parent of the classloader that will be used to load
// generated classes
private ClassLoader baseClassLoader = this.getClass().getClassLoader();
// the Java compiler is responsible for compiling the generated source code classes
private CompilerAdapter javaCompiler = new ANTCompilerAdapter();
// folders for src and bin
private String srcFolder = null;
private String binFolder = null;
public KnowledgeBaseManager() {
super();
this.setWorkingDirRoot("takeWorkingDir/");
// init compiler adapter
String compilerAdapterName = this.getCompilerAdapterClassName();
try {
LOGGER.info("Trying to install compiler adapter " + compilerAdapterName);
javaCompiler = (CompilerAdapter)Class.forName(compilerAdapterName).newInstance();
LOGGER.debug("Installed Java compiler adapter " + compilerAdapterName);
}
catch (Exception x) {
LOGGER.error("Error installing Java compiler adapter " + compilerAdapterName,x);
}
}
protected String getCompilerAdapterClassName() {
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.5")) {
return "nz.org.take.deployment.ant.ANTCompilerAdapter";
}
return "nz.org.take.deployment.jsr199.JSR199CompilerAdapter";
}
/**
* Get an instance of the compiled knowledge base.
* @param spec the interface to be implemented by the compiled knowledge base
* @param ksource the knowledge source (a kb, a script, xml file or similar)
* @return an instance of the kb
* @throws TakeException
*/
public I getKnowledgeBase(Class spec,KnowledgeSource ksource) throws TakeException {
return this.getKnowledgeBase(spec, ksource,new HashMap<String,Object> (),new HashMap<String,Object> ());
}
/**
* Get an instance of the compiled knowledge base.
* @param spec the interface to be implemented by the compiled knowledge base
* @param ksource the knowledge source (a kb, a script, xml file or similar)
* @param constants bindings for the objects referenced in the kb
* @return an instance of the kb
* @throws TakeException
*/
public I getKnowledgeBase(Class spec,KnowledgeSource ksource,Map<String,Object> constants) throws TakeException {
return this.getKnowledgeBase(spec, ksource,constants,new HashMap<String,Object> ());
}
/**
* Get an instance of the compiled knowledge base.
* @param spec the interface to be implemented by the compiled knowledge base
* @param ksource the knowledge source (a kb, a script, xml file or similar)
* @param constants bindings for the objects referenced in the kb
* @param factStores bindings for the fact stores referenced in the kb
* @return an instance of the kb
* @throws TakeException
*/
public I getKnowledgeBase(Class spec,KnowledgeSource ksource,Map<String,Object> constants, Map<String,Object> factStores) throws TakeException {
KnowledgeBase kb = ksource.getKnowledgeBase();
assert(spec.isInterface());
checkFolder(workingDirRoot);
checkFolder(srcFolder);
checkFolder(binFolder);
Location location = new DefaultLocation(srcFolder);
String version = "impl_v"+dateFormat.format(new Date());
String packageName = spec.getPackage().getName() + '.'+version;
nz.org.take.compiler.Compiler kbCompiler = new DefaultCompiler();
kbCompiler.setLocation(location);
kbCompiler.add(new JalopyCodeFormatter());
kbCompiler.setGenerateDataClassesForQueryPredicates(false); // part of interface !
kbCompiler.setPackageName(packageName);
kbCompiler.setClassName(className);
kbCompiler.setInterfaceNames(spec.getName());
kbCompiler.setNameGenerator(new DefaultNameGenerator());
String interfacePackageName = spec.getPackage().getName();
kbCompiler.setImportStatements(interfacePackageName+".*"); // the interface
kbCompiler.compile(kb);
javaCompiler.compile(packageName,srcFolder,binFolder);
// copy resource from src to bin folder
copyResources(new File(srcFolder),binFolder);
// load class
String fullClassName = packageName+'.'+className;
try {
URL classLoc = new File(binFolder).toURL();
ClassLoader classloader = new URLClassLoader(new URL[]{classLoc},this.baseClassLoader);
// handle bindings, i.e. bind names to objects that are referenced in rules as constant terms
String constantClassName = packageName+'.'+kbCompiler.getNameGenerator().getConstantRegistryClassName();
setupBindings(constants,constantClassName,classloader);
String factStoreClassName = packageName+'.'+kbCompiler.getNameGenerator().getFactStoreRegistryClassName();
setupBindings(factStores,factStoreClassName,classloader);
// load class
Class clazz = classloader.loadClass(fullClassName);
return (I)clazz.newInstance();
}
catch (Exception x) {
throw new DeploymentException ("Cannot load generated class "+fullClassName,x);
}
}
private void copyResources(File from,String context) {
File[] files = from.listFiles();
if (files!=null) {
FileInputStream in;
for (File f:files) {
if (!f.getName().endsWith(".java")) {
if (f.isDirectory()) {
copyResources(f,context+'/'+f.getName());
}
else {
try {
String to = context+'/'+f.getName();
in = new FileInputStream(f);
FileOutputStream out = new FileOutputStream(to);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1)
out.write(buffer, 0, bytesRead);
out.close();
in.close();
}
catch (IOException e) {
// e.printStackTrace(); TODO logging
}
}
}
}
}
}
private void setupBindings(Map<String,Object> bindings, String constantClassName,ClassLoader classloader) throws TakeException{
Class constantClass = null;
if (bindings.size()>0) {
try {
constantClass = classloader.loadClass(constantClassName);
}
catch (Exception x) {
throw new DeploymentException("Cannot load generated constant class " + constantClassName,x);
}
for (Entry<String,Object> binding:bindings.entrySet()) {
try {
Field field = constantClass.getField(binding.getKey());
field.set(null,binding.getValue()); // fields are static
} catch (Exception x) {
throw new DeploymentException("Cannot set field " + binding.getKey() + " to value " + binding.getValue()+ " in generated constant class " + constantClassName,x);
}
}
}
if (this.checkBindingsForCompleteness && constantClass!=null) {
for (Field field:constantClass.getFields()) {
if (!bindings.containsKey(field.getName())) {
throw new DeploymentException("There is no binding for field " + field.getName() + " in class " + constantClass);
}
}
}
}
public String getWorkingDirRoot() {
return workingDirRoot;
}
public void setWorkingDirRoot(String workingDirRoot) {
this.workingDirRoot = workingDirRoot;
this.setSrcFolder(workingDirRoot+"src/");
this.setBinFolder(workingDirRoot+"bin/");
}
private void checkFolder(String folder) {
File f = new File(folder);
if (!f.exists())
f.mkdir();
}
public boolean isCheckBindingsForCompleteness() {
return checkBindingsForCompleteness;
}
public void setCheckBindingsForCompleteness(boolean checkBindingsForCompleteness) {
this.checkBindingsForCompleteness = checkBindingsForCompleteness;
}
public ClassLoader getBaseClassLoader() {
return baseClassLoader;
}
public void setBaseClassLoader(ClassLoader baseClassLoader) {
this.baseClassLoader = baseClassLoader;
}
public CompilerAdapter getJavaCompiler() {
return javaCompiler;
}
public void setJavaCompiler(CompilerAdapter javaCompiler) {
this.javaCompiler = javaCompiler;
}
public String getSrcFolder() {
return srcFolder;
}
public void setSrcFolder(String srcFolder) {
this.srcFolder = srcFolder;
}
public String getBinFolder() {
return binFolder;
}
public void setBinFolder(String binFolder) {
this.binFolder = binFolder;
}
}
|
package com.example.legia.mobileweb.DTO;
public class menuMain {
private int idMenu;
private String tenMenu;
public menuMain(int idMenu, String tenMenu) {
this.idMenu = idMenu;
this.tenMenu = tenMenu;
}
public int getIdMenu() {
return idMenu;
}
public void setIdMenu(int idMenu) {
this.idMenu = idMenu;
}
public String getTenMenu() {
return tenMenu;
}
public void setTenMenu(String tenMenu) {
this.tenMenu = tenMenu;
}
}
|
package com.sleekbyte.tailor.functional;
import com.sleekbyte.tailor.common.Messages;
import com.sleekbyte.tailor.common.Rules;
import com.sleekbyte.tailor.common.Severity;
import com.sleekbyte.tailor.output.Printer;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Functional tests for lower camel case rule.
*/
@RunWith(MockitoJUnitRunner.class)
public class LowerCamelCaseTest extends RuleTest {
private int c = 4;
@Override
protected String[] getCommandArgs() {
return new String[]{ "--only=lower-camel-case" };
}
@Override
protected void addAllExpectedMsgs() {
addExpectedMsg(7, 5, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(8, 5, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(16, 14, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(20,22, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(26, 8, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(30, 19, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(46, 16, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(80, 17, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(85, 17, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(91, 9, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(163, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(164, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(165, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(176, 10, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(177, 10, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(190, 10, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
addExpectedMsg(200, 10, Severity.WARNING, Messages.VARIABLE + Messages.NAMES + Messages.LOWER_CAMEL_CASE);
}
private void addExpectedMsg(int line, int column) {
this.expectedMessages.add(Printer.genOutputStringForTest(Rules.LOWER_CAMEL_CASE, inputFile.getName(), line,
column, priority, msg));
}
} |
package ru.moneydeal.app.group;
import androidx.annotation.NonNull;
import androidx.room.Entity;
@Entity(tableName = "statistics", primaryKeys = {"groupId", "from", "to"})
public class StatisticEntity {
@NonNull
public String groupId;
@NonNull
public String from;
@NonNull
public String to;
@NonNull
public Integer amount;
public StatisticEntity(String groupId, String from, String to, Integer amount) {
this.groupId = groupId;
this.from = from;
this.to = to;
this.amount = amount;
}
}
|
package org.campustalk.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.campustalk.entity.CampusTalkUsers;
import org.campustalk.sql.dbUser;
import org.campustalk.util.EmailHelper;
import org.campustalk.util.FieldValidator;
import org.campustalk.util.OtherUtil;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Servlet implementation class UserRegistration
*/
@WebServlet(description = "User Registration Servlet", urlPatterns = { "/User/Registration/New" })
public class UserNewRegistration extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UserNewRegistration() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
@SuppressWarnings("unused")
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
JSONObject jResponse = new JSONObject();
dbUser objUser = new dbUser();
try {
boolean errorFlag = false;
String responseMessage = "";
String errorMsgSep = "";
FieldValidator objValidation = new FieldValidator();
String email, firstName, lastName, gender, pictureUrl, registerWith, password;
jResponse.put("status", "fail");
jResponse.put("message", "Something Wrong!, Please Try Again");
email = request.getParameter("email");
if (!objValidation.isEmail(email)) {
errorFlag = true;
responseMessage += errorMsgSep + "Invalid Email";
errorMsgSep = ",";
}
firstName = request.getParameter("firstName");
lastName = request.getParameter("lastName");
if (request.getParameter("gender") != null) {
gender = request.getParameter("gender").toUpperCase();
if (!(gender.equals("MALE") || gender.equals("FEMALE"))) {
errorFlag = true;
responseMessage += errorMsgSep + "Invalid Gender";
errorMsgSep = ",";
}
}
pictureUrl = request.getParameter("pictureUrl");
registerWith = request.getParameter("registerWith");
password = request.getParameter("password");
if (!objValidation.isSimplePassword(password)) {
errorFlag = true;
responseMessage += errorMsgSep + "Invalid Password";
errorMsgSep = ",";
}
if (errorFlag) {
} else {
CampusTalkUsers ctUser = new CampusTalkUsers();
ctUser = objUser.getUserDetailFromEmail(request
.getParameter("email"));
if (ctUser.getId() == 0) {
responseMessage = "Invalid Email, Please Contact System Administrator";
} else {
System.out.println(ctUser.getStatus());
if (ctUser.getStatus().equals("N")) {
ctUser.setFirstName(request.getParameter("firstName"));
ctUser.setLastName(request.getParameter("lastName"));
ctUser.setGender(request.getParameter("gender"));
ctUser.setPictureUrl(request.getParameter("pictureUrl"));
ctUser.setRegisterWith(request
.getParameter("registerWith"));
ctUser.setAuthString(OtherUtil.getRandomeString());
ctUser.setPassword(request.getParameter("password"));
objUser.registerNewuserDetail(ctUser);
jResponse.put("status", "success");
// send Email
EmailHelper.registrationVerifyEmail(ctUser);
responseMessage = "Please Check Email To Verify";
} else {
if (ctUser.getStatus().equals("R")) {
responseMessage = "A/C is already Created but Not Verified, Please Check your email";
} else {
responseMessage = "A/C is already Created, Please Login";
}
}
}
}
jResponse.put("message", responseMessage);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.println(jResponse);
}
} |
/*
* 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 command.library;
import command.framework.Command;
import interfaces.IDrive;
import interfaces.IOutputter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author BPS
*/
class CmdHelp extends Command {
protected CmdHelp(String name, IDrive drive) {
super(name, drive);
}
@Override
public void execute(IOutputter outputter) {
if(this.getParameterCount()==0){
System.out.println("CD\t: Displays the name of or changes the current directory");
System.out.println("DIR\t: Displays a list of files and subdirectories in a directory");
System.out.println("EXIT\t: Quits the CMD.EXE.");
System.out.println("FORMAT\t: Formats a disk for use with Windows.");
System.out.println("HELP\t: Provides Help Information for Windows commands.");
System.out.println("LABEL\t: Creates, changes, or deletes the volume label of a disk.");
System.out.println("MKDIR\t: Creates a directory");
System.out.println("MKFILE\t: Creates a file");
System.out.println("MOVE\t: Moves one or more files from one directorie to another directory.");
}else{
String command = this.getParameterAt(0).toLowerCase();
if(command.equals("cd")){
System.out.println("CD\t: Displays the name of or changes the current directory.");
}else if(command.equals("dir")){
System.out.println("DIR\t: Displays a list of files and subdirectories in a directory.");
}else if(command.equals("exit")){
System.out.println("EXIT\t: Quits the CMD.EXE.");
}else if(command.equals("format")){
System.out.println("FORMAT\t: Formats a disk for use with Windows.");
}else if(command.equals("help")){
System.out.println("HELP\t: Provides Help Information for Windows commands.");
}else if(command.equals("label")){
System.out.println("LABEL\t: Creates, changes, or deletes the volume label of a disk.");
}else if(command.equals("mkdir")){
System.out.println("MKDIR\t: Creates a directory");
}else if(command.equals("mkfile")){
System.out.println("MKFILE\t: Creates a file");
}else if(command.equals("move")){
System.out.println("MOVE\t: Moves one or more files from one directorie to another directory.");
}else{
System.err.print("Error: This command is not supported by the help utility.");
}
}
}
}
|
package org.lxy.exception;
/**
* @author menglanyingfei
* @date 2017-3-23
*/
public class Demo1_Exception {
/**
* @param args
*/
public static void main(String[] args) {
try {
int a = 10 / 0;
System.out.println(a);
} catch (Exception e) {
System.out.println("你好, 除数不能为0!");
}
}
}
|
package com.bl.Functional.Quadratic;
import java.util.Scanner;
public class QuadraticMain {
public static void main(String[] args) {
// TODO2 Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a in quadratic equation");
double a = sc.nextDouble();
System.out.println("Enter the value od b in quadratic equation");
double b = sc.nextDouble();
System.out.println("Enter the value of c in quadratic equation");
double c = sc.nextDouble();
QuadraticBL Qbl = new QuadraticBL();
Qbl.QuadraticRoots(a, b, c);
}
}
|
package x.java;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class JavaRulePathTest {
} |
package com.herz.data_structures.bst.model;
import java.util.Comparator;
public class Tree<T> {
private Node<T> mRoot;
private final Comparator<? super T> mComparator;
public Tree(Comparator<? super T> comparator) {
mRoot = null;
mComparator = comparator;
}
public void add(T data) {
if (mRoot != null) {
this.add(new Node<T>(data), mRoot);
} else {
mRoot = new Node<>(data);
}
}
public void add(Node<T> data, Node<T> base) {
int difference = mComparator.compare(data.getData(), base.getData());
if (difference > 0) {
if (base.getLeft() != null) {
this.add(data, base.getLeft());
} else {
base.setLeft(data);
}
} else if (difference < 0) {
if (base.getRight() != null) {
this.add(data, base.getRight());
} else {
base.setRight(data);
}
}
}
public SimpleList<T> inOrder() {
// TODO:
SimpleList<T> simpleList = new SimpleList<>();
inOrder(simpleList, mRoot);
return null;
}
private void inOrder(SimpleList<? super T> simpleList, Node<T> aux) {
if (null != aux) {
T data = aux.getData();
Node<T> right = aux.getRight();
Node<T> left = aux.getLeft();
if (null == aux.getLeft()) {
simpleList.add(data);
this.inOrder(simpleList, right);
} else {
this.inOrder(simpleList, left);
}
}
}
}
|
package com.tencent.mm.ui.chatting.b.b;
import android.content.Intent;
import android.view.MenuItem;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.b.u;
public interface af extends u {
void T(Intent intent);
boolean a(MenuItem menuItem, bd bdVar);
void ax(Intent intent);
boolean g(bd bdVar, boolean z);
}
|
package dynamicprogramming.diceroll;
public class Solution {
/**
* We have n dice, each having k faces with a number from 1 to k.
* We need to find the number of ways to roll these nnn dice such that the sum of numbers on them is equal to target.
* @param args
*/
public static void main(String[] args) {
}
final int MOD = 1000000007;
/**
* Brute-force solution
* O(n*k*target): time complexity
* @param n
* @param k
* @param target
* @return
*/
public int numRollsToTarget(int n, int k, int target) {
// memorization
Integer[][] memo = new Integer[n + 1][target + 1];
return waysToTarget(memo, 0, n, 0, target, k);
}
private int waysToTarget(Integer[][] memo, int diceIndex, int n, int currSum, int target, int k) {
// all the n dice are traversed, the sum must be equal to target for valid combination
if (diceIndex == n) {
return currSum == target ? 1 : 0;
}
// we have already calculated the answer so no need to go into recursion
if (memo[diceIndex][currSum] != null) {
return memo[diceIndex][currSum];
}
int ways = 0;
for (int i = 1; i <= Math.min(k, target - currSum); i++) {
ways = (ways + waysToTarget(memo, diceIndex + 1, n, currSum + i, target, k));
}
return memo[diceIndex][currSum] = ways;
}
// really difficult, I don't really understand lol!!!!
private static int waysToTargetBottomUp(int n) {
return -1;
}
// the number of ways to roll n dices to get sum value equals to s
// intuitive approach
private static int algoMemo(int n, int k, int s) {
int[][] memo = new int[n+1][s+1];
for (int i = 0; i < memo.length; i++) {
for (int j = 0; j < memo[0].length; j++) {
memo[i][j] = -1;
}
}
return numRollsToTargetSecondIdea(memo, 0, n, k, 0, s);
}
private static int numRollsToTargetSecondIdea(int[][] memo, int diceIndex, int n, int k, int currentSum, int targetSum) {
if (diceIndex == n) {
return currentSum == targetSum ? 1 : 0;
}
if (memo[diceIndex][currentSum] != -1) {
return memo[diceIndex][currentSum];
}
int ways = 0;
for (int x = 1; x <= k; x++) {
ways = ways + numRollsToTargetSecondIdea(memo, diceIndex + 1, n, k, currentSum + x, targetSum);
}
memo[diceIndex][currentSum] = ways;
return memo[diceIndex][currentSum];
}
private static int numRollsToTargetIntuitive(int n, int k, int s) {
if (s < 0) return 0;
if (n == 0) {
if (s == 0) return 1;
else return 0;
}
int result = 0;
for (int x = 1; x <= k; x++) {
result = result + numRollsToTargetIntuitive(n - 1, k, s - x);
}
return result;
}
}
|
package game;
import ai.*;
import game.GameController.PlayerAssignments;
import gui.TriggeredGUI;
import state.*;
public class Game {
public static void main(String[] args) {
Game game = new Game();
TextOutput.setDebugMode(true);
int id = Integer.parseInt(args[0]);
int useServer = Integer.parseInt(args[1]);
int vis = Integer.parseInt(args[2]);
int ai = Integer.parseInt(args[3]);
game.run(id, useServer, vis, ai, args[4], Integer.parseInt(args[5]));
}
public void run(int id, int server, int vis, int ai, String host, int port)
{
// create all the object for the game
ClientGameState state = new ClientGameState();
GameController controller = new GameController(id, host, port);
TriggeredGUI gui = new TriggeredGUI();
// initialise the class that scores the boards
/*
FreedomDistanceBoardScorer boardScorer = new FreedomDistanceBoardScorer();
boardScorer.setDistanceWeighting(20);
*/
// initialise Smart AI
SmartAI sAi = new SmartAI();
/*
// initialise the Mr X AI
MinMaxAi mrXAi = new MinMaxAi();
mrXAi.setBoardScorer(boardScorer);
// set the ai parameters
mrXAi.setPly(3);
mrXAi.setAlphaBetaTolerance(0.0);
mrXAi.setMaxEvaluations(-1);
mrXAi.setUseQuiescenceExpansion(false);
mrXAi.setQuiescenceThreshold(25);
mrXAi.setQuiescenceDepthLimit(1);
mrXAi.setUseAlphaBetaPruning(true);
mrXAi.setUseRandomChoice(false);
mrXAi.setUseQuiescentChoice(false);
mrXAi.setRandomChoiceTolerance(0.0);
mrXAi.setTimeLimit(3000); // about 3 seconds
// initialise the detective AI
SimpleDetectiveAI detectiveAI = new SimpleDetectiveAI();
*/
// register the Ai readable and client controllable objects (local game state)
controller.registerAIReadable(state);
controller.registerClientControllable(state);
// register the gui and the ai
/*
controller.setMrXAI(mrXAi);
controller.setDetectiveAI(detectiveAI);
*/
controller.setAI(sAi);
controller.registerGUI(gui);
// specify the mode of the game we are playing
if(vis == 0)
controller.setVisualise(false);
else
controller.setVisualise(true);
if(ai == 0)
controller.setPlayerAssignments(PlayerAssignments.AllAI);
else if (ai == 1)
controller.setPlayerAssignments(PlayerAssignments.MrXAI);
else
controller.setPlayerAssignments(PlayerAssignments.AllGui);
if(server==1)
controller.setUseServer(true);
else
controller.setUseServer(false); // note, server mode will not work
// run the game
controller.run("Test Session");
}
}
|
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;
public class Block extends JComponent
{
//private int value;
private Color color;
private int level; //number 0-7 used to indicate what "level" the block is, corresponds to a color
private Color[] sequence = new Color[] {Color.lightGray, Color.red, Color.orange, Color.yellow, Color.green, Color.cyan, Color.blue, Color.magenta, Color.white, Color.black,};
public Block()
{
level=0;
color = sequence[level];
}
public Block(int Level)
{
level = Level;
color = sequence[Level];
}
public Color getColor()
{
return color;
}
public int getLevel()
{
return level;
}
public void levelUp()
{
level++;
color = sequence[level];
}
public void setLevel(int Level)
{
level = Level;
color = sequence[level];
}
} |
package com.LinkedList;
import java.io.*;
import java.util.*;
class NodeDD{
int data;
NodeDD next;
NodeDD(int d){
data=d;
next=null;
}
}
class Solution
{
public static NodeDD removeDuplicates(NodeDD head) {
if (head == null || head.next == null){
return head;
}
if (head.data == head.next.data){
head.next = head.next.next;
removeDuplicates(head);
}else{
removeDuplicates(head.next);
}
return head;
}
// private static NodeDD removeDuplicates(NodeDD head) {
//
// //Write your code here
// if(head == null){
// return head;
// }
//
// NodeDD curr = head;
//
// while(curr != null && curr.next != null){
// NodeDD prev = curr;
// NodeDD next = curr.next;
//
// int cd = curr.data;
//
// while(next != null){
// if(cd == next.data){
// if(next.next != null){
// prev.next = next.next;
// next = next.next;
//
// }else{
// prev.next = null;
// next = null;
// }
// }else{
// next = next.next;
// prev = prev.next;
// }
// }
// curr = curr.next;
//// cd = curr.data;
// }
//
// return head;
//
//}
private static NodeDD insert(NodeDD head,int data)
{
NodeDD p=new NodeDD(data);
if(head==null)
head=p;
else if(head.next==null)
head.next=p;
else
{
NodeDD start=head;
while(start.next!=null)
start=start.next;
start.next=p;
}
return head;
}
private static void display(NodeDD head)
{
NodeDD start=head;
while(start!=null)
{
System.out.print(start.data+" ");
start=start.next;
}
}
public static void main(String args[]) throws FileNotFoundException {
Scanner sc = new Scanner( new File("input/dummy"));
NodeDD head=null;
int T=sc.nextInt();
while(T-->0){
int ele=sc.nextInt();
head=insert(head,ele);
}
head=removeDuplicates(head);
display(head);
}
} |
package com.sunteam.library.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.sunteam.common.menu.BaseActivity;
import com.sunteam.common.menu.MenuConstant;
import com.sunteam.common.tts.TtsUtils;
import com.sunteam.common.utils.CommonUtils;
import com.sunteam.common.utils.ConfirmDialog;
import com.sunteam.common.utils.Tools;
import com.sunteam.common.utils.dialog.ConfirmListener;
import com.sunteam.common.utils.dialog.PromptListener;
import com.sunteam.library.R;
import com.sunteam.library.asynctask.LoginAsyncTask;
import com.sunteam.library.utils.PublicUtils;
import com.sunteam.library.utils.TTSUtils;
public class AccountLogin extends BaseActivity implements OnFocusChangeListener, View.OnKeyListener, TextWatcher {
private String mTitle; // 菜单标题
private TextView mTvTitle;
private View mLine = null;
private TextView mTvUserNameHint; // 用户名
private EditText mEtUserName; // 用户名编辑控件
private TextView mTvPasswdHint; // 密码
private EditText mEtPasswd; // 密码编辑控件
private Button mBtConfirm; // 登录按钮
private Button mBtCancel; // 取消按钮
private int fontColor, backgroundColor, hightColor;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getIntentPara();
initView();
}
@Override
public void onBackPressed() {
returnConfirm();
}
private void getIntentPara() {
Intent intent = getIntent();
mTitle = intent.getStringExtra(MenuConstant.INTENT_KEY_TITLE);
if (null == mTitle) {
finish();
return;
}
}
private void initView() {
Tools mTools = new Tools(AccountLogin.this);
fontColor = mTools.getFontColor();
backgroundColor = mTools.getBackgroundColor();
hightColor = mTools.getHighlightColor();
this.getWindow().setBackgroundDrawable(new ColorDrawable(mTools.getBackgroundColor()));
setContentView(R.layout.library_account_login);
mTvTitle = (TextView) findViewById(R.id.library_account_login_title);
mTvTitle.setText(mTitle);
mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel()); // 设置title字号
mTvTitle.setHeight(mTools.convertSpToPixel(mTools.getFontSize()));
mTvTitle.setTextColor(fontColor); // 设置title的文字颜色
mLine = (View) findViewById(R.id.library_account_login_line);
mLine.setBackgroundColor(fontColor); // 设置分割线的背景色
// 用户名
mTvUserNameHint = (TextView) findViewById(R.id.library_account_login_username_hint);
mTvUserNameHint.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
mTvUserNameHint.setTextColor(fontColor);
mEtUserName = (EditText) findViewById(R.id.library_account_login_username_input);
mEtUserName.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
mEtUserName.setHintTextColor(fontColor);
mEtUserName.setTextColor(fontColor);
// 密码
mTvPasswdHint = (TextView) findViewById(R.id.library_account_login_passwd_hint);
mTvPasswdHint.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
mTvPasswdHint.setTextColor(fontColor);
mEtPasswd = (EditText) findViewById(R.id.library_account_login_passwd_input);
mEtPasswd.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
mEtPasswd.setHintTextColor(fontColor);
mEtPasswd.setTextColor(fontColor);
// Button
mBtConfirm = (Button) findViewById(R.id.library_account_login_confirm);
mBtConfirm.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
mBtConfirm.setTextColor(fontColor);
mBtConfirm.setBackgroundColor(mTools.getBackgroundColor());
mBtCancel = (Button) findViewById(R.id.library_account_login_cancel);
mBtCancel.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
mBtCancel.setTextColor(fontColor);
mBtCancel.setBackgroundColor(mTools.getBackgroundColor());
// 设置编辑框按键监听
mEtUserName.setOnKeyListener(this);
mEtPasswd.setOnKeyListener(this);
// 添加编辑框文本变化监听
mEtUserName.addTextChangedListener(this);
mEtPasswd.addTextChangedListener(this);
// 设置焦点监听
mEtUserName.setOnFocusChangeListener(this);
mEtPasswd.setOnFocusChangeListener(this);
mBtConfirm.setOnFocusChangeListener(this);
mBtCancel.setOnFocusChangeListener(this);
// TODO 设置测试账号
// 设置测试账号
// mEtUserName.setText("test1");
// mEtPasswd.setText("123");
mEtUserName.requestFocus();
TtsUtils.getInstance().speak(mTitle + "," + getFocusString());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = true;
switch (keyCode) {
case KeyEvent.KEYCODE_STAR: // 屏蔽星号键功能
case KeyEvent.KEYCODE_POUND: // 屏蔽井号键功能
break;
default:
ret = false;
break;
}
if (!ret) {
ret = super.onKeyDown(keyCode, event);
}
return ret;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean ret = true;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: // 删除尾部字符
ret = processKeyBack();
break;
case KeyEvent.KEYCODE_MENU: // 无效键要提示
invalidKey();
break;
// case KeyEvent.KEYCODE_0:
// case KeyEvent.KEYCODE_1:
// case KeyEvent.KEYCODE_2:
// case KeyEvent.KEYCODE_3:
// case KeyEvent.KEYCODE_4:
// case KeyEvent.KEYCODE_5:
// case KeyEvent.KEYCODE_6:
// case KeyEvent.KEYCODE_7:
// case KeyEvent.KEYCODE_8:
// case KeyEvent.KEYCODE_9:
// case KeyEvent.KEYCODE_STAR:
// case KeyEvent.KEYCODE_POUND:
// processInvalid();
// break;
default:
ret = false;
break;
}
if (!ret) {
ret = super.onKeyUp(keyCode, event);
}
return ret;
}
public void onClickForConfirm(View v) {
TtsUtils.getInstance().speak(mBtConfirm.getText().toString());
String account = mEtUserName.getText().toString();
String passwd = mEtPasswd.getText().toString();
if (checkInfoValid()) {
new LoginAsyncTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, account, passwd);
}
}
public void onClickForCancel(View v) {
// PublicUtils.showToast(this, mBtCancel.getText().toString(), true);
// 在按返回时,要确认是否退出
returnConfirm();
}
private String getFocusString() {
String s = "";
if (mEtUserName.isFocused()) {
s = mEtUserName.getText().toString();
if (s.isEmpty()) {
s = mEtUserName.getHint().toString();
} else {
mEtUserName.setSelection(s.length());
s = mTvUserNameHint.getText().toString() + "," + s;
}
} else if (mEtPasswd.isFocused()) {
s = mEtPasswd.getText().toString();
if (s.isEmpty()) {
s = mEtPasswd.getHint().toString();
} else {
mEtPasswd.setSelection(s.length());
s = mTvPasswdHint.getText().toString() + "," + s;
}
} else if (mBtConfirm.isFocused()) {
s = mBtConfirm.getText().toString();
} else if (mBtCancel.isFocused()) {
s = mBtCancel.getText().toString();
}
return s;
}
private String getFocusHint() {
String s = "";
if (mEtUserName.isFocused()) {
s = mEtUserName.getHint().toString();
} else if (mEtPasswd.isFocused()) {
s = mEtPasswd.getHint().toString();
}
return s;
}
// 处理【退出】键:1.焦点不在编辑框时,直接返回;2.焦点在编辑框且编辑框内容为空时直接返回;3.焦点在编辑框且编辑框内容不为空则删除编辑框尾部字符
@SuppressWarnings("unused")
private void delTailCh(EditText et) {
String s = et.getText().toString();
if (s.isEmpty()) {
s = et.getHint().toString();
} else {
int newLen = s.length() - 1;
et.setText(s.substring(0, newLen));
et.setSelection(newLen);
s = getResources().getString(R.string.common_delete) + ", " + s.substring(newLen);
if (0 == newLen) { // 朗读提示信息
s = s + ", " + et.getHint().toString();
} else { // 朗读剩余字符串
s = s + ", " + et.getText().toString();
}
}
TtsUtils.getInstance().speak(s);
}
// 处理【退出】键: 焦点在编辑控件上则删除尾部字符;否则退出当前界面
private boolean processKeyBack() {
boolean ret = true;
EditText mEditText = null;
if (mEtUserName.isFocused()) {
mEditText = mEtUserName;
} else if (mEtPasswd.isFocused()) {
mEditText = mEtPasswd;
}
if (null == mEditText) {
ret = false;
} else {
if (mEditText.getText().toString().isEmpty()) {
// 已经为空时再按【返回】键,退出当前界面
// returnConfirm();
invalidKey(mEditText);
} else {
// delTailCh(mEditText);
CommonUtils.sendKeyEvent(KeyEvent.KEYCODE_DEL);
}
}
return ret;
}
// 焦点变化
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
String s = getFocusString();
TtsUtils.getInstance().speak(s);
}
// Button需要设置背景和焦点色
if(v.getId() == R.id.library_account_login_confirm || v.getId() == R.id.library_account_login_cancel){
if(hasFocus){
v.setBackgroundColor(hightColor);
toggleInputmethodWindow(this);
} else{
v.setBackgroundColor(backgroundColor);
}
}
}
// 在编辑控件中截获按键
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
View v1;
if (KeyEvent.KEYCODE_DPAD_LEFT == keyCode) {
// 截获左方向键, 定位到上一个控件;不要用ACTION_UP,因为系统用ACTION_DOWN切换焦点,如果从其它控件切换过来,此时会收到抬起事件,焦点就切走了
if (KeyEvent.ACTION_DOWN == event.getAction()) {
v1 = v.focusSearch(View.FOCUS_UP);
if (null != v1) {
v1.requestFocus();
}
}
return true;
}
if (KeyEvent.KEYCODE_DPAD_RIGHT == keyCode || KeyEvent.KEYCODE_DPAD_CENTER == keyCode || KeyEvent.KEYCODE_ENTER == keyCode) {
// 截获右方向键, 定位到下一个控件;不要用ACTION_UP,因为系统用ACTION_DOWN切换焦点,如果从其它控件切换过来,此时会收到抬起事件,焦点就切走了
if (KeyEvent.ACTION_DOWN == event.getAction()) {
v1 = v.focusSearch(View.FOCUS_DOWN);
if (null != v1) {
v1.requestFocus();
}
}
return true;
}
// 把其它键都传给下一个控件
return false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (0 == after && count > 0) {
String s1 = s.toString().substring(start, start + count);
s1 = getResources().getString(R.string.common_delete) + " " + s1;
TtsUtils.getInstance().speak(s1);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 朗读新增数据;暂不朗读,因为afterTextChanged()中朗读完整字符串
if (count <= 0) {
return;
}
String s1 = s.toString().substring(start, start + count);
TtsUtils.getInstance().speak(s1);
}
@Override
public void afterTextChanged(Editable s) {
// 朗读完整字符串
String s1 = s.toString();
if (null == s1 || s1.isEmpty()) {
s1 = getFocusHint();
}
TtsUtils.getInstance().speak(s1, TtsUtils.TTS_QUEUE_ADD);
}
// 显示、隐藏切换
private void toggleInputmethodWindow(Context context) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
// 显示、隐藏切换
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
// 退出时要用户确认
private void returnConfirm() {
String title = getResources().getString(R.string.common_dialog_confirm_return_title);
ConfirmDialog mConfirmDialog = new ConfirmDialog(this, title);
mConfirmDialog.setConfirmListener(new ConfirmListener() {
@Override
public void doConfirm() {
finish();
}
@Override
public void doCancel() {
}
});
mConfirmDialog.show();
}
private boolean checkInfoValid() {
boolean ret = false;
String account = mEtUserName.getText().toString();
String passwd = mEtPasswd.getText().toString();
EditText mEditText = null; // 用于设置焦点
int id = 0;
if (account.isEmpty()) {
id = R.string.library_account_username_empty;
mEditText = mEtUserName;
} else if (passwd.isEmpty()) {
id = R.string.library_account_passwd_empty;
mEditText = mEtPasswd;
} else {
ret = true;
}
if (0 != id) {
final EditText curEditText = mEditText;
PublicUtils.showToast(this, getResources().getString(id), new PromptListener() {
@Override
public void onComplete() {
if (null != curEditText) {
curEditText.requestFocus();
}
}
});
}
return ret;
}
// 非法键提示信息:请输入页码,同时,播报当前页码。
private void invalidKey(EditText mEditText) {
String s;
final String etStr;
if (null != mEditText) {
s = mEditText.getHint().toString();
etStr = mEditText.getText().toString();
} else {
s = getResources().getString(R.string.library_account_invalidkey_hint);
etStr = "";
}
PublicUtils.showToast(this, s, new PromptListener() {
@Override
public void onComplete() {
TTSUtils.getInstance().speakMenu(etStr);
}
});
}
// 非法键提示信息:请输入页码,同时,播报当前页码。
private void invalidKey() {
EditText mEditText = null;
if (mEtUserName.isFocused()) {
mEditText = mEtUserName;
} else if (mEtPasswd.isFocused()) {
mEditText = mEtPasswd;
} else {
return;
}
invalidKey(mEditText);
}
// 判断是否为无效键,若是则提示“请输入”
// private void processInvalid() {
// if (mEtUserName.isFocused() || mEtPasswd.isFocused()) {
// return;
// }
// final String s = getResources().getString(R.string.library_account_invalidkey_hint);
// PublicUtils.showToast(this, s);
// }
}
|
package edu.kit.pse.osip.core.model.behavior;
import edu.kit.pse.osip.core.model.base.AbstractTank;
/**
* An alarm which monitors whether the fill level breaks a given threshold.
*
* @author Maximilian Schwarzmann
* @version 1.0
*/
public class FillAlarm extends TankAlarm<Float> {
/**
* Constructs a new FillAlarm.
*
* @param tank The tank to monitor.
* @param threshold The fill level threshold in % between 0 and 1.
* @param behavior Whether the alarm should trigger if the fill level is above or below the threshold.
*/
public FillAlarm(AbstractTank tank, Float threshold, AlarmBehavior behavior) {
super(tank, threshold, behavior);
}
/**
* Returns the fill level.
*
* @return the fill level.
*/
@Override
protected final Float getNotifiedValue() {
return getTank().getFillLevel();
}
}
|
package com.tencent.mm.plugin.sysvideo.ui.video;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import com.tencent.mm.sdk.platformtools.x;
class VideoRecorderUI$3 implements Callback {
final /* synthetic */ VideoRecorderUI ovr;
VideoRecorderUI$3(VideoRecorderUI videoRecorderUI) {
this.ovr = videoRecorderUI;
}
public final void surfaceCreated(SurfaceHolder surfaceHolder) {
x.d("MicroMsg.VideoRecorderUI", "surfaceCreated");
if (VideoRecorderUI.h(this.ovr).a(this.ovr, VideoRecorderUI.q(this.ovr)) != 0) {
VideoRecorderUI.s(this.ovr);
}
}
public final void surfaceDestroyed(SurfaceHolder surfaceHolder) {
x.d("MicroMsg.VideoRecorderUI", "surfaceDestroyed");
VideoRecorderUI.b(this.ovr, true);
VideoRecorderUI.h(this.ovr).ccP();
}
public final void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
x.d("MicroMsg.VideoRecorderUI", "surfaceChanged for:" + i + " w:" + i2 + " h:" + i3);
if (VideoRecorderUI.h(this.ovr).b(surfaceHolder) != 0) {
VideoRecorderUI.s(this.ovr);
}
VideoRecorderUI.a(this.ovr, false);
VideoRecorderUI.b(this.ovr, false);
VideoRecorderUI.x(this.ovr);
}
}
|
package edu.byu.cs.superasteroids.database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import edu.byu.cs.superasteroids.model.Level;
/**
* Created by Azulius on 2/18/16.
*/
public class LevelDao {
private SQLiteDatabase db;
public LevelDao(SQLiteDatabase db) {
this.db = db;
}
/** Gets all Level objects from the DB
*
* @return Array of all Level objects in the DB
*/
public ArrayList<Level> getAll(){
final String SQL = "select id, title, hint, width, height, musicPath " +
"from Levels";
ArrayList<Level> result = new ArrayList<>();
Cursor cursor = db.rawQuery(SQL, new String[]{});
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Level level = new Level();
level.setId(cursor.getInt(0));
level.setTitle(cursor.getString(1));
level.setHint(cursor.getString(2));
level.setWidth(cursor.getInt(3));
level.setHeight(cursor.getInt(4));
level.setBounds(cursor.getInt(3),cursor.getInt(4));
level.setMusicPath(cursor.getString(5));
result.add(level);
cursor.moveToNext();
}
}
finally {
cursor.close();
}
return result;
}
/** Inserts an Level into the DB
*
* @param level Level to add
*/
public boolean insert(Level level){
ContentValues values = new ContentValues();
values.put("number", level.getNumber());
values.put("title", level.getTitle());
values.put("hint", level.getHint());
values.put("width", level.getWidth());
values.put("height", level.getHeight());
values.put("musicPath", level.getMusicPath());
long id = db.insert("Levels", null, values);
if (id >= 0) {
level.setId(((int) id));
return true;
}
else {
return false;
}
}
/** Clears all Levels from the DB
*
*/
public void clearAll(){
final String SQL = "delete from Levels";
db.execSQL(SQL);
}
}
|
package com.akhil.todo.models;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@RedisHash("USER")
public class User implements Serializable {
@Id
String username;
@NotNull
@NotEmpty
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = new BCryptPasswordEncoder().encode(password);
}
}
|
import java.sql.Timestamp;
import java.util.Date;
/**
* @author richer.sun
* @description test
* @date 2021/11/4 6:46 下午
*/
public class Test {
public static void main(String[] args) {
long currentTimeMillis = System.currentTimeMillis();
System.out.println(currentTimeMillis);
Timestamp timestamp = new Timestamp(currentTimeMillis);
System.out.println(timestamp);
}
}
|
package LeetCode.Problems.easy;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] arg0) {
int[] r = twoSum(new int[]{-1, -2, -3, -4, -5}, -8);
System.out.println(Arrays.toString(r));
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length ; i++) {
int tofind = target - nums[i];
if (map.containsKey(tofind) ){
return new int[]{i,map.get(tofind)};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("no such sum");
}
}
|
package uoc.miquel.pac3;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import uoc.miquel.pac3.model.BookContent;
import uoc.miquel.pac3.model.CommonConstants;
/**
* An activity representing a list of Books. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {@link BookDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class BookListActivity extends AppCompatActivity {
private final static String TAG = "BookListActivity";
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
private FirebaseAuth mAuth;
private FirebaseDatabase database;
private SimpleItemRecyclerViewAdapter adapter;
private DatabaseReference myRef;
private SwipeRefreshLayout swipeContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_list);
/**
* Firebase. Gets the reference of the database and authenticates.
*/
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("books");
mAuth.signInWithEmailAndPassword("miqasals@gmail.com", "123456")
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
downloadBooks();
} else {
Toast.makeText(BookListActivity.this, "Sign In Failed",
Toast.LENGTH_SHORT).show();
}
}
});
// Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
// Floating Action Button.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Swipe Container
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshBookList();
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
// RecyclerView. Get the reference of the view objects and inflates the list
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.book_list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
setupRecyclerView(recyclerView);
if (findViewById(R.id.book_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}////////////// onCreate
/**
* Called when the activity is inititated with the SINGLE_TOP flag set. The intents lauched with this
* flag only can be processed in this method (not getIntent())
* @param intent Intent received.
*/
@Override
protected void onNewIntent(Intent intent) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (intent != null && intent.getAction() != null && intent.hasExtra(CommonConstants.POSITION_KEY)) {
// Action DETAIL intent
if (intent.getAction().equalsIgnoreCase(CommonConstants.ACTION_DETAIL)) {
int receivedPosition = intent.getIntExtra(CommonConstants.POSITION_KEY, -1);
if (receivedPosition > -1 && receivedPosition < BookContent.getBooks().size()) {
viewBook(receivedPosition);
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
// Action ERASE intent
} else if (intent.getAction().equalsIgnoreCase(CommonConstants.ACTION_ERASE)) {
int receivedPosition = intent.getIntExtra(CommonConstants.POSITION_KEY, -1);
if (receivedPosition > -1 && receivedPosition < BookContent.getBooks().size()) {
removeBook(receivedPosition);
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
}
// If the action is MAIN only will load the list normally.
}
}
/**
* Download the books from Firebase. Called once the application authenticates
* successfully in remote database.
*/
private void downloadBooks() {
swipeContainer.setRefreshing(true);
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange");
if (dataSnapshot != null) {
getBooksFromDataSnapshot(dataSnapshot);
}
myRef.removeEventListener(this);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
getBooksFromDB();
myRef.removeEventListener(this);
}
});
}
private void refreshBookList() {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange");
if (dataSnapshot != null) {
getBooksFromDataSnapshot(dataSnapshot);
}
myRef.removeEventListener(this);
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", databaseError.toException());
getBooksFromDB();
myRef.removeEventListener(this);
}
});
}
/**
* Get the books from the local database and refresh the list view.
*/
private void getBooksFromDB() {
List<BookContent.BookItem> values = BookContent.getBooks();
adapter.setItems(values);
swipeContainer.setRefreshing(false);
}
/**
* Parse the list of books received from Firebase, save them in the local database and
* refresh the list view. If the received data are not correct or unreadable the function
* get the books from local database and refresh the list.
*
* @param dataSnapshot Obtained from Firebase in onDataChange() function.
*/
private void getBooksFromDataSnapshot(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
GenericTypeIndicator<ArrayList<BookContent.BookItem>> genericTypeIndicator =
new GenericTypeIndicator<ArrayList<BookContent.BookItem>>() {};
ArrayList<BookContent.BookItem> values = dataSnapshot.getValue(genericTypeIndicator);
if (values != null) {
// Save data in database
for (BookContent.BookItem bookItem : values) {
if (!BookContent.exists(bookItem)) {
bookItem.save();
}
}
adapter.setItems(BookContent.getBooks()); //Changed to prevent the position error on clicking to the list elements.
swipeContainer.setRefreshing(false);
} else {
getBooksFromDB();
}
}
/**
* Configure the recycler view adapter and call the inflater method setAdapter().
* @param recyclerView View object reference
*/
private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
adapter = new SimpleItemRecyclerViewAdapter(new ArrayList<BookContent.BookItem>());
recyclerView.setAdapter(adapter);
}
/**
* Start the detail activity or replace the detail fragment depending if the display shows the detail fragment
* or not. Called when the user tap to the DETAIL button of the notification received or when the user tap
* over an element from the list.
* @param position Position in the list of the element to modify.
*/
public void viewBook(int position) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putInt(BookDetailFragment.ARG_ITEM_ID, position);
BookDetailFragment fragment = new BookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Intent intent = new Intent(this, BookDetailActivity.class);
intent.putExtra(BookDetailFragment.ARG_ITEM_ID, position);
startActivity(intent);
}
}
/**
* Erase the referenced book from the local database. Called when the user tap to the DETAIL button of the
* notification received.
* @param position Position in the list of the element to modify.
*/
public void removeBook (int position) {
BookContent.BookItem book = BookContent.getBooks().get(position);
book.delete();
Toast.makeText(this,book.getTitle() + " ELIMINADO", Toast.LENGTH_SHORT).show();
adapter.setItems(BookContent.getBooks());
}
//////////////////////// RECYCLER ADAPTER ////////////////////////
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private List<BookContent.BookItem> mValues;
private final static int EVEN = 0;
private final static int ODD = 1;
public SimpleItemRecyclerViewAdapter(List<BookContent.BookItem> items) {
mValues = items;
}
public void setItems(List<BookContent.BookItem> items) {
mValues = items;
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
int type;
if (position % 2 == 0) {
type = EVEN;
} else {
type = ODD;
}
return type;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
if (viewType == EVEN) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_list_content, parent, false);
} else if (viewType == ODD) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_list_content_odd, parent, false);
}
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mTitleView.setText(mValues.get(position).title);
holder.mAuthorView.setText(mValues.get(position).author);
holder.mView.setTag(position);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int currentPos = (int) v.getTag();
/*
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putInt(BookDetailFragment.ARG_ITEM_ID, currentPos);
BookDetailFragment fragment = new BookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, BookDetailActivity.class);
intent.putExtra(BookDetailFragment.ARG_ITEM_ID, currentPos);
context.startActivity(intent);
}
*/
viewBook(currentPos);
}
});
}
@Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mTitleView;
public final TextView mAuthorView;
public BookContent.BookItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mTitleView = (TextView) view.findViewById(R.id.title);
mAuthorView = (TextView) view.findViewById(R.id.author);
}
@Override
public String toString() {
return super.toString() + " '" + mTitleView.getText() + "'";
}
}
} ///////////// End RECYCLER ADAPTER
}
|
package org.apache.maven;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.internal.MavenWorkspaceReader;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.repository.WorkspaceRepository;
import org.eclipse.aether.util.artifact.ArtifactIdUtils;
/**
* An implementation of a workspace reader that knows how to search the Maven reactor for artifacts, either as packaged
* jar if it has been built, or only compile output directory if packaging hasn't happened yet.
*
* @author Jason van Zyl
*/
@Named( ReactorReader.HINT )
@SessionScoped
class ReactorReader
implements MavenWorkspaceReader
{
public static final String HINT = "reactor";
private static final Collection<String> COMPILE_PHASE_TYPES =
Arrays.asList( "jar", "ejb-client", "war", "rar", "ejb3", "par", "sar", "wsr", "har", "app-client" );
private Map<String, MavenProject> projectsByGAV;
private Map<String, List<MavenProject>> projectsByGA;
private WorkspaceRepository repository;
@Inject
ReactorReader( MavenSession session )
{
projectsByGAV = session.getProjectMap();
projectsByGA = new HashMap<>( projectsByGAV.size() * 2 );
for ( MavenProject project : projectsByGAV.values() )
{
String key = ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() );
List<MavenProject> projects = projectsByGA.get( key );
if ( projects == null )
{
projects = new ArrayList<>( 1 );
projectsByGA.put( key, projects );
}
projects.add( project );
}
repository = new WorkspaceRepository( "reactor", new HashSet<>( projectsByGAV.keySet() ) );
}
//
// Public API
//
public WorkspaceRepository getRepository()
{
return repository;
}
public File findArtifact( Artifact artifact )
{
String projectKey = ArtifactUtils.key( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() );
MavenProject project = projectsByGAV.get( projectKey );
if ( project != null )
{
File file = find( project, artifact );
if ( file == null && project != project.getExecutionProject() )
{
file = find( project.getExecutionProject(), artifact );
}
return file;
}
return null;
}
public List<String> findVersions( Artifact artifact )
{
String key = ArtifactUtils.versionlessKey( artifact.getGroupId(), artifact.getArtifactId() );
List<MavenProject> projects = projectsByGA.get( key );
if ( projects == null || projects.isEmpty() )
{
return Collections.emptyList();
}
List<String> versions = new ArrayList<>();
for ( MavenProject project : projects )
{
if ( find( project, artifact ) != null )
{
versions.add( project.getVersion() );
}
}
return Collections.unmodifiableList( versions );
}
@Override
public Model findModel( Artifact artifact )
{
String projectKey = ArtifactUtils.key( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() );
MavenProject project = projectsByGAV.get( projectKey );
return project == null ? null : project.getModel();
}
//
// Implementation
//
private File find( MavenProject project, Artifact artifact )
{
if ( "pom".equals( artifact.getExtension() ) )
{
return project.getFile();
}
Artifact projectArtifact = findMatchingArtifact( project, artifact );
if ( hasArtifactFileFromPackagePhase( projectArtifact ) )
{
return projectArtifact.getFile();
}
else if ( !hasBeenPackaged( project ) )
{
// fallback to loose class files only if artifacts haven't been packaged yet
// and only for plain old jars. Not war files, not ear files, not anything else.
if ( isTestArtifact( artifact ) )
{
if ( project.hasLifecyclePhase( "test-compile" ) )
{
return new File( project.getBuild().getTestOutputDirectory() );
}
}
else
{
String type = artifact.getProperty( "type", "" );
if ( project.hasLifecyclePhase( "compile" ) && COMPILE_PHASE_TYPES.contains( type ) )
{
return new File( project.getBuild().getOutputDirectory() );
}
}
}
// The fall-through indicates that the artifact cannot be found;
// for instance if package produced nothing or classifier problems.
return null;
}
private boolean hasArtifactFileFromPackagePhase( Artifact projectArtifact )
{
return projectArtifact != null && projectArtifact.getFile() != null && projectArtifact.getFile().exists();
}
private boolean hasBeenPackaged( MavenProject project )
{
return project.hasLifecyclePhase( "package" ) || project.hasLifecyclePhase( "install" )
|| project.hasLifecyclePhase( "deploy" );
}
/**
* Tries to resolve the specified artifact from the artifacts of the given project.
*
* @param project The project to try to resolve the artifact from, must not be <code>null</code>.
* @param requestedArtifact The artifact to resolve, must not be <code>null</code>.
* @return The matching artifact from the project or <code>null</code> if not found. Note that this
*/
private Artifact findMatchingArtifact( MavenProject project, Artifact requestedArtifact )
{
String requestedRepositoryConflictId = ArtifactIdUtils.toVersionlessId( requestedArtifact );
Artifact mainArtifact = RepositoryUtils.toArtifact( project.getArtifact() );
if ( requestedRepositoryConflictId.equals( ArtifactIdUtils.toVersionlessId( mainArtifact ) ) )
{
return mainArtifact;
}
for ( Artifact attachedArtifact : RepositoryUtils.toArtifacts( project.getAttachedArtifacts() ) )
{
if ( attachedArtifactComparison( requestedArtifact, attachedArtifact ) )
{
return attachedArtifact;
}
}
return null;
}
private boolean attachedArtifactComparison( Artifact requested, Artifact attached )
{
//
// We are taking as much as we can from the DefaultArtifact.equals(). The requested artifact has no file so
// we want to remove that from the comparison.
//
return requested.getArtifactId().equals( attached.getArtifactId() )
&& requested.getGroupId().equals( attached.getGroupId() )
&& requested.getVersion().equals( attached.getVersion() )
&& requested.getExtension().equals( attached.getExtension() )
&& requested.getClassifier().equals( attached.getClassifier() );
}
/**
* Determines whether the specified artifact refers to test classes.
*
* @param artifact The artifact to check, must not be {@code null}.
* @return {@code true} if the artifact refers to test classes, {@code false} otherwise.
*/
private static boolean isTestArtifact( Artifact artifact )
{
return ( "test-jar".equals( artifact.getProperty( "type", "" ) ) )
|| ( "jar".equals( artifact.getExtension() ) && "tests".equals( artifact.getClassifier() ) );
}
}
|
package com.lubarov.daniel.web.html;
import com.lubarov.daniel.data.dictionary.KeyValuePair;
import com.lubarov.daniel.data.sequence.ImmutableArray;
import com.lubarov.daniel.data.sequence.ImmutableSequence;
import com.lubarov.daniel.data.stack.DynamicArray;
import com.lubarov.daniel.data.stack.MutableStack;
import com.lubarov.daniel.data.table.sequential.ImmutableArrayTable;
import com.lubarov.daniel.data.table.sequential.ImmutableSequentialTable;
import com.lubarov.daniel.data.util.Check;
public final class Element implements Node {
public static final class Builder {
private final Tag tag;
private final MutableStack<Node> children = DynamicArray.create();
private final MutableStack<KeyValuePair<String, String>> attributes = DynamicArray.create();
public Builder(Tag tag) {
this.tag = Check.notNull(tag);
}
public Builder addChild(Node child) {
children.pushBack(child);
return this;
}
public Builder addRawText(String text) {
return addChild(TextNode.rawText(text));
}
public Builder addEscapedText(String text) {
return addChild(TextNode.escapedText(text));
}
public Builder addChildren(Node... children) {
for (Node child : children)
addChild(child);
return this;
}
public Builder addChildren(Iterable<? extends Node> children) {
for (Node child : children)
addChild(child);
return this;
}
public Builder setRawAttribute(String attribute, String value) {
attributes.pushBack(new KeyValuePair<>(attribute, value));
return this;
}
public Builder setRawAttribute(Attribute attribute, String value) {
return setRawAttribute(attribute.toString(), value);
}
public Builder setEscapedAttribtue(String attribute, String value) {
return setRawAttribute(attribute, EscapeUtils.htmlEncode(value));
}
public Builder setEscapedAttribtue(Attribute attribute, String value) {
return setRawAttribute(attribute, EscapeUtils.htmlEncode(value));
}
public Element build() {
return new Element(this);
}
}
private final Tag tag;
private final ImmutableSequence<Node> children;
private final ImmutableSequentialTable<String, String> attributes;
public Element(Tag tag) {
this.tag = tag;
this.children = ImmutableArray.create();
this.attributes = ImmutableArrayTable.create();
}
public Element(Tag tag, Node... children) {
this.tag = tag;
this.children = ImmutableArray.create(children);
this.attributes = ImmutableArrayTable.create();
}
public Element(Tag tag, Iterable<? extends Node> children) {
this.tag = tag;
this.children = ImmutableArray.copyOf(children);
this.attributes = ImmutableArrayTable.create();
}
private Element(Builder builder) {
this.tag = builder.tag;
this.children = builder.children.toImmutable();
this.attributes = ImmutableArrayTable.copyOf(builder.attributes);
}
@Override
public String toString() {
if (children.isEmpty() && tag != Tag.TEXTAREA)
return String.format("<%s%s />", tag, getAttributes());
StringBuilder sb = new StringBuilder();
sb.append(String.format("<%s%s>", tag, getAttributes()));
for (Node child : children)
sb.append(child);
sb.append(String.format("</%s>", tag));
return sb.toString();
}
private String getAttributes() {
StringBuilder sb = new StringBuilder();
for (KeyValuePair<String, String> attribute : attributes)
sb.append(String.format(" %s=\"%s\"", attribute.getKey(), attribute.getValue()));
return sb.toString();
}
}
|
package enibdiscovery.enibdiscovery.model;
import android.util.Log;
import java.util.List;
public class QuestionEdm {
private int mQuestionEdm;
private List<Integer> mChoiceListEdm;
private int mAnswerIndexEdm;
public QuestionEdm(int questionEdm, List<Integer> choiceListEdm, int answerIndexEdm){
this.setQuestionEdm(questionEdm);
this.setChoiceListEdm(choiceListEdm);
this.setAnswerIndexEdm(answerIndexEdm);
}
public int getQuestionEdm() {
Integer i= mQuestionEdm;
Log.d("getQuestionEdm",i.toString());
return mQuestionEdm;
}
public void setQuestionEdm(int QuestionEdm) {
mQuestionEdm = QuestionEdm;
}
public List<Integer> getChoiceListEdm() {
return mChoiceListEdm;
}
public void setChoiceListEdm(List<Integer> choiceListEdm) {
if (choiceListEdm == null) {
throw new IllegalArgumentException("Impossible null");
}
mChoiceListEdm = choiceListEdm;
}
public int getAnswerIndexEdm() {
return mAnswerIndexEdm;
}
public void setAnswerIndexEdm(int answerIndexEdm) {
if (answerIndexEdm < 0 || answerIndexEdm >= mChoiceListEdm.size()) {
throw new IllegalArgumentException("Impossible index");
}
mAnswerIndexEdm = answerIndexEdm;
}
} |
package com.tencent.mm.plugin.pwdgroup.ui;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
class FacingCreateChatRoomAllInOneUI$8 implements AnimationListener {
final /* synthetic */ FacingCreateChatRoomAllInOneUI mam;
final /* synthetic */ Animation mao;
FacingCreateChatRoomAllInOneUI$8(FacingCreateChatRoomAllInOneUI facingCreateChatRoomAllInOneUI, Animation animation) {
this.mam = facingCreateChatRoomAllInOneUI;
this.mao = animation;
}
public final void onAnimationStart(Animation animation) {
}
public final void onAnimationRepeat(Animation animation) {
}
public final void onAnimationEnd(Animation animation) {
FacingCreateChatRoomAllInOneUI.g(this.mam).aPm();
FacingCreateChatRoomAllInOneUI.g(this.mam).startAnimation(this.mao);
}
}
|
package Interface;
import GestionnaireDonnees.BDDSingleton;
import GestionnaireDonnees.Donnee;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class HistoriqueUtilisateurControlleur {
@FXML public TableView TableHistorique;
@FXML public TableColumn<HistoriqueUtilisateur,String> TypeOperation;
@FXML public TableColumn<HistoriqueUtilisateur,String> Description;
@FXML public TableColumn<HistoriqueUtilisateur,String> DateHeure;
@FXML public DatePicker DateDeb;
@FXML public DatePicker DateFin;
private ArrayList<String> liste_a_generer2 = new ArrayList<>();
@FXML
public void GenererHistorique1() throws FileNotFoundException, SQLException {
FileChooser fileChooser = new FileChooser();
//Set extension filter for text files
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog((new Stage()));
if (file != null) {
//System.out.println(file.getPath());
if (liste_a_generer2 != null)
{
//System.out.println("entree dans .");
BDDSingleton bdd = BDDSingleton.getInstance();
////System.out.println(liste_a_generer.get(0).toString());
bdd.genererFichier(file,liste_a_generer2);
}
Donnee data = new Donnee("Generation de fichiers","L'utilisateur a genere le fichier d'historique");
}
else
System.out.println( " no enter ..");
}
public void consulterClicked(javafx.event.ActionEvent actionEvent) throws SQLException {
if (liste_a_generer2 != null)
{
liste_a_generer2.clear();
}
if (DateDeb.getValue()!=null && DateFin.getValue()!=null) {
if (DateDeb.getValue().isAfter(DateFin.getValue())) {
String s1 = "Information";
String s2 = "";
String s3 = "Vous avez saisi une 'DATE FIN' qui est avant la 'DATE DEBUT' !";
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(s1);
alert.setHeaderText(s3);
alert.setContentText(s2);
alert.showAndWait();
alert.close();
return;
}
String datedeb = DateDeb.getValue().toString();
String datefin = DateFin.getValue().toString();
//System.out.println(datedeb);
datedeb = "\"" + datedeb + "\"";
datefin = "\"" + datefin + "\"";
BDDSingleton bdd = BDDSingleton.getInstance();
String requete = "select * from HistoriqueUtilisateur where heureDeclanchement between " + datedeb + " and " + datefin + "" +
" and mail_utilisateur = ";
ResultSet rs = bdd.decisionRequete(requete);
TypeOperation.setCellValueFactory(new PropertyValueFactory<>("TypeOperation"));
DateHeure.setCellValueFactory(new PropertyValueFactory<>("DateHeure"));
Description.setCellValueFactory(new PropertyValueFactory<>("Description"));
TableHistorique.setItems(getHistorique(rs));
}
else {
String s1 = "Information";
String s2 = "";
String s3 = "Veuillez saisir une 'DATE DEBUT' et une 'DATE FIN' !";
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(s1);
alert.setHeaderText(s3);
alert.setContentText(s2);
alert.showAndWait();
alert.close();
}
}
private ObservableList getHistorique(ResultSet rs) throws SQLException {
ObservableList<HistoriqueUtilisateur> historique = FXCollections.observableArrayList();
String TypeOperation ;
String DateHeure ;
String Description ;
int num ;
int i = 0 ;
while(rs.next()){
TypeOperation = rs.getString("type_operation");
DateHeure = rs.getString("heureDeclanchement");
Description=rs.getString("descriptionOperation");
historique.add(new HistoriqueUtilisateur(TypeOperation,DateHeure,Description));
String ligne = historique.get(i).toString();
liste_a_generer2.add(ligne);
i++;
}
Donnee d = new Donnee("Consultation d'historique","L'utilisateur a consulte son historique");
return historique;
}
}
|
package com.fireblaze.foodiee.adapters;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.fireblaze.foodiee.R;
import com.fireblaze.foodiee.models.DrawerItem;
import java.util.List;
/**
* Created by chait on 8/27/2016.
*/
public class DrawerAdapter extends ArrayAdapter<DrawerItem>{
Context context;
List<DrawerItem> items;
int layoutResID;
public DrawerAdapter(Context context,int layoutResID, List<DrawerItem> items){
super(context,layoutResID,items);
this.context = context;
this.items = items;
this.layoutResID = layoutResID;
}
@NonNull
@Override
public View getView(int position, View convertView,@NonNull ViewGroup parent) {
DrawerItemHolder drawerItemHolder;
View view = convertView;
if(view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerItemHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerItemHolder.itemName = (TextView) view.findViewById(R.id.drawer_item_title);
drawerItemHolder.icon = (ImageView) view.findViewById(R.id.drawer_item_icon);
view.setTag(drawerItemHolder);
} else {
drawerItemHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem d = (DrawerItem) this.items.get(position);
drawerItemHolder.icon.setImageDrawable(view.getResources().getDrawable(d.getImgResID()));
drawerItemHolder.itemName.setText(d.getItemName());
return view;
}
private static class DrawerItemHolder{
TextView itemName;
ImageView icon;
}
}
|
package crdhn.sis.server;
import crdhn.sis.configuration.Config;
import crdhn.sis.controller.UserController;
import firo.Firo;
import static firo.Firo.*;
public class ServiceDaemon {
public static void main(String[] args) throws NoSuchMethodException {
Firo.getInstance().init(Config.getParamString("service", "host", "localhost"), Config.getParamInt("service", "port", 1301));
Firo.getInstance().initializeControllerFromPackage(Config.getParamString("service", "controllerPackage", "crdhn.sis.controller"), ServiceDaemon.class);
get("/hello", (req, res) -> {
System.out.println("abc");
return "";
});
//insert Organization
UserController.insertAcountOrganization();
}
}
|
package arun.problems.ds.arrays;
import java.util.Stack;
public class PrintNextBiggestNumberForEachElement {
public static void main(String a[]) {
int[] input = {2};
PrintNextBiggestNumberForEachElement print = new PrintNextBiggestNumberForEachElement();
print.printNextBiggest(input);
}
/**
* The brute force for this problem will end up in O(N^2)
* Better solution could be implemented using a Stack.
*
* Logic:
* =====
* Initialize the stack with first element and follow the steps:
*
* Iterate through the array from 2nd element
* Step1: Make element as next, compare the stacks top element with next
* Step2: While stack element is less than next, then next is the next element for the popped element
* Step3: Keep popping the element from the stack as long as it is empty or
* If next is less than stack element
* Step4: Push the next to stack, so that next element can be for that element.
* Step5: After the completion of array iteration, pop out all the elements in the stack and pritn "-1".
* As no bigger number found for those.
*
*
*
* @param input
*/
public void printNextBiggest(int[] input) {
if (input == null)
return;
Stack<Integer> stack = new Stack<Integer>();
stack.push(input[0]);
for(int i = 1; i < input.length; i++) {
int bigNext = input[i];
while(!stack.isEmpty()) {
int number = stack.peek();
if(bigNext > number) {
System.out.println(number + " --> " + bigNext);
stack.pop();
} else {
break;
}
}
stack.push(bigNext);
}
while(!stack.isEmpty()) {
System.out.println(stack.pop() + " --> -1" );
}
}
}
|
package android.support.design.widget;
import android.graphics.drawable.Drawable;
class FloatingActionButton$b implements p {
final /* synthetic */ FloatingActionButton fu;
private FloatingActionButton$b(FloatingActionButton floatingActionButton) {
this.fu = floatingActionButton;
}
/* synthetic */ FloatingActionButton$b(FloatingActionButton floatingActionButton, byte b) {
this(floatingActionButton);
}
public final float getRadius() {
return ((float) this.fu.getSizeDimension()) / 2.0f;
}
public final void d(int i, int i2, int i3, int i4) {
FloatingActionButton.c(this.fu).set(i, i2, i3, i4);
this.fu.setPadding(FloatingActionButton.d(this.fu) + i, FloatingActionButton.d(this.fu) + i2, FloatingActionButton.d(this.fu) + i3, FloatingActionButton.d(this.fu) + i4);
}
public final void setBackgroundDrawable(Drawable drawable) {
FloatingActionButton.a(this.fu, drawable);
}
public final boolean ak() {
return FloatingActionButton.e(this.fu);
}
}
|
package com.javakc.ssm.modules.batchOut.service;
/**
* @ClassName batchOutService
* @Description TODO
* @Author Administrator
* @Date 2020/3/21 11:49
* @Version 1.0
**/
public class BatchOutService {
}
|
package com.rc.portal.service;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.vo.TLeader;
import com.rc.portal.vo.TMember;
import com.rc.portal.vo.TMemberAccount;
import com.rc.portal.vo.TMemberBaseMessageExt;
import com.rc.portal.vo.TMemberExample;
import com.rc.portal.vo.TMemberThreeBinding;
public interface TMemberManager {
int countByExample(TMemberExample example) throws SQLException;
int deleteByExample(TMemberExample example) throws SQLException;
int deleteByPrimaryKey(Long id) throws SQLException;
Long insert(TMember record) throws SQLException;
Long insertSelective(TMember record,TLeader leader) throws SQLException;
List selectByExample(TMemberExample example) throws SQLException;
TMember selectByPrimaryKey(Long id) throws SQLException;
int updateByExampleSelective(TMember record, TMemberExample example) throws SQLException;
int updateByExample(TMember record, TMemberExample example) throws SQLException;
int updateByPrimaryKeySelective(TMember record) throws SQLException;
int updateByPrimaryKey(TMember record) throws SQLException;
Long saveTMemberAccount(TMemberAccount record) throws SQLException;
Long saveMemberThreeBinding(TMemberThreeBinding record) throws SQLException;
Long savetmemberbasemessageext(TMemberBaseMessageExt record)
throws SQLException;
}
|
package client.by.epam.fullparser.start;
import client.by.epam.fullparser.view.View;
import org.apache.log4j.PropertyConfigurator;
/**
* Start point of client.
*/
public class Start {
private static final String LOGGER_CONFIG = "E:\\EpamCourse\\FullParser\\out\\production\\FullParser\\log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(LOGGER_CONFIG);
new View().start();
}
}
|
package handlers;
import controller.Controller;
import model.Key;
public class DoorOne implements DoorChain
{
private DoorChain nextDoor;
@Override
public void setNextDoor(DoorChain nextDoor)
{
this.nextDoor = nextDoor;
}
@Override
public void tryDoor(Key key)
{
if (key.getvalue() == 1)
{
Controller.getInstance().openLeftDoor();
}
else
{
this.nextDoor.tryDoor(key);
}
}
} |
package com.mbirtchnell.ocmjea.domain;
public class ComponentFactory
{
public static Component createComponent(ComponentCategory selectedComponentCategory)
{
Component component = null;
switch(selectedComponentCategory)
{
case DOOR:
component = new Door();
break;
case ROOF:
component = new Roof();
break;
case FOUNDATION:
component = new Foundation();
break;
case WALL:
component = new Wall();
break;
case WINDOW:
component = new Window();
break;
default:
break;
}
return component;
}
}
|
package mygroup;
// 单链表是否含有循环
public class CheckLoopInList {
static class MyNode {
MyNode(int d) {
data = d;
}
MyNode(int d, MyNode n) {
data = d;
next = n;
}
int data;
MyNode next;
}
static class MyList {
MyNode head;
MyList(MyNode n) { head = n; }
void print() {
MyNode h = head;
while(h != null) {
System.out.print(h.data);
h = h.next;
}
}
boolean checkLoop() {
if (head == null) { // empty
return false;
}
MyNode n = head.next;
if (n == null) { // single node
return false;
}
MyNode nNext = n.next;
while(n != null && nNext != null) {
n = n.next;
nNext = nNext.next;
if (nNext == null) {
return false; // 到达末尾
}
nNext = nNext.next;
if (n == nNext) {
return true;
}
}
return false; // 没有找到
}
}
public static void main(String[] args) {
MyNode head = new MyNode(6);
MyNode loop = new MyNode(7, new MyNode(2, new MyNode(0, new MyNode(4, new MyNode(9, head)))));
head.next = loop;
MyList l = new MyList(head);
System.out.println(l.checkLoop()); // 应当打印true
}
}
|
package software.design.consulate.model.dto.application;
public class EditApplicationDto extends CreateApplicationDto {
protected Long id;
public EditApplicationDto() {
}
public EditApplicationDto(Long id) {
this.id = id;
}
public EditApplicationDto(String title, String content, String firstName, String lastName, String maidenName, String email, char sex, String martialState, String birthday, String passportCreationTime, String passportExpirationTime, String pesel, String passportGenerator, String purpose, String arriveTime, int visitationLength, String nationalities, String passportNumber, Long id) {
super(title, content, firstName, lastName, maidenName, email, sex, martialState, birthday, passportCreationTime, passportExpirationTime, pesel, passportGenerator, purpose, arriveTime, visitationLength, nationalities, passportNumber);
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
package com.facebook.react.flat;
import android.util.SparseIntArray;
import java.util.Arrays;
final class VerticalDrawCommandManager extends ClippingDrawCommandManager {
VerticalDrawCommandManager(FlatViewGroup paramFlatViewGroup, DrawCommand[] paramArrayOfDrawCommand) {
super(paramFlatViewGroup, paramArrayOfDrawCommand);
}
public static void fillMaxMinArrays(DrawCommand[] paramArrayOfDrawCommand, float[] paramArrayOffloat1, float[] paramArrayOffloat2, SparseIntArray paramSparseIntArray) {
float f = 0.0F;
int i;
for (i = 0; i < paramArrayOfDrawCommand.length; i++) {
if (paramArrayOfDrawCommand[i] instanceof DrawView) {
DrawView drawView = (DrawView)paramArrayOfDrawCommand[i];
paramSparseIntArray.append(drawView.reactTag, i);
f = Math.max(f, drawView.mLogicalBottom);
} else {
f = Math.max(f, paramArrayOfDrawCommand[i].getBottom());
}
paramArrayOffloat1[i] = f;
}
for (i = paramArrayOfDrawCommand.length - 1; i >= 0; i--) {
if (paramArrayOfDrawCommand[i] instanceof DrawView) {
f = Math.min(f, ((DrawView)paramArrayOfDrawCommand[i]).mLogicalTop);
} else {
f = Math.min(f, paramArrayOfDrawCommand[i].getTop());
}
paramArrayOffloat2[i] = f;
}
}
public static void fillMaxMinArrays(NodeRegion[] paramArrayOfNodeRegion, float[] paramArrayOffloat1, float[] paramArrayOffloat2) {
float f = 0.0F;
int i;
for (i = 0; i < paramArrayOfNodeRegion.length; i++) {
f = Math.max(f, paramArrayOfNodeRegion[i].getTouchableBottom());
paramArrayOffloat1[i] = f;
}
for (i = paramArrayOfNodeRegion.length - 1; i >= 0; i--) {
f = Math.min(f, paramArrayOfNodeRegion[i].getTouchableTop());
paramArrayOffloat2[i] = f;
}
}
final int commandStartIndex() {
int j = Arrays.binarySearch(this.mCommandMaxBottom, this.mClippingRect.top);
int i = j;
if (j < 0)
i = j ^ 0xFFFFFFFF;
return i;
}
final int commandStopIndex(int paramInt) {
float[] arrayOfFloat = this.mCommandMinTop;
int i = Arrays.binarySearch(arrayOfFloat, paramInt, arrayOfFloat.length, this.mClippingRect.bottom);
paramInt = i;
if (i < 0)
paramInt = i ^ 0xFFFFFFFF;
return paramInt;
}
final boolean regionAboveTouch(int paramInt, float paramFloat1, float paramFloat2) {
return (this.mRegionMaxBottom[paramInt] < paramFloat2);
}
final int regionStopIndex(float paramFloat1, float paramFloat2) {
int j = Arrays.binarySearch(this.mRegionMinTop, paramFloat2 + 1.0E-4F);
int i = j;
if (j < 0)
i = j ^ 0xFFFFFFFF;
return i;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\flat\VerticalDrawCommandManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.example.springbootrestdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springbootrestdemo.controller.dto.MobilePhoneDto;
import com.example.springbootrestdemo.entites.MobilePhone;
import com.example.springbootrestdemo.exception.MobilePhoneNotFoundException;
import com.example.springbootrestdemo.service.MobilePhoneService;
import io.swagger.v3.oas.annotations.Operation;
@RestController
@RequestMapping("/mobile")
public class MobilePhoneController {
@Autowired
private MobilePhoneService service;
@GetMapping("/mobiles")
@Operation(summary = "To find all MobilePhones")
public List<MobilePhone> get() {
return service.getAllMobiles();
}
@PostMapping("/add")
@Operation(summary = "To Add MobilePhone")
public ResponseEntity<?> post(@RequestBody MobilePhone mobilePhone) {
ResponseEntity<?> response = null;
try {
response = new ResponseEntity<MobilePhone>(service.saveMobilePhone(mobilePhone), HttpStatus.OK);
} catch (MobilePhoneNotFoundException e) {
response = new ResponseEntity<String>(e.getMessage(), HttpStatus.OK);
}
return response;
}
@GetMapping("/get/{id}")
@Operation(summary = "To find MobilePhone by using id")
public MobilePhone getById(@PathVariable (value = "id") long id) {
return service.getMobilePhoneById(id);
}
@PutMapping("/edit")
@Operation(summary = "To edit MobilePhone details")
public void put(@RequestBody MobilePhone mobilePhone) {
service.editMobilephone(mobilePhone);
}
@DeleteMapping("/delete/{id}")
@Operation(summary = "To delete MobilePhone by using id")
public void delete(@PathVariable (value = "id") long id) {
service.deleteMobilePhone(id);
}
@GetMapping("/MobilePhones")
@Operation(summary = "To find all MobilePhone Dto data")
public List<MobilePhoneDto> getAll() {
return service.getAllMobilePhones();
}
}
|
import java.awt.*;
import java.awt.event.*;
class Images extends Frame
{
static Image img;
Images()
{
img=Toolkit.getDefaultToolkit().getImage("Prabhas.jpg");
MediaTracker track=new MediaTracker(this);
track.addImage(img,0);
try
{
track.waitForID(0);
}
catch(InterruptedException ie)
{
}
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawImage(img,40,50,750,750,null);
}
public static void main(String args[])
{
Images i=new Images();
i.setSize(800,800);
i.setTitle("My Images");
i.setIconImage(img);
i.setVisible(true);
}
} |
package com.allinpay.its.boss.framework.utils;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @author YM
*/
public class ParameterRequestWrapper extends HttpServletRequestWrapper {
private Map<String, String[]> params;
private ServletInputStream servletInputStream;
private int contentLength;
public ParameterRequestWrapper(HttpServletRequest request,
Map<String, String[]> newParams) {
super(request);
this.params = newParams;
}
public ParameterRequestWrapper(HttpServletRequest request,
ServletInputStream in, int contentLength) {
super(request);
this.params = null;
this.servletInputStream = in;
this.contentLength = contentLength;
}
public Map<String, String[]> getParameterMap() {
if (this.params == null)
return super.getParameterMap();
return this.params;
}
public Enumeration<String> getParameterNames() {
if (this.params == null)
return super.getParameterNames();
Vector l = new Vector(this.params.keySet());
return l.elements();
}
public String[] getParameterValues(String name) {
if (this.params == null)
return super.getParameterValues(name);
Object v = this.params.get(name);
if (v == null)
return null;
if ((v instanceof String[]))
return (String[]) (String[]) v;
if ((v instanceof String)) {
return new String[] { (String) v };
}
return new String[] { v.toString() };
}
public String getParameter(String name) {
if (this.params == null)
return super.getParameter(name);
Object v = this.params.get(name);
if (v == null)
return null;
if ((v instanceof String[])) {
String[] strArr = (String[]) (String[]) v;
if (strArr.length > 0) {
return strArr[0];
}
return null;
}
if ((v instanceof String)) {
return (String) v;
}
return v.toString();
}
public int getContentLength() {
if (this.servletInputStream == null)
return super.getContentLength();
return this.contentLength;
}
public ServletInputStream getInputStream() throws IOException {
if (this.servletInputStream == null)
return super.getInputStream();
return this.servletInputStream;
}
} |
package com.bat.commoncode.exceptions;
import com.bat.commoncode.enums.ConstantEnum;
/**
* 程序中的小惊喜
*
* @author ZhengYu
* @version 1.0 2019/10/31 17:19
**/
public class SurpriseException extends RuntimeException {
public SurpriseException() {
super(ConstantEnum.GLOBAL_SURPRISE.msg());
}
}
|
package net.minecraft.stats;
public interface IStatType {
String format(int paramInt);
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\stats\IStatType.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package core.common;
import java.util.List;
import core.common.exception.CommonException;
/**
* Interface responsavel por definir as operações de comunicação com o banco de dados.
* @author Daniel Menezes <tt>daniel.afmenezes@gmail.com</tt>
* @param <E> Entidade
*/
public interface CommonService<E extends CommonBean> {
/**
* Remove a entidade da base de dados.
* @param E Entidade a ser removida
* @throws CommonException Em caso de exceção.
*/
public void delete(E entity) throws CommonException;
/**
* Remove um conjunto de entidades pela lista de identificadores.
* @param listId Lista de identificadores
* @throws CommonException Em caso de exceção.
*/
public void deleteByIds(List<Integer> listId) throws CommonException;
/**
* Recupera todas as entidades.
* @return Lista de entidades
* @throws CommonException Em caso de exceção.
*/
public List<E> findAll() throws CommonException;
/**
* Recupera todas as entidades com ordenação.
* @param orderBy Cláusula order by para ser adicionada à query.
* @return Lista de entidades
* @throws CommonException Em caso de exceção.
*/
public List<E> findAll(String orderBy) throws CommonException;
/**
* Recupera uma entidade pelo identificador
* @param id Identificador
* @return Entidade
* @throws CommonException Em caso de exceção.
*/
public E findById(Integer id) throws CommonException;
/**
* Recupera uma lista de entidades pelos identificadores
* @param listId Lista de identificadores
* @return Lista de entidades
* @throws CommonException Em caso de exceção.
*/
public List<E> findByIds(List<Integer> listId) throws CommonException;
/**
* Recupera todas as entidades pelos identificadores com ordenação.
* @param campo Campo a ser ordenado
* @param tipoOrdenacao <tt>ASC / DESC </tt>
* @return Lista de entidades
* @throws CommonException Em caso de exceção.
*/
public List<E> findAllOrderBy(String campo, String tipoOrdenacao) throws CommonException;
/**
* Persiste uma lista entidades.
* @param objList Lista de entidades a ser persistida
* @throws CommonException Em caso de exceção.
*/
public void saveOrUpdateAll(List<E> objList) throws CommonException;
/**
* Persiste uma entidade.
* @param entity Entidade a ser persistida
* @return Objeto persistido em banco
* @throws CommonException Em caso de exceção.
*/
public E saveOrUpdate (E entity) throws CommonException;
} |
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.customer.dao.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import de.hybris.bootstrap.annotations.IntegrationTest;
import de.hybris.platform.core.model.c2l.CountryModel;
import de.hybris.platform.core.model.user.AddressModel;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.servicelayer.ServicelayerTest;
import de.hybris.platform.servicelayer.i18n.CommonI18NService;
import de.hybris.platform.servicelayer.user.UserService;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
/**
* JUnit test suite for {@link DefaultCustomerAccountDao}
*/
@IntegrationTest
public class DefaultCustomerAccountDaoTest extends ServicelayerTest
{
private static final String TEST_CUSTOMER_UID = "accountcustomer@test.com";
@Resource
private UserService userService;
@Resource
private DefaultCustomerAccountDao defaultCustomerAccountDao;
@Resource
private CommonI18NService commonI18NService;
private CustomerModel customer;
@Before
public void setUp() throws Exception
{
createCoreData();
createDefaultUsers();
importCsv("/commerceservices/test/testCustomerAccount.impex", "utf-8");
customer = userService.getUserForUID(TEST_CUSTOMER_UID, CustomerModel.class);
}
@Test
public void shouldGetDeliveryAddress()
{
final List<CountryModel> deliveryCountries = new ArrayList<>();
deliveryCountries.add(commonI18NService.getCountry("US"));
List<AddressModel> deliveryAddress = defaultCustomerAccountDao.findAddressBookDeliveryEntriesForCustomer(customer,
deliveryCountries);
assertNotNull("deliveryAddress is null", deliveryAddress);
assertEquals("deliveryAddress size is not 1", 1, deliveryAddress.size());
deliveryCountries.add(commonI18NService.getCountry("GB"));
deliveryAddress = defaultCustomerAccountDao.findAddressBookDeliveryEntriesForCustomer(customer, deliveryCountries);
assertNotNull("deliveryAddress is null", deliveryAddress);
assertEquals("deliveryAddress size is not 2", 2, deliveryAddress.size());
}
@Test
public void shouldNotGetDeliveryAddress()
{
final List<CountryModel> deliveryCountries = new ArrayList<>();
deliveryCountries.add(commonI18NService.getCountry("NONEXIST"));
final List<AddressModel> deliveryAddress = defaultCustomerAccountDao.findAddressBookDeliveryEntriesForCustomer(customer,
deliveryCountries);
assertNotNull("deliveryAddress is null", deliveryAddress);
assertEquals("deliveryAddress size is not 0", 0, deliveryAddress.size());
}
}
|
package com.alium.ic.domains;
// Generated 2013-06-19 17:36:03 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* AgencjaObszUm generated by hbm2java
*/
@Entity
@Table(name = "agencja_obsz_um", catalog = "finalna")
public class AgencjaObszUm implements java.io.Serializable {
private Integer id;
private SlowObszar slowObszar;
private AgencjaUmowa agencjaUmowa;
private Date wd;
private String op;
public AgencjaObszUm() {
}
public AgencjaObszUm(SlowObszar slowObszar, AgencjaUmowa agencjaUmowa,
Date wd, String op) {
this.slowObszar = slowObszar;
this.agencjaUmowa = agencjaUmowa;
this.wd = wd;
this.op = op;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_obszar", nullable = false)
public SlowObszar getSlowObszar() {
return this.slowObszar;
}
public void setSlowObszar(SlowObszar slowObszar) {
this.slowObszar = slowObszar;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_umowa", nullable = false)
public AgencjaUmowa getAgencjaUmowa() {
return this.agencjaUmowa;
}
public void setAgencjaUmowa(AgencjaUmowa agencjaUmowa) {
this.agencjaUmowa = agencjaUmowa;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "wd", nullable = false, length = 19)
public Date getWd() {
return this.wd;
}
public void setWd(Date wd) {
this.wd = wd;
}
@Column(name = "op", nullable = false, length = 30)
public String getOp() {
return this.op;
}
public void setOp(String op) {
this.op = op;
}
}
|
package lab1_16;
public class List<D>{
private Node<D> head = null, end = null;
private int listSize = 0;
private static class Node<D>{
private D data;
private Node<D> next;
public Node(D d, Node<D> n){
data = d;
next = n;
}
}
public List(){}
public int getListSize(){
return listSize;
}
public boolean isEmpty(){
return listSize == 0;
}
public void addNode(D d){
Node<D> current = new Node<D>(d, null);
if(isEmpty()){
head = current;
end = current;
}else{
end.next = current;
end = current;
}
listSize++;
}
public void addNode(D d,int i){
Node<D> add = new Node<D>(d, null),current = head;
int t = 0;
if(isEmpty()){
head = add;
end = add;
}else{
if(i == 0){
add.next = head;
head = add;
}else{
while (t < listSize-1 && t < i-1){
current = current.next;
t++;
}
add.next = current.next;
current.next = add;
}
if(add.next == null){
end = add;
}
}
listSize++;
}
public void delNode(int i){
int t = 0;
Node<D> current = head;
if(!isEmpty()){
if(i == 0){
head = head.next;
current.data = null;
current.next = null;
current = head;
}else{
while (t < listSize-1 && t < i-1){
current = current.next;
t++;
}
current.next.data = null;
current.next = current.next.next;
}
if(current.next == null){
end = head;
}
listSize--;
}else{
System.out.println("List already empty");
}
}
public void printData(){
Node<D> current = head;
if(!isEmpty()){
while (current != null){
System.out.println(current.data);
current = current.next;
}
}else {
System.out.println("Лист пуст");
}
}
public D viewData(int i){
Node<D> current = head;
int t = 0;
if(!isEmpty()){
while (t < listSize-1 && t < i-1){
current = current.next;
t++;
}
return current.data;
}else {
System.out.println("No data here");
return null;
}
}
} |
package string_test;
import java.lang.reflect.Field;
/**
* Description:
*
* @author Baltan
* @date 2018/9/25 22:50
*/
public class Test6 {
public static void main(String[] args) throws Exception {
String str = "abc";
System.out.println(str);
Class<? extends String> clazz = str.getClass();
Field value = clazz.getDeclaredField("value");
value.setAccessible(true);
char[] obj = (char[]) value.get(str);
obj[1] = 's';
// value.set(str, new char[]{'q'});
System.out.println(str);
}
}
|
package cn.chinaunicom.monitor.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
import cn.chinaunicom.monitor.R;
import cn.chinaunicom.monitor.beans.HostIp;
import cn.chinaunicom.monitor.viewholders.OnlyTextViewHolder;
/**
* Created by yfYang on 2017/10/30.
*/
public class OnlyTextSpinnerAdapter extends BaseAdapter {
private Context context;
private List<String> items;
private OnlyTextViewHolder viewHolder;
public OnlyTextSpinnerAdapter(Context context, List<String> items) {
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null != convertView) {
viewHolder = (OnlyTextViewHolder) convertView.getTag();
} else {
convertView = View.inflate(context, R.layout.my_simple_spinner_item, null);
viewHolder = new OnlyTextViewHolder(convertView);
convertView.setTag(viewHolder);
}
viewHolder.text.setText(items.get(position));
return convertView;
}
}
|
package org.team3128.common.hardware.gyroscope;
/**
* Interface to define a gyro sensor, which has minimal methods that allow for
* the setting and retrieval of yaw.
*
* Takes the convention of counter-clockwise rotation as positive.
*
* @author Ronak Roy
*/
public interface Gyro {
/**
* Gets the current yaw of the robot, with counterclockwise as positive. The
* function is continuous, so it ranges from negative infinity to positive
* infinity.
*
* @return robot yaw, in degrees
*/
public double getAngle();
/**
* Gets the rate of change of the yaw of the robot, with counterclockwise
* rotations as positive.
*
* @return angular velocity, in degrees/second
*/
public double getRate();
/**
* Gets the pitch of the robot in degrees
*
* @return robot pitch, in degrees
*/
public double getPitch();
public double getRoll();
/**
* Gives the gyro reading an offset such that the current position is read as 0
* degrees.
*/
public void reset();
/**
* Gives the gyro reading an offset such that the current position is read as
* whatever desired angle.
*
* @param angle - The angle to consider the current position as.
*/
public void setAngle(double angle);
} |
/**
* 47. 礼物的最大价值
* Medium
*/
public class Solution {
public int maxValue(int[][] grid) {
int[] row = new int[grid[0].length + 1];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
row[j + 1] = Math.max(row[j], row[j + 1]) + grid[i][j];
}
}
return row[row.length - 1];
}
public static void main(String[] args) {
Solution s = new Solution();
int[][][] grids = {
{
{ 1, 3, 1 },
{ 1, 5, 1 },
{ 4, 2, 1 }
},
{
{ 1, 3, 1 },
{ 1, 5, 1 },
{ 10, 2, 1 }
}
};
for (int[][] g : grids) {
System.out.println(s.maxValue(g));
}
}
}
|
package so.ego.space.domains.project.presentation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import so.ego.space.domains.project.application.MemberFindService;
import so.ego.space.domains.project.application.dto.MemberFindResponse;
import so.ego.space.domains.project.application.dto.ProjectFindAllResponse;
@RequiredArgsConstructor
@RestController
public class MemberFindController {
private final MemberFindService memberFindService;
@GetMapping("/members/{project_id}")
public MemberFindResponse findProjectMember(@PathVariable Long project_id){
return memberFindService.findProjectMember(project_id);
}
}
|
package banyuan.day02.practice04;
import java.util.Scanner;
/**
* @author newpc
* <p>
* 声明一个int型的数组,循环接收8个学生的成绩,计算这8个学生的总分及平均分、最高分和最低分
*/
public class P06 {
public static void main(String[] args) {
double sum = 0;
double avg = 0;
int max;
int min;
int[] arr = new int[8];
Scanner in = new Scanner(System.in);
System.out.println("请依次输入8名学生的成绩:");
for (int i = 0; i < arr.length; i++) {
int input = in.nextInt();
arr[i] = input;
}
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
avg = sum / arr.length;
min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
System.out.println("sum=" + sum + "avg=" + avg + "min=" + min + "max=" + max);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.