blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b4fe566ffd7ed66164f34b44f893a5e5e56ebfa | b8bd0161d72c4ca1eca465dde3f2d898ca9f5f39 | /src/com/itedu365/best5201/Before.java | a18a975ed421f4f54f8000122a5836c79329bb01 | [] | no_license | cakin24/TheBestCodeAndArchitectOptimize | 2a3f07242ada411c0533c1587f88f90cf84fca1f | bdc671f410df0a46d89d20f468e4b08ce8f0703a | refs/heads/master | 2020-09-15T20:43:05.916235 | 2019-11-23T07:58:38 | 2019-11-23T07:58:38 | 223,552,748 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 748 | java | /*
* 本书配套视频教程网址(架构师系列培训):
* www.365itedu.com
* 365IT学院,让学习变得更简单!
*/
package com.itedu365.best5201;
/**
*
* 【Java代码与架构之完美优化——实战经典】
*
* 52、避免捕获NullPointerException或Error
*
* @author 颜廷吉
*/
public class Before {
// 调用method1
public static void method2() {
try {
// 抛出AssertionError(Error子类)
assert -1 >= 0 : "有负数!";
} catch (Error e) {
// 截获Error错误
e.printStackTrace();
} catch (NullPointerException e) {
// 截获NullPointerException
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
562407ac6bab9710b23ada2065bee1cc0413f49f | e28f2c9cbee582c442d9d63d1bcd68b929db18a6 | /oopIntro/src/oopIntro/Product.java | 9f548e4e1a4046b416fdd36063a195bcbbcd6cd2 | [] | no_license | ramazankayis/JavaCampHomeWork | 3ef05d94712bc8f3b6a62c141b40e4e1b376dc5a | 08e877f40791893cafe018ef72402528ea512008 | refs/heads/master | 2023-07-04T11:35:09.486180 | 2021-08-08T14:30:51 | 2021-08-08T14:30:51 | 365,373,553 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,193 | java | package oopIntro;
public class Product {
int id;
String name;
double unitPrice;
String detail;
double discount;
double unitPriceAfterDiscount;
public Product() {
}
public Product(int id, String name, double unitPrice, String detail,double discount,double unitPriceAfterDiscount) {
super();
this.id = id;
this.name = name;
this.unitPrice = unitPrice;
this.detail = detail;
this.discount= discount;
this.unitPriceAfterDiscount= unitPriceAfterDiscount;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getUnitPriceAfterDiscount() {
return this.unitPrice- (this.unitPrice*this.discount/100);
}
}
| [
"[email protected]"
] | |
d72fd328a00834d6beb15c4170181ef9b227de6f | 83b6a9a3d2be905c940b9166f7056c89c720eaf1 | /compling.core/source/compling/gui/GrammarWritingUtilities.java | 3715a1e6e4c6a40905b6a42739b33dd07ff5affb | [] | no_license | icsi-berkeley/ecg_compling | 75a07f301a9598661fa71ba5d764094b06b953b3 | 89c810d49119ba7cb76a7323ebbf051a9cfb9b9c | refs/heads/master | 2021-09-15T01:57:44.493832 | 2015-12-14T18:42:08 | 2015-12-14T18:42:08 | 26,875,943 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,470 | java | // =============================================================================
//File : GrammarWritingUtilities.java
//Author : emok
//Change Log : Created on Jul 28, 2007
//=============================================================================
package compling.gui;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import compling.annotation.AnnotationException;
import compling.annotation.childes.ChildesAnnotation.GoldStandardAnnotation;
import compling.annotation.childes.ChildesIterator;
import compling.annotation.childes.ChildesTranscript;
import compling.annotation.childes.ChildesTranscript.ChildesClause;
import compling.annotation.childes.ChildesTranscript.ChildesEvent;
import compling.annotation.childes.ChildesTranscript.ChildesItem;
import compling.annotation.childes.FeatureBasedEntity.Binding;
import compling.annotation.childes.FeatureBasedEntity.ExtendedFeatureBasedEntity;
import compling.context.ContextException.ItemNotDefinedException;
import compling.context.ContextModel;
import compling.context.ContextUtilities.MiniOntologyFormatter;
import compling.context.ContextUtilities.OntologyGraphPrinter;
import compling.context.ContextUtilities.SimpleOntologyPrinter;
import compling.context.MiniOntology;
import compling.grammar.GrammarException;
import compling.grammar.ecg.ECGGrammarUtilities;
import compling.grammar.ecg.ECGGrammarUtilities.SimpleGrammarPrinter;
import compling.grammar.ecg.Grammar;
import compling.grammar.unificationgrammar.TypeSystemException;
import compling.gui.LearnerPrefs.LP;
import compling.parser.ParserException;
import compling.parser.ecgparser.Analysis;
import compling.parser.ecgparser.ECGAnalyzer;
import compling.parser.ecgparser.NoECGAnalysisFoundException;
import compling.simulator.Simulator;
import compling.simulator.SimulatorException;
import compling.simulator.SimulatorException.ScriptNotFoundException;
import compling.util.Pair;
import compling.util.PriorityQueue;
import compling.util.fileutil.ExtensionFileFilter;
import compling.util.fileutil.FileUtils;
import compling.utterance.Word;
//=============================================================================
public class GrammarWritingUtilities {
static PrintStream printStream = System.out;
private Set<Pair<String, String>> undefinedLex = new LinkedHashSet<Pair<String, String>>();
private Set<String> undefinedScripts = new LinkedHashSet<String>();
private Set<String> undefinedTypes = new LinkedHashSet<String>();
private boolean analyze = false;
private boolean simulate = false;
private boolean makeSnapShots = false;
private int fileCounter = 1;
File output = null;
List<File> dataFiles = null;
String ontFileName = null;
StringBuffer defs = null;
Grammar grammar = null;
Simulator simulator = null;
ContextModel contextModel = null;
ECGAnalyzer analyzer = null;
LearnerPrefs preferences = null;
public GrammarWritingUtilities(LearnerPrefs prefs) {
try {
preferences = prefs;
makeSnapShots = preferences.getSetting(LP.OUTPUT_SNAPSHOTS) == null ? false : Boolean.valueOf(preferences
.getSetting(LP.OUTPUT_SNAPSHOTS));
output = preferences.getSetting(LP.OUTPUT_SNAPSHOTS_PATH) == null ? null : new File(
preferences.getSetting(LP.OUTPUT_SNAPSHOTS_PATH));
if (output != null && output.isFile() && !makeSnapShots) {
setPrintStream(new PrintStream(output));
}
File baseDirectory = preferences.getBaseDirectory();
List<String> dpaths = preferences.getList(LP.DATA_PATHS);
String dext = preferences.getSetting(LP.DATA_EXTENSIONS);
dataFiles = FileUtils.getFilesUnder(baseDirectory, dpaths, new ExtensionFileFilter(dext));
grammar = ECGGrammarUtilities.read(preferences);
grammar.update();
contextModel = grammar.getContextModel();
List<String> spaths = preferences.getList(LP.SCRIPT_PATHS);
String sext = preferences.getSetting(LP.SCRIPT_EXTENSIONS);
simulator = new Simulator(contextModel, FileUtils.getFilesUnder(baseDirectory, spaths,
new ExtensionFileFilter(sext)));
analyze = Boolean.valueOf(preferences.getSetting(LP.ANALYZE));
simulate = Boolean.valueOf(preferences.getSetting(LP.SIMULATE));
}
catch (IOException ioe) {
outputErrorMessage(ioe);
}
catch (TypeSystemException e) {
outputErrorMessage(e);
}
}
protected static void setPrintStream(PrintStream printStream) {
GrammarWritingUtilities.printStream = printStream;
}
protected void outputErrorMessage(Exception e) {
System.out.println(e.getMessage());
if (e.getCause() != null) {
System.err.println(e.getMessage());
System.err.println(e.getCause().getMessage());
}
if (!(e instanceof ScriptNotFoundException || e instanceof ItemNotDefinedException || e.getMessage().contains(
"No speech act annotation found"))) {
e.printStackTrace(System.err);
}
}
public Grammar getGrammar() {
return grammar;
}
protected void checkGoldStandardAnnotation(ChildesClause clause) {
GoldStandardAnnotation annotation = clause.getChildesAnnotation().getGoldStandardTier().getContent();
String vern = clause.getChildesAnnotation().getVernacularTier().getContent();
for (ExtendedFeatureBasedEntity tag : annotation.getArgumentStructureAnnotations()) {
if (tag.getSpanLeft() != null && tag.getSpanRight() != null) {
int left = tag.getSpanLeft();
int right = tag.getSpanRight();
printStream.print(tag.getJDOMElement().getName() + "\t");
printStream.print(vern.substring(left, right) + "\t");
if (tag.getAttributeValue("ref") != null) {
printStream.print(tag.getAttributeValue("ref"));
}
else {
printStream.print(tag.getCategory());
}
printStream.print("\t");
if (tag.getCategory() != null && tag.getCategory().toLowerCase().contains("state")) {
try {
printStream.print(tag.getBinding("property").iterator().next().getAttributeValue("value"));
}
catch (NullPointerException e) {
}
}
printStream.println("\t" + clause.getSource());
for (String role : tag.getRoles()) {
for (Binding binding : tag.getBinding(role)) {
if (binding.getSpanLeft() != null && binding.getSpanRight() != null) {
int bleft = binding.getSpanLeft();
int bright = binding.getSpanRight();
printStream.print("\t");
printStream.print(vern.substring(bleft, bright) + "\t");
if (binding.getAttributeValue("ref") != null) {
printStream.print(binding.getAttributeValue("ref"));
}
else if (binding.getAttributeValue("value") != null) {
printStream.print(binding.getAttributeValue("value"));
}
else {
printStream.print(binding.getField());
}
printStream.print("\t");
if (binding.getAttributeValue("subcat") != null) {
printStream.print(binding.getAttributeValue("subcat"));
}
printStream.println("\t" + clause.getSource());
}
}
}
}
// System.out.println(tag);
}
// System.out.println(annotation);
}
protected void checkLexicon(ChildesClause clause, Grammar grammar) {
List<Word> undefinedWords = new ArrayList<Word>();
List<Word> words = clause.getElements();
for (Word word : words) {
try {
// grammar.getLexicalConstruction("\"" + word.getOrthography() + "\"");
}
catch (GrammarException ge) {
undefinedWords.add(word);
int index = words.indexOf(word);
String chinese = clause.getChildesAnnotation().getVernacularTier().getWordsAt(index, index + 1);
boolean added = undefinedLex.add(new Pair<String, String>(word.getOrthography(), String.valueOf(chinese)));
if (added) {
System.out.println(word.getOrthography() + " : " + chinese);
}
}
}
}
protected void printUtterance(ChildesClause clause) {
List<Word> words = clause.getElements();
StringBuilder sb = new StringBuilder();
for (Word word : words) {
sb.append(word.getOrthography()).append(' ');
}
System.out.println(sb);
}
protected void crazyCounting(ChildesClause clause) {
Word targetWord = new Word("gei3");
List<Word> words = clause.getElements();
int index = words.indexOf(targetWord);
if (index != -1) {
String vern = clause.getChildesAnnotation().getVernacularTier().getContent();
GoldStandardAnnotation annotation = clause.getChildesAnnotation().getGoldStandardTier().getContent();
for (ExtendedFeatureBasedEntity tag : annotation.getAllAnnotations()) {
if (tag.getSpanLeft() != null && tag.getSpanLeft() == index && tag.getSpanRight() == index + 1) {
System.out.println(vern + "\t" + tag.getCategory());
break;
}
else if (tag.getType() != null && tag.getType().equals("benefaction")
|| tag.getType().equals("malefaction")) {
System.out.println(vern + "\t" + tag.getType());
break;
}
}
}
}
protected void analyzeUtterance(ChildesClause clause) {
System.out.println("Analyzing.... ");
printUtterance(clause);
PriorityQueue<?> pqa;
try {
if (analyzer.robust()) {
pqa = analyzer.getBestPartialParses(clause);
}
else {
pqa = analyzer.getBestParses(clause);
}
while (pqa.size() > 0) {
System.out.println("\n\nRETURNED ANALYSIS\n____________________________\n");
System.out.println("Cost: " + pqa.getPriority());
System.out.println(pqa.next());
}
}
catch (NoECGAnalysisFoundException neafe) {
System.out.println("\n\nEXCEPTIONALLY BAD ANALYSIS\n____________________________\n");
for (Analysis a : neafe.getAnalyses()) {
System.out.println(a);
}
}
catch (ParserException pe) {
System.err.println(pe.getLocalizedMessage());
pe.printStackTrace();
System.out.println(analyzer.getParserLog());
}
}
protected void processTranscript(File datafile) throws IOException {
ChildesTranscript transcript = new ChildesTranscript(datafile);
if (simulate) {
simulator.initializeParticipants(transcript.getParticipantIDs());
simulator.initializeSetting(transcript.getSettingEntitiesAndBindings(),
transcript.getSetupEntitiesAndBindings());
}
ChildesIterator transcriptIter = transcript.iterator();
while (transcriptIter.hasNext()) {
try {
ChildesItem item = transcriptIter.next();
if (item instanceof ChildesClause) {
ChildesClause clause = (ChildesClause) item;
if (clause.size() > 0) {
// System.out.println("clause id = " + clause.getID());
if (simulate) {
boolean success = simulator.registerUtterance(clause, new HashSet<String>());
}
checkLexicon(clause, grammar);
// checkGoldStandardAnnotation(clause);
// printUtterance(clause);
// crazyCounting(clause);
// printStatus(success, verbose);
if (analyze) {
analyzeUtterance(clause);
}
}
}
else if (item instanceof ChildesEvent && simulate) {
boolean success = simulator.simulateEvent((ChildesEvent) item);
if (!success)
System.out.println(item.getID() + " " + success);
// printStatus(success, verbose);
}
if (makeSnapShots) {
makeSnapShot();
}
}
catch (ScriptNotFoundException snfe) {
// outputErrorMessage(snfe);
undefinedScripts.add(snfe.getScriptName());
}
catch (ItemNotDefinedException infe) {
// outputErrorMessage(infe);
undefinedTypes.add(infe.getUnknownItem());
}
catch (SimulatorException se) {
outputErrorMessage(se);
}
}
if (!makeSnapShots && output != null) {
outputContextModelGraph();
}
}
protected void processTranscripts() {
try {
for (File dataFile : dataFiles) {
System.out.println("Processing... " + dataFile.getName() + " ..... ");
System.out.flush();
grammar.getContextModel().reset();
if (analyze) {
analyzer = new ECGAnalyzer(grammar);
}
processTranscript(dataFile);
}
}
catch (IOException ioe) {
outputErrorMessage(ioe);
}
catch (AnnotationException ae) {
outputErrorMessage(ae);
}
catch (SimulatorException se) {
outputErrorMessage(se);
}
catch (GrammarException ge) {
outputErrorMessage(ge);
}
finally {
outputToFile();
}
}
public void outputToFile() {
printStream.println("============================");
printStream.println("Undefined Lexical Items");
printStream.println("============================");
for (Pair<String, String> lex : undefinedLex) {
printStream.println(lex.getFirst() + ":" + lex.getSecond());
}
printStream.println("\n\n");
printStream.println("============================");
printStream.println("Undefined Types");
printStream.println("============================");
for (String type : undefinedTypes) {
printStream.println(type);
}
printStream.println("\n\n");
printStream.println("============================");
printStream.println("Undefined Scripts");
printStream.println("============================");
for (String script : undefinedScripts) {
printStream.println(script);
}
}
public void outputContextModelGraph() {
MiniOntology.setFormatter(new OntologyGraphPrinter());
printStream.println(contextModel.getMiniOntology());
}
public void makeSnapShot() throws IOException {
int zeros = 3 - String.valueOf(fileCounter).length();
String count = "";
for (int i = 0; i < zeros; i++) {
count += "0";
}
count += String.valueOf(fileCounter);
String filename = "contextModel" + count + ".dt";
File snapshot = new File(output, filename);
setPrintStream(new PrintStream(snapshot));
outputContextModelGraph();
String[] cmd = { "cmd", "/c", "dot", "-Nshape=polygon", "-Nsides=6", "-o",
output.getPath() + File.separator + "cm" + count + ".png", "-Tpng", snapshot.getPath() };
Runtime.getRuntime().exec(cmd);
fileCounter++;
}
public void printStatus(boolean success, boolean verbose) {
System.out.println(success);
if (verbose) {
System.out.println("*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*");
MiniOntologyFormatter old = MiniOntology.getFormatter();
MiniOntology.setFormatter(new SimpleOntologyPrinter());
System.out.println(contextModel.getMiniOntology());
MiniOntology.setFormatter(old);
System.out.println("~~~~~~~~~~~~~ cache ~~~~~~~~~~~~~~");
System.out.println(contextModel.getContextModelCache());
System.out.println("*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*");
}
}
public static void setLoggingLevel(Level level) {
Logger rootLogger = LogManager.getLogManager().getLogger("");
for (Handler existing : rootLogger.getHandlers()) {
rootLogger.removeHandler(existing);
}
rootLogger.setLevel(level);
rootLogger.addHandler(new LoggingHandler());
}
public static void main(String[] argv) throws IOException {
if (argv.length < 1) {
String errormsg = "usage: <learner preference file>";
System.err.println(errormsg);
System.exit(1);
}
LearnerPrefs prefs = new LearnerPrefs(argv[0]);
String globalLoggingLevel = prefs.getLoggingLevels().get(ComplingPackage.GLOBAL);
Level loggingLevel = globalLoggingLevel != null ? Level.parse(globalLoggingLevel) : Level.INFO;
setLoggingLevel(loggingLevel);
GrammarWritingUtilities util = new GrammarWritingUtilities(prefs);
Grammar.setFormatter(new SimpleGrammarPrinter());
util.processTranscripts();
}
}
| [
"[email protected]"
] | |
1502cd15ddaa6390d5b447788d44e011d2ee6608 | c08be51efd0f0ebc6061177dfec4b897c602c858 | /clinic/src/main/java/org/fhi360/lamis/modules/clinic/service/ClinicService.java | ee520e7259b86afe0a00cd07348cfaaff791e2ee | [] | no_license | lamisplus/fhi360-lamis3updates | de4ee811975e9f00e52f2c46096003179f362d67 | ee573cf2b9291f91b2cb1ef230b386ba26bc63e3 | refs/heads/master | 2022-12-02T20:37:37.480801 | 2020-08-19T08:37:14 | 2020-08-19T08:37:14 | 288,662,576 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,545 | java | package org.fhi360.lamis.modules.clinic.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fhi360.lamis.modules.clinic.web.rest.vm.ClinicVM;
import org.lamisplus.modules.lamis.legacy.domain.entities.*;
import org.lamisplus.modules.lamis.legacy.domain.entities.enumerations.ClientStatus;
import org.lamisplus.modules.lamis.legacy.domain.repositories.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class ClinicService {
private final ClinicRepository clinicRepository;
private final PatientRepository patientRepository;
private final StatusHistoryRepository statusHistoryRepository;
private final ClinicOpportunisticInfectionRepository clinicOpportunisticInfectionRepository;
private final ClinicAdhereRepository clinicAdhereRepository;
private final AdhereRepository adhereRepository;
private final OpportunisticInfectionRepository opportunisticInfectionRepository;
private final DevolveRepository devolveRepository;
private final JdbcTemplate jdbcTemplate;
public Clinic saveClinic(ClinicVM vm) {
Clinic clinic = vm.getClinic();
if (clinic.getCommence() != null && clinic.getCommence()) {
patientRepository.findById(clinic.getPatient().getId()).ifPresent(patient -> {
patient.setDateStarted(clinic.getDateVisit());
patientRepository.save(patient);
StatusHistory history = new StatusHistory();
history.setFacility(patient.getFacility());
history.setPatient(patient);
history.setStatus(ClientStatus.ART_START);
history.setDateStatus(clinic.getDateVisit());
});
}
List<OpportunisticInfection> infections;
List<Adhere> adheres;
if (!clinic.isNew()) {
infections = clinicOpportunisticInfectionRepository.findByClinic(clinic).stream()
.map(ClinicOpportunisticInfection::getOpportunisticInfection)
.filter(i -> vm.getOiList().contains(i))
.collect(Collectors.toList());
clinic.getOpportunisticInfections().clear();
clinic.getOpportunisticInfections().addAll(infections);
adheres = clinicAdhereRepository.findByClinic(clinic).stream()
.map(ClinicAdhere::getAdhere)
.filter(ca -> vm.getAdhereList().contains(ca))
.collect(Collectors.toList());
clinic.getAdheres().clear();
clinic.getAdheres().addAll(adheres);
}
if (vm.getOiList() != null) {
vm.getOiList().forEach(oi -> {
if (oi != null && oi.getId() != null) {
opportunisticInfectionRepository.findById(oi.getId())
.ifPresent(o -> clinic.getOpportunisticInfections().add(o));
}
});
}
if (vm.getAdhereList() != null) {
vm.getAdhereList().forEach(adhere -> {
if (adhere != null && adhere.getId() != null) {
adhereRepository.findById(adhere.getId())
.ifPresent(a -> clinic.getAdheres().add(a));
}
});
}
if (vm.getAdrList() != null) {
List<ClinicAdverseDrugReaction> cadr = vm.getAdrList().stream()
.map(ca -> {
ca.setClinic(clinic);
return ca;
})
.collect(Collectors.toList());
clinic.getClinicAdverseDrugReactions().addAll(cadr);
}
return clinicRepository.save(clinic);
}
public void deleteClinic(String clinicId) {
clinicRepository.findByUuid(clinicId).ifPresent(clinic -> deleteClinic(clinic.getId()));
}
public void deleteClinic(Long clinicId) {
clinicRepository.findById(clinicId).ifPresent(clinic -> {
Patient patient = clinic.getPatient();
devolveRepository.findByPatient(patient)
.forEach(devolve -> {
if (devolve.getRelatedClinic() != null && Objects.equals(clinicId, devolve.getRelatedClinic().getId())) {
devolve.setRelatedClinic(null);
devolveRepository.save(devolve);
}
});
if (clinic.getCommence() != null && clinic.getCommence()
&& patient.getDateStarted().equals(clinic.getDateVisit())) {
patient.setDateStarted(null);
patientRepository.save(patient);
statusHistoryRepository.findByPatient(patient).stream()
.filter(s -> s.getStatus().equals(ClientStatus.ART_START))
.forEach(statusHistoryRepository::delete);
}
clinicRepository.delete(clinic);
});
}
public Boolean enrolledOnOTZ(Long patientId) {
try {
Boolean enrolled = jdbcTemplate.queryForObject("select (extra->'otz'->>'enrolledOnOTZ')::boolean from clinic where " +
"patient_id = ? and commence = true", Boolean.class, patientId);
return enrolled != null ? enrolled : false;
} catch (Exception e) {
return false;
}
}
}
| [
"[email protected]"
] | |
9ac55d7e21aceaf9575b514bee48862be1d5a197 | f25287f4e5dc9e8e965e90bb6105ea64f55dfb87 | /app/src/main/java/com/hanks/mvc/base/BaseConstant.java | 827c50ec0b0b2c553113ec51f837251c5638387d | [] | no_license | hanks7/Mvc | c149a76ede81a4b76b1ffb08424619457a281a6e | 24ff2860af1f015d47006d97ffdc2bb5bf4b2fe5 | refs/heads/master | 2020-05-07T16:50:55.862444 | 2019-04-11T07:56:09 | 2019-04-11T07:56:09 | 180,702,208 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 255 | java | package com.hanks.mvc.base;
/**
* @author 侯建军 [email protected]
* @class com.hanks.mvc.base.BaseConstant
* @time 2019/4/11 14:19
* @description 请填写描述
*/
public class BaseConstant {
public final static boolean IS_RELEASE = false;
}
| [
"[email protected]"
] | |
4f9c7d4bb9177929b36008da6a5891e529e4acdf | 2749a4353814e8a8e6e88cd019a327e66c7761b1 | /src/main/java/com/rsw/views/ProgressWebView.java | 24a07a429fbe482d67b619dfb5bd90d0172fc3c4 | [] | no_license | renshiwu/BetterHealth | f3ac6ff024789f909e0f8b93610fc8db02420563 | 61c6d501c8bccfa10d849a8254e2fcf8292626af | refs/heads/main | 2022-12-31T13:12:50.448472 | 2020-10-23T01:34:27 | 2020-10-23T01:34:27 | 306,498,670 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,306 | java | package com.rsw.views;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.widget.ProgressBar;
@SuppressWarnings("deprecation")
public class ProgressWebView extends WebView {
private ProgressBar progressbar;
public ProgressWebView(Context context, AttributeSet attrs) {
super(context, attrs);
progressbar = new ProgressBar(context, null,
android.R.attr.progressBarStyleHorizontal);
progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
3, 0, 0));
addView(progressbar);
setWebChromeClient(new myWebChromeClient());
}
public class myWebChromeClient extends android.webkit.WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressbar.setVisibility(GONE);
} else {
if (progressbar.getVisibility() == GONE)
progressbar.setVisibility(VISIBLE);
progressbar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
}
// @Override
// protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
// lp.x = l;
// lp.y = t;
// progressbar.setLayoutParams(lp);
// super.onScrollChanged(l, t, oldl, oldt);
// }
} | [
"[email protected]"
] | |
d2b4c9b6a974c05123728ce1df91df46e981b8bf | b65a1caab3ed0ed42e17d5592f3e9ba2ac446c1e | /Session8-SCF/src/Animal.java | a22a00c932dcacf9864f4a7f774d44d81b36c007 | [] | no_license | meta-ashish-bansal/GET2020 | c68c222a1dd08221cd0eb69ffa2d4240cde5c66d | 76530b7a8256f44f8f2de1ebbbe3f48edefa7f19 | refs/heads/master | 2023-01-24T19:55:02.969999 | 2020-04-15T16:27:38 | 2020-04-15T16:27:38 | 232,491,015 | 0 | 0 | null | 2020-01-08T07:24:56 | 2020-01-08T06:07:39 | null | UTF-8 | Java | false | false | 483 | java |
abstract public class Animal {
int ageOfAnimal;
static int counter =0;
final int animalId;
String animalName;
String categoryOfAnimal;
float weightOfAnimal;
String soundOfAnimal;
public Animal(int age,String name, String category, float weight,String sound) {
this.ageOfAnimal = age;
this.animalName = name;
this.categoryOfAnimal = category;
this.weightOfAnimal = weight;
animalId = counter++;
soundOfAnimal = sound;
}
abstract public String getSound();
}
| [
"[email protected]"
] | |
101611cac879e2231f115747c8959a9299d2e06c | d4caf6382751541d8d14a639f0cabc2fb9a21f13 | /src/main/java/org/alArbiyaHotelManagement/model/NotificationDeliveryBoy.java | 5f6993190a5b6738f2f1046436d20dd0974e1c1a | [] | no_license | iyashiyas/alArbiyaHotelManagement | 24661326b90bb5b6578dc140703d5fa3dc04dc3c | d9fa509d284933329644db27f2c9637a52e5cab1 | refs/heads/master | 2021-01-12T17:42:41.140524 | 2017-05-24T07:27:09 | 2017-05-24T07:27:09 | 71,627,373 | 0 | 1 | null | 2016-10-23T12:17:20 | 2016-10-22T08:43:01 | Java | UTF-8 | Java | false | false | 1,682 | java | package org.alArbiyaHotelManagement.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "NOTIFICATIONDELIVERYBOY")
public class NotificationDeliveryBoy {
@Id
@GeneratedValue
@Column(name="NOTIFICATION_ID")
private long id;
@Column(name="ROOM_ID")
private long roomId;
@Column(name="ORDER_ID")
private long orderId;
@Column(name="READ_STATUS")
private String readStatus;
@Column(name="ORDER_STATUS")
private String orderStatus;
@Column(name="DELIVERY_BOY_ID")
private long deliveryBoyId;
@Column(name="DELIVERY_BOY_NAME")
private String deliveryBoyName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getRoomId() {
return roomId;
}
public void setRoomId(long roomId) {
this.roomId = roomId;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public String getReadStatus() {
return readStatus;
}
public void setReadStatus(String readStatus) {
this.readStatus = readStatus;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public long getDeliveryBoyId() {
return deliveryBoyId;
}
public void setDeliveryBoyId(long deliveryBoyId) {
this.deliveryBoyId = deliveryBoyId;
}
public String getDeliveryBoyName() {
return deliveryBoyName;
}
public void setDeliveryBoyName(String deliveryBoyName) {
this.deliveryBoyName = deliveryBoyName;
}
}
| [
"[email protected]"
] | |
753747a0f235dbc9b600ccd8a2e4626f852b882e | a1e58fe75651b47e44aedd768ce4c4c0e618c7ac | /webPersona/src/main/java/pe/reniec/webpersona/dao/dao.java | 56a373b5b21f72c438f6ce9602cb635f113647e3 | [] | no_license | PierCajo/NegociosJavaNet | 65c5e91a7ca15ed91acc3635920bc8cc9afc1044 | 3319861da99f30d41f4a17a84f3c3908dd3d9aac | refs/heads/master | 2021-01-15T21:19:13.581332 | 2012-10-09T03:33:40 | 2012-10-09T03:33:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,347 | java | package pe.reniec.webpersona.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import pe.reniec.webpersona.excepcion.DAOExcepcion;
import pe.reniec.webpersona.modelo.Persona;
import pe.reniec.webpersona.util.ConexionBD;
public class dao extends BaseDao {
public int login(String dni) throws DAOExcepcion {
System.out.println("login" + dni);
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int valor = 0;
try {
String query = "select estado from persona where dni=?";
System.out.println(query);
con = ConexionBD.obtenerConexion();
System.out.println("ya obtuvo la conexion");
stmt = con.prepareStatement(query);
System.out.println("despues de preparar");
stmt.setString(1, dni);
rs = stmt.executeQuery();
if (rs.next()) {
valor = rs.getInt("estado");
}
} catch (SQLException e) {
System.err.println(e.getMessage());
throw new DAOExcepcion(e.getMessage());
} finally {
this.cerrarResultSet(rs);
this.cerrarStatement(stmt);
this.cerrarConexion(con);
}
if (valor == 0) {
return 0;
} else {
return valor;
}
}
public Collection<Persona> ValidarInfo(String dni) throws DAOExcepcion {
Collection<Persona> lstPersona = new ArrayList<Persona>();
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Persona persona = new Persona();
try {
String query = "select Dni,Nombres,Apellidos,direccion,telefono,Estado from persona where Dni=?";
System.out.println(query);
con = ConexionBD.obtenerConexion();
System.out.println("ya obtuvo la conexion");
stmt = con.prepareStatement(query);
stmt.setString(1, dni);
rs = stmt.executeQuery();
//if (rs.next()) {
// valor = rs.getInt("estado");
//}
// String query = "select Dni,Nombres,Apellidos,direccion,telefono,Estado from persona where dni=?";
// System.out.println(query);
// con = ConexionBD.obtenerConexion();
// System.out.println("ya obtuvo la conexion");
// stmt = con.prepareStatement(query);
// System.out.println("antes de pasar el parametrpo");
// stmt.setString(1, dni);
// rs = stmt.executeQuery();
if (rs.next()) {
//while (rs.next()) {
persona.setDni(rs.getString("dni"));
persona.setNombres(rs.getString("nombres"));
persona.setApellidos(rs.getString("apellidos"));
persona.setDireccion(rs.getString("direccion"));
persona.setTelefono(rs.getString("telefono"));
persona.setEstado(rs.getInt("estado"));
System.out.println(persona.getApellidos());
lstPersona.add(persona);
//}
} else {
persona.setDni("000000");
persona.setNombres("No Autorizada");
persona.setApellidos("No Autorizada");
persona.setDireccion("No Autorizada");
persona.setTelefono("No Autorizada");
persona.setEstado(0);
lstPersona.add(persona);
}
} catch (SQLException e) {
System.err.println("msg"+e.getMessage());
throw new DAOExcepcion(e.getMessage());
} finally {
this.cerrarResultSet(rs);
this.cerrarStatement(stmt);
this.cerrarConexion(con);
}
System.out.println("listado de personas");
//System.out.println(lstPersona.size());
return lstPersona;
//return persona.getApellidos();
}
}
| [
"[email protected]"
] | |
7f991f28eab8e16eba41cabe5e2f197600b23108 | ad80d2061bfbb06cbee5aef707d6c60de25cbe98 | /src/ArrayInJava/CountCharacterInString.java | 692624dd4d01fbe3657f7566877f54c6bfddd473 | [] | no_license | Vutienbka/JavaWeb-Abuntu | 5ae7d1deb1ffce65ee8695b005014465d03c91a0 | ba3bf99ac0663a07a45cab7982d81eeb8a6cabc5 | refs/heads/master | 2020-12-07T16:32:59.113203 | 2020-01-18T08:06:51 | 2020-01-18T08:06:51 | 232,752,053 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package ArrayInJava;
import java.util.Scanner;
public class CountCharacterInString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Nhap chuoi:");
String string = scanner.nextLine();
System.out.println("Nhap ky tu can tim:");
// string.charAt(i): lay ky tu tai vij tri thu i trong chuoi
char character = scanner.nextLine().charAt(0);
char[] charArray = string.toCharArray(); //doi chuoi thanh mang ky tu
int count = 0;
for(int i=0; i< charArray.length; i++)
if(charArray[i] == character)
count ++;
System.out.println("So ky tu " + character + " trong chuoi da nhap la: " + count);
}
}
| [
"[email protected]"
] | |
9fa1f4498fcfc4d232c92eb95a7fa5761677ee83 | 8e689d49971806aee78ae205d8c3be69dd688c06 | /portal.ejb/src/main/java/org/vamdc/portal/session/queryLog/PersistentQueryLog.java | 7840f9a3a8820f3d973358f839074e9402662eee | [] | no_license | VAMDC/VAMDC-Portal | 25666b9e39f36e09479d8118dcd0b91a04ac3065 | 01698a22649b6b3026686a39fd69cd71c8fb4fc8 | refs/heads/master | 2022-06-03T22:44:31.463316 | 2022-05-18T15:52:28 | 2022-05-18T15:52:28 | 27,481,771 | 1 | 0 | null | 2022-05-18T15:52:29 | 2014-12-03T10:29:29 | Java | UTF-8 | Java | false | false | 2,087 | java | package org.vamdc.portal.session.queryLog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.persistence.EntityManager;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.vamdc.portal.entity.query.HttpHeadResponse;
import org.vamdc.portal.entity.query.Query;
import org.vamdc.portal.entity.security.User;
import org.vamdc.portal.session.security.UserInfo;
@Name("persistentQueryLog")
public class PersistentQueryLog {
@Logger private Log log;
@In private UserInfo auth;
@In private EntityManager entityManager;
@SuppressWarnings("unchecked")
public List<Query> getStoredQueries(){
List<Query> queries = null;
User user = auth.getUser();
if (user!=null){
queries=entityManager.createQuery("from Query where user.username =:username").setParameter("username", user.getUsername()).getResultList();
}
if (queries!=null && queries.size()>0){
return Collections.unmodifiableList(queries);
}
return new ArrayList<Query>();
}
public void save(Query query) {
deleteStaleResponses(query.getQueryID());
entityManager.persist(query);
for (HttpHeadResponse response:query.getResponses()){
response.setQuery(query);
entityManager.persist(response);
}
}
private void deleteStaleResponses(Integer queryID){
User user = auth.getUser();
if (user!=null&& queryID!=null){
entityManager.createQuery("delete from HttpHeadResponse where queryID = :queryID")
.setParameter("queryID", queryID).executeUpdate();
}
}
public void delete(Integer queryID) {
User user = auth.getUser();
if (user!=null){
Query toRemove = (Query)entityManager.createQuery("from Query where user.username = :username and queryID = :queryID")
.setParameter("username",user.getUsername())
.setParameter("queryID", queryID).getSingleResult();
for (HttpHeadResponse response:toRemove.getResponses())
entityManager.remove(response);
entityManager.remove(toRemove);
}
}
}
| [
"[email protected]"
] | |
867fd82b56c8e51fbb189474b57c5bf0035bfc31 | c5ea8613c7da6d35107851f5d83be477d3851234 | /src/main/java/io/hanmomhanda/wubwur/Application.java | 8d7be8c3bc05f89b451c1d790631e592caf3b3fc | [] | no_license | hanmomhanda/wubwur | 277950ca05c805fb96ebffe826f975e420df0f96 | 009d15075470bfad09d14c460374bd521a2391ed | refs/heads/master | 2016-09-10T15:39:37.699708 | 2015-08-10T23:43:28 | 2015-08-10T23:43:28 | 40,087,149 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 662 | java | package io.hanmomhanda.wubwur;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
//
// System.out.println("만세~");
//
// String[] beanNames = ctx.getBeanDefinitionNames();
// Arrays.sort(beanNames);
// for(String beanName : beanNames) {
// System.out.println(beanName);
// }
}
}
| [
"[email protected]"
] | |
34a2549450aefd06fa78e85793dd950d9bb569d5 | cae0c60a38d3ed25f59039c0d9fdcb123d53e21c | /src/com/example/alex/common/ShowResultUtil.java | 3fc60dc302fbaba6661d868319cf220ff2502357 | [] | no_license | liangxiaofei1100/AndroidStudy | a340ff3f11c933635cd0adea3a83118a29778090 | 1b5ef2222be57935c5126c3ae4bc62b9375f8857 | refs/heads/master | 2016-09-05T14:27:07.287326 | 2015-10-19T01:58:05 | 2015-10-19T01:58:05 | 9,311,010 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 691 | java | package com.example.alex.common;
import android.widget.TextView;
public class ShowResultUtil {
private TextView mTextView;
public ShowResultUtil() {
}
public ShowResultUtil(TextView textView) {
mTextView = textView;
}
public void showInTextView(String msg) {
showInTextView(mTextView, msg);
}
public static void showInTextView(TextView textView, String msg) {
if (textView != null) {
if (!msg.endsWith("\n")) {
textView.append(TimeUtil.getCurrentTime() + " " + msg + '\n');
} else {
textView.append(TimeUtil.getCurrentTime() + " " + msg);
}
}
}
}
| [
"[email protected]"
] | |
63e06e0bb8c078c96404b7da328ea2841d8ac4c3 | 507ac956031d03763e57b17b7f3e42b877a940b2 | /CodeTP3-20191120/BreadthFirstSearch.java | b0bc81903285504bd7c666756845a5c322208ab9 | [] | no_license | Krisy98/tp3Algo_genAleaArbresCouvrants | 6a190151c6ade2ec5f413d35dc3b677f3c6cacce | bcd89fad90b4ce7bce3586131365de5ecf1c3967 | refs/heads/master | 2020-09-13T19:04:17.600619 | 2019-12-10T22:46:31 | 2019-12-10T22:46:31 | 222,876,819 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,103 | java | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BreadthFirstSearch {
public static ArrayList<Arc> generateTree(Graph graph, int source) {
ArrayList<Arc> tree = new ArrayList<>();
List<Integer> waitingList = new LinkedList();
List<Boolean> visited = new LinkedList<>();
for (int index=0; index < graph.order; index++) visited.add(false);
waitingList.add(source);
visited.add(source, true);
while (waitingList.size() != 0){
source = waitingList.get(0);
waitingList.remove(0);
for (int index=0; index < graph.outAdjacency.get(source).size(); index++){
int destination = graph.outAdjacency.get(source).get(index).support.dest;
if (!visited.get(destination).booleanValue()){
tree.add(graph.outAdjacency.get(source).get(index));
visited.set(destination, true);
waitingList.add(destination);
}
}
}
return tree;
}
}
| [
"[email protected]"
] | |
493448cebff51c78fc06e0e27cdda99b5b287fc7 | 5596290192e725ab0cc7a3e2713d009ed4d4611c | /sp02-itemservice/src/main/java/com/tedu/sp02/item/controller/ItemController.java | 1f55e8751814b0e256f07d449621d8339bbf8ef7 | [] | no_license | huangZH90/test1 | 41163d52adf238335afdd9de4cf1c9228ab3f4f0 | 632331bf3e1bddd177c1b5d8ed418df86142b1c4 | refs/heads/master | 2020-07-11T20:19:49.128512 | 2019-08-28T02:08:33 | 2019-08-28T02:08:33 | 204,636,449 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,503 | java | package com.tedu.sp02.item.controller;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.tedu.sp01.pojo.Item;
import com.tedu.sp01.service.ItemService;
import com.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class ItemController {
@Autowired
private ItemService itemService;
@Value("${server.port}")
private int port;
@GetMapping("/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws Exception{
log.info("server.port="+port+", orderId="+orderId);
///--设置随机延迟
//long t = new Random().nextInt(5000);
//if(Math.random()<0.6) {
// log.info("item-service-"+port+" - 暂停 "+t);
// Thread.sleep(t);
//}
///~~
List<Item> items = itemService.getItems(orderId);
return JsonResult.ok(items).msg("port="+port);
}
@PostMapping("/decreaseNumber")
public JsonResult decreaseNumber(@RequestBody List<Item> items) {
itemService.decreaseNumbers(items);
return JsonResult.ok();
}
}
| [
"[email protected]"
] | |
f6277e74260878f825f4b6a9be6371fb8d526347 | 2eac4f51a2e4363349e852ce3af8ca234c1a13f7 | /fx/trunk/fx-datamanager/src/main/java/com/jeff/fx/datamanager/TimeRange.java | 476bb3bd9df5a590fb994a170d20d0bd4760dbfd | [] | no_license | johnffracassi/jcfx | 4e19ac0fdba174db0fe3eb2fc8848652a5c99c11 | b0a2349fdd1de0bf60c7ccf9a17af4e43e0a1727 | refs/heads/master | 2016-09-05T15:13:49.981403 | 2011-07-21T05:54:28 | 2011-07-21T05:54:28 | 41,260,482 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 665 | java | package com.jeff.fx.datamanager;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.joda.time.LocalTime;
public class TimeRange extends JPanel {
private static final long serialVersionUID = 999290000L;
private TimePicker start;
private TimePicker end;
public TimeRange() {
start = new TimePicker();
end = new TimePicker();
init();
}
public LocalTime getStart() {
return start.getTime();
}
public LocalTime getEnd() {
return end.getTime();
}
private void init() {
setLayout(new FlowLayout(3));
add(new JLabel("Start Time"));
add(start);
add(new JLabel("End Time"));
add(end);
}
}
| [
"jeffcann@360c4b46-674e-11de-9b35-9190732fe600"
] | jeffcann@360c4b46-674e-11de-9b35-9190732fe600 |
e7efad81032445f208ee3f2c1a1635f77bef69c1 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/org/apache/hadoop/hdfs/TestDFSShell.java | 9f0cff116fc63f26f965a29d58037701b220fdbd | [] | no_license | STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919811 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | null | UTF-8 | Java | false | false | 129,329 | java | /**
* 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 org.apache.hadoop.hdfs;
import DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY;
import DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY;
import DFSConfigKeys.DFS_PERMISSIONS_SUPERUSERGROUP_KEY;
import FSDirectory.DOT_INODES_STRING;
import FSDirectory.DOT_RESERVED_STRING;
import FSInputChecker.LOG;
import HdfsClientConfigKeys.DFS_NAMENODE_RPC_PORT_DEFAULT;
import HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.Permission;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.DistributedFileSystem;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclEntryScope;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.server.datanode.FsDatasetTestUtils;
import org.apache.hadoop.hdfs.server.namenode.AclTestHelpers;
import org.apache.hadoop.hdfs.tools.DFSAdmin;
import org.apache.hadoop.net.ServerSocketUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.test.PathUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Time;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Level;
import org.hamcrest.CoreMatchers;
import org.hamcrest.core.StringContains;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.Thread.State.TIMED_WAITING;
/**
* This class tests commands from DFSShell.
*/
public class TestDFSShell {
private static final Logger LOG = LoggerFactory.getLogger(TestDFSShell.class);
private static final AtomicInteger counter = new AtomicInteger();
private final int SUCCESS = 0;
private final int ERROR = 1;
static final String TEST_ROOT_DIR = PathUtils.getTestDirName(TestDFSShell.class);
private static final String RAW_A1 = "raw.a1";
private static final String TRUSTED_A1 = "trusted.a1";
private static final String USER_A1 = "user.a1";
private static final byte[] RAW_A1_VALUE = new byte[]{ 50, 50, 50 };
private static final byte[] TRUSTED_A1_VALUE = new byte[]{ 49, 49, 49 };
private static final byte[] USER_A1_VALUE = new byte[]{ 49, 50, 51 };
private static final int BLOCK_SIZE = 1024;
private static MiniDFSCluster miniCluster;
private static DistributedFileSystem dfs;
@Rule
public Timeout globalTimeout = new Timeout((30 * 1000));// 30s
@Test(timeout = 30000)
public void testZeroSizeFile() throws IOException {
// create a zero size file
final File f1 = new File(TestDFSShell.TEST_ROOT_DIR, "f1");
Assert.assertTrue((!(f1.exists())));
Assert.assertTrue(f1.createNewFile());
Assert.assertTrue(f1.exists());
Assert.assertTrue(f1.isFile());
Assert.assertEquals(0L, f1.length());
// copy to remote
final Path root = TestDFSShell.mkdir(TestDFSShell.dfs, new Path("/testZeroSizeFile/zeroSizeFile"));
final Path remotef = new Path(root, "dst");
TestDFSShell.show(((("copy local " + f1) + " to remote ") + remotef));
TestDFSShell.dfs.copyFromLocalFile(false, false, new Path(f1.getPath()), remotef);
// getBlockSize() should not throw exception
TestDFSShell.show(("Block size = " + (TestDFSShell.dfs.getFileStatus(remotef).getBlockSize())));
// copy back
final File f2 = new File(TestDFSShell.TEST_ROOT_DIR, "f2");
Assert.assertTrue((!(f2.exists())));
TestDFSShell.dfs.copyToLocalFile(remotef, new Path(f2.getPath()));
Assert.assertTrue(f2.exists());
Assert.assertTrue(f2.isFile());
Assert.assertEquals(0L, f2.length());
f1.delete();
f2.delete();
}
@Test(timeout = 30000)
public void testRecursiveRm() throws IOException {
final Path parent = new Path("/testRecursiveRm", "parent");
final Path child = new Path(parent, "child");
TestDFSShell.dfs.mkdirs(child);
try {
TestDFSShell.dfs.delete(parent, false);
Assert.fail("Should have failed because dir is not empty");
} catch (IOException e) {
// should have thrown an exception
}
TestDFSShell.dfs.delete(parent, true);
Assert.assertFalse(TestDFSShell.dfs.exists(parent));
}
@Test(timeout = 30000)
public void testDu() throws IOException {
int replication = 2;
PrintStream psBackup = System.out;
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream psOut = new PrintStream(out);
System.setOut(psOut);
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
try {
final Path myPath = new Path("/testDu", "dir");
Assert.assertTrue(TestDFSShell.dfs.mkdirs(myPath));
Assert.assertTrue(TestDFSShell.dfs.exists(myPath));
final Path myFile = new Path(myPath, "file");
TestDFSShell.writeFile(TestDFSShell.dfs, myFile);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile));
final Path myFile2 = new Path(myPath, "file2");
TestDFSShell.writeFile(TestDFSShell.dfs, myFile2);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile2));
Long myFileLength = TestDFSShell.dfs.getFileStatus(myFile).getLen();
Long myFileDiskUsed = myFileLength * replication;
Long myFile2Length = TestDFSShell.dfs.getFileStatus(myFile2).getLen();
Long myFile2DiskUsed = myFile2Length * replication;
String[] args = new String[2];
args[0] = "-du";
args[1] = myPath.toString();
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertTrue((val == 0));
String returnString = out.toString();
out.reset();
// Check if size matches as expected
Assert.assertThat(returnString, StringContains.containsString(myFileLength.toString()));
Assert.assertThat(returnString, StringContains.containsString(myFileDiskUsed.toString()));
Assert.assertThat(returnString, StringContains.containsString(myFile2Length.toString()));
Assert.assertThat(returnString, StringContains.containsString(myFile2DiskUsed.toString()));
// Check that -du -s reports the state of the snapshot
String snapshotName = "ss1";
Path snapshotPath = new Path(myPath, (".snapshot/" + snapshotName));
TestDFSShell.dfs.allowSnapshot(myPath);
Assert.assertThat(TestDFSShell.dfs.createSnapshot(myPath, snapshotName), CoreMatchers.is(snapshotPath));
Assert.assertThat(TestDFSShell.dfs.delete(myFile, false), CoreMatchers.is(true));
Assert.assertThat(TestDFSShell.dfs.exists(myFile), CoreMatchers.is(false));
args = new String[3];
args[0] = "-du";
args[1] = "-s";
args[2] = snapshotPath.toString();
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertThat(val, CoreMatchers.is(0));
returnString = out.toString();
out.reset();
Long combinedLength = myFileLength + myFile2Length;
Long combinedDiskUsed = myFileDiskUsed + myFile2DiskUsed;
Assert.assertThat(returnString, StringContains.containsString(combinedLength.toString()));
Assert.assertThat(returnString, StringContains.containsString(combinedDiskUsed.toString()));
// Check if output is rendered properly with multiple input paths
final Path myFile3 = new Path(myPath, "file3");
TestDFSShell.writeByte(TestDFSShell.dfs, myFile3);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile3));
args = new String[3];
args[0] = "-du";
args[1] = myFile3.toString();
args[2] = myFile2.toString();
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals("Return code should be 0.", 0, val);
returnString = out.toString();
out.reset();
Assert.assertTrue(returnString.contains(("1 2 " + (myFile3.toString()))));
Assert.assertTrue(returnString.contains(("25 50 " + (myFile2.toString()))));
} finally {
System.setOut(psBackup);
}
}
@Test(timeout = 180000)
public void testDuSnapshots() throws IOException {
final int replication = 2;
final PrintStream psBackup = System.out;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final PrintStream psOut = new PrintStream(out);
final FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
try {
System.setOut(psOut);
final Path parent = new Path("/testDuSnapshots");
final Path dir = new Path(parent, "dir");
TestDFSShell.mkdir(TestDFSShell.dfs, dir);
final Path file = new Path(dir, "file");
TestDFSShell.writeFile(TestDFSShell.dfs, file);
final Path file2 = new Path(dir, "file2");
TestDFSShell.writeFile(TestDFSShell.dfs, file2);
final Long fileLength = TestDFSShell.dfs.getFileStatus(file).getLen();
final Long fileDiskUsed = fileLength * replication;
final Long file2Length = TestDFSShell.dfs.getFileStatus(file2).getLen();
final Long file2DiskUsed = file2Length * replication;
/* Construct dir as follows:
/test/dir/file <- this will later be deleted after snapshot taken.
/test/dir/newfile <- this will be created after snapshot taken.
/test/dir/file2
Snapshot enabled on /test
*/
// test -du on /test/dir
int ret = -1;
try {
ret = shell.run(new String[]{ "-du", dir.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, ret);
String returnString = out.toString();
TestDFSShell.LOG.info(("-du return is:\n" + returnString));
// Check if size matches as expected
Assert.assertTrue(returnString.contains(fileLength.toString()));
Assert.assertTrue(returnString.contains(fileDiskUsed.toString()));
Assert.assertTrue(returnString.contains(file2Length.toString()));
Assert.assertTrue(returnString.contains(file2DiskUsed.toString()));
out.reset();
// take a snapshot, then remove file and add newFile
final String snapshotName = "ss1";
final Path snapshotPath = new Path(parent, (".snapshot/" + snapshotName));
TestDFSShell.dfs.allowSnapshot(parent);
Assert.assertThat(TestDFSShell.dfs.createSnapshot(parent, snapshotName), CoreMatchers.is(snapshotPath));
TestDFSShell.rmr(TestDFSShell.dfs, file);
final Path newFile = new Path(dir, "newfile");
TestDFSShell.writeFile(TestDFSShell.dfs, newFile);
final Long newFileLength = TestDFSShell.dfs.getFileStatus(newFile).getLen();
final Long newFileDiskUsed = newFileLength * replication;
// test -du -s on /test
ret = -1;
try {
ret = shell.run(new String[]{ "-du", "-s", parent.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, ret);
returnString = out.toString();
TestDFSShell.LOG.info(("-du -s return is:\n" + returnString));
Long combinedLength = (fileLength + file2Length) + newFileLength;
Long combinedDiskUsed = (fileDiskUsed + file2DiskUsed) + newFileDiskUsed;
Assert.assertTrue(returnString.contains(combinedLength.toString()));
Assert.assertTrue(returnString.contains(combinedDiskUsed.toString()));
out.reset();
// test -du on /test
ret = -1;
try {
ret = shell.run(new String[]{ "-du", parent.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, ret);
returnString = out.toString();
TestDFSShell.LOG.info(("-du return is:\n" + returnString));
Assert.assertTrue(returnString.contains(combinedLength.toString()));
Assert.assertTrue(returnString.contains(combinedDiskUsed.toString()));
out.reset();
// test -du -s -x on /test
ret = -1;
try {
ret = shell.run(new String[]{ "-du", "-s", "-x", parent.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, ret);
returnString = out.toString();
TestDFSShell.LOG.info(("-du -s -x return is:\n" + returnString));
Long exludeSnapshotLength = file2Length + newFileLength;
Long excludeSnapshotDiskUsed = file2DiskUsed + newFileDiskUsed;
Assert.assertTrue(returnString.contains(exludeSnapshotLength.toString()));
Assert.assertTrue(returnString.contains(excludeSnapshotDiskUsed.toString()));
out.reset();
// test -du -x on /test
ret = -1;
try {
ret = shell.run(new String[]{ "-du", "-x", parent.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, ret);
returnString = out.toString();
TestDFSShell.LOG.info(("-du -x return is:\n" + returnString));
Assert.assertTrue(returnString.contains(exludeSnapshotLength.toString()));
Assert.assertTrue(returnString.contains(excludeSnapshotDiskUsed.toString()));
out.reset();
} finally {
System.setOut(psBackup);
}
}
@Test(timeout = 180000)
public void testCountSnapshots() throws IOException {
final PrintStream psBackup = System.out;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final PrintStream psOut = new PrintStream(out);
System.setOut(psOut);
final FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
try {
final Path parent = new Path("/testCountSnapshots");
final Path dir = new Path(parent, "dir");
TestDFSShell.mkdir(TestDFSShell.dfs, dir);
final Path file = new Path(dir, "file");
TestDFSShell.writeFile(TestDFSShell.dfs, file);
final Path file2 = new Path(dir, "file2");
TestDFSShell.writeFile(TestDFSShell.dfs, file2);
final long fileLength = TestDFSShell.dfs.getFileStatus(file).getLen();
final long file2Length = TestDFSShell.dfs.getFileStatus(file2).getLen();
final Path dir2 = new Path(parent, "dir2");
TestDFSShell.mkdir(TestDFSShell.dfs, dir2);
/* Construct dir as follows:
/test/dir/file <- this will later be deleted after snapshot taken.
/test/dir/newfile <- this will be created after snapshot taken.
/test/dir/file2
/test/dir2 <- this will later be deleted after snapshot taken.
Snapshot enabled on /test
*/
// take a snapshot
// then create /test/dir/newfile and remove /test/dir/file, /test/dir2
final String snapshotName = "s1";
final Path snapshotPath = new Path(parent, (".snapshot/" + snapshotName));
TestDFSShell.dfs.allowSnapshot(parent);
Assert.assertThat(TestDFSShell.dfs.createSnapshot(parent, snapshotName), CoreMatchers.is(snapshotPath));
TestDFSShell.rmr(TestDFSShell.dfs, file);
TestDFSShell.rmr(TestDFSShell.dfs, dir2);
final Path newFile = new Path(dir, "new file");
TestDFSShell.writeFile(TestDFSShell.dfs, newFile);
final Long newFileLength = TestDFSShell.dfs.getFileStatus(newFile).getLen();
// test -count on /test. Include header for easier debugging.
int val = -1;
try {
val = shell.run(new String[]{ "-count", "-v", parent.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
String returnString = out.toString();
TestDFSShell.LOG.info(("-count return is:\n" + returnString));
Scanner in = new Scanner(returnString);
in.nextLine();
Assert.assertEquals(3, in.nextLong());// DIR_COUNT
Assert.assertEquals(3, in.nextLong());// FILE_COUNT
Assert.assertEquals(((fileLength + file2Length) + newFileLength), in.nextLong());// CONTENT_SIZE
out.reset();
// test -count -x on /test. Include header for easier debugging.
val = -1;
try {
val = shell.run(new String[]{ "-count", "-x", "-v", parent.toString() });
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
returnString = out.toString();
TestDFSShell.LOG.info(("-count -x return is:\n" + returnString));
in = new Scanner(returnString);
in.nextLine();
Assert.assertEquals(2, in.nextLong());// DIR_COUNT
Assert.assertEquals(2, in.nextLong());// FILE_COUNT
Assert.assertEquals((file2Length + newFileLength), in.nextLong());// CONTENT_SIZE
out.reset();
} finally {
System.setOut(psBackup);
}
}
@Test(timeout = 30000)
public void testPut() throws IOException {
// remove left over crc files:
new File(TestDFSShell.TEST_ROOT_DIR, ".f1.crc").delete();
new File(TestDFSShell.TEST_ROOT_DIR, ".f2.crc").delete();
final File f1 = TestDFSShell.createLocalFile(new File(TestDFSShell.TEST_ROOT_DIR, "f1"));
final File f2 = TestDFSShell.createLocalFile(new File(TestDFSShell.TEST_ROOT_DIR, "f2"));
final Path root = TestDFSShell.mkdir(TestDFSShell.dfs, new Path("/testPut"));
final Path dst = new Path(root, "dst");
TestDFSShell.show("begin");
final Thread copy2ndFileThread = new Thread() {
@Override
public void run() {
try {
TestDFSShell.show(((("copy local " + f2) + " to remote ") + dst));
TestDFSShell.dfs.copyFromLocalFile(false, false, new Path(f2.getPath()), dst);
} catch (IOException ioe) {
TestDFSShell.show(("good " + (StringUtils.stringifyException(ioe))));
return;
}
// should not be here, must got IOException
Assert.assertTrue(false);
}
};
// use SecurityManager to pause the copying of f1 and begin copying f2
SecurityManager sm = System.getSecurityManager();
System.out.println(("SecurityManager = " + sm));
System.setSecurityManager(new SecurityManager() {
private boolean firstTime = true;
@Override
public void checkPermission(Permission perm) {
if (firstTime) {
Thread t = Thread.currentThread();
if (!(t.toString().contains("DataNode"))) {
String s = "" + (Arrays.asList(t.getStackTrace()));
if (s.contains("FileUtil.copyContent")) {
// pause at FileUtil.copyContent
firstTime = false;
copy2ndFileThread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
}
}
});
TestDFSShell.show(((("copy local " + f1) + " to remote ") + dst));
TestDFSShell.dfs.copyFromLocalFile(false, false, new Path(f1.getPath()), dst);
TestDFSShell.show("done");
try {
copy2ndFileThread.join();
} catch (InterruptedException e) {
}
System.setSecurityManager(sm);
// copy multiple files to destination directory
final Path destmultiple = TestDFSShell.mkdir(TestDFSShell.dfs, new Path(root, "putmultiple"));
Path[] srcs = new Path[2];
srcs[0] = new Path(f1.getPath());
srcs[1] = new Path(f2.getPath());
TestDFSShell.dfs.copyFromLocalFile(false, false, srcs, destmultiple);
srcs[0] = new Path(destmultiple, "f1");
srcs[1] = new Path(destmultiple, "f2");
Assert.assertTrue(TestDFSShell.dfs.exists(srcs[0]));
Assert.assertTrue(TestDFSShell.dfs.exists(srcs[1]));
// move multiple files to destination directory
final Path destmultiple2 = TestDFSShell.mkdir(TestDFSShell.dfs, new Path(root, "movemultiple"));
srcs[0] = new Path(f1.getPath());
srcs[1] = new Path(f2.getPath());
TestDFSShell.dfs.moveFromLocalFile(srcs, destmultiple2);
Assert.assertFalse(f1.exists());
Assert.assertFalse(f2.exists());
srcs[0] = new Path(destmultiple2, "f1");
srcs[1] = new Path(destmultiple2, "f2");
Assert.assertTrue(TestDFSShell.dfs.exists(srcs[0]));
Assert.assertTrue(TestDFSShell.dfs.exists(srcs[1]));
f1.delete();
f2.delete();
}
/**
* check command error outputs and exit statuses.
*/
@Test(timeout = 30000)
public void testErrOutPut() throws Exception {
PrintStream bak = null;
try {
Path root = new Path("/nonexistentfile");
bak = System.err;
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream tmp = new PrintStream(out);
System.setErr(tmp);
String[] argv = new String[2];
argv[0] = "-cat";
argv[1] = root.toUri().getPath();
int ret = ToolRunner.run(new FsShell(), argv);
Assert.assertEquals(" -cat returned 1 ", 1, ret);
String returned = out.toString();
Assert.assertTrue("cat does not print exceptions ", ((returned.lastIndexOf("Exception")) == (-1)));
out.reset();
argv[0] = "-rm";
argv[1] = root.toString();
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" -rm returned 1 ", 1, ret);
returned = out.toString();
out.reset();
Assert.assertTrue("rm prints reasonable error ", ((returned.lastIndexOf("No such file or directory")) != (-1)));
argv[0] = "-rmr";
argv[1] = root.toString();
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" -rmr returned 1", 1, ret);
returned = out.toString();
Assert.assertTrue("rmr prints reasonable error ", ((returned.lastIndexOf("No such file or directory")) != (-1)));
out.reset();
argv[0] = "-du";
argv[1] = "/nonexistentfile";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertTrue(" -du prints reasonable error ", ((returned.lastIndexOf("No such file or directory")) != (-1)));
out.reset();
argv[0] = "-dus";
argv[1] = "/nonexistentfile";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertTrue(" -dus prints reasonable error", ((returned.lastIndexOf("No such file or directory")) != (-1)));
out.reset();
argv[0] = "-ls";
argv[1] = "/nonexistenfile";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertTrue(" -ls does not return Found 0 items", ((returned.lastIndexOf("Found 0")) == (-1)));
out.reset();
argv[0] = "-ls";
argv[1] = "/nonexistentfile";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" -lsr should fail ", 1, ret);
out.reset();
TestDFSShell.dfs.mkdirs(new Path("/testdir"));
argv[0] = "-ls";
argv[1] = "/testdir";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertTrue(" -ls does not print out anything ", ((returned.lastIndexOf("Found 0")) == (-1)));
out.reset();
argv[0] = "-ls";
argv[1] = "/user/nonxistant/*";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" -ls on nonexistent glob returns 1", 1, ret);
out.reset();
argv[0] = "-mkdir";
argv[1] = "/testdir";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertEquals(" -mkdir returned 1 ", 1, ret);
Assert.assertTrue(" -mkdir returned File exists", ((returned.lastIndexOf("File exists")) != (-1)));
Path testFile = new Path("/testfile");
OutputStream outtmp = TestDFSShell.dfs.create(testFile);
outtmp.write(testFile.toString().getBytes());
outtmp.close();
out.reset();
argv[0] = "-mkdir";
argv[1] = "/testfile";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertEquals(" -mkdir returned 1", 1, ret);
Assert.assertTrue(" -mkdir returned this is a file ", ((returned.lastIndexOf("not a directory")) != (-1)));
out.reset();
argv[0] = "-mkdir";
argv[1] = "/testParent/testChild";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertEquals(" -mkdir returned 1", 1, ret);
Assert.assertTrue(" -mkdir returned there is No file or directory but has testChild in the path", ((returned.lastIndexOf("testChild")) == (-1)));
out.reset();
argv = new String[3];
argv[0] = "-mv";
argv[1] = "/testfile";
argv[2] = "/no-such-dir/file";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("mv failed to rename", 1, ret);
out.reset();
argv = new String[3];
argv[0] = "-mv";
argv[1] = "/testfile";
argv[2] = "/testfiletest";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertTrue("no output from rename", ((returned.lastIndexOf("Renamed")) == (-1)));
out.reset();
argv[0] = "-mv";
argv[1] = "/testfile";
argv[2] = "/testfiletmp";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertTrue(" unix like output", ((returned.lastIndexOf("No such file or")) != (-1)));
out.reset();
argv = new String[1];
argv[0] = "-du";
TestDFSShell.dfs.mkdirs(TestDFSShell.dfs.getHomeDirectory());
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertEquals(" no error ", 0, ret);
Assert.assertTrue("empty path specified", ((returned.lastIndexOf("empty string")) == (-1)));
out.reset();
argv = new String[3];
argv[0] = "-test";
argv[1] = "-d";
argv[2] = "/no/such/dir";
ret = ToolRunner.run(shell, argv);
returned = out.toString();
Assert.assertEquals(" -test -d wrong result ", 1, ret);
Assert.assertTrue(returned.isEmpty());
} finally {
if (bak != null) {
System.setErr(bak);
}
}
}
@Test
public void testMoveWithTargetPortEmpty() throws Exception {
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).format(true).numDataNodes(2).nameNodePort(ServerSocketUtil.waitForPort(DFS_NAMENODE_RPC_PORT_DEFAULT, 60)).waitSafeMode(true).build();
FileSystem srcFs = cluster.getFileSystem();
FsShell shell = new FsShell();
shell.setConf(conf);
String[] argv = new String[2];
argv[0] = "-mkdir";
argv[1] = "/testfile";
ToolRunner.run(shell, argv);
argv = new String[3];
argv[0] = "-mv";
argv[1] = (getUri()) + "/testfile";
argv[2] = ("hdfs://" + (getUri().getHost())) + "/testfile2";
int ret = ToolRunner.run(shell, argv);
Assert.assertEquals("mv should have succeeded", 0, ret);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test(timeout = 30000)
public void testURIPaths() throws Exception {
Configuration srcConf = new HdfsConfiguration();
Configuration dstConf = new HdfsConfiguration();
MiniDFSCluster srcCluster = null;
MiniDFSCluster dstCluster = null;
File bak = new File(PathUtils.getTestDir(getClass()), "testURIPaths");
bak.mkdirs();
try {
srcCluster = new MiniDFSCluster.Builder(srcConf).numDataNodes(2).build();
dstConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, bak.getAbsolutePath());
dstCluster = new MiniDFSCluster.Builder(dstConf).numDataNodes(2).build();
FileSystem srcFs = srcCluster.getFileSystem();
FileSystem dstFs = dstCluster.getFileSystem();
FsShell shell = new FsShell();
shell.setConf(srcConf);
// check for ls
String[] argv = new String[2];
argv[0] = "-ls";
argv[1] = (getUri().toString()) + "/";
int ret = ToolRunner.run(shell, argv);
Assert.assertEquals("ls works on remote uri ", 0, ret);
// check for rm -r
dstFs.mkdirs(new Path("/hadoopdir"));
argv = new String[2];
argv[0] = "-rmr";
argv[1] = (getUri().toString()) + "/hadoopdir";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(("-rmr works on remote uri " + (argv[1])), 0, ret);
// check du
argv[0] = "-du";
argv[1] = (getUri().toString()) + "/";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("du works on remote uri ", 0, ret);
// check put
File furi = new File(TestDFSShell.TEST_ROOT_DIR, "furi");
TestDFSShell.createLocalFile(furi);
argv = new String[3];
argv[0] = "-put";
argv[1] = furi.toURI().toString();
argv[2] = (getUri().toString()) + "/furi";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" put is working ", 0, ret);
// check cp
argv[0] = "-cp";
argv[1] = (getUri().toString()) + "/furi";
argv[2] = (getUri().toString()) + "/furi";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" cp is working ", 0, ret);
Assert.assertTrue(srcFs.exists(new Path("/furi")));
// check cat
argv = new String[2];
argv[0] = "-cat";
argv[1] = (getUri().toString()) + "/furi";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" cat is working ", 0, ret);
// check chown
dstFs.delete(new Path("/furi"), true);
dstFs.delete(new Path("/hadoopdir"), true);
String file = "/tmp/chownTest";
Path path = new Path(file);
Path parent = new Path("/tmp");
Path root = new Path("/");
TestDFSShell.writeFile(dstFs, path);
TestDFSShell.runCmd(shell, "-chgrp", "-R", "herbivores", ((getUri().toString()) + "/*"));
confirmOwner(null, "herbivores", dstFs, parent, path);
TestDFSShell.runCmd(shell, "-chown", "-R", ":reptiles", ((getUri().toString()) + "/"));
confirmOwner(null, "reptiles", dstFs, root, parent, path);
// check if default hdfs:/// works
argv[0] = "-cat";
argv[1] = "hdfs:///furi";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals(" default works for cat", 0, ret);
argv[0] = "-ls";
argv[1] = "hdfs:///";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("default works for ls ", 0, ret);
argv[0] = "-rmr";
argv[1] = "hdfs:///furi";
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("default works for rm/rmr", 0, ret);
} finally {
if (null != srcCluster) {
srcCluster.shutdown();
}
if (null != dstCluster) {
dstCluster.shutdown();
}
}
}
/**
* Test that -head displays first kilobyte of the file to stdout.
*/
@Test(timeout = 30000)
public void testHead() throws Exception {
final int fileLen = 5 * (TestDFSShell.BLOCK_SIZE);
// create a text file with multiple KB bytes (and multiple blocks)
final Path testFile = new Path("testHead", "file1");
final String text = RandomStringUtils.randomAscii(fileLen);
try (OutputStream pout = TestDFSShell.dfs.create(testFile)) {
pout.write(text.getBytes());
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
final String[] argv = new String[]{ "-head", testFile.toString() };
final int ret = ToolRunner.run(new FsShell(TestDFSShell.dfs.getConf()), argv);
Assert.assertEquals((((Arrays.toString(argv)) + " returned ") + ret), 0, ret);
Assert.assertEquals((("-head returned " + (out.size())) + " bytes data, expected 1KB"), 1024, out.size());
// tailed out last 1KB of the file content
Assert.assertArrayEquals("Head output doesn't match input", text.substring(0, 1024).getBytes(), out.toByteArray());
out.reset();
}
/**
* Test that -tail displays last kilobyte of the file to stdout.
*/
@Test(timeout = 30000)
public void testTail() throws Exception {
final int fileLen = 5 * (TestDFSShell.BLOCK_SIZE);
// create a text file with multiple KB bytes (and multiple blocks)
final Path testFile = new Path("testTail", "file1");
final String text = RandomStringUtils.randomAscii(fileLen);
try (OutputStream pout = TestDFSShell.dfs.create(testFile)) {
pout.write(text.getBytes());
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
final String[] argv = new String[]{ "-tail", testFile.toString() };
final int ret = ToolRunner.run(new FsShell(TestDFSShell.dfs.getConf()), argv);
Assert.assertEquals((((Arrays.toString(argv)) + " returned ") + ret), 0, ret);
Assert.assertEquals((("-tail returned " + (out.size())) + " bytes data, expected 1KB"), 1024, out.size());
// tailed out last 1KB of the file content
Assert.assertArrayEquals("Tail output doesn't match input", text.substring((fileLen - 1024)).getBytes(), out.toByteArray());
out.reset();
}
/**
* Test that -tail -f outputs appended data as the file grows.
*/
@Test(timeout = 30000)
public void testTailWithFresh() throws Exception {
final Path testFile = new Path("testTailWithFresh", "file1");
TestDFSShell.dfs.create(testFile);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
final Thread tailer = new Thread() {
@Override
public void run() {
final String[] argv = new String[]{ "-tail", "-f", testFile.toString() };
try {
ToolRunner.run(new FsShell(TestDFSShell.dfs.getConf()), argv);
} catch (Exception e) {
TestDFSShell.LOG.error("Client that tails the test file fails", e);
} finally {
out.reset();
}
}
};
tailer.start();
// wait till the tailer is sleeping
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return (tailer.getState()) == (TIMED_WAITING);
}
}, 100, 10000);
final String text = RandomStringUtils.randomAscii(((TestDFSShell.BLOCK_SIZE) / 2));
try (OutputStream pout = TestDFSShell.dfs.create(testFile)) {
pout.write(text.getBytes());
}
// The tailer should eventually show the file contents
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return Arrays.equals(text.getBytes(), out.toByteArray());
}
}, 100, 10000);
}
@Test(timeout = 30000)
public void testText() throws Exception {
final Configuration conf = TestDFSShell.dfs.getConf();
textTest(new Path("/texttest").makeQualified(TestDFSShell.dfs.getUri(), TestDFSShell.dfs.getWorkingDirectory()), conf);
final FileSystem lfs = FileSystem.getLocal(conf);
textTest(new Path(TestDFSShell.TEST_ROOT_DIR, "texttest").makeQualified(getUri(), getWorkingDirectory()), conf);
}
@Test(timeout = 30000)
public void testCopyToLocal() throws IOException {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
String root = TestDFSShell.createTree(TestDFSShell.dfs, "copyToLocal");
// Verify copying the tree
{
try {
Assert.assertEquals(0, TestDFSShell.runCmd(shell, "-copyToLocal", (root + "*"), TestDFSShell.TEST_ROOT_DIR));
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
File localroot = new File(TestDFSShell.TEST_ROOT_DIR, "copyToLocal");
File localroot2 = new File(TestDFSShell.TEST_ROOT_DIR, "copyToLocal2");
File f1 = new File(localroot, "f1");
Assert.assertTrue("Copying failed.", f1.isFile());
File f2 = new File(localroot, "f2");
Assert.assertTrue("Copying failed.", f2.isFile());
File sub = new File(localroot, "sub");
Assert.assertTrue("Copying failed.", sub.isDirectory());
File f3 = new File(sub, "f3");
Assert.assertTrue("Copying failed.", f3.isFile());
File f4 = new File(sub, "f4");
Assert.assertTrue("Copying failed.", f4.isFile());
File f5 = new File(localroot2, "f1");
Assert.assertTrue("Copying failed.", f5.isFile());
f1.delete();
f2.delete();
f3.delete();
f4.delete();
f5.delete();
sub.delete();
}
// Verify copying non existing sources do not create zero byte
// destination files
{
String[] args = new String[]{ "-copyToLocal", "nosuchfile", TestDFSShell.TEST_ROOT_DIR };
try {
Assert.assertEquals(1, shell.run(args));
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
File f6 = new File(TestDFSShell.TEST_ROOT_DIR, "nosuchfile");
Assert.assertTrue((!(f6.exists())));
}
}
@Test(timeout = 30000)
public void testCount() throws Exception {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
String root = TestDFSShell.createTree(TestDFSShell.dfs, "count");
// Verify the counts
TestDFSShell.runCount(root, 2, 4, shell);
TestDFSShell.runCount((root + "2"), 2, 1, shell);
TestDFSShell.runCount((root + "2/f1"), 0, 1, shell);
TestDFSShell.runCount((root + "2/sub"), 1, 0, shell);
final FileSystem localfs = FileSystem.getLocal(TestDFSShell.dfs.getConf());
Path localpath = new Path(TestDFSShell.TEST_ROOT_DIR, "testcount");
localpath = localpath.makeQualified(getUri(), getWorkingDirectory());
localfs.mkdirs(localpath);
final String localstr = localpath.toString();
System.out.println(("localstr=" + localstr));
TestDFSShell.runCount(localstr, 1, 0, shell);
Assert.assertEquals(0, TestDFSShell.runCmd(shell, "-count", root, localstr));
}
@Test(timeout = 30000)
public void testTotalSizeOfAllFiles() throws Exception {
final Path root = new Path("/testTotalSizeOfAllFiles");
TestDFSShell.dfs.mkdirs(root);
// create file under root
FSDataOutputStream File1 = TestDFSShell.dfs.create(new Path(root, "File1"));
File1.write("hi".getBytes());
File1.close();
// create file under sub-folder
FSDataOutputStream File2 = TestDFSShell.dfs.create(new Path(root, "Folder1/File2"));
File2.write("hi".getBytes());
File2.close();
// getUsed() should return total length of all the files in Filesystem
Assert.assertEquals(4, TestDFSShell.dfs.getUsed(root));
}
@Test(timeout = 30000)
public void testFilePermissions() throws IOException {
Configuration conf = new HdfsConfiguration();
// test chmod on local fs
FileSystem fs = FileSystem.getLocal(conf);
testChmod(conf, fs, new File(TestDFSShell.TEST_ROOT_DIR, "chmodTest").getAbsolutePath());
conf.set(DFS_PERMISSIONS_ENABLED_KEY, "true");
// test chmod on DFS
fs = TestDFSShell.dfs;
conf = TestDFSShell.dfs.getConf();
testChmod(conf, fs, "/tmp/chmodTest");
// test chown and chgrp on DFS:
FsShell shell = new FsShell();
shell.setConf(conf);
/* For dfs, I am the super user and I can change owner of any file to
anything. "-R" option is already tested by chmod test above.
*/
String file = "/tmp/chownTest";
Path path = new Path(file);
Path parent = new Path("/tmp");
Path root = new Path("/");
TestDFSShell.writeFile(fs, path);
TestDFSShell.runCmd(shell, "-chgrp", "-R", "herbivores", "/*", "unknownFile*");
confirmOwner(null, "herbivores", fs, parent, path);
TestDFSShell.runCmd(shell, "-chgrp", "mammals", file);
confirmOwner(null, "mammals", fs, path);
TestDFSShell.runCmd(shell, "-chown", "-R", ":reptiles", "/");
confirmOwner(null, "reptiles", fs, root, parent, path);
TestDFSShell.runCmd(shell, "-chown", "python:", "/nonExistentFile", file);
confirmOwner("python", "reptiles", fs, path);
TestDFSShell.runCmd(shell, "-chown", "-R", "hadoop:toys", "unknownFile", "/");
confirmOwner("hadoop", "toys", fs, root, parent, path);
// Test different characters in names
TestDFSShell.runCmd(shell, "-chown", "hdfs.user", file);
confirmOwner("hdfs.user", null, fs, path);
TestDFSShell.runCmd(shell, "-chown", "_Hdfs.User-10:_hadoop.users--", file);
confirmOwner("_Hdfs.User-10", "_hadoop.users--", fs, path);
TestDFSShell.runCmd(shell, "-chown", "hdfs/[email protected]:asf-projects", file);
confirmOwner("hdfs/[email protected]", "asf-projects", fs, path);
TestDFSShell.runCmd(shell, "-chgrp", "[email protected]/100", file);
confirmOwner(null, "[email protected]/100", fs, path);
}
/**
* Tests various options of DFSShell.
*/
@Test(timeout = 120000)
public void testDFSShell() throws Exception {
/* This tests some properties of ChecksumFileSystem as well.
Make sure that we create ChecksumDFS
*/
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
// First create a new directory with mkdirs
Path myPath = new Path("/testDFSShell/mkdirs");
Assert.assertTrue(TestDFSShell.dfs.mkdirs(myPath));
Assert.assertTrue(TestDFSShell.dfs.exists(myPath));
Assert.assertTrue(TestDFSShell.dfs.mkdirs(myPath));
// Second, create a file in that directory.
Path myFile = new Path("/testDFSShell/mkdirs/myFile");
TestDFSShell.writeFile(TestDFSShell.dfs, myFile);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile));
Path myFile2 = new Path("/testDFSShell/mkdirs/myFile2");
TestDFSShell.writeFile(TestDFSShell.dfs, myFile2);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile2));
// Verify that rm with a pattern
{
String[] args = new String[2];
args[0] = "-rm";
args[1] = "/testDFSShell/mkdirs/myFile*";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertTrue((val == 0));
Assert.assertFalse(TestDFSShell.dfs.exists(myFile));
Assert.assertFalse(TestDFSShell.dfs.exists(myFile2));
// re-create the files for other tests
TestDFSShell.writeFile(TestDFSShell.dfs, myFile);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile));
TestDFSShell.writeFile(TestDFSShell.dfs, myFile2);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile2));
}
// Verify that we can read the file
{
String[] args = new String[3];
args[0] = "-cat";
args[1] = "/testDFSShell/mkdirs/myFile";
args[2] = "/testDFSShell/mkdirs/myFile2";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run: " + (StringUtils.stringifyException(e))));
}
Assert.assertTrue((val == 0));
}
TestDFSShell.dfs.delete(myFile2, true);
// Verify that we get an error while trying to read an nonexistent file
{
String[] args = new String[2];
args[0] = "-cat";
args[1] = "/testDFSShell/mkdirs/myFile1";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertTrue((val != 0));
}
// Verify that we get an error while trying to delete an nonexistent file
{
String[] args = new String[2];
args[0] = "-rm";
args[1] = "/testDFSShell/mkdirs/myFile1";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertTrue((val != 0));
}
// Verify that we succeed in removing the file we created
{
String[] args = new String[2];
args[0] = "-rm";
args[1] = "/testDFSShell/mkdirs/myFile";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertTrue((val == 0));
}
// Verify touch/test
{
String[] args;
int val;
args = new String[3];
args[0] = "-test";
args[1] = "-e";
args[2] = "/testDFSShell/mkdirs/noFileHere";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
args[1] = "-z";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
args = new String[2];
args[0] = "-touchz";
args[1] = "/testDFSShell/mkdirs/isFileHere";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
args = new String[2];
args[0] = "-touchz";
args[1] = "/testDFSShell/mkdirs/thisDirNotExists/isFileHere";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
args = new String[3];
args[0] = "-test";
args[1] = "-e";
args[2] = "/testDFSShell/mkdirs/isFileHere";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
args[1] = "-d";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
args[1] = "-z";
val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
}
// Verify that cp from a directory to a subdirectory fails
{
String[] args = new String[2];
args[0] = "-mkdir";
args[1] = "/testDFSShell/dir1";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
// this should fail
String[] args1 = new String[3];
args1[0] = "-cp";
args1[1] = "/testDFSShell/dir1";
args1[2] = "/testDFSShell/dir1/dir2";
val = 0;
try {
val = shell.run(args1);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
// this should succeed
args1[0] = "-cp";
args1[1] = "/testDFSShell/dir1";
args1[2] = "/testDFSShell/dir1foo";
val = -1;
try {
val = shell.run(args1);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
// this should fail
args1[0] = "-cp";
args1[1] = "/";
args1[2] = "/test";
val = 0;
try {
val = shell.run(args1);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
}
// Verify -test -f negative case (missing file)
{
String[] args = new String[3];
args[0] = "-test";
args[1] = "-f";
args[2] = "/testDFSShell/mkdirs/noFileHere";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
}
// Verify -test -f negative case (directory rather than file)
{
String[] args = new String[3];
args[0] = "-test";
args[1] = "-f";
args[2] = "/testDFSShell/mkdirs";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
}
// Verify -test -f positive case
{
TestDFSShell.writeFile(TestDFSShell.dfs, myFile);
Assert.assertTrue(TestDFSShell.dfs.exists(myFile));
String[] args = new String[3];
args[0] = "-test";
args[1] = "-f";
args[2] = myFile.toString();
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
}
// Verify -test -s negative case (missing file)
{
String[] args = new String[3];
args[0] = "-test";
args[1] = "-s";
args[2] = "/testDFSShell/mkdirs/noFileHere";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
}
// Verify -test -s negative case (zero length file)
{
String[] args = new String[3];
args[0] = "-test";
args[1] = "-s";
args[2] = "/testDFSShell/mkdirs/isFileHere";
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(1, val);
}
// Verify -test -s positive case (nonzero length file)
{
String[] args = new String[3];
args[0] = "-test";
args[1] = "-s";
args[2] = myFile.toString();
int val = -1;
try {
val = shell.run(args);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
}
// Verify -test -w/-r
{
Path permDir = new Path("/testDFSShell/permDir");
Path permFile = new Path("/testDFSShell/permDir/permFile");
TestDFSShell.mkdir(TestDFSShell.dfs, permDir);
TestDFSShell.writeFile(TestDFSShell.dfs, permFile);
// Verify -test -w positive case (dir exists and can write)
final String[] wargs = new String[3];
wargs[0] = "-test";
wargs[1] = "-w";
wargs[2] = permDir.toString();
int val = -1;
try {
val = shell.run(wargs);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
// Verify -test -r positive case (file exists and can read)
final String[] rargs = new String[3];
rargs[0] = "-test";
rargs[1] = "-r";
rargs[2] = permFile.toString();
try {
val = shell.run(rargs);
} catch (Exception e) {
System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage())));
}
Assert.assertEquals(0, val);
// Verify -test -r negative case (file exists but cannot read)
TestDFSShell.runCmd(shell, "-chmod", "600", permFile.toString());
UserGroupInformation smokeUser = UserGroupInformation.createUserForTesting("smokeUser", new String[]{ "hadoop" });
smokeUser.doAs(new PrivilegedExceptionAction<String>() {
@Override
public String run() throws Exception {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
int exitCode = shell.run(rargs);
Assert.assertEquals(1, exitCode);
return null;
}
});
// Verify -test -w negative case (dir exists but cannot write)
TestDFSShell.runCmd(shell, "-chown", "-R", "not_allowed", permDir.toString());
TestDFSShell.runCmd(shell, "-chmod", "-R", "700", permDir.toString());
smokeUser.doAs(new PrivilegedExceptionAction<String>() {
@Override
public String run() throws Exception {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
int exitCode = shell.run(wargs);
Assert.assertEquals(1, exitCode);
return null;
}
});
// cleanup
TestDFSShell.dfs.delete(permDir, true);
}
}
static interface TestGetRunner {
String run(int exitcode, String... options) throws IOException;
}
@Test(timeout = 30000)
public void testRemoteException() throws Exception {
UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting("tmpname", new String[]{ "mygroup" });
PrintStream bak = null;
try {
Path p = new Path("/foo");
TestDFSShell.dfs.mkdirs(p);
TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (448))));
bak = System.err;
tmpUGI.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
FsShell fshell = new FsShell(TestDFSShell.dfs.getConf());
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream tmp = new PrintStream(out);
System.setErr(tmp);
String[] args = new String[2];
args[0] = "-ls";
args[1] = "/foo";
int ret = ToolRunner.run(fshell, args);
Assert.assertEquals("returned should be 1", 1, ret);
String str = out.toString();
Assert.assertTrue("permission denied printed", ((str.indexOf("Permission denied")) != (-1)));
out.reset();
return null;
}
});
} finally {
if (bak != null) {
System.setErr(bak);
}
}
}
@Test(timeout = 30000)
public void testGet() throws IOException {
GenericTestUtils.setLogLevel(FSInputChecker.LOG, Level.ALL);
final String fname = "testGet.txt";
Path root = new Path("/test/get");
final Path remotef = new Path(root, fname);
final Configuration conf = new HdfsConfiguration();
// Set short retry timeouts so this test runs faster
conf.setInt(WINDOW_BASE_KEY, 10);
TestDFSShell.TestGetRunner runner = new TestDFSShell.TestGetRunner() {
private int count = 0;
private final FsShell shell = new FsShell(conf);
public String run(int exitcode, String... options) throws IOException {
String dst = new File(TestDFSShell.TEST_ROOT_DIR, (fname + (++(count)))).getAbsolutePath();
String[] args = new String[(options.length) + 3];
args[0] = "-get";
args[((args.length) - 2)] = remotef.toString();
args[((args.length) - 1)] = dst;
for (int i = 0; i < (options.length); i++) {
args[(i + 1)] = options[i];
}
TestDFSShell.show(("args=" + (Arrays.asList(args))));
try {
Assert.assertEquals(exitcode, shell.run(args));
} catch (Exception e) {
Assert.assertTrue(StringUtils.stringifyException(e), false);
}
return exitcode == 0 ? DFSTestUtil.readFile(new File(dst)) : null;
}
};
File localf = TestDFSShell.createLocalFile(new File(TestDFSShell.TEST_ROOT_DIR, fname));
MiniDFSCluster cluster = null;
DistributedFileSystem dfs = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).format(true).build();
dfs = cluster.getFileSystem();
TestDFSShell.mkdir(dfs, root);
dfs.copyFromLocalFile(false, false, new Path(localf.getPath()), remotef);
String localfcontent = DFSTestUtil.readFile(localf);
Assert.assertEquals(localfcontent, runner.run(0));
Assert.assertEquals(localfcontent, runner.run(0, "-ignoreCrc"));
// find block files to modify later
List<FsDatasetTestUtils.MaterializedReplica> replicas = TestDFSShell.getMaterializedReplicas(cluster);
// Shut down miniCluster and then corrupt the block files by overwriting a
// portion with junk data. We must shut down the miniCluster so that threads
// in the data node do not hold locks on the block files while we try to
// write into them. Particularly on Windows, the data node's use of the
// FileChannel.transferTo method can cause block files to be memory mapped
// in read-only mode during the transfer to a client, and this causes a
// locking conflict. The call to shutdown the miniCluster blocks until all
// DataXceiver threads exit, preventing this problem.
dfs.close();
cluster.shutdown();
TestDFSShell.show(("replicas=" + replicas));
TestDFSShell.corrupt(replicas, localfcontent);
// Start the miniCluster again, but do not reformat, so prior files remain.
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).format(false).build();
dfs = cluster.getFileSystem();
Assert.assertEquals(null, runner.run(1));
String corruptedcontent = runner.run(0, "-ignoreCrc");
Assert.assertEquals(localfcontent.substring(1), corruptedcontent.substring(1));
Assert.assertEquals(((localfcontent.charAt(0)) + 1), corruptedcontent.charAt(0));
} finally {
if (null != dfs) {
try {
dfs.close();
} catch (Exception e) {
}
}
if (null != cluster) {
cluster.shutdown();
}
localf.delete();
}
}
/**
* Test -stat [format] <path>... prints statistics about the file/directory
* at <path> in the specified format.
*/
@Test(timeout = 30000)
public void testStat() throws Exception {
final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
final Path testDir1 = new Path("testStat", "dir1");
TestDFSShell.dfs.mkdirs(testDir1);
final Path testFile2 = new Path(testDir1, "file2");
DFSTestUtil.createFile(TestDFSShell.dfs, testFile2, (2 * (TestDFSShell.BLOCK_SIZE)), ((short) (3)), 0);
final FileStatus status1 = TestDFSShell.dfs.getFileStatus(testDir1);
final String mtime1 = fmt.format(new Date(status1.getModificationTime()));
final String atime1 = fmt.format(new Date(status1.getAccessTime()));
long now = Time.now();
TestDFSShell.dfs.setTimes(testFile2, (now + 3000), (now + 6000));
final FileStatus status2 = TestDFSShell.dfs.getFileStatus(testFile2);
final String mtime2 = fmt.format(new Date(status2.getModificationTime()));
final String atime2 = fmt.format(new Date(status2.getAccessTime()));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), null);
out.reset();
TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), null, testDir1);
Assert.assertEquals(("Unexpected -stat output: " + out), out.toString(), String.format("%s%n", mtime1));
out.reset();
TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), null, testDir1, testFile2);
Assert.assertEquals(("Unexpected -stat output: " + out), out.toString(), String.format("%s%n%s%n", mtime1, mtime2));
TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), "%F %u:%g %b %y %n");
out.reset();
TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), "%F %a %A %u:%g %b %y %n", testDir1);
Assert.assertTrue(out.toString(), out.toString().contains(mtime1));
Assert.assertTrue(out.toString(), out.toString().contains("directory"));
Assert.assertTrue(out.toString(), out.toString().contains(status1.getGroup()));
Assert.assertTrue(out.toString(), out.toString().contains(status1.getPermission().toString()));
int n = status1.getPermission().toShort();
int octal = (((((n >>> 9) & 1) * 1000) + (((n >>> 6) & 7) * 100)) + (((n >>> 3) & 7) * 10)) + (n & 7);
Assert.assertTrue(out.toString(), out.toString().contains(String.valueOf(octal)));
out.reset();
TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), "%F %a %A %u:%g %b %x %y %n", testDir1, testFile2);
n = status2.getPermission().toShort();
octal = (((((n >>> 9) & 1) * 1000) + (((n >>> 6) & 7) * 100)) + (((n >>> 3) & 7) * 10)) + (n & 7);
Assert.assertTrue(out.toString(), out.toString().contains(mtime1));
Assert.assertTrue(out.toString(), out.toString().contains(atime1));
Assert.assertTrue(out.toString(), out.toString().contains("regular file"));
Assert.assertTrue(out.toString(), out.toString().contains(status2.getPermission().toString()));
Assert.assertTrue(out.toString(), out.toString().contains(String.valueOf(octal)));
Assert.assertTrue(out.toString(), out.toString().contains(mtime2));
Assert.assertTrue(out.toString(), out.toString().contains(atime2));
}
@Test(timeout = 30000)
public void testLsr() throws Exception {
final Configuration conf = TestDFSShell.dfs.getConf();
final String root = TestDFSShell.createTree(TestDFSShell.dfs, "lsr");
TestDFSShell.dfs.mkdirs(new Path(root, "zzz"));
TestDFSShell.runLsr(new FsShell(conf), root, 0);
final Path sub = new Path(root, "sub");
TestDFSShell.dfs.setPermission(sub, new FsPermission(((short) (0))));
final UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
final String tmpusername = (ugi.getShortUserName()) + "1";
UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting(tmpusername, new String[]{ tmpusername });
String results = tmpUGI.doAs(new PrivilegedExceptionAction<String>() {
@Override
public String run() throws Exception {
return TestDFSShell.runLsr(new FsShell(conf), root, 1);
}
});
Assert.assertTrue(results.contains("zzz"));
}
/**
* default setting is file:// which is not a DFS
* so DFSAdmin should throw and catch InvalidArgumentException
* and return -1 exit code.
*
* @throws Exception
*
*/
@Test(timeout = 30000)
public void testInvalidShell() throws Exception {
Configuration conf = new Configuration();// default FS (non-DFS)
DFSAdmin admin = new DFSAdmin();
admin.setConf(conf);
int res = admin.run(new String[]{ "-refreshNodes" });
Assert.assertEquals("expected to fail -1", res, (-1));
}
// Preserve Copy Option is -ptopxa (timestamps, ownership, permission, XATTR,
// ACLs)
@Test(timeout = 120000)
public void testCopyCommandsWithPreserveOption() throws Exception {
FsShell shell = null;
final String testdir = "/tmp/TestDFSShell-testCopyCommandsWithPreserveOption-" + (TestDFSShell.counter.getAndIncrement());
final Path hdfsTestDir = new Path(testdir);
try {
TestDFSShell.dfs.mkdirs(hdfsTestDir);
Path src = new Path(hdfsTestDir, "srcfile");
TestDFSShell.dfs.create(src).close();
TestDFSShell.dfs.setAcl(src, Lists.newArrayList(AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, "foo", ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, "bar", READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, OTHER, EXECUTE)));
FileStatus status = TestDFSShell.dfs.getFileStatus(src);
final long mtime = status.getModificationTime();
final long atime = status.getAccessTime();
final String owner = status.getOwner();
final String group = status.getGroup();
final FsPermission perm = status.getPermission();
TestDFSShell.dfs.setXAttr(src, TestDFSShell.USER_A1, TestDFSShell.USER_A1_VALUE);
TestDFSShell.dfs.setXAttr(src, TestDFSShell.TRUSTED_A1, TestDFSShell.TRUSTED_A1_VALUE);
shell = new FsShell(TestDFSShell.dfs.getConf());
// -p
Path target1 = new Path(hdfsTestDir, "targetfile1");
String[] argv = new String[]{ "-cp", "-p", src.toUri().toString(), target1.toUri().toString() };
int ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -p is not working", SUCCESS, ret);
FileStatus targetStatus = TestDFSShell.dfs.getFileStatus(target1);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
FsPermission targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
Map<String, byte[]> xattrs = TestDFSShell.dfs.getXAttrs(target1);
Assert.assertTrue(xattrs.isEmpty());
List<AclEntry> acls = TestDFSShell.dfs.getAclStatus(target1).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptop
Path target2 = new Path(hdfsTestDir, "targetfile2");
argv = new String[]{ "-cp", "-ptop", src.toUri().toString(), target2.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptop is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(target2);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(target2);
Assert.assertTrue(xattrs.isEmpty());
acls = TestDFSShell.dfs.getAclStatus(target2).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptopx
Path target3 = new Path(hdfsTestDir, "targetfile3");
argv = new String[]{ "-cp", "-ptopx", src.toUri().toString(), target3.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptopx is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(target3);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(target3);
Assert.assertEquals(xattrs.size(), 2);
Assert.assertArrayEquals(TestDFSShell.USER_A1_VALUE, xattrs.get(TestDFSShell.USER_A1));
Assert.assertArrayEquals(TestDFSShell.TRUSTED_A1_VALUE, xattrs.get(TestDFSShell.TRUSTED_A1));
acls = TestDFSShell.dfs.getAclStatus(target3).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptopa
Path target4 = new Path(hdfsTestDir, "targetfile4");
argv = new String[]{ "-cp", "-ptopa", src.toUri().toString(), target4.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptopa is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(target4);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(target4);
Assert.assertTrue(xattrs.isEmpty());
acls = TestDFSShell.dfs.getAclStatus(target4).getEntries();
Assert.assertFalse(acls.isEmpty());
Assert.assertTrue(targetStatus.hasAcl());
Assert.assertEquals(TestDFSShell.dfs.getAclStatus(src), TestDFSShell.dfs.getAclStatus(target4));
// -ptoa (verify -pa option will preserve permissions also)
Path target5 = new Path(hdfsTestDir, "targetfile5");
argv = new String[]{ "-cp", "-ptoa", src.toUri().toString(), target5.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptoa is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(target5);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(target5);
Assert.assertTrue(xattrs.isEmpty());
acls = TestDFSShell.dfs.getAclStatus(target5).getEntries();
Assert.assertFalse(acls.isEmpty());
Assert.assertTrue(targetStatus.hasAcl());
Assert.assertEquals(TestDFSShell.dfs.getAclStatus(src), TestDFSShell.dfs.getAclStatus(target5));
} finally {
if (null != shell) {
shell.close();
}
}
}
@Test(timeout = 120000)
public void testCopyCommandsWithRawXAttrs() throws Exception {
FsShell shell = null;
final String testdir = "/tmp/TestDFSShell-testCopyCommandsWithRawXAttrs-" + (TestDFSShell.counter.getAndIncrement());
final Path hdfsTestDir = new Path(testdir);
final Path rawHdfsTestDir = new Path(("/.reserved/raw" + testdir));
try {
TestDFSShell.dfs.mkdirs(hdfsTestDir);
final Path src = new Path(hdfsTestDir, "srcfile");
final String rawSrcBase = "/.reserved/raw" + testdir;
final Path rawSrc = new Path(rawSrcBase, "srcfile");
TestDFSShell.dfs.create(src).close();
final Path srcDir = new Path(hdfsTestDir, "srcdir");
final Path rawSrcDir = new Path(("/.reserved/raw" + testdir), "srcdir");
TestDFSShell.dfs.mkdirs(srcDir);
final Path srcDirFile = new Path(srcDir, "srcfile");
final Path rawSrcDirFile = new Path(("/.reserved/raw" + srcDirFile));
TestDFSShell.dfs.create(srcDirFile).close();
final Path[] paths = new org.apache.hadoop.fs.Path[]{ rawSrc, rawSrcDir, rawSrcDirFile };
final String[] xattrNames = new String[]{ TestDFSShell.USER_A1, TestDFSShell.RAW_A1 };
final byte[][] xattrVals = new byte[][]{ TestDFSShell.USER_A1_VALUE, TestDFSShell.RAW_A1_VALUE };
for (int i = 0; i < (paths.length); i++) {
for (int j = 0; j < (xattrNames.length); j++) {
TestDFSShell.dfs.setXAttr(paths[i], xattrNames[j], xattrVals[j]);
}
}
shell = new FsShell(TestDFSShell.dfs.getConf());
/* Check that a file as the source path works ok. */
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, src, hdfsTestDir, false);
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrc, hdfsTestDir, false);
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, src, rawHdfsTestDir, false);
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrc, rawHdfsTestDir, true);
/* Use a relative /.reserved/raw path. */
final Path savedWd = TestDFSShell.dfs.getWorkingDirectory();
try {
TestDFSShell.dfs.setWorkingDirectory(new Path(rawSrcBase));
final Path relRawSrc = new Path("../srcfile");
final Path relRawHdfsTestDir = new Path("..");
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, relRawSrc, relRawHdfsTestDir, true);
} finally {
TestDFSShell.dfs.setWorkingDirectory(savedWd);
}
/* Check that a directory as the source path works ok. */
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, srcDir, hdfsTestDir, false);
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrcDir, hdfsTestDir, false);
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, srcDir, rawHdfsTestDir, false);
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrcDir, rawHdfsTestDir, true);
/* Use relative in an absolute path. */
final String relRawSrcDir = ("./.reserved/../.reserved/raw/../raw" + testdir) + "/srcdir";
final String relRawDstDir = "./.reserved/../.reserved/raw/../raw" + testdir;
doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, new Path(relRawSrcDir), new Path(relRawDstDir), true);
} finally {
if (null != shell) {
shell.close();
}
TestDFSShell.dfs.delete(hdfsTestDir, true);
}
}
// verify cp -ptopxa option will preserve directory attributes.
@Test(timeout = 120000)
public void testCopyCommandsToDirectoryWithPreserveOption() throws Exception {
FsShell shell = null;
final String testdir = "/tmp/TestDFSShell-testCopyCommandsToDirectoryWithPreserveOption-" + (TestDFSShell.counter.getAndIncrement());
final Path hdfsTestDir = new Path(testdir);
try {
TestDFSShell.dfs.mkdirs(hdfsTestDir);
Path srcDir = new Path(hdfsTestDir, "srcDir");
TestDFSShell.dfs.mkdirs(srcDir);
TestDFSShell.dfs.setAcl(srcDir, Lists.newArrayList(AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, "foo", ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.DEFAULT, GROUP, "bar", READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, OTHER, EXECUTE)));
// set sticky bit
TestDFSShell.dfs.setPermission(srcDir, new FsPermission(ALL, READ_EXECUTE, EXECUTE, true));
// Create a file in srcDir to check if modification time of
// srcDir to be preserved after copying the file.
// If cp -p command is to preserve modification time and then copy child
// (srcFile), modification time will not be preserved.
Path srcFile = new Path(srcDir, "srcFile");
TestDFSShell.dfs.create(srcFile).close();
FileStatus status = TestDFSShell.dfs.getFileStatus(srcDir);
final long mtime = status.getModificationTime();
final long atime = status.getAccessTime();
final String owner = status.getOwner();
final String group = status.getGroup();
final FsPermission perm = status.getPermission();
TestDFSShell.dfs.setXAttr(srcDir, TestDFSShell.USER_A1, TestDFSShell.USER_A1_VALUE);
TestDFSShell.dfs.setXAttr(srcDir, TestDFSShell.TRUSTED_A1, TestDFSShell.TRUSTED_A1_VALUE);
shell = new FsShell(TestDFSShell.dfs.getConf());
// -p
Path targetDir1 = new Path(hdfsTestDir, "targetDir1");
String[] argv = new String[]{ "-cp", "-p", srcDir.toUri().toString(), targetDir1.toUri().toString() };
int ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -p is not working", SUCCESS, ret);
FileStatus targetStatus = TestDFSShell.dfs.getFileStatus(targetDir1);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
FsPermission targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
Map<String, byte[]> xattrs = TestDFSShell.dfs.getXAttrs(targetDir1);
Assert.assertTrue(xattrs.isEmpty());
List<AclEntry> acls = TestDFSShell.dfs.getAclStatus(targetDir1).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptop
Path targetDir2 = new Path(hdfsTestDir, "targetDir2");
argv = new String[]{ "-cp", "-ptop", srcDir.toUri().toString(), targetDir2.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptop is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(targetDir2);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(targetDir2);
Assert.assertTrue(xattrs.isEmpty());
acls = TestDFSShell.dfs.getAclStatus(targetDir2).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptopx
Path targetDir3 = new Path(hdfsTestDir, "targetDir3");
argv = new String[]{ "-cp", "-ptopx", srcDir.toUri().toString(), targetDir3.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptopx is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(targetDir3);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(targetDir3);
Assert.assertEquals(xattrs.size(), 2);
Assert.assertArrayEquals(TestDFSShell.USER_A1_VALUE, xattrs.get(TestDFSShell.USER_A1));
Assert.assertArrayEquals(TestDFSShell.TRUSTED_A1_VALUE, xattrs.get(TestDFSShell.TRUSTED_A1));
acls = TestDFSShell.dfs.getAclStatus(targetDir3).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptopa
Path targetDir4 = new Path(hdfsTestDir, "targetDir4");
argv = new String[]{ "-cp", "-ptopa", srcDir.toUri().toString(), targetDir4.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptopa is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(targetDir4);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(targetDir4);
Assert.assertTrue(xattrs.isEmpty());
acls = TestDFSShell.dfs.getAclStatus(targetDir4).getEntries();
Assert.assertFalse(acls.isEmpty());
Assert.assertTrue(targetStatus.hasAcl());
Assert.assertEquals(TestDFSShell.dfs.getAclStatus(srcDir), TestDFSShell.dfs.getAclStatus(targetDir4));
// -ptoa (verify -pa option will preserve permissions also)
Path targetDir5 = new Path(hdfsTestDir, "targetDir5");
argv = new String[]{ "-cp", "-ptoa", srcDir.toUri().toString(), targetDir5.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptoa is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(targetDir5);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
xattrs = TestDFSShell.dfs.getXAttrs(targetDir5);
Assert.assertTrue(xattrs.isEmpty());
acls = TestDFSShell.dfs.getAclStatus(targetDir5).getEntries();
Assert.assertFalse(acls.isEmpty());
Assert.assertTrue(targetStatus.hasAcl());
Assert.assertEquals(TestDFSShell.dfs.getAclStatus(srcDir), TestDFSShell.dfs.getAclStatus(targetDir5));
} finally {
if (shell != null) {
shell.close();
}
}
}
// Verify cp -pa option will preserve both ACL and sticky bit.
@Test(timeout = 120000)
public void testCopyCommandsPreserveAclAndStickyBit() throws Exception {
FsShell shell = null;
final String testdir = "/tmp/TestDFSShell-testCopyCommandsPreserveAclAndStickyBit-" + (TestDFSShell.counter.getAndIncrement());
final Path hdfsTestDir = new Path(testdir);
try {
TestDFSShell.dfs.mkdirs(hdfsTestDir);
Path src = new Path(hdfsTestDir, "srcfile");
TestDFSShell.dfs.create(src).close();
TestDFSShell.dfs.setAcl(src, Lists.newArrayList(AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, "foo", ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, "bar", READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, OTHER, EXECUTE)));
// set sticky bit
TestDFSShell.dfs.setPermission(src, new FsPermission(ALL, READ_EXECUTE, EXECUTE, true));
FileStatus status = TestDFSShell.dfs.getFileStatus(src);
final long mtime = status.getModificationTime();
final long atime = status.getAccessTime();
final String owner = status.getOwner();
final String group = status.getGroup();
final FsPermission perm = status.getPermission();
shell = new FsShell(TestDFSShell.dfs.getConf());
// -p preserves sticky bit and doesn't preserve ACL
Path target1 = new Path(hdfsTestDir, "targetfile1");
String[] argv = new String[]{ "-cp", "-p", src.toUri().toString(), target1.toUri().toString() };
int ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp is not working", SUCCESS, ret);
FileStatus targetStatus = TestDFSShell.dfs.getFileStatus(target1);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
FsPermission targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
List<AclEntry> acls = TestDFSShell.dfs.getAclStatus(target1).getEntries();
Assert.assertTrue(acls.isEmpty());
Assert.assertFalse(targetStatus.hasAcl());
// -ptopa preserves both sticky bit and ACL
Path target2 = new Path(hdfsTestDir, "targetfile2");
argv = new String[]{ "-cp", "-ptopa", src.toUri().toString(), target2.toUri().toString() };
ret = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -ptopa is not working", SUCCESS, ret);
targetStatus = TestDFSShell.dfs.getFileStatus(target2);
Assert.assertEquals(mtime, targetStatus.getModificationTime());
Assert.assertEquals(atime, targetStatus.getAccessTime());
Assert.assertEquals(owner, targetStatus.getOwner());
Assert.assertEquals(group, targetStatus.getGroup());
targetPerm = targetStatus.getPermission();
Assert.assertTrue(perm.equals(targetPerm));
acls = TestDFSShell.dfs.getAclStatus(target2).getEntries();
Assert.assertFalse(acls.isEmpty());
Assert.assertTrue(targetStatus.hasAcl());
Assert.assertEquals(TestDFSShell.dfs.getAclStatus(src), TestDFSShell.dfs.getAclStatus(target2));
} finally {
if (null != shell) {
shell.close();
}
}
}
// force Copy Option is -f
@Test(timeout = 30000)
public void testCopyCommandsWithForceOption() throws Exception {
FsShell shell = null;
final File localFile = new File(TestDFSShell.TEST_ROOT_DIR, "testFileForPut");
final String localfilepath = new Path(localFile.getAbsolutePath()).toUri().toString();
final String testdir = "/tmp/TestDFSShell-testCopyCommandsWithForceOption-" + (TestDFSShell.counter.getAndIncrement());
final Path hdfsTestDir = new Path(testdir);
try {
TestDFSShell.dfs.mkdirs(hdfsTestDir);
localFile.createNewFile();
TestDFSShell.writeFile(TestDFSShell.dfs, new Path(testdir, "testFileForPut"));
shell = new FsShell();
// Tests for put
String[] argv = new String[]{ "-put", "-f", localfilepath, testdir };
int res = ToolRunner.run(shell, argv);
Assert.assertEquals("put -f is not working", SUCCESS, res);
argv = new String[]{ "-put", localfilepath, testdir };
res = ToolRunner.run(shell, argv);
Assert.assertEquals("put command itself is able to overwrite the file", ERROR, res);
// Tests for copyFromLocal
argv = new String[]{ "-copyFromLocal", "-f", localfilepath, testdir };
res = ToolRunner.run(shell, argv);
Assert.assertEquals("copyFromLocal -f is not working", SUCCESS, res);
argv = new String[]{ "-copyFromLocal", localfilepath, testdir };
res = ToolRunner.run(shell, argv);
Assert.assertEquals("copyFromLocal command itself is able to overwrite the file", ERROR, res);
// Tests for cp
argv = new String[]{ "-cp", "-f", localfilepath, testdir };
res = ToolRunner.run(shell, argv);
Assert.assertEquals("cp -f is not working", SUCCESS, res);
argv = new String[]{ "-cp", localfilepath, testdir };
res = ToolRunner.run(shell, argv);
Assert.assertEquals("cp command itself is able to overwrite the file", ERROR, res);
} finally {
if (null != shell)
shell.close();
if (localFile.exists())
localFile.delete();
}
}
/* [refs HDFS-5033]
return a "Permission Denied" message instead of "No such file or Directory"
when trying to put/copyFromLocal a file that doesn't have read access
*/
@Test(timeout = 30000)
public void testCopyFromLocalWithPermissionDenied() throws Exception {
FsShell shell = null;
PrintStream bak = null;
final File localFile = new File(TestDFSShell.TEST_ROOT_DIR, "testFileWithNoReadPermissions");
final String localfilepath = new Path(localFile.getAbsolutePath()).toUri().toString();
final String testdir = "/tmp/TestDFSShell-CopyFromLocalWithPermissionDenied-" + (TestDFSShell.counter.getAndIncrement());
final Path hdfsTestDir = new Path(testdir);
try {
TestDFSShell.dfs.mkdirs(hdfsTestDir);
localFile.createNewFile();
localFile.setReadable(false);
TestDFSShell.writeFile(TestDFSShell.dfs, new Path(testdir, "testFileForPut"));
shell = new FsShell();
// capture system error messages, snarfed from testErrOutPut()
bak = System.err;
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream tmp = new PrintStream(out);
System.setErr(tmp);
// Tests for put
String[] argv = new String[]{ "-put", localfilepath, testdir };
int res = ToolRunner.run(shell, argv);
Assert.assertEquals("put is working", ERROR, res);
String returned = out.toString();
Assert.assertTrue(" outputs Permission denied error message", ((returned.lastIndexOf("Permission denied")) != (-1)));
// Tests for copyFromLocal
argv = new String[]{ "-copyFromLocal", localfilepath, testdir };
res = ToolRunner.run(shell, argv);
Assert.assertEquals("copyFromLocal -f is working", ERROR, res);
returned = out.toString();
Assert.assertTrue(" outputs Permission denied error message", ((returned.lastIndexOf("Permission denied")) != (-1)));
} finally {
if (bak != null) {
System.setErr(bak);
}
if (null != shell)
shell.close();
if (localFile.exists())
localFile.delete();
TestDFSShell.dfs.delete(hdfsTestDir, true);
}
}
/**
* Test -setrep with a replication factor that is too low. We have to test
* this here because the mini-miniCluster used with testHDFSConf.xml uses a
* replication factor of 1 (for good reason).
*/
@Test(timeout = 30000)
public void testSetrepLow() throws Exception {
Configuration conf = new Configuration();
conf.setInt(DFS_NAMENODE_REPLICATION_MIN_KEY, 2);
MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
MiniDFSCluster cluster = builder.numDataNodes(2).format(true).build();
FsShell shell = new FsShell(conf);
cluster.waitActive();
final String testdir = "/tmp/TestDFSShell-testSetrepLow";
final Path hdfsFile = new Path(testdir, "testFileForSetrepLow");
final PrintStream origOut = System.out;
final PrintStream origErr = System.err;
try {
final FileSystem fs = cluster.getFileSystem();
Assert.assertTrue("Unable to create test directory", fs.mkdirs(new Path(testdir)));
fs.create(hdfsFile, true).close();
// Capture the command output so we can examine it
final ByteArrayOutputStream bao = new ByteArrayOutputStream();
final PrintStream capture = new PrintStream(bao);
System.setOut(capture);
System.setErr(capture);
final String[] argv = new String[]{ "-setrep", "1", hdfsFile.toString() };
try {
Assert.assertEquals("Command did not return the expected exit code", 1, shell.run(argv));
} finally {
System.setOut(origOut);
System.setErr(origErr);
}
Assert.assertTrue(("Error message is not the expected error message" + (bao.toString())), bao.toString().startsWith(("setrep: Requested replication factor of 1 is less than " + ("the required minimum of 2 for /tmp/TestDFSShell-" + "testSetrepLow/testFileForSetrepLow"))));
} finally {
shell.close();
cluster.shutdown();
}
}
// setrep for file and directory.
@Test(timeout = 30000)
public void testSetrep() throws Exception {
FsShell shell = null;
final String testdir1 = "/tmp/TestDFSShell-testSetrep-" + (TestDFSShell.counter.getAndIncrement());
final String testdir2 = testdir1 + "/nestedDir";
final Path hdfsFile1 = new Path(testdir1, "testFileForSetrep");
final Path hdfsFile2 = new Path(testdir2, "testFileForSetrep");
final Short oldRepFactor = new Short(((short) (2)));
final Short newRepFactor = new Short(((short) (3)));
try {
String[] argv;
Assert.assertThat(TestDFSShell.dfs.mkdirs(new Path(testdir2)), CoreMatchers.is(true));
shell = new FsShell(TestDFSShell.dfs.getConf());
TestDFSShell.dfs.create(hdfsFile1, true).close();
TestDFSShell.dfs.create(hdfsFile2, true).close();
// Tests for setrep on a file.
argv = new String[]{ "-setrep", newRepFactor.toString(), hdfsFile1.toString() };
Assert.assertThat(shell.run(argv), CoreMatchers.is(SUCCESS));
Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile1).getReplication(), CoreMatchers.is(newRepFactor));
Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile2).getReplication(), CoreMatchers.is(oldRepFactor));
// Tests for setrep
// Tests for setrep on a directory and make sure it is applied recursively.
argv = new String[]{ "-setrep", newRepFactor.toString(), testdir1 };
Assert.assertThat(shell.run(argv), CoreMatchers.is(SUCCESS));
Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile1).getReplication(), CoreMatchers.is(newRepFactor));
Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile2).getReplication(), CoreMatchers.is(newRepFactor));
} finally {
if (shell != null) {
shell.close();
}
}
}
@Test(timeout = 300000)
public void testAppendToFile() throws Exception {
final int inputFileLength = 1024 * 1024;
File testRoot = new File(TestDFSShell.TEST_ROOT_DIR, "testAppendtoFileDir");
testRoot.mkdirs();
File file1 = new File(testRoot, "file1");
File file2 = new File(testRoot, "file2");
TestDFSShell.createLocalFileWithRandomData(inputFileLength, file1);
TestDFSShell.createLocalFileWithRandomData(inputFileLength, file2);
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
cluster.waitActive();
try {
FileSystem dfs = cluster.getFileSystem();
Assert.assertTrue(("Not a HDFS: " + (getUri())), (dfs instanceof DistributedFileSystem));
// Run appendToFile once, make sure that the target file is
// created and is of the right size.
Path remoteFile = new Path("/remoteFile");
FsShell shell = new FsShell();
shell.setConf(conf);
String[] argv = new String[]{ "-appendToFile", file1.toString(), file2.toString(), remoteFile.toString() };
int res = ToolRunner.run(shell, argv);
Assert.assertThat(res, CoreMatchers.is(0));
Assert.assertThat(dfs.getFileStatus(remoteFile).getLen(), CoreMatchers.is((((long) (inputFileLength)) * 2)));
// Run the command once again and make sure that the target file
// size has been doubled.
res = ToolRunner.run(shell, argv);
Assert.assertThat(res, CoreMatchers.is(0));
Assert.assertThat(dfs.getFileStatus(remoteFile).getLen(), CoreMatchers.is((((long) (inputFileLength)) * 4)));
} finally {
cluster.shutdown();
}
}
@Test(timeout = 300000)
public void testAppendToFileBadArgs() throws Exception {
final int inputFileLength = 1024 * 1024;
File testRoot = new File(TestDFSShell.TEST_ROOT_DIR, "testAppendToFileBadArgsDir");
testRoot.mkdirs();
File file1 = new File(testRoot, "file1");
TestDFSShell.createLocalFileWithRandomData(inputFileLength, file1);
// Run appendToFile with insufficient arguments.
FsShell shell = new FsShell();
shell.setConf(TestDFSShell.dfs.getConf());
String[] argv = new String[]{ "-appendToFile", file1.toString() };
int res = ToolRunner.run(shell, argv);
Assert.assertThat(res, CoreMatchers.not(0));
// Mix stdin with other input files. Must fail.
Path remoteFile = new Path("/remoteFile");
argv = new String[]{ "-appendToFile", file1.toString(), "-", remoteFile.toString() };
res = ToolRunner.run(shell, argv);
Assert.assertThat(res, CoreMatchers.not(0));
}
@Test(timeout = 30000)
public void testSetXAttrPermission() throws Exception {
UserGroupInformation user = UserGroupInformation.createUserForTesting("user", new String[]{ "mygroup" });
PrintStream bak = null;
try {
Path p = new Path("/foo");
TestDFSShell.dfs.mkdirs(p);
bak = System.err;
final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setErr(new PrintStream(out));
// No permission to write xattr
TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (448))));
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
Assert.assertEquals("Returned should be 1", 1, ret);
String str = out.toString();
Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1)));
out.reset();
return null;
}
});
int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
// No permission to read and remove
TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (488))));
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// Read
int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.a1", "/foo" });
Assert.assertEquals("Returned should be 1", 1, ret);
String str = out.toString();
Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1)));
out.reset();
// Remove
ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-x", "user.a1", "/foo" });
Assert.assertEquals("Returned should be 1", 1, ret);
str = out.toString();
Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1)));
out.reset();
return null;
}
});
} finally {
if (bak != null) {
System.setErr(bak);
}
}
}
/* HDFS-6413 xattr names erroneously handled as case-insensitive */
@Test(timeout = 30000)
public void testSetXAttrCaseSensitivity() throws Exception {
PrintStream bak = null;
try {
Path p = new Path("/mydir");
TestDFSShell.dfs.mkdirs(p);
bak = System.err;
final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "User.Foo", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo" }, new String[]{ });
doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "user.FOO", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO" }, new String[]{ });
doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "USER.foo", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO", "user.foo" }, new String[]{ });
doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "USER.fOo", "-v", "myval", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO", "user.foo", "user.fOo=\"myval\"" }, new String[]{ "user.Foo=", "user.FOO=", "user.foo=" });
doSetXattr(out, fshell, new String[]{ "-setfattr", "-x", "useR.foo", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO" }, new String[]{ "foo" });
doSetXattr(out, fshell, new String[]{ "-setfattr", "-x", "USER.FOO", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo" }, new String[]{ "FOO" });
doSetXattr(out, fshell, new String[]{ "-setfattr", "-x", "useR.Foo", "/mydir" }, new String[]{ "-getfattr", "-n", "User.Foo", "/mydir" }, new String[]{ }, new String[]{ "Foo" });
} finally {
if (bak != null) {
System.setOut(bak);
}
}
}
/**
* Test to make sure that user namespace xattrs can be set only if path has
* access and for sticky directorries, only owner/privileged user can write.
* Trusted namespace xattrs can be set only with privileged users.
*
* As user1: Create a directory (/foo) as user1, chown it to user1 (and
* user1's group), grant rwx to "other".
*
* As user2: Set an xattr (should pass with path access).
*
* As user1: Set an xattr (should pass).
*
* As user2: Read the xattr (should pass). Remove the xattr (should pass with
* path access).
*
* As user1: Read the xattr (should pass). Remove the xattr (should pass).
*
* As user1: Change permissions only to owner
*
* As User2: Set an Xattr (Should fail set with no path access) Remove an
* Xattr (Should fail with no path access)
*
* As SuperUser: Set an Xattr with Trusted (Should pass)
*/
@Test(timeout = 30000)
public void testSetXAttrPermissionAsDifferentOwner() throws Exception {
final String root = "/testSetXAttrPermissionAsDifferentOwner";
final String USER1 = "user1";
final String GROUP1 = "supergroup";
final UserGroupInformation user1 = UserGroupInformation.createUserForTesting(USER1, new String[]{ GROUP1 });
final UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2", new String[]{ "mygroup2" });
final UserGroupInformation SUPERUSER = UserGroupInformation.getCurrentUser();
PrintStream bak = null;
try {
TestDFSShell.dfs.mkdirs(new Path(root));
TestDFSShell.dfs.setOwner(new Path(root), USER1, GROUP1);
bak = System.err;
final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setErr(new PrintStream(out));
// Test 1. Let user1 be owner for /foo
user1.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final int ret = ToolRunner.run(fshell, new String[]{ "-mkdir", root + "/foo" });
Assert.assertEquals("Return should be 0", 0, ret);
out.reset();
return null;
}
});
// Test 2. Give access to others
user1.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// Give access to "other"
final int ret = ToolRunner.run(fshell, new String[]{ "-chmod", "707", root + "/foo" });
Assert.assertEquals("Return should be 0", 0, ret);
out.reset();
return null;
}
});
// Test 3. Should be allowed to write xattr if there is a path access to
// user (user2).
user2.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", root + "/foo" });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
return null;
}
});
// Test 4. There should be permission to write xattr for
// the owning user with write permissions.
user1.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", root + "/foo" });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
return null;
}
});
// Test 5. There should be permission to read non-owning user (user2) if
// there is path access to that user and also can remove.
user2.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// Read
int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.a1", root + "/foo" });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
// Remove
ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-x", "user.a1", root + "/foo" });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
return null;
}
});
// Test 6. There should be permission to read/remove for
// the owning user with path access.
user1.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
return null;
}
});
// Test 7. Change permission to have path access only to owner(user1)
user1.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// Give access to "other"
final int ret = ToolRunner.run(fshell, new String[]{ "-chmod", "700", root + "/foo" });
Assert.assertEquals("Return should be 0", 0, ret);
out.reset();
return null;
}
});
// Test 8. There should be no permissions to set for
// the non-owning user with no path access.
user2.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// set
int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a2", root + "/foo" });
Assert.assertEquals("Returned should be 1", 1, ret);
final String str = out.toString();
Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1)));
out.reset();
return null;
}
});
// Test 9. There should be no permissions to remove for
// the non-owning user with no path access.
user2.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// set
int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-x", "user.a2", root + "/foo" });
Assert.assertEquals("Returned should be 1", 1, ret);
final String str = out.toString();
Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1)));
out.reset();
return null;
}
});
// Test 10. Superuser should be allowed to set with trusted namespace
SUPERUSER.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// set
int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "trusted.a3", root + "/foo" });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
return null;
}
});
} finally {
if (bak != null) {
System.setErr(bak);
}
}
}
/* 1. Test that CLI throws an exception and returns non-0 when user does
not have permission to read an xattr.
2. Test that CLI throws an exception and returns non-0 when a non-existent
xattr is requested.
*/
@Test(timeout = 120000)
public void testGetFAttrErrors() throws Exception {
final UserGroupInformation user = UserGroupInformation.createUserForTesting("user", new String[]{ "mygroup" });
PrintStream bakErr = null;
try {
final Path p = new Path("/testGetFAttrErrors");
TestDFSShell.dfs.mkdirs(p);
bakErr = System.err;
final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setErr(new PrintStream(out));
// No permission for "other".
TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (448))));
{
final int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", p.toString() });
Assert.assertEquals("Returned should be 0", 0, ret);
out.reset();
}
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.a1", p.toString() });
String str = out.toString();
Assert.assertTrue("xattr value was incorrectly returned", ((str.indexOf("1234")) == (-1)));
out.reset();
return null;
}
});
{
final int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.nonexistent", p.toString() });
String str = out.toString();
Assert.assertTrue("xattr value was incorrectly returned", ((str.indexOf("getfattr: At least one of the attributes provided was not found")) >= 0));
out.reset();
}
} finally {
if (bakErr != null) {
System.setErr(bakErr);
}
}
}
/**
* Test that the server trash configuration is respected when
* the client configuration is not set.
*/
@Test(timeout = 30000)
public void testServerConfigRespected() throws Exception {
deleteFileUsingTrash(true, false);
}
/**
* Test that server trash configuration is respected even when the
* client configuration is set.
*/
@Test(timeout = 30000)
public void testServerConfigRespectedWithClient() throws Exception {
deleteFileUsingTrash(true, true);
}
/**
* Test that the client trash configuration is respected when
* the server configuration is not set.
*/
@Test(timeout = 30000)
public void testClientConfigRespected() throws Exception {
deleteFileUsingTrash(false, true);
}
/**
* Test that trash is disabled by default.
*/
@Test(timeout = 30000)
public void testNoTrashConfig() throws Exception {
deleteFileUsingTrash(false, false);
}
@Test(timeout = 30000)
public void testListReserved() throws IOException {
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
FileSystem fs = cluster.getFileSystem();
FsShell shell = new FsShell();
shell.setConf(conf);
FileStatus test = fs.getFileStatus(new Path("/.reserved"));
Assert.assertEquals(DOT_RESERVED_STRING, test.getPath().getName());
// Listing /.reserved/ should show 2 items: raw and .inodes
FileStatus[] stats = fs.listStatus(new Path("/.reserved"));
Assert.assertEquals(2, stats.length);
Assert.assertEquals(DOT_INODES_STRING, stats[0].getPath().getName());
Assert.assertEquals(conf.get(DFS_PERMISSIONS_SUPERUSERGROUP_KEY), stats[0].getGroup());
Assert.assertEquals("raw", stats[1].getPath().getName());
Assert.assertEquals(conf.get(DFS_PERMISSIONS_SUPERUSERGROUP_KEY), stats[1].getGroup());
// Listing / should not show /.reserved
stats = fs.listStatus(new Path("/"));
Assert.assertEquals(0, stats.length);
// runCmd prints error into System.err, thus verify from there.
PrintStream syserr = System.err;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setErr(ps);
try {
TestDFSShell.runCmd(shell, "-ls", "/.reserved");
Assert.assertEquals(0, baos.toString().length());
TestDFSShell.runCmd(shell, "-ls", "/.reserved/raw/.reserved");
Assert.assertTrue(baos.toString().contains("No such file or directory"));
} finally {
System.setErr(syserr);
cluster.shutdown();
}
}
@Test(timeout = 30000)
public void testMkdirReserved() throws IOException {
try {
TestDFSShell.dfs.mkdirs(new Path("/.reserved"));
Assert.fail("Can't mkdir /.reserved");
} catch (Exception e) {
// Expected, HadoopIllegalArgumentException thrown from remote
Assert.assertTrue(e.getMessage().contains("\".reserved\" is reserved"));
}
}
@Test(timeout = 30000)
public void testRmReserved() throws IOException {
try {
TestDFSShell.dfs.delete(new Path("/.reserved"), true);
Assert.fail("Can't delete /.reserved");
} catch (Exception e) {
// Expected, InvalidPathException thrown from remote
Assert.assertTrue(e.getMessage().contains("Invalid path name /.reserved"));
}
}
// (timeout = 30000)
@Test
public void testCopyReserved() throws IOException {
final File localFile = new File(TestDFSShell.TEST_ROOT_DIR, "testFileForPut");
localFile.createNewFile();
final String localfilepath = new Path(localFile.getAbsolutePath()).toUri().toString();
try {
TestDFSShell.dfs.copyFromLocalFile(new Path(localfilepath), new Path("/.reserved"));
Assert.fail("Can't copyFromLocal to /.reserved");
} catch (Exception e) {
// Expected, InvalidPathException thrown from remote
Assert.assertTrue(e.getMessage().contains("Invalid path name /.reserved"));
}
final String testdir = GenericTestUtils.getTempPath("TestDFSShell-testCopyReserved");
final Path hdfsTestDir = new Path(testdir);
TestDFSShell.writeFile(TestDFSShell.dfs, new Path(testdir, "testFileForPut"));
final Path src = new Path(hdfsTestDir, "srcfile");
TestDFSShell.dfs.create(src).close();
Assert.assertTrue(TestDFSShell.dfs.exists(src));
// runCmd prints error into System.err, thus verify from there.
PrintStream syserr = System.err;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setErr(ps);
try {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
TestDFSShell.runCmd(shell, "-cp", src.toString(), "/.reserved");
Assert.assertTrue(baos.toString().contains("Invalid path name /.reserved"));
} finally {
System.setErr(syserr);
}
}
@Test(timeout = 30000)
public void testChmodReserved() throws IOException {
// runCmd prints error into System.err, thus verify from there.
PrintStream syserr = System.err;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setErr(ps);
try {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
TestDFSShell.runCmd(shell, "-chmod", "777", "/.reserved");
Assert.assertTrue(baos.toString().contains("Invalid path name /.reserved"));
} finally {
System.setErr(syserr);
}
}
@Test(timeout = 30000)
public void testChownReserved() throws IOException {
// runCmd prints error into System.err, thus verify from there.
PrintStream syserr = System.err;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setErr(ps);
try {
FsShell shell = new FsShell(TestDFSShell.dfs.getConf());
TestDFSShell.runCmd(shell, "-chown", "user1", "/.reserved");
Assert.assertTrue(baos.toString().contains("Invalid path name /.reserved"));
} finally {
System.setErr(syserr);
}
}
@Test(timeout = 30000)
public void testSymLinkReserved() throws IOException {
try {
TestDFSShell.dfs.createSymlink(new Path("/.reserved"), new Path("/rl1"), false);
Assert.fail("Can't create symlink to /.reserved");
} catch (Exception e) {
// Expected, InvalidPathException thrown from remote
Assert.assertTrue(e.getMessage().contains("Invalid target name: /.reserved"));
}
}
@Test(timeout = 30000)
public void testSnapshotReserved() throws IOException {
final Path reserved = new Path("/.reserved");
try {
TestDFSShell.dfs.allowSnapshot(reserved);
Assert.fail("Can't allow snapshot on /.reserved");
} catch (FileNotFoundException e) {
Assert.assertTrue(e.getMessage().contains("Directory does not exist"));
}
try {
TestDFSShell.dfs.createSnapshot(reserved, "snap");
Assert.fail("Can't create snapshot on /.reserved");
} catch (FileNotFoundException e) {
Assert.assertTrue(e.getMessage().contains("Directory/File does not exist"));
}
}
}
| [
"[email protected]"
] | |
44553053d9d0a61dc7929ccd22b03423746d8368 | 4c1f4cb5e454b2d7b9bd6c006c2b4475a1e00e6b | /JPA/cassandra/src/main/java/nivance/jpa/cassandra/prepare/support/exception/CassandraInsufficientReplicasAvailableException.java | 35758fd04a0075498a4218e2d93dacd9c5483d88 | [] | no_license | nivance/OSGi_Project | cabfa6ed4b73481a64a6e2bd30d205ead86b0318 | 57347607207461a3c1cfd36ac87ab7acdab38ed1 | refs/heads/master | 2020-07-04T03:02:58.766971 | 2015-01-16T13:01:11 | 2015-01-16T13:01:11 | 29,348,180 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,556 | java | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 nivance.jpa.cassandra.prepare.support.exception;
import org.springframework.dao.TransientDataAccessException;
/**
* Spring data access exception for Cassandra when insufficient replicas are available for a given consistency level.
*
* @author Matthew T. Adams
*/
public class CassandraInsufficientReplicasAvailableException extends TransientDataAccessException {
private static final long serialVersionUID = 6415130674604814905L;
private int numberRequired;
private int numberAlive;
public CassandraInsufficientReplicasAvailableException(String msg) {
super(msg);
}
public CassandraInsufficientReplicasAvailableException(int numberRequired, int numberAlive, String msg,
Throwable cause) {
super(msg, cause);
this.numberRequired = numberRequired;
this.numberAlive = numberAlive;
}
public int getNumberRequired() {
return numberRequired;
}
public int getNumberAlive() {
return numberAlive;
}
}
| [
"[email protected]"
] | |
27cf4568090da43b4730734337274857c4f88116 | e0abcd6fb8d5f5bc884be64e9e2838ff43386e25 | /src/main/java/football/tickets/service/mapper/OrderMapper.java | df2a1a2186d171d00675e401757d7b1079fe90d2 | [] | no_license | Nazar-yo/football-tickets-app | 77754fb5566fecc6e01b763afb1a7bb01d9a96ac | 5a8d9c9eaef41a6a1fb8102c8e707cffc2a9a627 | refs/heads/main | 2023-06-12T13:53:03.097060 | 2021-07-09T19:36:06 | 2021-07-09T19:36:06 | 376,284,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,078 | java | package football.tickets.service.mapper;
import football.tickets.dto.response.OrderResponseDto;
import football.tickets.model.Order;
import football.tickets.model.Ticket;
import football.tickets.util.DateTimePatternUtil;
import java.time.format.DateTimeFormatter;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
@Component
public class OrderMapper implements ResponseDtoMapper<OrderResponseDto, Order> {
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(DateTimePatternUtil.DATE_TIME_PATTERN);
@Override
public OrderResponseDto mapToDto(Order order) {
OrderResponseDto responseDto = new OrderResponseDto();
responseDto.setId(order.getId());
responseDto.setUserId(order.getUser().getId());
responseDto.setOrderTime(order.getOrderTime().format(formatter));
responseDto.setTicketIds(order.getTickets()
.stream()
.map(Ticket::getId)
.collect(Collectors.toList()));
return responseDto;
}
}
| [
"[email protected]"
] | |
d4961b60287dfc4ade651c0bb165285dad860d3e | 6f2d0bb2639fc607b1ef9573b1aa606d63fe6f96 | /src/test/java/com/affinitas/sudoku/SudokuTestUtils.java | 77a9f8c1d5f7bf12b24afe64e2da826dd1712c38 | [] | no_license | ganoush/sudoku | fb756c7a11e28263fec9fa7539110978289721eb | c357393d3040f3accbff5c398a0d436e3303ebd1 | refs/heads/master | 2021-01-13T16:00:38.858531 | 2017-01-20T03:23:11 | 2017-01-20T03:23:11 | 76,747,249 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,135 | java | package com.affinitas.sudoku;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import java.nio.charset.Charset;
/**
* Created by ganeshnagarajan on 12/18/16.
*/
public class SudokuTestUtils {
public static int[][] SUDOKU_ONE_MOVE_FINISH={
{0,3,4,6,7,8,9,1,2},
{6,7,2,1,9,5,3,4,8},
{1,9,8,3,4,2,5,6,7},
{8,5,9,7,6,1,4,2,3},
{4,2,6,8,5,3,7,9,1},
{7,1,3,9,2,4,8,5,6},
{9,6,1,5,3,7,2,8,4},
{2,8,7,4,1,9,6,3,5},
{3,4,5,2,8,6,1,7,9}
};
public static int[][] SUDOKU_INVALID_MOVE={
{0,3,3,6,7,8,9,1,2},
{6,7,2,1,9,5,3,4,8},
{1,9,8,3,4,2,5,6,7},
{8,5,9,7,6,1,4,2,3},
{4,2,6,8,5,3,7,9,1},
{7,1,3,9,2,4,8,5,6},
{9,6,1,5,3,7,2,8,4},
{2,8,7,4,1,9,6,3,5},
{3,4,5,2,8,6,1,7,9}
};
public static int[][] SUDOKU_COMPLETION={
{5,3,4,6,7,8,9,1,2},
{6,7,2,1,9,5,3,4,8},
{1,9,8,3,4,2,5,6,7},
{8,5,9,7,6,1,4,2,3},
{4,2,6,8,5,3,7,9,1},
{7,1,3,9,2,4,8,5,6},
{9,6,1,5,3,7,2,8,4},
{2,8,7,4,1,9,6,3,5},
{3,4,5,2,8,6,1,7,9}
};
public static int[][] SUDOKU_INVALID_NUMBER={
{15,3,4,6,7,8,9,1,2},
{6,7,2,1,9,5,3,4,8},
{1,9,8,3,4,2,5,6,7},
{8,5,9,7,6,1,4,2,3},
{4,2,6,8,5,3,7,9,1},
{7,1,3,9,2,4,8,5,6},
{9,6,1,5,3,7,2,8,4},
{2,8,7,4,1,9,6,3,5},
{3,4,5,2,8,6,1,7,9}
};
public static final MediaType SUDOKU_REQUEST_JSON_TYPE = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8")
);
public static String asJsonString(final Object obj) {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| [
"[email protected]"
] | |
d7c0bceaea7448de904d2e501bae16681b2c7e17 | 27dced2adec698f50508e38c3a7db6e39f3b7d96 | /src/main/java/com/novarch/jojomod/entities/stands/dirtyDeedsDoneDirtCheap/EntityDirtyDeedsDoneDirtCheap.java | e4906b78b34ad6aa6eec8ecf312b5add660d2d68 | [] | no_license | kingcrimson-13/JoJo-s-Bizarre-Survival | 297a2755f5ac3fe2c314d1b700d91d61d4b2431d | 5ce4bdb8382b7c944ad955d73401bce8c01258c9 | refs/heads/master | 2022-11-15T20:45:52.424455 | 2020-06-24T19:07:18 | 2020-06-24T19:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,755 | java | package com.novarch.jojomod.entities.stands.dirtyDeedsDoneDirtCheap;
import com.novarch.jojomod.capabilities.stand.Stand;
import com.novarch.jojomod.entities.stands.EntityStandBase;
import com.novarch.jojomod.entities.stands.EntityStandPunch;
import com.novarch.jojomod.events.EventD4CTeleportProcessor;
import com.novarch.jojomod.init.DimensionInit;
import com.novarch.jojomod.init.EntityInit;
import com.novarch.jojomod.init.SoundInit;
import com.novarch.jojomod.util.DimensionHopTeleporter;
import com.novarch.jojomod.util.Util;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.server.ServerWorld;
import javax.annotation.ParametersAreNonnullByDefault;
@SuppressWarnings("ConstantConditions")
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
public class EntityDirtyDeedsDoneDirtCheap extends EntityStandBase {
private int oratick = 0;
private int oratickr = 0;
public EntityDirtyDeedsDoneDirtCheap(EntityType<? extends EntityStandBase> type, World world) {
super(type, world);
this.spawnSound = SoundInit.SPAWN_D4C.get();
this.standID = Util.StandID.dirtyDeedsDoneDirtCheap;
}
public EntityDirtyDeedsDoneDirtCheap(World world) {
super(EntityInit.D4C.get(), world);
this.spawnSound = SoundInit.SPAWN_D4C.get();
this.standID = Util.StandID.dirtyDeedsDoneDirtCheap;
}
/**
* Used to shorten the code of the method below, removing the need to make a <code>new</code> {@link DimensionHopTeleporter} every time {@link Entity}# changeDimension is called.
*
* @param entity The {@link Entity} that will be transported.
* @param type The {@link DimensionType} the entity will be transported to.
*/
private void changeDimension(DimensionType type, Entity entity) {
entity.changeDimension(type, new DimensionHopTeleporter((ServerWorld) entity.getEntityWorld(), entity.getPosX(), entity.getPosY(), entity.getPosZ()));
}
private void transportEntity(Entity entity) {
if (entity.world.getDimension().getType() == DimensionType.OVERWORLD)
changeDimension(DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE), entity);
else if (entity.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE))
changeDimension(DimensionType.OVERWORLD, entity);
else if (entity.world.getDimension().getType() == DimensionType.THE_NETHER)
changeDimension(DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER), entity);
else if (entity.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER))
changeDimension(DimensionType.THE_NETHER, entity);
else if (entity.world.getDimension().getType() == DimensionType.THE_END)
changeDimension(DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END), entity);
else if (entity.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END))
changeDimension(DimensionType.THE_END, entity);
}
private void changePlayerDimension(PlayerEntity player) {
if (player.world.getDimension().getType() == DimensionType.OVERWORLD)
EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE));
else if (player.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE))
EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.OVERWORLD);
else if (player.world.getDimension().getType() == DimensionType.THE_NETHER)
EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER));
else if (player.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER))
EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.THE_NETHER);
else if (player.world.getDimension().getType() == DimensionType.THE_END)
EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END));
else if (player.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END))
EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.THE_END);
}
@Override
public void tick() {
super.tick();
this.fallDistance = 0.0F;
if (getMaster() != null) {
PlayerEntity player = getMaster();
Stand.getLazyOptional(player).ifPresent(props -> {
if (props.getCooldown() > 0)
props.subtractCooldown(1);
player.addPotionEffect(new EffectInstance(Effects.RESISTANCE, 40, 2));
if ((player.world.getBlockState(new BlockPos(player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ() - 1)).getMaterial() != Material.AIR && player.world.getBlockState(new BlockPos(player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ() + 1)).getMaterial() != Material.AIR) || (player.world.getBlockState(new BlockPos(player.getPosition().getX() - 1, player.getPosition().getY(), player.getPosition().getZ())).getMaterial() != Material.AIR && player.world.getBlockState(new BlockPos(player.getPosition().getX() + 1, player.getPosition().getY(), player.getPosition().getZ())).getMaterial() != Material.AIR)) {
if (player.isCrouching() || player.isAirBorne) {
if (props.getAbility() && props.getCooldown() <= 0) {
changePlayerDimension(player);
world.getServer().getWorld(this.dimension).getEntities()
.filter(entity -> entity instanceof LivingEntity)
.filter(entity -> !(entity instanceof PlayerEntity))
.filter(entity -> !(entity instanceof EntityStandBase))
.filter(entity -> entity.getDistance(player) < 3.0f || entity.getDistance(this) < 3.0f)
.forEach(this::transportEntity);
world.getPlayers()
.stream()
.filter(playerEntity -> Stand.getCapabilityFromPlayer(playerEntity).getStandID() != Util.StandID.GER)
.filter(playerEntity -> player.getDistance(player) < 3.0f || playerEntity.getDistance(this) < 3.0f)
.forEach(this::changePlayerDimension);
player.getFoodStats().addStats(-3, 0.0f);
props.setStandOn(false);
props.setCooldown(200);
this.remove();
}
}
}
});
if (standOn) {
followMaster();
setRotationYawHead(player.rotationYaw);
setRotation(player.rotationYaw, player.rotationPitch);
if (!player.isAlive())
remove();
if (player.isSprinting()) {
if (attackSwing(player))
this.oratick++;
if (this.oratick == 1) {
if (!player.isCreative())
player.getFoodStats().addStats(-1, 0.0F);
if (!this.world.isRemote)
this.orarush = true;
}
} else if (attackSwing(getMaster())) {
if (!this.world.isRemote) {
this.oratick++;
if (this.oratick == 1) {
this.world.playSound(null, new BlockPos(this.getPosX(), this.getPosY(), this.getPosZ()), SoundInit.PUNCH_MISS.get(), getSoundCategory(), 1.0F, 0.8F / (this.rand.nextFloat() * 0.4F + 1.2F) + 0.5F);
EntityStandPunch.DirtyDeedsDoneDirtCheap dirtyDeedsDoneDirtCheap = new EntityStandPunch.DirtyDeedsDoneDirtCheap(this.world, this, player);
dirtyDeedsDoneDirtCheap.shoot(player, player.rotationPitch, player.rotationYaw, 2.0F, 0.2F);
this.world.addEntity(dirtyDeedsDoneDirtCheap);
}
}
}
if (player.swingProgressInt == 0)
this.oratick = 0;
if (this.orarush) {
player.setSprinting(false);
this.oratickr++;
if (this.oratickr >= 10)
if (!this.world.isRemote) {
player.setSprinting(false);
EntityStandPunch.DirtyDeedsDoneDirtCheap dirtyDeedsDoneDirtCheap1 = new EntityStandPunch.DirtyDeedsDoneDirtCheap(this.world, this, player);
dirtyDeedsDoneDirtCheap1.setRandomPositions();
dirtyDeedsDoneDirtCheap1.shoot(player, player.rotationPitch, player.rotationYaw, 2.0F, 0.2F);
this.world.addEntity(dirtyDeedsDoneDirtCheap1);
EntityStandPunch.DirtyDeedsDoneDirtCheap dirtyDeedsDoneDirtCheap2 = new EntityStandPunch.DirtyDeedsDoneDirtCheap(this.world, this, player);
dirtyDeedsDoneDirtCheap2.setRandomPositions();
dirtyDeedsDoneDirtCheap2.shoot(player, player.rotationPitch, player.rotationYaw, 2.0F, 0.2F);
this.world.addEntity(dirtyDeedsDoneDirtCheap2);
}
if (this.oratickr >= 80) {
this.orarush = false;
this.oratickr = 0;
}
}
}
}
}
}
| [
"[email protected]"
] | |
a7851e562d3e04e91012cb75c03dbb883d3c6594 | 3796020d9086ad76b298266776bc8114b293bb63 | /src/ventanas/GuardarEnArcade.java | b1086976df6498840a033041f040b98c0b45ab3a | [] | no_license | Ibaii99/AirFootball | b7cfee071d7874a585570c404262edb218ae8334 | e11a2aa01f6c1c06016c8ded815b775a27515313 | refs/heads/master | 2023-09-03T11:44:30.554364 | 2021-11-22T16:17:36 | 2021-11-22T16:17:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,074 | java | package ventanas;
import javax.swing.JFrame;
import entidades.BaseDeDatos;
import fisicas.FisicasNuevas;
import objetos.ScrollablePanel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
public class GuardarEnArcade extends JFrame {
private JTextField textField;
private JTable table;
/** Ventana donde salen los registros de las puntuaciones mas altas de arcade y donde guardamos nuestro registro
* @param bd
* @param fisicas
* @param ganadosArcade Partidos ganados en modo arcade
*/
public GuardarEnArcade(BaseDeDatos bd, FisicasNuevas fisicas, int ganadosArcade) {
setSize(474, 203);
ScrollablePanel panelClasificacion = new ScrollablePanel(new BorderLayout()); //Implementamos aqui la clase ScrollablePanel por problemas con el JScrollPane
panelClasificacion.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.FIT);
panelClasificacion.setScrollableHeight(ScrollablePanel.ScrollableSizeHint.STRETCH);
getContentPane().add(panelClasificacion, BorderLayout.CENTER);
DefaultTableModel model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Usuario");
model.addColumn("Partidas ganadas");
String header[] = { "Usuario", "Partidos ganados" };
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn column1 = table.getTableHeader().getColumnModel().getColumn(i);
column1.setHeaderValue(header[i]);
}
table.getTableHeader().setFont(table.getTableHeader().getFont().deriveFont(Font.BOLD));
anadirATabla(model, bd);
getContentPane().setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane(table);
panelClasificacion.add(scrollPane);
getContentPane().add(panelClasificacion);
JPanel panelNorte = new JPanel();
getContentPane().add(panelNorte, BorderLayout.NORTH);
JLabel lblUsuario = new JLabel("Usuario:");
panelNorte.add(lblUsuario);
textField = new JTextField();
panelNorte.add(textField);
textField.setColumns(10);
JButton btnGuardar = new JButton("Guardar");
panelNorte.add(btnGuardar);
btnGuardar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (textField.getText() == null || textField.getText() == "") {
JOptionPane.showMessageDialog(null, "Introduce el usuario.", "ERROR DE GUARDADO",
JOptionPane.WARNING_MESSAGE);
} else {
bd.init();
bd.getCon().createStatement().executeUpdate("INSERT INTO Arcade(Usuario, 'Partidos ganados') "
+ "VALUES ('" + textField.getText() + "', " + ganadosArcade + ");");
bd.close();
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "NO SE HA PODIDO INTRODUCIR A LA BASE DE DATOS", "ERROR",
JOptionPane.WARNING_MESSAGE);
e1.printStackTrace();
}
Inicio i = new Inicio(bd, fisicas);
i.setVisible(true);
dispose();
}
});
setVisible(true);
}
private void anadirATabla(DefaultTableModel model, BaseDeDatos bd) {
try {
bd.init();
String query = "SELECT * FROM ARCADE ORDER BY \"Partidos Ganados\" DESC;";
ResultSet rs = bd.getCon().createStatement().executeQuery(query);
while (rs.next()) {
String nombre = rs.getString("Usuario");
int ganados = rs.getInt("Partidos Ganados");
model.addRow(new Object[] { nombre, ganados });
}
rs.close();
bd.close();
} catch (Exception eee) {
eee.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
8a9af205a7018411129f749f62209e7fdd54c4f3 | a1aa05955e90a73e4fe38c2bd9eab6456a974c50 | /src/optimization/genetic/operator/mutation/MutationByDistribution.java | 8ca6b0c53f13b1e96eb5ceb025ee13aa8ee009fa | [] | no_license | game013/EvolutiveComputation | ae429afc86979fa40ebfa6b0c0ca1aefdd8fbc5e | fd31d0be7f0a6192213cbd7f449f8530d00300d5 | refs/heads/master | 2021-01-24T18:57:25.904491 | 2017-06-02T04:23:52 | 2017-06-02T04:23:52 | 84,480,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,501 | java | /**
* COPYRIGHT (C) 2015. All Rights Reserved.
*/
package optimization.genetic.operator.mutation;
import java.util.Optional;
import optimization.distribution.Distribution;
import optimization.distribution.ParametricalDistribution;
import optimization.function.fitness.Function;
import optimization.function.space.Space;
import optimization.util.type.Solution;
import optimization.util.type.SolutionParameter;
import optimization.util.type.constant.ParameterName;
/**
* @author Oscar Garavito
*
*/
public class MutationByDistribution<C> implements GeneticMutator<double[], C> {
/**
* Distribution to be used in variation.
*/
private final Distribution distribution;
/**
* @param distribution
*/
public MutationByDistribution(Distribution distribution) {
this.distribution = distribution;
}
/*
* (non-Javadoc)
* @see
* optimization.genetic.operator.mutation.GeneticMutator#mutate(optimization
* .util.type.Solution, optimization.function.fitness.Function,
* optimization.function.space.Space)
*/
@Override
public Solution<double[], C> mutate(Solution<double[], C> child, Function<double[], C> fitnessFunction,
Space<double[]> space) {
// Mutation of endogenous parameter
Optional<SolutionParameter> parameters = child.getParameters();
if (parameters.isPresent() && Math.random() < 0.05) {
double oldSigma = (double) parameters.get().get(ParameterName.SIGMA);
double alpha = 1.0 + 1.0 / Math.sqrt(20);
double newSigma = Math.random() >= 0.5 ? oldSigma * alpha : oldSigma / alpha;
parameters.get().set(ParameterName.SIGMA, newSigma);
}
if (ParametricalDistribution.class.isAssignableFrom(this.distribution.getClass())) {
((ParametricalDistribution) this.distribution).setParameters(parameters);
}
Solution<double[], C> solution = GeneticMutator.super.mutate(child, fitnessFunction, space);
return solution;
}
/*
* (non-Javadoc)
* @see
* optimization.genetic.operator.GeneticMutator#mutate(java.lang.Object,
* optimization.function.fitness.Function,
* optimization.function.space.Space)
*/
@Override
public double[] mutate(double[] origin, Function<double[], C> fitnessFunction, Space<double[]> space) {
double[] result = new double[origin.length];
for (int i = 0; i < origin.length; i++) {
double delta = distribution.nextRandom();
result[i] = delta + origin[i];
}
return result;
}
/**
* @return the distribution
*/
public Distribution getDistribution() {
return distribution;
}
}
| [
"[email protected]"
] | |
18a62610fe603df3c20cdaa20ccc33e761fa0587 | dbea5534f5f53f5bb206cd007d6bf9de6b81aaf1 | /src/main/java/com/example/course/controller/CourseTypeController.java | f0f40994d83abb8e1ac6b0fb49d055b592737921 | [] | no_license | nicexgk/course | edad4bc9a1015053a0d2c7186e9abdcf5bba9a71 | 86076704eada7bc2e6aa30c0c2cdfcd8deac90e9 | refs/heads/master | 2020-04-30T08:59:33.329330 | 2019-03-24T16:09:15 | 2019-03-24T16:09:15 | 176,733,728 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 764 | java | package com.example.course.controller;
import com.example.course.entity.CourseType;
import com.example.course.service.CourseTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
@RestController
@RequestMapping("/course")
public class CourseTypeController {
@Autowired
CourseTypeService courseTypeService;
@RequestMapping("/type/catalog")
public ArrayList<CourseType> courseTypeCatalog(){
ArrayList<CourseType> courseTypeList = courseTypeService.courseTypeNavigation();
return courseTypeList;
}
}
| [
"[email protected]"
] | |
41ecb51f6ed47a0200b01c645bf2d7d960826134 | f4e15ee34808877459d81fd601d6be03bdfb4a9d | /org/fourthline/cling/registry/RegistrationException.java | e1b953845245b8b6f43a3bde891e61c9a3ad38ce | [] | no_license | Lianite/wurm-server-reference | 369081debfa72f44eafc6a080002c4a3970f8385 | e4dd8701e4af13901268cf9a9fa206fcb5196ff0 | refs/heads/master | 2023-07-22T16:06:23.426163 | 2020-04-07T23:15:35 | 2020-04-07T23:15:35 | 253,933,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 692 | java | //
// Decompiled by Procyon v0.5.30
//
package org.fourthline.cling.registry;
import org.fourthline.cling.model.ValidationError;
import java.util.List;
public class RegistrationException extends RuntimeException
{
public List<ValidationError> errors;
public RegistrationException(final String s) {
super(s);
}
public RegistrationException(final String s, final Throwable throwable) {
super(s, throwable);
}
public RegistrationException(final String s, final List<ValidationError> errors) {
super(s);
this.errors = errors;
}
public List<ValidationError> getErrors() {
return this.errors;
}
}
| [
"[email protected]"
] | |
004473548c98114b19509050b985027559307074 | a5cc431cc84994751051e23d91e17a0a6a85ff5f | /app/src/main/java/com/udacity/popularmovies/events/DownloadedMovieListEvent.java | 455f691203f12655cfc93b9af3bdd5339c12deb1 | [
"MIT"
] | permissive | erickprieto/UdacityPopularMoviesApp | 12ecd0b5d4c17a71ac3de61e971273d78ab2e700 | 1a1fa732b8d9101f2ec3531e9880a71fb26eed6a | refs/heads/master | 2020-04-01T06:31:23.397791 | 2018-11-11T04:50:15 | 2018-11-11T04:50:15 | 108,640,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package com.udacity.popularmovies.events;
import com.udacity.popularmovies.models.Movie;
import java.util.List;
public class DownloadedMovieListEvent {
private boolean popularMovie;
private List<Movie> modelos;
public DownloadedMovieListEvent(List<Movie> modelos, boolean popularMovie) {
this.modelos = modelos;
this.popularMovie = popularMovie;
}
public List<Movie> getModelos() {
return modelos;
}
public void setModelos(List<Movie> modelos) {
this.modelos = modelos;
}
public boolean isPopularMovie() {
return popularMovie;
}
public void setPopularMovie(boolean popularMovie) {
this.popularMovie = popularMovie;
}
}
| [
"[email protected]"
] | |
5e121a25da2dbaa52b43e4be2fb2a9931386bbfa | 0912390024c0b9d11c85a48a462f1296260b5c55 | /app/src/main/java/com/demoapp/android/comics/Connect.java | 40b5ede3626cda11f4b6402cdfd18527ae6a398f | [] | no_license | yasir095/prjcom | 33c5c8b502953ee72d10e20d0f7935fd540af64d | 7f41175aa5430f13f7dd60e7e39503f7a3564365 | refs/heads/master | 2020-07-17T12:31:04.868426 | 2017-07-17T22:22:32 | 2017-07-17T22:22:32 | 94,318,440 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package com.demoapp.android.comics;
import com.demoapp.android.comics.helper.Utils;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
/**
* Created by yasirmahmood on 17/07/2017.
*/
public class Connect
{
@Inject Config config;
@Inject Utils utils;
private ComicApp app;
public Connect(ComicApp app) {
((ComicApp) app).getComponent().inject(this);
}
private Map<String, String> generateDefaultParams()
{
String ts = utils.getCurrentTimestamp();
HashMap<String, String> params = new HashMap<>();
params.put("apikey", config.getPublicApiKey());
params.put("ts", ts);
params.put("hash", utils.md5(ts+config.getPrivateApiKey()+config.getPublicApiKey()));
params.put("limit", "100");
return params;
}
}
| [
"[email protected]"
] | |
f03e225c52e06a004f3cc2422a6b046296857ab1 | aa60ca068c5d56bf494f502a8392ce0967ae97b5 | /advance-interview-practice/src/main/java/leetcode/contests/ContetsAE/Contests10.java | a6a9f605b8090b1bb8cf9ac019c99f0d83dc2dcf | [] | no_license | cyadav1010/spiceworks | 4c5727325ecaf25442133b2b0f0fca35d2e39227 | d7dc09824b81ae91395ec071e7f5fd6fa55dfbd5 | refs/heads/master | 2022-12-31T18:16:06.402553 | 2020-09-06T06:04:30 | 2020-09-06T06:04:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,319 | java | package leetcode.contests.ContetsAE;
import com.google.common.base.Strings;
import org.junit.Test;
import java.net.Inet4Address;
import java.sql.Struct;
import java.util.*;
import java.util.stream.IntStream;
public class Contests10 {
@Test
public void ContestsSolution() {
List<Integer> a = new ArrayList<>();
String s = "rrlrlrllrlrlrlrlrlrlrllrlrlrrrrlrlrlr";
// 37
// 1
// 5
// 2014650
a.add(2);
a.add(5);
a.add(4);
a.add(6);
a.add(8);
// System.out.println(segment(3, a));
String[] A = {"tars", "rats", "arts", "star"};
// System.out.println(numSimilarGroups(A));
int[][] graph = {{1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 1, 0, 0, 0, 0, 1},
{0, 0, 0, 1, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
{0, 0, 0, 0, 0, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 1, 1, 1, 1, 0, 1, 0, 0, 1}};
int[] in = {9, 0, 2};
// System.out.println(minMalwareSpread(graph, in));
int[] prices = {70, 4, 83, 56, 94, 72, 78, 43, 2, 86, 65, 100, 94, 56, 41, 66, 3, 33, 10, 3, 45, 94, 15, 12, 78, 60, 58, 0, 58, 15, 21, 7, 11, 41, 12, 96, 83, 77, 47, 62, 27, 19, 40, 63, 30, 4, 77, 52, 17, 57, 21, 66, 63, 29, 51, 40, 37, 6, 44, 42, 92, 16, 64, 33, 31, 51, 36, 0, 29, 95, 92, 35, 66, 91, 19, 21, 100, 95, 40, 61, 15, 83, 31, 55, 59, 84, 21, 99, 45, 64, 90, 25, 40, 6, 41, 5, 25, 52, 59, 61, 51, 37, 92, 90, 20, 20, 96, 66, 79, 28, 83, 60, 91, 30, 52, 55, 1, 99, 8, 68, 14, 84, 59, 5, 34, 93, 25, 10, 93, 21, 35, 66, 88, 20, 97, 25, 63, 80, 20, 86, 33, 53, 43, 86, 53, 55, 61, 77, 9, 2, 56, 78, 43, 19, 68, 69, 49, 1, 6, 5, 82, 46, 24, 33, 85, 24, 56, 51, 45, 100, 94, 26, 15, 33, 35, 59, 25, 65, 32, 26, 93, 73, 0, 40, 92, 56, 76, 18, 2, 45, 64, 66, 64, 39, 77, 1, 55, 90, 10, 27, 85, 40, 95, 78, 39, 40, 62, 30, 12, 57, 84, 95, 86, 57, 41, 52, 77, 17, 9, 15, 33, 17, 68, 63, 59, 40, 5, 63, 30, 86, 57, 5, 55, 47, 0, 92, 95, 100, 25, 79, 84, 93, 83, 93, 18, 20, 32, 63, 65, 56, 68, 7, 31, 100, 88, 93, 11, 43, 20, 13, 54, 34, 29, 90, 50, 24, 13, 44, 89, 57, 65, 95, 58, 32, 67, 38, 2, 41, 4, 63, 56, 88, 39, 57, 10, 1, 97, 98, 25, 45, 96, 35, 22, 0, 37, 74, 98, 14, 37, 77, 54, 40, 17, 9, 28, 83, 13, 92, 3, 8, 60, 52, 64, 8, 87, 77, 96, 70, 61, 3, 96, 83, 56, 5, 99, 81, 94, 3, 38, 91, 55, 83, 15, 30, 39, 54, 79, 55, 86, 85, 32, 27, 20, 74, 91, 99, 100, 46, 69, 77, 34, 97, 0, 50, 51, 21, 12, 3, 84, 84, 48, 69, 94, 28, 64, 36, 70, 34, 70, 11, 89, 58, 6, 90, 86, 4, 97, 63, 10, 37, 48, 68, 30, 29, 53, 4, 91, 7, 56, 63, 22, 93, 69, 93, 1, 85, 11, 20, 41, 36, 66, 67, 57, 76, 85, 37, 80, 99, 63, 23, 71, 11, 73, 41, 48, 54, 61, 49, 91, 97, 60, 38, 99, 8, 17, 2, 5, 56, 3, 69, 90, 62, 75, 76, 55, 71, 83, 34, 2, 36, 56, 40, 15, 62, 39, 78, 7, 37, 58, 22, 64, 59, 80, 16, 2, 34, 83, 43, 40, 39, 38, 35, 89, 72, 56, 77, 78, 14, 45, 0, 57, 32, 82, 93, 96, 3, 51, 27, 36, 38, 1, 19, 66, 98, 93, 91, 18, 95, 93, 39, 12, 40, 73, 100, 17, 72, 93, 25, 35, 45, 91, 78, 13, 97, 56, 40, 69, 86, 69, 99, 4, 36, 36, 82, 35, 52, 12, 46, 74, 57, 65, 91, 51, 41, 42, 17, 78, 49, 75, 9, 23, 65, 44, 47, 93, 84, 70, 19, 22, 57, 27, 84, 57, 85, 2, 61, 17, 90, 34, 49, 74, 64, 46, 61, 0, 28, 57, 78, 75, 31, 27, 24, 10, 93, 34, 19, 75, 53, 17, 26, 2, 41, 89, 79, 37, 14, 93, 55, 74, 11, 77, 60, 61, 2, 68, 0, 15, 12, 47, 12, 48, 57, 73, 17, 18, 11, 83, 38, 5, 36, 53, 94, 40, 48, 81, 53, 32, 53, 12, 21, 90, 100, 32, 29, 94, 92, 83, 80, 36, 73, 59, 61, 43, 100, 36, 71, 89, 9, 24, 56, 7, 48, 34, 58, 0, 43, 34, 18, 1, 29, 97, 70, 92, 88, 0, 48, 51, 53, 0, 50, 21, 91, 23, 34, 49, 19, 17, 9, 23, 43, 87, 72, 39, 17, 17, 97, 14, 29, 4, 10, 84, 10, 33, 100, 86, 43, 20, 22, 58, 90, 70, 48, 23, 75, 4, 66, 97, 95, 1, 80, 24, 43, 97, 15, 38, 53, 55, 86, 63, 40, 7, 26, 60, 95, 12, 98, 15, 95, 71, 86, 46, 33, 68, 32, 86, 89, 18, 88, 97, 32, 42, 5, 57, 13, 1, 23, 34, 37, 13, 65, 13, 47, 55, 85, 37, 57, 14, 89, 94, 57, 13, 6, 98, 47, 52, 51, 19, 99, 42, 1, 19, 74, 60, 8, 48, 28, 65, 6, 12, 57, 49, 27, 95, 1, 2, 10, 25, 49, 68, 57, 32, 99, 24, 19, 25, 32, 89, 88, 73, 96, 57, 14, 65, 34, 8, 82, 9, 94, 91, 19, 53, 61, 70, 54, 4, 66, 26, 8, 63, 62, 9, 20, 42, 17, 52, 97, 51, 53, 19, 48, 76, 40, 80, 6, 1, 89, 52, 70, 38, 95, 62, 24, 88, 64, 42, 61, 6, 50, 91, 87, 69, 13, 58, 43, 98, 19, 94, 65, 56, 72, 20, 72, 92, 85, 58, 46, 67, 2, 23, 88, 58, 25, 88, 18, 92, 46, 15, 18, 37, 9, 90, 2, 38, 0, 16, 86, 44, 69, 71, 70, 30, 38, 17, 69, 69, 80, 73, 79, 56, 17, 95, 12, 37, 43, 5, 5, 6, 42, 16, 44, 22, 62, 37, 86, 8, 51, 73, 46, 44, 15, 98, 54, 22, 47, 28, 11, 75, 52, 49, 38, 84, 55, 3, 69, 100, 54, 66, 6, 23, 98, 22, 99, 21, 74, 75, 33, 67, 8, 80, 90, 23, 46, 93, 69, 85, 46, 87, 76, 93, 38, 77, 37, 72, 35, 3, 82, 11, 67, 46, 53, 29, 60, 33, 12, 62, 23, 27, 72, 35, 63, 68, 14, 35, 27, 98, 94, 65, 3, 13, 48, 83, 27, 84, 86, 49, 31, 63, 40, 12, 34, 79, 61, 47, 29, 33, 52, 100, 85, 38, 24, 1, 16, 62, 89, 36, 74, 9, 49, 62, 89};
System.out.println(maxProfit(1000000000, prices));
}
public int maxProfit(int k, int[] prices) {
int n = prices.length;
System.out.println(n);
if (k == 0 || n <= 1) return 0;
int[][] dp = new int[2][n];
int min = prices[0];
int ans = 0;
if(k>n/2){
for (int i = 1; i < n; i++) {
ans+=Math.max(0, prices[i]-prices[i-1]);
}
return ans;
}
for (int i = 1; i < n; i++) {
if (prices[i] - min > 0) {
dp[0][i] = prices[i] - min;
ans = Math.max(ans, dp[0][i]);
}
min = Math.min(min, prices[i]);
}
for (int t = 2; t<=(n/2)+1 && t <= k; t++) {
int max = 0;
dp[1] = new int[n];
for (int last = 0; last < n; last++) {
if (dp[0][last] > 0) {
max = Math.max(dp[0][last], max);
}
if (max > 0 && last + 2 < n) {
min = prices[last + 1];
for (int i = last + 2; i < n; i++) {
if (prices[i] - min > 0) {
dp[1][i] = Math.max(dp[1][i], max + prices[i] - min);
ans = Math.max(ans, dp[1][i]);
}
min = Math.min(min, prices[i]);
}
}
}
dp[0] = dp[1];
}
return ans;
}
public int numSimilarGroups(String[] A) {
int l = A.length;
UnionFind unionFind = new UnionFind(l);
IntStream.range(0, l).forEach(i ->
IntStream.range(i + 1, l)
.forEach(j -> unionFind.group(A, i, j)));
return unionFind.result;
}
class UnionFind {
int parent[];
int result = 0;
UnionFind(Integer n) {
parent = new int[n];
IntStream.range(0, n).forEach(i -> parent[i] = i);
result = n;
}
public void group(String[] A, int i, int j) {
if (isSimilar(A[i], A[j])) {
union(i, j);
}
}
public int union(int i, int j) {
int p1 = findGroupId(i);
int p2 = findGroupId(j);
if (p1 == p2) {
return p1;
}
parent[p2] = p1;
result--;
return result;
}
public int findGroupId(int i) {
if (parent[i] == i) {
return i;
}
parent[i] = findGroupId(parent[i]);
return parent[i];
}
public boolean isSimilar(String a, String b) {
int l = a.length();
long diff = IntStream.range(0, l)
.filter(i -> a.charAt(i) != b.charAt(i))
.count();
return diff == 0 || diff == 2;
}
}
public static int segment(int x, List<Integer> space) {
int last = 0;
int n = space.size();
int max = 0;
for (int i = 1; i < x; i++) {
if (space.get(i) <= space.get(last)) {
last = i;
}
}
max = Math.max(max, space.get(last));
for (int i = x; i < n; ) {
if (i - x + 1 <= last) {
if (space.get(i) <= space.get(last)) {
last = i;
}
max = Math.max(max, space.get(last));
i++;
} else {
last++;
int t = last;
while (t <= i) {
if (space.get(t) <= space.get(last)) {
last = t;
}
t++;
}
}
}
return max;
}
public int minMalwareSpread(int[][] graph, int[] initial) {
int m = graph.length;
int n = graph[0].length;
List<Integer>[] network = new ArrayList[301];
IntStream.range(0, m).forEach(i ->
network[i] = new ArrayList<>());
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j -> {
if (graph[i][j] == 1) {
network[i].add(j);
network[j].add(i);
}
})
);
int l = initial.length;
boolean visited[] = new boolean[301];
int group[] = new int[301];
IntStream.range(0, l).forEach(i ->
group[initial[i]] = 1);
IntStream.range(0, l).forEach(i -> {
if (!visited[initial[i]])
dfsMaxGroup(network, initial[i], initial[i], group, visited);
});
int ans = -1;
int c = 0;
int tt = 0;
int ans2 = 0;
for (int i = 0; i < 301; i++) {
if (group[i] >= 1) {
if (c == 0) {
ans = i;
c = 1;
} else {
if (group[i] > group[ans]) {
ans = i;
}
}
} else {
if (group[i] == -1 && tt == 0) {
ans2 = i;
tt = 1;
}
}
}
return ans > 0 ? ans : ans2;
}
public int dfsMaxGroup(List<Integer>[] network, int prt, int node, int group[], boolean visited[]) {
if ((prt != node && group[node] == 1) || group[node] == -1) {
group[node] = -1;
return -1;
}
if (visited[node]) {
return 0;
}
visited[node] = true;
List<Integer> adjs = network[node];
int nodes = 1;
Map<Integer, Double> map = new HashMap<>();
for (int nd : adjs) {
int t = dfsMaxGroup(network, prt, nd, group, visited);
if (t == -1) {
if (group[node] == 1) {
group[node] = -1;
}
return -1;
}
nodes += t;
}
if (group[node] == 1) {
group[node] = nodes;
}
return nodes;
}
public static long prison(int n, int m, List<Integer> h, List<Integer> v) {
int hh = h.size();
int vv = v.size();
boolean[] hvis = new boolean[n + 2];
boolean[] vvis = new boolean[m + 2];
for (int i = 0; i < hh; i++) {
hvis[h.get(i)] = true;
}
for (int i = 0; i < vv; i++) {
vvis[v.get(i)] = true;
}
int hmax = 1;
int lastFound = 0;
for (int i = 1; i <= n + 1; i++) {
if (!hvis[i]) {
hmax = Math.max(hmax, i - lastFound);
lastFound = i;
}
}
int vmax = 1;
lastFound = 0;
for (int i = 1; i <= m + 1; i++) {
if (!vvis[i]) {
vmax = Math.max(vmax, i - lastFound);
lastFound = i;
}
}
return hmax * vmax;
}
}
| [
"[email protected]"
] | |
22016160da415a7c681a1086b08814e49ae71f4d | 92f0b33fc3c1dc4caf051edf31c5f42d2d9d5b88 | /SeleniumPractice/src/selpkg/FbSignUp.java | 5f1fbe932720bddd49bf2bf276362f9894a4a230 | [] | no_license | LavleenKaur/SeleniumPractice | f627fecda6ca0ae385bc06aea9b1247df27e9301 | bcba7b22f37b0b3ac7ce82cb9568837f77be119b | refs/heads/master | 2022-12-12T10:25:32.638224 | 2020-09-16T05:14:53 | 2020-09-16T05:14:53 | 294,924,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,028 | java | package selpkg;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class FbSignUp {
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver","../SeleniumPractice/chromedriver.exe");
ChromeDriver driver=new ChromeDriver();
driver.get("https://www.facebook.com");
driver.manage().window().maximize();
WebElement createacc=driver.findElement(By.id("u_0_2"));
createacc.click();
Thread.sleep(3000);
//driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
WebElement fname=driver.findElement(By.name("firstname"));
fname.sendKeys("Anne");
WebElement lname=driver.findElement(By.name("lastname"));
lname.sendKeys("Peterson");
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement email1=driver.findElement(By.id("u_1_g"));//id of email textbox
email1.sendKeys("[email protected]");
WebElement email2=driver.findElement(By.id("u_1_j"));//id of email textbox
email2.sendKeys("[email protected]");
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement newpass=driver.findElement(By.name("reg_passwd__"));
newpass.sendKeys("Anne@123");
WebElement dobday=driver.findElement(By.id("day"));
Select d=new Select(dobday);
d.selectByIndex(10);//selecting date 10 by passing the index from dropdown
WebElement dobmonth=driver.findElement(By.id("month"));
Select m=new Select(dobmonth);
m.selectByVisibleText("Jul");// selecting month July by passing the text from dropdown
WebElement dobyear=driver.findElement(By.id("year"));
Select y=new Select(dobyear);
y.selectByValue("1995");//passing value 1995
WebElement gender=driver.findElement(By.cssSelector("input[value='1']"));
gender.click();
WebElement signup=driver.findElement(By.name("websubmit"));
signup.click();
}
}
| [
"hp@hp"
] | hp@hp |
1d5b24e739787a6d52ef376e3a41a99a04a00273 | 670db6fc228ad7ef92aaad838415fb2e4143805b | /src/my/program/resumeemulator/ResumeActivity.java | 606f6e12d906911f344173283de44f52a93295cd | [] | no_license | seriizel/ResumeEmulator | fde05ce161e42f65a2888ebd58918e122b1c1e57 | 3b1e64b42d8cb928a08c6f87f4259c1d1638b333 | refs/heads/master | 2020-05-01T07:13:47.628136 | 2013-09-14T20:46:00 | 2013-09-14T20:46:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,084 | java | package my.program.resumeemulator;
import java.util.Calendar;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
public class ResumeActivity extends Activity {
private Button buttonDate, buttonSend;
private TextView textDate;
private Spinner spinnerGender;
private EditText editFIO, editPost, editSalary, editPhone, editEmail;
private int Year;
private int Month;
private int Day;
static final int DATE_DIALOG_ID = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resume);
buttonDate = (Button) findViewById(R.id.buttonDate);
buttonSend = (Button) findViewById(R.id.buttonSend);
textDate = (TextView) findViewById(R.id.textDate);
spinnerGender = (Spinner) findViewById(R.id.spinnerGender);
editFIO = (EditText) findViewById(R.id.editFIO);
editPost = (EditText) findViewById(R.id.editPost);
editSalary = (EditText) findViewById(R.id.editSalary);
editPhone = (EditText) findViewById(R.id.editPhone);
editEmail = (EditText) findViewById(R.id.editEmail);
Calendar c = Calendar.getInstance();
Year = c.get(Calendar.YEAR);
Month = c.get(Calendar.MONTH);
Day = c.get(Calendar.DAY_OF_MONTH);
buttonDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
buttonSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ResumeActivity.this, AnswerActivity.class);
intent.putExtra("Resume", editFIO.getText().toString()+"\n"
+ textDate.getText().toString()+"\n"
+ spinnerGender.getSelectedItem().toString()+"\n"
+ editPost.getText().toString()+"\n"
+ editSalary.getText().toString()+"\n"
+ editPhone.getText().toString()+"\n"
+ editEmail.getText().toString());
startActivity(intent);
}
});
updateDisplay();
}
private void updateDisplay() {
textDate.setText(
new StringBuilder()
.append(Day).append(".")
.append(Month+1).append(".")
.append(Year));
}
private DatePickerDialog.OnDateSetListener DateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, DateSetListener, Year, Month, Day);
}
}
| [
"[email protected]"
] | |
a16796f894dd12c2472f64d7d6be29a48a201d35 | cbee4fba2eb0794f679de498a69e340f80f58de2 | /app/src/main/java/com/gg/habittrain/SerialNumberHelper.java | e63898a08aa59660719aff97ff398e3869f8bdbd | [] | no_license | Andayoung/HabitTrain | 335b3407661e45507c9d00357de21e474449f85d | 79b9701722550b56b00e13471858482adfa5155d | refs/heads/master | 2021-01-01T15:37:35.315713 | 2017-07-19T01:06:25 | 2017-07-19T01:06:25 | 96,086,801 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,449 | java | package com.gg.habittrain;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* Created by Administrator on 2017/6/22 0022.
*/
public class SerialNumberHelper {
private Context context;
public SerialNumberHelper() {
}
public SerialNumberHelper(Context context) {
super();
this.context = context;
}
public void save2File(String text) {
try {
File path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if(!path.mkdirs()) {
Log.e("licence", "Directory not created");
}
File file=new File(path,"my.uu");
FileOutputStream output = new FileOutputStream(file);
output.write(text.getBytes("utf-8"));
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String read4File() {
StringBuilder sb = new StringBuilder("");
try {
File path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if(!path.mkdirs()) {
Log.e("licence", "Directory not created");
}
File file=new File(path, "my.uu");
FileInputStream input = new FileInputStream(file);
byte[] temp = new byte[1024];
int len = 0;
while ((len = input.read(temp)) > 0) {
sb.append(new String(temp, 0, len));
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public void deleteFile(){
File path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if(!path.mkdirs()) {
Log.e("licence", "Directory not created");
}
File file=new File(path, "my.uu");
if(file.isFile()&&file.exists()){
file.delete();
}
}
} | [
"[email protected]"
] | |
5365a211f124896ff7c669504b74b8d1631d19d7 | a2353927105bf7d503fe47f23b87c6cc7a75e27c | /src/test/java/pl/pateman/wiredi/testcomponents/impl/LettersOnlyRandomStringGenerator.java | b163ce0d79ad7f7f2ac6e6aaa9dd41eaf986695d | [
"Unlicense"
] | permissive | pateman/WireDI | e1e022e625af6f5ce29cbc51b66df1ceeb0f8562 | eee4fcecbe71da89ed2025ae370a1bffe84fbd42 | refs/heads/master | 2020-04-08T21:10:58.688958 | 2019-04-28T17:36:44 | 2019-04-28T17:36:44 | 159,733,168 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 704 | java | package pl.pateman.wiredi.testcomponents.impl;
import pl.pateman.wiredi.annotation.WireComponent;
import pl.pateman.wiredi.testcomponents.RandomStringGenerator;
import java.util.Random;
@WireComponent(name = "lettersOnlyRandomStringGenerator", multiple = true)
public class LettersOnlyRandomStringGenerator extends AbstractRandomStringGenerator implements RandomStringGenerator {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST";
private final Random random;
public LettersOnlyRandomStringGenerator() {
random = new Random();
}
@Override
public String generate() {
return getRandomString(ALPHABET, random, 6);
}
}
| [
"[email protected]"
] | |
49055873ab95ce70e76b318217f7324825f2910b | f7fbc015359f7e2a7bae421918636b608ea4cef6 | /base-one/tags/hsqldb_1_8_0_RC8/src/org/hsqldb/util/SqlServerTransferHelper.java | 9e583d8ac7d5007a57eb69bac4bb85099a4fa287 | [] | no_license | svn2github/hsqldb | cdb363112cbdb9924c816811577586f0bf8aba90 | 52c703b4d54483899d834b1c23c1de7173558458 | refs/heads/master | 2023-09-03T10:33:34.963710 | 2019-01-18T23:07:40 | 2019-01-18T23:07:40 | 155,365,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,200 | java | /* Copyright (c) 2001-2005, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.util;
import java.sql.Types;
// sqlbob@users 20020325 - patch 1.7.0 - reengineering
/**
* Conversions from SQLServer7 databases
*
* @version 1.7.0
*/
class SqlServerTransferHelper extends TransferHelper {
private boolean firstTinyintRow;
private boolean firstSmallintRow;
SqlServerTransferHelper() {
super();
}
SqlServerTransferHelper(TransferDb database, Traceable t, String q) {
super(database, t, q);
}
String formatTableName(String t) {
if (t == null) {
return t;
}
if (t.equals("")) {
return t;
}
if (t.indexOf(' ') != -1) {
return ("[" + t + "]");
} else {
return (formatIdentifier(t));
}
}
int convertFromType(int type) {
// MS SQL 7 specific problems (Northwind database)
if (type == 11) {
tracer.trace("Converted DATETIME (type 11) to TIMESTAMP");
type = Types.TIMESTAMP;
} else if (type == -9) {
tracer.trace("Converted NVARCHAR (type -9) to VARCHAR");
type = Types.VARCHAR;
} else if (type == -8) {
tracer.trace("Converted NCHAR (type -8) to VARCHAR");
type = Types.VARCHAR;
} else if (type == -10) {
tracer.trace("Converted NTEXT (type -10) to VARCHAR");
type = Types.VARCHAR;
} else if (type == -1) {
tracer.trace("Converted LONGTEXT (type -1) to LONGVARCHAR");
type = Types.LONGVARCHAR;
}
return (type);
}
void beginTransfer() {
firstSmallintRow = true;
firstTinyintRow = true;
}
Object convertColumnValue(Object value, int column, int type) {
// solves a problem for MS SQL 7
if ((type == Types.SMALLINT) && (value instanceof Integer)) {
if (firstSmallintRow) {
firstSmallintRow = false;
tracer.trace("SMALLINT: Converted column " + column
+ " Integer to Short");
}
value = new Short((short) ((Integer) value).intValue());
} else if ((type == Types.TINYINT) && (value instanceof Integer)) {
if (firstTinyintRow) {
firstTinyintRow = false;
tracer.trace("TINYINT: Converted column " + column
+ " Integer to Byte");
}
value = new Byte((byte) ((Integer) value).intValue());
}
return (value);
}
}
| [
"(no author)@7c7dc5f5-a22d-0410-a3af-b41755a11667"
] | (no author)@7c7dc5f5-a22d-0410-a3af-b41755a11667 |
56d514349bd610e23c6b825f47481327d5d7740c | a491e10b5d37084a704678a7dc3cf72c66e221fc | /jpa basic/practice6/src/main/java/hello/jpa/domain/item/Book.java | 01920a347c76e30c8a249a60179865cb47fa1452 | [] | no_license | YeomJaeSeon/jpa | 4a784210cdb78e0b71e4b591eb0ab29dceed0317 | cc5747d539c3ee19293cfd43340157764fcf241c | refs/heads/master | 2023-06-17T06:14:28.618269 | 2021-07-19T07:40:42 | 2021-07-19T07:40:42 | 371,958,152 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 434 | java | package hello.jpa.domain.item;
import javax.persistence.Entity;
@Entity
public class Book extends Item{
private String author;
private String isbn;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
}
| [
"[email protected]"
] | |
3912c9bb97e52ed8adb77a185f423ed24d0f3ab7 | 92f377ccf3e18a03e6fea09bf81b813e4c6f0cdd | /OpenWeatherMap/src/main/java/com/example/demo/service/CityInterface.java | 9303f7fc37763247a5ee0759d5a6245d454f7508 | [] | no_license | milosboskovic1991/OpenWeatherMap | c531049f29b03a06092abaf2bf0a7760b608d8ad | d55d6e427d66604da047e0d800999bb405d1ae3b | refs/heads/master | 2020-04-28T21:57:12.444565 | 2019-03-14T17:48:06 | 2019-03-14T17:48:06 | 175,600,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package com.example.demo.service;
import java.util.List;
import com.example.demo.entity.City;
import com.example.demo.entity.dto.CityDto;
public interface CityInterface {
public List<CityDto> findAll();
public City getCityByName(String name);
public List<City> getTemperatureForAllCities(List<City> cities);
public void updateCityTemperature();
}
| [
"[email protected]"
] | |
49c139e98e3f49225e57b27d81da29b9292c8ab2 | a048507c1807397329a558e84a5b0f69e66437d3 | /boot/boot/src/main/java/com/cimr/boot/utils/IdGener.java | b174f5b16da308ecbad9d2da9cf85d6ef84d1f4a | [] | no_license | jlf1997/learngit | 0ffd6fec5c6e9ad10ff14ff838396e1ef53a06f3 | d6d7eba1c0bf6c76f49608dd2537594af2cd4ee9 | refs/heads/master | 2021-01-17T07:10:30.004555 | 2018-11-08T09:15:13 | 2018-11-08T09:15:13 | 59,822,610 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,112 | java | package com.cimr.boot.utils;
public class IdGener {
private SnowflakeIdWorker idForRejectOrder;
private SnowflakeIdWorker idForOrder;
private SnowflakeIdWorker id;
private IdGener(){
idForOrder = new SnowflakeIdWorker(0, 0);
idForRejectOrder = new SnowflakeIdWorker(1, 0);
id = new SnowflakeIdWorker(2, 0);
}
public static IdGener getInstance(){
return Singleton.INSTANCE.getInstance();
}
private static enum Singleton{
INSTANCE;
private IdGener singleton;
//JVM会保证此方法绝对只调用一次
private Singleton(){
singleton = new IdGener();
}
public IdGener getInstance(){
return singleton;
}
}
/**
* 获取订单编号
* @return
*/
public long getOrderId() {
return idForOrder.nextId();
}
/**
* 获取退货单号
* @return
*/
public long getRejectOrderId() {
return idForRejectOrder.nextId();
}
public long getNormalId() {
return id.nextId();
}
}
| [
"[email protected]"
] | |
385542916850e2e917aa962b3c8abb488088d437 | 75dd6abb91d1ea8639acf97bb53ae1a44b73a91e | /src/main/java/com/xq/tmall/tmall05/dao/UserMapper.java | 04589505cb15b007b64416a66eba5fbe1b77bd0a | [
"Apache-2.0"
] | permissive | ZGM-zgm/Tmali | 068476444d8767fd55666f7ae335236b9075892d | a5304bc67166dea9c3f56c507319b86be13d136a | refs/heads/master | 2022-12-14T23:41:25.531539 | 2020-09-15T03:28:00 | 2020-09-15T03:28:00 | 293,762,502 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 767 | java | package com.xq.tmall.tmall05.dao;
import com.xq.tmall.tmall05.entity.User;
import com.xq.tmall.tmall05.util.OrderUtil;
import com.xq.tmall.tmall05.util.PageUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
Integer insertOne(@Param("user") User user);
Integer updateOne(@Param("user") User user);
List<User> select(@Param("user") User user, @Param("orderUtil") OrderUtil orderUtil, @Param("pageUtil") PageUtil pageUtil);
User selectOne(@Param("user_id") Integer user_id);
User selectByLogin(@Param("user_name") String user_name, @Param("user_password") String user_password);
Integer selectTotal(@Param("user") User user);
}
| [
"[email protected]"
] | |
7e594ea4ab997cfc5c7ae9f31dc2b9e65a41d997 | c03b0bf06f5dd0236b0ffbc655bb317cdac265ea | /EmpLeaveMngmnt3/src/com/manager/ManagerLogin.java | dc7b841fbead503f93999a4c04ecbb26ee53a482 | [] | no_license | mjay118/javatrainingg | de4a1d97f8cc0710b3ef9092592cc48a83612bc2 | c4450ef020c12dfa717419afaf85e189784b36af | refs/heads/main | 2023-06-22T00:38:50.335832 | 2021-02-10T19:26:15 | 2021-02-10T19:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,092 | java | package com.manager;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ManagerLogin extends HttpServlet {
Connection con=null;
PreparedStatement ps=null;
public void init(ServletConfig config) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/empMngmnt";
String uname = "root";
String pass = "1234";
try {
con = DriverManager.getConnection(url, uname, pass);
System.out.println(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String email=request.getParameter("email");
String password=request.getParameter("password");
String sql="select * from manager where email=? and password=?";
try {
ps=con.prepareStatement(sql);
ps.setString(1, email);
ps.setString(2, password);
HttpSession hs=request.getSession();
ResultSet rs = ps.executeQuery();
if(rs.next()) {
hs.setAttribute("semail", email);
hs.setAttribute("id", rs.getInt(1));
hs.setAttribute("name", rs.getString(2));
response.sendRedirect("./manager_home.html?msg=Login Suceessful");
}
else {
response.sendRedirect("./manager_login.html?msg=Login UnSuceessful");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
0e796814908e65b9e6947779876bd03e4c73d29e | 9ca7ea8ed22d19554bacc45e5005f7853fdbdd84 | /test/fiduciaryadvisor/OffshoreTest.java | ce6518a45d1d84daea2d0bc6812f102de271c4a1 | [] | no_license | tschultz1216/FiduciaryAdviser | 3d6f2218aaecff23c2af5357af0ddfae72a3bb1b | 9062f54a68f90ffe34c3d638fe1131c00f3a7e44 | refs/heads/master | 2020-03-16T03:22:49.316230 | 2018-05-08T13:03:17 | 2018-05-08T13:03:17 | 132,486,362 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,405 | java | package fiduciaryadvisor;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Leng Ghuy, Deborah Lawrence, Todd Schultz
* @class CSCI-338 Software Engineering
* @assignment Team Project - FiduciaryInvestmentAdviser
* @date May 8th, 2018
*/
public class OffshoreTest {
public OffshoreTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of calculate method, of class Offshore.
*/
@Test
public void testCalculate() {
System.out.println("calculate");
float money = 7000F;
int years = 40;
Offshore instance = new Offshore();
float expResult = 10422.046875F;
float result = instance.calculate(money, years);
assertEquals(expResult, result, 0.0001);
}
/**
* Test of getRisk method, of class Offshore.
*/
@Test
public void testGetRisk() {
System.out.println("getRisk");
Offshore instance = new Offshore();
boolean expResult = true;
boolean result = instance.getRisk();
assertEquals(expResult, result);
}
}
| [
"[email protected]"
] | |
69be543911cc4fd86deff47cdb6ab662583e878a | b8958890c54183b82100fd5d91229ab952c63dae | /DoctorsSprBoot/src/main/java/org/corona/DoctorDao.java | 87e7fb396fd0820ed9c4e56ea56a2fe33215b1c1 | [] | no_license | darkknight77/eclipse-workspace | 1250ddf1d0375c9139a961de4bcf56714646e56a | 9ddf02b4a753eb9f1e7d3418249d11cbbb8ba933 | refs/heads/master | 2022-12-24T14:46:44.814828 | 2020-09-21T15:53:54 | 2020-09-21T15:53:54 | 238,225,943 | 0 | 0 | null | 2022-12-16T05:24:56 | 2020-02-04T14:29:35 | JavaScript | UTF-8 | Java | false | false | 4,352 | java | package org.corona;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public class DoctorDao {
private static final Logger logger = Logger.getLogger(DoctorDao.class);
@Autowired
private EntityManagerFactory entityManagerFactory;
@SuppressWarnings("unchecked")
public List<DoctorModel> getDoctors() {
List<DoctorModel> doctors = new ArrayList<DoctorModel>();
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
/*
* Session session = null; try { session = sessionFactory.openSession();
* session.beginTransaction(); doctors =
* session.createQuery("From Doctors").list();
* System.out.println("Doctors are : " + doctors);
*
* } catch (Exception e) {} return doctors;
*/
return session.createQuery("FROM Doctors").list();
}
@SuppressWarnings("unchecked")
public List<DoctorModel> searchDoctors(String doctorName) {
List<DoctorModel> doctorsList = new ArrayList<DoctorModel>();
String query = "SELECT d.* FROM Doctors d WHERE d.Dname like '%" + doctorName + "%' ";
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
List<Object[]> doctorObjects =
session.createSQLQuery(query).list();
for (Object[] object : doctorObjects) {
int id = ((BigInteger) object[0]).intValue();
String name = (String) object[1];
float salary = (float) object[2];
String specialization = (String) object[3];
DoctorModel doctor = new DoctorModel(id, name, salary, specialization);
System.out.println(doctor);
doctorsList.add(doctor);
}
logger.info(doctorsList);
/*
* Session session = null; try {
*
* session = sessionFactory.openSession(); session.beginTransaction(); String
* query = "SELECT d.* FROM Doctors d WHERE d.Dname like '%" + doctorName +
* "%' "; List<Object[]> doctorObjects = session.createSQLQuery(query).list();
*
* for (Object[] object : doctorObjects) {
*
* int id = ((BigInteger) object[0]).intValue(); String name = (String)
* object[1]; float salary = (float) object[2]; String specialization = (String)
* object[3];
*
* DoctorModel doctor = new DoctorModel(id, name, salary, specialization);
* System.out.println(doctor); doctorsList.add(doctor); }
*
* logger.info(doctorsList);
*
* } catch (Exception e) { System.out.println("dao search doctors error");
* e.printStackTrace(); }
*
* return doctorsList;
*/
return doctorsList;
}
public DoctorModel getDoctor(int id) {
DoctorModel doctor = new DoctorModel();
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
doctor = (DoctorModel) session.get(DoctorModel.class, id);
/*
* Session session = null; try {
*
* session = sessionFactory.openSession(); session.beginTransaction(); doctor =
* (DoctorModel) session.get(DoctorModel.class, id); } catch (Exception e) {
* e.printStackTrace(); }
*
*/
return doctor;
}
public void updateDoctor(DoctorModel doctor) {
/*
* Session session = null;
*
* try { session = sessionFactory.openSession(); session.beginTransaction();
* session.saveOrUpdate(doctor); session.getTransaction().commit(); } catch
* (Exception e) { e.printStackTrace(); }
*/
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
session.beginTransaction();
session.saveOrUpdate(doctor);
session.getTransaction().commit();
}
public void deleteDoctor(int id) {
/*
* Session session = null; try { session = sessionFactory.openSession();
* session.beginTransaction(); session.delete(doctor);
* session.getTransaction().commit(); } catch (Exception e) {
* e.printStackTrace(); }
*/
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
session.beginTransaction();
DoctorModel doctor=session.get(DoctorModel.class,id);
session.delete(doctor);
session.getTransaction().commit();
}
}
| [
"[email protected]"
] | |
170f33b50662aa0883eec71a3bad48e94fdbe3ec | de2d2b955407d06269115dfb1558793967392f02 | /bai10_session_cookie_trong_spring/bai_tap/create_product_cart/src/main/java/vn/codegym/controller/ProductController.java | fef78f3ad03b25d4777d083791081145c86e4d15 | [] | no_license | khoa110298/NguyenKhoa_C0920G1_Module4 | 89ff3f29c10e395bee58da68ddde48b26c39fc48 | cb26b558ed4b89043c1739b3a08669b82b1a0218 | refs/heads/master | 2023-02-21T01:02:45.837677 | 2021-01-28T08:06:54 | 2021-01-28T08:06:54 | 325,424,265 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 782 | java | package vn.codegym.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import vn.codegym.service.ProductService;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
ProductService productService;
@GetMapping({"", "/list"})
public String listProduct(Model model) {
model.addAttribute("productList", productService.findAll());
return "/list";
}
@GetMapping("{id}/view")
public String formView(@PathVariable("id") Integer id, Model model) {
model.addAttribute("product", productService.findById(id));
return "view";
}
}
| [
"[email protected]"
] | |
917c5cd7d86e5e191c405f759dca8b6f249e407a | 9fce01d889bf907b87b618c97c4b83cd3a69155d | /gy/javaprog/_OOTPJava1/Feladatmegoldasok/13Szelekciok/Udvariassag/Udvariassag1.java | d968ed34240ea85f3bed5b81c431d9a2cd07b5d7 | [] | no_license | 8emi95/elte-ik-pt1 | c235dea0f11f90f96487f232ff9122497c86d4a6 | 45c24fe8436c29054b7a8ffecb2f55dbd3cb3f42 | refs/heads/master | 2020-04-29T09:16:14.310592 | 2019-03-16T19:48:50 | 2019-03-16T19:48:50 | 176,018,106 | 0 | 0 | null | null | null | null | ISO-8859-2 | Java | false | false | 1,099 | java | /*
* Feladatmegoldások/13. fejezet
* Udvariassag1.java
*
* Angster Erzsébet: OO tervezés és programozás, Java I. kötet
* 2001.02.01.
*/
import extra.*;
public class Udvariassag1 {
public static void main(String[] args) {
final int AKTEV = 2001;
int korZsofi = AKTEV-Console.readInt("Zsófi születési éve: ");
int korKati = AKTEV-Console.readInt("Kati születési éve: ");
int korJuli = AKTEV-Console.readInt("Juli születési éve: ");
if (korZsofi >= korKati && korKati >= korJuli)
System.out.println("Zsófi, Kati, Juli");
else if (korZsofi >= korJuli && korJuli >= korKati)
System.out.println("Zsófi, Juli, Kati");
else if (korKati >= korZsofi && korZsofi >= korJuli)
System.out.println("Kati, Zsófi, Juli");
else if (korKati >= korJuli && korJuli >= korZsofi)
System.out.println("Kati, Juli, Zsófi");
else if (korJuli >= korZsofi && korZsofi >= korKati)
System.out.println("Juli, Zsófi, Kati");
else //(korJuli >= korKati && korKati >= korZsofi)
System.out.println("Juli, Kati, Zsófi");
}
}
| [
"[email protected]"
] | |
a5515901793bce040e912fa219b6cc3cdb160947 | a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb | /domain-20180129/src/main/java/com/aliyun/domain20180129/models/QueryFailingReasonListForQualificationRequest.java | 75067eb1303101c6acbd1c845b288db382f3fcff | [
"Apache-2.0"
] | permissive | aliyun/alibabacloud-java-sdk | 83a6036a33c7278bca6f1bafccb0180940d58b0b | 008923f156adf2e4f4785a0419f60640273854ec | refs/heads/master | 2023-09-01T04:10:33.640756 | 2023-09-01T02:40:45 | 2023-09-01T02:40:45 | 288,968,318 | 40 | 45 | null | 2023-06-13T02:47:13 | 2020-08-20T09:51:08 | Java | UTF-8 | Java | false | false | 1,933 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.domain20180129.models;
import com.aliyun.tea.*;
public class QueryFailingReasonListForQualificationRequest extends TeaModel {
@NameInMap("InstanceId")
public String instanceId;
@NameInMap("Lang")
public String lang;
@NameInMap("Limit")
public Integer limit;
@NameInMap("QualificationType")
public String qualificationType;
@NameInMap("UserClientIp")
public String userClientIp;
public static QueryFailingReasonListForQualificationRequest build(java.util.Map<String, ?> map) throws Exception {
QueryFailingReasonListForQualificationRequest self = new QueryFailingReasonListForQualificationRequest();
return TeaModel.build(map, self);
}
public QueryFailingReasonListForQualificationRequest setInstanceId(String instanceId) {
this.instanceId = instanceId;
return this;
}
public String getInstanceId() {
return this.instanceId;
}
public QueryFailingReasonListForQualificationRequest setLang(String lang) {
this.lang = lang;
return this;
}
public String getLang() {
return this.lang;
}
public QueryFailingReasonListForQualificationRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
public Integer getLimit() {
return this.limit;
}
public QueryFailingReasonListForQualificationRequest setQualificationType(String qualificationType) {
this.qualificationType = qualificationType;
return this;
}
public String getQualificationType() {
return this.qualificationType;
}
public QueryFailingReasonListForQualificationRequest setUserClientIp(String userClientIp) {
this.userClientIp = userClientIp;
return this;
}
public String getUserClientIp() {
return this.userClientIp;
}
}
| [
"[email protected]"
] | |
7a83cd283621432fe6b5fa50e64b06ff009d6846 | df2cc5237efd95c9893cddc1dc345bde80b2319e | /ly-order/src/main/java/com/leyou/order/mapper/OrderDetailMapper.java | 8038ace9f38660113c441139389a35417436e58b | [] | no_license | risero/leyou | 2a32b0d396fac69f74a8c05d4108aa089ec51dd0 | 60eceb32a156c071c175690673d6b6bc4ea925f7 | refs/heads/master | 2022-12-22T06:13:20.020488 | 2019-05-24T00:57:29 | 2019-05-24T00:57:29 | 165,045,801 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 188 | java | package com.leyou.order.mapper;
import com.leyou.common.mapper.BaseMapper;
import com.leyou.order.pojo.OrderDetail;
public interface OrderDetailMapper extends BaseMapper<OrderDetail>{
}
| [
"risero/[email protected]"
] | risero/[email protected] |
303c2b97d1013d842bbd225559415b11095886cc | 75c4712ae3f946db0c9196ee8307748231487e4b | /src/main/java/com/alipay/api/domain/KoubeiMarketingToolIsvMerchantQueryModel.java | 0f773e5bf9216a7d9e588200b03071dc4e620e31 | [
"Apache-2.0"
] | permissive | yuanbaoMarvin/alipay-sdk-java-all | 70a72a969f464d79c79d09af8b6b01fa177ac1be | 25f3003d820dbd0b73739d8e32a6093468d9ed92 | refs/heads/master | 2023-06-03T16:54:25.138471 | 2021-06-25T14:48:21 | 2021-06-25T14:48:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 819 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* ISV查询商户列表接口
*
* @author auto create
* @since 1.0, 2017-08-04 15:15:46
*/
public class KoubeiMarketingToolIsvMerchantQueryModel extends AlipayObject {
private static final long serialVersionUID = 5542822888334852492L;
/**
* 页码
*/
@ApiField("page_num")
private String pageNum;
/**
* 每页大小
*/
@ApiField("page_size")
private String pageSize;
public String getPageNum() {
return this.pageNum;
}
public void setPageNum(String pageNum) {
this.pageNum = pageNum;
}
public String getPageSize() {
return this.pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
}
| [
"[email protected]"
] | |
8ee5071eb8efea1c0e6c0e75b255d92a8d9b43c8 | 0426e3ca5c4ab793305cfdfc648c914305f3ab6a | /app/src/test/java/com/example/fyl/androidtest/ExampleUnitTest.java | fdb586792a6805e0f6c011d877cf7a9d90b0ef0e | [] | no_license | fuyanli/VersionTest | a400eb50e000bee738aa0cd6b2e3f1172fed25f3 | 76875ee8e995aca9745c548903b8df17263ff234 | refs/heads/master | 2021-01-13T03:34:07.934510 | 2016-12-25T08:52:45 | 2016-12-25T08:52:45 | 77,313,105 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 405 | java | package com.example.fyl.androidtest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
07e6de543872b7b3d8acb468c0e127a3b83ce097 | e033c5750927060bcb30caa19e5f896f3de6dbd6 | /event-hook-example/src/main/java/com/nexse/swat/liferay/examples/hook/example2/GlobalPreEventAction.java | bb34cbadf756ca5174fcc213759c51e54a1a1fef | [] | no_license | ganeshvidyayug/liferay-playground | 53c4c97f3b948a2373375c2a578554a0c80d2718 | ecb3c915c1dd9d30878cbe8d1cf30e3c33d86d50 | refs/heads/master | 2020-04-19T16:13:55.150153 | 2012-09-26T14:50:57 | 2012-09-26T14:50:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 925 | java | package com.nexse.swat.liferay.examples.hook.example2;
import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GlobalPreEventAction extends Action {
private static final Log log = LogFactoryUtil.getLog(GlobalPreEventAction.class);
@Override
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
final String answer = request.getHeader("answer");
log.info("answer=" + answer);
if ("42".equals(answer)) {
log.info("the answer is correct, you shall pass");
} else {
throw new ActionException("the answer is incorrect, you shall not pass");
}
}
}
| [
"[email protected]"
] | |
ceb3d5852e71bbb9ba82fe162a120f896bc7d745 | 7466500a4bb756a067fcf8d16efdc8b5f5e9beb5 | /app/src/main/java/com/example/lamlethanhthe/studyhelper/MapsModules/DirectionFinderListener.java | a125db2c7bfd6fe5caf4b15b6fa6bb3a963193e5 | [] | no_license | lltthe/studyhelper | 9fe27579616b835caae206fd60c2218803343bdb | 4491e8392109a844ec64a0cd7c0638e5bff80832 | refs/heads/master | 2020-03-18T19:31:53.109900 | 2018-05-28T12:55:10 | 2018-05-28T12:55:10 | 135,159,891 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 269 | java | package com.example.lamlethanhthe.studyhelper.MapsModules;
import java.util.List;
/**
* Created by Mai Thanh Hiep on 4/3/2016.
*/
public interface DirectionFinderListener {
void onDirectionFinderStart();
void onDirectionFinderSuccess(List<Route> route);
}
| [
"[email protected]"
] | |
cb7bb5cd8670369f7e79d39d916bc5d1db3867d7 | 221da31486cdaeab91b1ed4962ac4f693954e18d | /MyApplication/app/src/main/java/com/example/myapplication/MainActivity.java | 5ddbc03e698c11f22a330c76181efcdcfde25f03 | [] | no_license | Ralpinn/AudioRecord | abe57a2621130a39456a613f97f74db9262ef953 | a10ce04c94e9070a30910f2ce8cd042d2634e0bf | refs/heads/master | 2023-01-14T17:52:49.299257 | 2020-11-17T12:00:07 | 2020-11-17T12:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,528 | java | package com.example.myapplication;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
MenuItem menuItem;
LinearLayout linearSearch;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearSearch = findViewById(R.id.linearSreach);
toolbar = findViewById(R.id.toolbar);
bottomNavigationView = findViewById(R.id.bottom_nav);
displayFragment(R.id.mnuInfo);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
displayFragment(item.getItemId());
return true;
}
});
// setSupportActionBar(toolbar);
}
private void displayFragment(int itemId) {
Fragment fragment = null;
switch (itemId){
case R.id.mnuHome:
toolbar.setVisibility(View.GONE);
linearSearch.setVisibility(View.VISIBLE);
fragment = new HomeFragment();
if(menuItem != null) {
menuItem.setVisible(false);
}
break;
case R.id.mnuAccount:
toolbar.setVisibility(View.GONE);
linearSearch.setVisibility(View.VISIBLE);
fragment = new AccountFragment();
break;
case R.id.mnuInfo:
toolbar.setVisibility(View.VISIBLE);
linearSearch.setVisibility(View.GONE);
setSupportActionBar(toolbar);
fragment = InfoFragment.newInstance("name", "name");
break;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content,fragment);
ft.commit();
}
}
| [
"[email protected]"
] | |
1c67d19f5fb281bb1d8df680763fdabc6e0e16f7 | 7541281283cc008353e48c5dc92c0b5ed87d77e1 | /src/com/ricky/chinaairpollution/PreferenceConnector.java | 11c86548dce658f16f02ef1150daff14b1eb5d71 | [] | no_license | orickyp/China-Air-Pollution | b1a242879b841399f97de6cc69df2bf35fe458f5 | 5f91dd8338d15cf6cd990e7f8772fac02d9ea084 | refs/heads/master | 2021-01-13T02:08:02.000105 | 2014-01-29T10:19:57 | 2014-01-29T10:19:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,914 | java | package com.ricky.chinaairpollution;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferenceConnector{
public static final int MODE = Context.MODE_PRIVATE;
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key, boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeFloat(Context context, String key, float value) {
getEditor(context).putFloat(key, value).commit();
}
public static float readFloat(Context context, String key, float defValue) {
return getPreferences(context).getFloat(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(Constants.PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
| [
"[email protected]"
] | |
f315a7919a1d0aa835dba113c77429ee6b4c7f89 | 7c5eda5713c05ea19cb6c536aa3589114848a68d | /Casestudy01/src/test/java/c3/Runner.java | d1477fd58304e79d54cfde276f330aca4f683b6f | [] | no_license | sushmavn05/sush | 679805e731e77d545fddb0cf88c653eea184d0c9 | ac97f376094d34c357c0b93a8146492eec7b000a | refs/heads/master | 2020-05-17T22:44:03.284715 | 2019-04-29T06:15:30 | 2019-04-29T06:15:30 | 184,010,999 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 146 | java | package c3;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
public class Runner {
}
| [
"[email protected]"
] | |
d011fc54eda5668440b7ab470d1c3e575daf8fd6 | 678ca04590085153844262e345491e6e18eef882 | /src/main/java/com/foxconn/fii/data/primary/repository/TestCpkSyncConfigRepository.java | 8bd31527fd56c6c244dae7abf7f0b063d9b398cd | [] | no_license | nguyencuongat97/test_system | 1e0bbbc404598b9c17c91b04d12ce3f76de315fb | 6d655a202b1f6571e3022dc1c7cfb8cb7e696fd5 | refs/heads/master | 2023-01-21T03:34:07.174133 | 2020-11-24T04:23:09 | 2020-11-24T04:23:09 | 315,518,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 364 | java | package com.foxconn.fii.data.primary.repository;
import com.foxconn.fii.data.primary.model.entity.TestCpkSyncConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface TestCpkSyncConfigRepository extends JpaRepository<TestCpkSyncConfig, Long> {
List<TestCpkSyncConfig> findAllByFactory(String factory);
}
| [
"[email protected]"
] | |
aa7d863199460ca7e99ebe4e7c8124ea82f81de3 | 4abcad5139f329a9182d5aded385ad6228a531ea | /src/main/java/project/model/Accounts.java | e2ee0e5d70c7083eae3f544ae0a065cc2442e062 | [] | no_license | phongltth1807075/ProjectSpringPrivate | 2e30bf0ce6c2fe758d2acd681ad31ef86b244ae2 | f6a3a35a47bb8df907057c353071740d9ab0387d | refs/heads/master | 2022-12-06T20:54:20.192598 | 2020-09-08T10:15:48 | 2020-09-08T10:15:48 | 293,818,134 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,914 | java | package project.model;
import javax.persistence.*;
import java.util.List;
@Entity
public class Accounts {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int accountId;
private String accountName;
private String phoneNumber;
private String email;
private String address;
private long createdAt;
private long updatedAt;
private long deletedAt;
private int gender;
private long birthday;
private int status;
private String password;
private String token;
@OneToOne(mappedBy = "accounts")
private Product product;
@ManyToMany(cascade = CascadeType.MERGE,fetch = FetchType.EAGER)
@JoinTable(name = "account_role",
joinColumns = @JoinColumn(name = "accountId"),
inverseJoinColumns = @JoinColumn(name = "roleId")
)
private List<Roles> rolesList;
public Accounts() {
}
public Accounts(String accountName, String phoneNumber, String email, String address, long createdAt, long updatedAt, long deletedAt, int gender, long birthday, int status, String password, String token, Product product, List<Roles> rolesList) {
this.accountName = accountName;
this.phoneNumber = phoneNumber;
this.email = email;
this.address = address;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.deletedAt = deletedAt;
this.gender = gender;
this.birthday = birthday;
this.status = status;
this.password = password;
this.token = token;
this.product = product;
this.rolesList = rolesList;
}
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public long getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(long updatedAt) {
this.updatedAt = updatedAt;
}
public long getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(long deletedAt) {
this.deletedAt = deletedAt;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public long getBirthday() {
return birthday;
}
public void setBirthday(long birthday) {
this.birthday = birthday;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public List<Roles> getRolesList() {
return rolesList;
}
public void setRolesList(List<Roles> rolesList) {
this.rolesList = rolesList;
}
}
| [
"[email protected]"
] | |
ace880d1ce340964ff5e3fa89848f1a348ec43a8 | 91e342347bce88e212d3d5d5ce92c26f5dd481cf | /creoson-json-const/src/com/simplifiedlogic/nitro/jshell/json/response/JLInterfaceResponseParams.java | 627264aaabfcf1a6c15797714912c83028757f99 | [
"MIT"
] | permissive | nexiles/creoson | 732d23bda6f59ee47d486b9ae91dee6f485c5a37 | 4e897be91841a5baa4b600097dd91d6140c18c44 | refs/heads/master | 2020-03-29T15:50:54.663265 | 2018-09-05T19:59:47 | 2018-09-05T19:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,557 | java | /*
* MIT LICENSE
* Copyright 2000-2018 Simplified Logic, Inc
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: The above copyright
* notice and this permission notice shall be included in all copies or
* substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",
* WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.simplifiedlogic.nitro.jshell.json.response;
/**
* Constants defining the JSON response parameters for the interface command
*
* @author Adam Andrews
*/
public interface JLInterfaceResponseParams {
// response fields
public static final String OUTPUT_FILENAME = "filename";
public static final String OUTPUT_DIRNAME = "dirname";
public static final String OUTPUT_MODEL = "file";
}
| [
"[email protected]"
] | |
41c340e9ea9343f42fd4684eb48a8a3d72810cfd | 8126110d26aed96860e8b3694725faff02cea1dc | /MyWorld.java | 059ddc2b44a6008a6d7c8f62fae1c59f7d97bccb | [] | no_license | buzhouke/mine-sweeping | d127491b1b6e9828b91d11148903f5a4bee30121 | 44edcba6099983c78ca80049edb7aa02be84a0b6 | refs/heads/master | 2022-11-23T07:17:51.491723 | 2020-07-27T13:54:05 | 2020-07-27T13:54:05 | 279,882,266 | 0 | 0 | null | 2020-07-15T14:02:19 | 2020-07-15T13:54:56 | null | UTF-8 | Java | false | false | 1,554 | java | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
/**
* Write a description of class MyWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MyWorld extends World
{
/**
* Constructor for objects of class MyWorld.
*
*/
public static Thunder[][] MyBlock = new Thunder[30][20];
public static Easy easy = new Easy(false,50);
public static Medium medium = new Medium(false,100);
public static Hard hard = new Hard(false,150);
public MyWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(800, 550, 1);
setBackground("Background.png");
//System.out.println("win!!");
long start = System.currentTimeMillis();
for(int i = 0;i < 30;i++){
for(int j = 0;j < 20;j++){
Thunder a = new Thunder(i,j,false);
addObject(a,i*25+38,j*25+38);
MyBlock[i][j] = a;
}
}
addObject(easy,200,230);
addObject(medium,400,230);
addObject(hard,600,230);
addObject(new Flag(),15,535);
addObject(new Help(),785,535);
easy.isStarted = false;
hard.isStarted = false;
medium.isStarted = false;
easy.getIt = false;
medium.getIt = false;
hard.getIt = false;
}
static Thunder[][] getClicked() {
return MyBlock;
}
}
| [
"[email protected]"
] | |
b89ba8308d7921966930d03268708462ed2a7c02 | 2d323b2fd7f40217d5c8bb8eb12614dcb4c0284f | /src/main/java/com/kudl/sidekick/pattern/observer/Observer.java | c9719d15e440b5b0d6f7d6c0595b4941062edf73 | [] | no_license | kudl/sidekick | a3105f7b8fb39112f44019cfbbc9139c206d6622 | 813f5df8be6cce2a2f08746af2208af745320968 | refs/heads/main | 2023-03-30T01:11:18.721251 | 2021-04-10T15:13:31 | 2021-04-10T15:13:31 | 309,612,768 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 144 | java | package com.kudl.sidekick.pattern.observer;
public interface Observer {
// Observer == Subscriber == Listener
void update(String message);
}
| [
"[email protected]"
] | |
8e2a6b62cb85b3fe1ee85307d3528257006c849b | fc9ee3227e167f8b3283207a41802680490dc415 | /src/javafxmvc/MainVenda.java | ec8bd2396b8a55a51b571f61a77c87397a45ce3f | [] | no_license | LucasGobbs/javafx-SistemaVidracaria | 4d592842c61339f7db1805d0a8f1bc08c80372ca | c111e2f0456008a496f264bef3a7fa4da2ed9454 | refs/heads/master | 2022-11-27T22:17:27.669779 | 2020-08-10T03:44:08 | 2020-08-10T03:44:08 | 285,979,637 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 667 | java | package javafxmvc;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainVenda extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("view/FXMLVenda.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Sistema de Vendas (JavaFX MVC)");
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| [
"[email protected]"
] | |
e06cb45b32521d61b221f7a8f3835d45d9b84772 | 69f98f9c73035e458b315bed2c1d43cc21f34e63 | /app/src/main/java/net/gringrid/siso/fragments/Sitter03GenderChildrenFragment.java | c6a3c07014b3366d1faac1bfe75e1efc8628d09d | [] | no_license | GrinGrid/siso | 31a80a392749d9a31796b330371b44aedca56b81 | c36f246bec74f057806d07e7c0ed759dadc98653 | refs/heads/master | 2020-04-12T10:38:08.301944 | 2017-01-03T13:23:59 | 2017-01-03T13:23:59 | 63,205,105 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,566 | java | package net.gringrid.siso.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import net.gringrid.siso.BaseActivity;
import net.gringrid.siso.R;
import net.gringrid.siso.models.User;
import net.gringrid.siso.util.SharedData;
import net.gringrid.siso.util.SisoUtil;
import net.gringrid.siso.views.SisoPicker;
import net.gringrid.siso.views.SisoToggleButton;
/**
* 구직정보 등록 > 기본정보 > 성별, 자녀정보
*/
public class Sitter03GenderChildrenFragment extends InputBaseFragment{
SisoToggleButton id_tg_btn_woman;
SisoToggleButton id_tg_btn_man;
int mRadioGender[] = new int[]{R.id.id_tg_btn_woman, R.id.id_tg_btn_man};
private TextView id_tv_next_btn;
private SisoPicker id_pk_daughter;
private SisoPicker id_pk_son;
public Sitter03GenderChildrenFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sitter03_gender_children, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
id_tv_next_btn = (TextView)view.findViewById(R.id.id_tv_next_btn);
id_tv_next_btn.setOnClickListener(this);
id_tg_btn_woman = (SisoToggleButton)view.findViewById(R.id.id_tg_btn_woman);
id_tg_btn_man = (SisoToggleButton)view.findViewById(R.id.id_tg_btn_man);
id_tg_btn_man.setOnClickListener(this);
id_tg_btn_woman.setOnClickListener(this);
id_pk_daughter = (SisoPicker)view.findViewById(R.id.id_pk_daughter);
id_pk_son = (SisoPicker)view.findViewById(R.id.id_pk_son);
loadData();
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: sitter2");
switch (v.getId()){
case R.id.id_tv_next_btn:
if(!isValidInput()) return;
saveData();
moveNext();
break;
case R.id.id_tg_btn_woman:
SisoUtil.selectRadio(mRadioGender, R.id.id_tg_btn_woman, getView());
break;
case R.id.id_tg_btn_man:
SisoUtil.selectRadio(mRadioGender, R.id.id_tg_btn_man, getView());
break;
}
}
@Override
protected void loadData() {
if(mUser.sitterInfo==null) return;
if(!TextUtils.isEmpty(mUser.sitterInfo.gender)){
if(mUser.sitterInfo.gender.equals(User.GENDER_WOMAN)){
id_tg_btn_woman.setChecked(true);
}else if(mUser.sitterInfo.gender.equals(User.GENDER_MAN)){
id_tg_btn_man.setChecked(true);
}
}
if(!TextUtils.isEmpty(mUser.sitterInfo.daughters)){
id_pk_daughter.setIndex(Integer.parseInt(mUser.sitterInfo.daughters));
}
if(!TextUtils.isEmpty(mUser.sitterInfo.sons)) {
id_pk_son.setIndex(Integer.parseInt(mUser.sitterInfo.sons));
}
}
@Override
protected boolean isValidInput() {
if(!SisoUtil.isRadioGroupSelected(mRadioGender, getView())){
SisoUtil.showErrorMsg(getContext(), R.string.invalid_gender_select);
return false;
}
return true;
}
@Override
protected void saveData() {
int gender = SisoUtil.getRadioValue(mRadioGender, getView());
int daughterNum = id_pk_daughter.getCurrentIndex();
int sonNum = id_pk_son.getCurrentIndex();
mUser.sitterInfo.gender = String.valueOf(gender);
mUser.sitterInfo.daughters = String.valueOf(daughterNum);
mUser.sitterInfo.sons = String.valueOf(sonNum);
Log.d(TAG, "onClick: mUser.sitterInfo : "+mUser.sitterInfo.toString());
SharedData.getInstance(getContext()).setObjectData(SharedData.USER, mUser);
}
@Override
protected void moveNext() {
CommonSkillFragment fragment = new CommonSkillFragment();
((BaseActivity) getActivity()).setFragment(fragment, R.string.sitter_basic_title);
}
}
| [
"[email protected]"
] | |
5490278106d8920d77043c4b30a1e3482f579e50 | 01089defe2f0d2baed6609c1128b0b91813f4053 | /src/main/java/com/github/dhaval_mehta/savetogoogledrive/config/SwaggerConfig.java | 8442d2030883cb11361f00fe055be2a11d598e8e | [
"MIT"
] | permissive | Riptide-11/cloud-transfer-backend | c695a388b0429bfa805887442fb94e33d30f306e | d49b210ddea079ea8ad0a6677895befbde9adfbd | refs/heads/master | 2022-12-04T15:41:19.501884 | 2020-08-25T14:37:12 | 2020-08-25T14:37:12 | 290,170,033 | 0 | 0 | MIT | 2020-08-25T09:18:11 | 2020-08-25T09:18:10 | null | UTF-8 | Java | false | false | 1,264 | java | package com.github.dhaval_mehta.savetogoogledrive.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false).select()
.apis(RequestHandlerSelectors
.basePackage("com.github.dhavalmehta1997.savetogoogledrive.controller.rest"))
.paths(PathSelectors.any()).build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Save to Drive Rest API")
.description("It is a free to upload file from url directly to Google Drive.")
.contact(new Contact("Riptide", null, "[email protected]")).version("1.0").build();
}
}
| [
"[email protected]"
] | |
546fcd353d1b3c226a8469d38a1983d990d98acc | da51dadb54086687353bedee1ad092a4cf53d5ae | /leetcode/94.二叉树的中序遍历.java | 4e36fecfa343fc3a8ba6c4ac996eb7eae9c98979 | [
"MIT"
] | permissive | liulixiang1988/algorithm | 9672d9fe65f58595a62050a21ab5dcf06e8c3635 | c58e5028651a3a124b90241720592f1a0c01a8fa | refs/heads/master | 2021-10-25T21:47:49.854983 | 2021-10-18T05:20:28 | 2021-10-18T05:20:28 | 199,172,561 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,232 | java | import java.util.ArrayList;
/*
* @lc app=leetcode.cn id=94 lang=java
*
* [94] 二叉树的中序遍历
*
* https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/
*
* algorithms
* Medium (68.57%)
* Likes: 309
* Dislikes: 0
* Total Accepted: 70.1K
* Total Submissions: 102.2K
* Testcase Example: '[1,null,2,3]'
*
* 给定一个二叉树,返回它的中序 遍历。
*
* 示例:
*
* 输入: [1,null,2,3]
* 1
* \
* 2
* /
* 3
*
* 输出: [1,3,2]
*
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
helper(root, list);
return list;
}
private void helper(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
helper(root.left, list);
list.add(root.val);
helper(root.right, list);
}
}
// @lc code=end
| [
"[email protected]"
] | |
d2d4971b481c57e602a001a701602ee93789c538 | 647762c3d8db6ca417fc9fd1e2ab87688fb0f68c | /app/src/main/java/com/example/fileencrypter/FileEnDecryptManager.java | f74d7dc36400ffc927c7cef27d2e28bd4c8948d7 | [] | no_license | sun98/FileEncrypter | 796ce0f916611cc976d210552cd71ef79bd559e5 | d21bad406ff14d5afa94e05f4db9c6942d8605b3 | refs/heads/master | 2020-03-21T02:07:26.250917 | 2018-06-20T04:47:52 | 2018-06-20T04:47:52 | 137,981,153 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,507 | java | package com.example.fileencrypter;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by Nibius at 2018/6/7 20:24.
*/
public class FileEnDecryptManager {
public static String key = "wenchen"; // 加密解密key
private String prefKey = "encrypted_files";
private Context context;
FileEnDecryptManager(Context context) {
this.context = context;
}
/**
* 加密入口
*
* @param fileUrl 文件绝对路径
* @return
*/
public boolean doEncrypt(String fileUrl) {
if (isDecrypted(fileUrl)) {
if (encrypt(fileUrl)) {
// 加密文件,同时在SharedPreference设置该文件已被加密过
SharedPreferences encrypted_files = context.getSharedPreferences(prefKey, MODE_PRIVATE);
SharedPreferences.Editor editor = encrypted_files.edit();
editor.putBoolean(fileUrl, false);
editor.apply();Toast.makeText(context, "加密成功!", Toast.LENGTH_LONG).show();
return true;
} else {
Toast.makeText(context, "加密失败!", Toast.LENGTH_LONG).show();
return false;
}
}
Toast.makeText(context, "文件已被加密过!", Toast.LENGTH_LONG).show();
return false;
}
private final int REVERSE_LENGTH = 28; // 加解密长度(Encryption length)
/**
* 加密或解密
*
* @param strFile 源文件绝对路径
* @return
*/
private boolean encrypt(String strFile) {
int len = REVERSE_LENGTH;
try {
File f = new File(strFile);
if (f.exists()) {
RandomAccessFile raf = new RandomAccessFile(f, "rw");
long totalLen = raf.length();
if (totalLen < REVERSE_LENGTH)
len = (int) totalLen;
FileChannel channel = raf.getChannel();
MappedByteBuffer buffer = channel.map(
FileChannel.MapMode.READ_WRITE, 0, REVERSE_LENGTH);
byte tmp;
for (int i = 0; i < len; ++i) {
byte rawByte = buffer.get(i);
if (i <= key.length() - 1) {
tmp = (byte) (rawByte ^ key.charAt(i)); // 异或运算(XOR operation)
} else {
tmp = (byte) (rawByte ^ i);
}
buffer.put(i, tmp);
}
buffer.force();
buffer.clear();
channel.close();
raf.close();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 解密入口
*
* @param fileUrl 源文件绝对路径
*/
public void doDecrypt(String fileUrl) {
try {
if (!isDecrypted(fileUrl)) {
// 如果没有被解密,则解密
decrypt(fileUrl);
Toast.makeText(context, "解密成功!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "文件未被加密过!", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void decrypt(String fileUrl) {
if (encrypt(fileUrl)) {
// 在SharedPreference里设置这个文件已经被解密
SharedPreferences.Editor editor = context.getSharedPreferences(prefKey, MODE_PRIVATE).edit();
editor.putBoolean(fileUrl, true);
editor.apply();
}
}
/**
* fileName 文件是否已经解密
*
* @param filePath
* @return
*/
private boolean isDecrypted(String filePath) {
SharedPreferences encrypted_files = context.getSharedPreferences(prefKey, MODE_PRIVATE);
Log.i("nib", "isDecrypted: " + filePath + encrypted_files.getBoolean(filePath, true));
return encrypted_files.getBoolean(filePath, true);
}
}
| [
"[email protected]"
] | |
9ec9d6580c17ec40051ad3b5372071465a77fdcb | 173fbf35be7b965cd1ee997eafcbfd0710bb6196 | /shua/src/leetcode26/Solution.java | c27fcbc6d325cb90a55e4dc0aaf877cc52cfa9cc | [] | no_license | ECNUIDT/mianshi | 74c9a101b762af6456963554844599762fdbb7f5 | e1d4240981625efb31f76a0991301b6f82574252 | refs/heads/master | 2020-03-28T19:43:07.585422 | 2018-09-16T14:52:11 | 2018-09-16T14:52:11 | 149,002,896 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 712 | java | package leetcode26;
import javax.sound.midi.Soundbank;
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length<=0){
return 0;
}
int curr=nums[0];
int loc=1;
for(int i=1;i<=nums.length-1;i++){
if(nums[i]!=curr){
nums[loc++]=nums[i];
curr=nums[i];
}
}
return loc;
}
public static void main(String[] args) {
int[] nums={1,1};
Solution sol=new Solution();
int loc=sol.removeDuplicates(nums);
for(int k=0;k<loc;k++){
System.out.println(nums[k]);
}
System.out.println("length: "+loc);
}
}
| [
"[email protected]"
] | |
22de388964dcd5d6b5fda4c0be090b038d1f93f2 | 75907df9261478e35fe7d98d9857400f3fac01b4 | /src/UmlUpdate.java | 235b13d29701b69b64340acf0cfcfd906c9b3bf2 | [] | no_license | prime21/my-UML-parser | 4c7a1d406efc042f20f8ce172c3d0e0224c8f723 | 099aa8e048d22e5bdd4423d2745e42947e297c7a | refs/heads/master | 2020-05-30T03:39:14.191747 | 2019-06-02T09:38:30 | 2019-06-02T09:38:30 | 189,520,046 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,186 | java | import com.oocourse.uml1.models.common.Direction;
import com.oocourse.uml1.models.common.ElementType;
import com.oocourse.uml1.models.elements.UmlAssociation;
import com.oocourse.uml1.models.elements.UmlAssociationEnd;
import com.oocourse.uml1.models.elements.UmlGeneralization;
import com.oocourse.uml1.models.elements.UmlInterfaceRealization;
import com.oocourse.uml1.models.elements.UmlParameter;
public class UmlUpdate {
private static void updopt(UmlTreeNode now) {
for (UmlTreeNode nxt: now.getSons()) {
if (((UmlParameter)nxt.getElm()).
getDirection().equals(Direction.RETURN)) {
((UmlOptNode)now).markRet();
}
else {
((UmlOptNode) now).markPar();
}
}
}
private static void updass(UmlTreeNode now) {
String end1 = ((UmlAssociation)now.getElm()).getEnd1();
String end2 = ((UmlAssociation)now.getElm()).getEnd2();
UmlTreeNode e1 =
NodePool.getInstance().get(Idmap.getInstance().get(end1));
e1 = NodePool.getInstance().get(Idmap.getInstance().get(
((UmlAssociationEnd)e1.getElm()).getReference()
));
UmlTreeNode e2 =
NodePool.getInstance().get(Idmap.getInstance().get(end2));
e2 = NodePool.getInstance().get(Idmap.getInstance().get(
((UmlAssociationEnd)e2.getElm()).getReference()
));
//System.out.println(e1.getElm().getName() + " " + e2.getElm().getName());
if (e1.getType().equals(ElementType.UML_CLASS)) {
((UmlClassNode) e1).add(e2);
}
else {
((UmlItfNode)e1).addinter(e2);
}
if (e2.getType().equals(ElementType.UML_CLASS)) {
((UmlClassNode) e2).add(e1);
}
else {
((UmlItfNode)e2).addinter(e1);
}
}
private static void updcls(UmlTreeNode now) {
for (UmlTreeNode nxt: now.getSons()) {
switch (nxt.getType()) {
case UML_ATTRIBUTE:
case UML_OPERATION:
((UmlClassNode)now).add(nxt);
break;
default:
break;
}
}
}
private static void updgen(UmlTreeNode now) {
UmlGeneralization g = (UmlGeneralization)(now.getElm());
int src = Idmap.getInstance().get(g.getSource());
int tar = Idmap.getInstance().get(g.getTarget());
UmlTreeNode e1 = NodePool.getInstance().get(src);
UmlTreeNode e2 = NodePool.getInstance().get(tar);
if (e1.getType().equals(ElementType.UML_CLASS)) {
((UmlClassNode)e1).setExtclass(e2);
((UmlClassNode)e2).addsoncls(e1);
}
else {
((UmlItfNode)e1).addup(e2);
((UmlItfNode)e2).adddn(e1);
}
}
private static void updreal(UmlTreeNode now) {
UmlInterfaceRealization g = (UmlInterfaceRealization) now.getElm();
int src = Idmap.getInstance().get(g.getSource());
int tar = Idmap.getInstance().get(g.getTarget());
UmlTreeNode e1 = NodePool.getInstance().get(src);
UmlTreeNode e2 = NodePool.getInstance().get(tar);
((UmlClassNode)e1).addinter(e2);
((UmlItfNode)e2).adddn(e1);
}
public static void upd(UmlTreeNode now) {
switch (now.getType()) {
case UML_ASSOCIATION_END:
case UML_ATTRIBUTE:
case UML_PARAMETER:
break;
case UML_OPERATION: // get all parameter
updopt(now);
break;
case UML_ASSOCIATION: // get two end
updass(now);
break;
case UML_CLASS: // get all operation, attribute
updcls(now);
break;
case UML_GENERALIZATION: // make father
updgen(now);
break;
case UML_INTERFACE_REALIZATION: // get interface realization
updreal(now);
break;
case UML_INTERFACE:
break;
default:
break;
}
}
}
| [
"[email protected]"
] | |
caefcfea1555585258d71f8bc88977b0d2008fae | 5bc9d8f92f38967cc9ecc03000c0606dbbb38f74 | /sca4j/modules/tags/sca4j-modules-parent-pom-0.9.6/runtime/generic/sca4j-generic-runtime-impl/src/main/java/org/sca4/runtime/generic/impl/contribution/ClasspathContributionProcessor.java | 2f6a38e10c577444900e1699abf8fece2a60069f | [] | no_license | codehaus/service-conduit | 795332fad474e12463db22c5e57ddd7cd6e2956e | 4687d4cfc16f7a863ced69ce9ca81c6db3adb6d2 | refs/heads/master | 2023-07-20T00:35:11.240347 | 2011-08-24T22:13:28 | 2011-08-24T22:13:28 | 36,342,601 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,680 | java | /**
* SCA4J
* Copyright (c) 2009 - 2099 Service Symphony Ltd
*
* Licensed to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. A copy of the license
* is included in this distrubtion or you may obtain a copy at
*
* http://www.opensource.org/licenses/apache2.0.php
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* This project contains code licensed from the Apache Software Foundation under
* the Apache License, Version 2.0 and original code from project contributors.
*
*
* Original Codehaus Header
*
* Copyright (c) 2007 - 2008 fabric3 project contributors
*
* Licensed to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. A copy of the license
* is included in this distrubtion or you may obtain a copy at
*
* http://www.opensource.org/licenses/apache2.0.php
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* This project contains code licensed from the Apache Software Foundation under
* the Apache License, Version 2.0 and original code from project contributors.
*
* Original Apache Header
*
* Copyright (c) 2005 - 2006 The Apache Software Foundation
*
* Apache Tuscany is an effort undergoing incubation at The Apache Software
* Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is
* required of all newly accepted projects until a further review indicates that
* the infrastructure, communications, and decision making process have stabilized
* in a manner consistent with other successful ASF projects. While incubation
* status is not necessarily a reflection of the completeness or stability of the
* code, it does indicate that the project has yet to be fully endorsed by the ASF.
*
* This product includes software developed by
* The Apache Software Foundation (http://www.apache.org/).
*/
package org.sca4.runtime.generic.impl.contribution;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.oasisopen.sca.annotation.EagerInit;
import org.oasisopen.sca.annotation.Reference;
import org.sca4j.fabric.services.contribution.processor.AbstractContributionProcessor;
import org.sca4j.fabric.util.FileHelper;
import org.sca4j.host.contribution.ContributionException;
import org.sca4j.spi.services.contenttype.ContentTypeResolutionException;
import org.sca4j.spi.services.contenttype.ContentTypeResolver;
import org.sca4j.spi.services.contribution.Action;
import org.sca4j.spi.services.contribution.Contribution;
/**
* Contribution processor for tests.
*
*/
@EagerInit
public class ClasspathContributionProcessor extends AbstractContributionProcessor {
@Reference protected ContentTypeResolver contentTypeResolver;
protected URL getManifestUrl(Contribution contribution) throws MalformedURLException {
return new URL(contribution.getLocation().toExternalForm() + "/META-INF/sca-contribution.xml");
}
protected void iterateArtifacts(Contribution contribution, Action action) throws ContributionException {
File root = FileHelper.toFile(contribution.getLocation());
assert root.isDirectory();
iterateArtifactsResursive(contribution, action, root);
}
private void iterateArtifactsResursive(Contribution contribution, Action action, File dir) throws ContributionException {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
iterateArtifactsResursive(contribution, action, file);
} else {
try {
URL entryUrl = file.toURI().toURL();
String contentType = contentTypeResolver.getContentType(entryUrl);
action.process(contribution, contentType, entryUrl);
} catch (MalformedURLException e) {
throw new ContributionException(e);
} catch (ContentTypeResolutionException e) {
throw new ContributionException(e);
}
}
}
}
}
| [
"meerajk@15bcc2b3-4398-4609-aa7c-97eea3cd106e"
] | meerajk@15bcc2b3-4398-4609-aa7c-97eea3cd106e |
e8d004c4cae7ad8bdd39f942c87e221a08da1616 | 1f97c624448169b1717a56919fec0e6b6e537399 | /src/main/java/com/github/candyacao/awesomenotes/dao/AttachVoMapper.java | 0dbcaf1a252ad31fb7d5e2273b13c972ac618470 | [
"Apache-2.0"
] | permissive | candyacao/awesomeblog | 39bdfd62015574920a0af611b30fd4b543e76639 | 3615afaa46d2a4392e06c983af375452f9803af9 | refs/heads/master | 2020-04-29T10:20:29.392876 | 2019-05-19T05:13:32 | 2019-05-19T05:13:32 | 176,058,962 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 981 | java | package com.github.candyacao.awesomenotes.dao;
import com.github.candyacao.awesomenotes.model.Vo.AttachVo;
import com.github.candyacao.awesomenotes.model.Vo.AttachVoExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
@Component
public interface AttachVoMapper {
long countByExample(AttachVoExample example);
int deleteByExample(AttachVoExample example);
int deleteByPrimaryKey(Integer id);
int insert(AttachVo record);
int insertSelective(AttachVo record);
List<AttachVo> selectByExample(AttachVoExample example);
AttachVo selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") AttachVo record, @Param("example") AttachVoExample example);
int updateByExample(@Param("record") AttachVo record, @Param("example") AttachVoExample example);
int updateByPrimaryKeySelective(AttachVo record);
int updateByPrimaryKey(AttachVo record);
} | [
"[email protected]"
] | |
e932db581214e87c402aaa769690215c9738ad3c | a562cb15829e9e1097fa7ed062316863d4bdd198 | /app/src/main/java/com/lidan/keylor/musicmaster/domain/Usecase.java | 30c6f8fdbf743445d7532456a116fa1d80933cc7 | [] | no_license | keylorsdu/MusicMaster | 1971cfed77613082bb68ffdedd5e037daea50dc2 | dd7bafd88b2399dcb08a955cbce7ebdce5560be3 | refs/heads/master | 2021-01-21T02:27:58.068917 | 2015-08-22T10:11:23 | 2015-08-22T10:11:23 | 38,816,770 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 144 | java | package com.lidan.keylor.musicmaster.domain;
/**
* Created by keylorlidan on 2015/8/16.
*/
public interface Usecase {
void execute();
}
| [
"[email protected]"
] | |
b9eb7748c33f87e495e1033ceb57964a87c2cbab | a63b30a7873f78e17e5afc6ba6ec49804e3203b6 | /src/com/company/Chicken.java | 3a2485ef9225a8e523ca1720a88ec6234232cbe2 | [] | no_license | polash04/FarmGame | 01bf2f0c98c8b1ff224dd9967a41c1930fad6d69 | d12bd615e84b52d7e77ef2eaa3918aefe001326c | refs/heads/main | 2023-03-04T09:32:21.315538 | 2021-02-21T20:59:09 | 2021-02-21T20:59:09 | 339,205,218 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 335 | java | package com.company;
import java.util.ArrayList;
public class Chicken extends Animal{
public static int Cost = 100;
public Chicken(boolean aBabyFlag) {
super(aBabyFlag);
myCost = Cost;
myMaxAge = 10;
BabyCount = 4;
FoodTypes = new FoodType[]{FoodType.Seeds, FoodType.Carrots};
}
}
| [
"[email protected]"
] | |
1536f9d944595104643f99d122087abdc99f7910 | 1112b050a19ef651879d9ce19ef7f8d64837bf1c | /Server/src/com/anu/Login.java | c9e328e89a04f2b371c68b23544c02e9803aa412 | [] | no_license | xfeier53/Snake | ffdf62279f7dc8aeda1967c5143d8950b5a17aba | ee077be462982384c51bacc5a5b43b066fd480ef | refs/heads/master | 2020-08-22T17:08:10.893425 | 2019-10-21T04:31:48 | 2019-10-21T04:31:48 | 216,443,975 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,070 | java | /*
Authorship: Feier Xiao
*/
package com.anu;
import java.sql.*;
public class Login {
public boolean userLogin(String account, String password){
boolean isLoginSuccessful = false;
String query = "SELECT * FROM AndroidUser WHERE Account = '" + account + "' and Password = '" + password + "'";
try{
// Get the driver class
Class.forName(CONSTANTS.DRIVER);
// Create connection and retrieve the result
Connection conn = DriverManager.getConnection(CONSTANTS.URL, CONSTANTS.USER, CONSTANTS.PASSWORD);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(query);
if(rs.next()){
isLoginSuccessful = true;
}
// close Connection and ResultSet
rs.close();
stm.close();
conn.close();
}catch (Exception e) {
System.out.println(e);
}
if(isLoginSuccessful){
return true;
} else {
return false;
}
}
} | [
"[email protected]"
] | |
efc7167403ff1c0b8481b4d4a3c6e82a612846de | 47b0c9b960f342f9d67b871ef76c25850bec76f0 | /ajiML/src/ajiML/Create.java | fe2ac33ad43f629e62153a9c95e478b6ecc9235b | [
"MIT"
] | permissive | SeelabFhdo/AjiL | 7588b386de57d3ed6faae6ccab376c55bc4cb353 | 452893898e51c9091e151fb0dc3b34f3bd3a50f7 | refs/heads/dev | 2021-07-04T08:40:20.909947 | 2019-05-10T12:11:41 | 2019-05-10T12:11:41 | 100,506,558 | 8 | 6 | MIT | 2019-05-10T12:15:17 | 2017-08-16T15:51:39 | Java | UTF-8 | Java | false | false | 274 | java | /**
*/
package ajiML;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Create</b></em>'.
* <!-- end-user-doc -->
*
*
* @see ajiML.AjiMLPackage#getCreate()
* @model
* @generated
*/
public interface Create extends Ability {
} // Create
| [
"[email protected]"
] | |
675f1b9fbf33e371b037da71878e47fa590deb06 | 5ec8a5ba340b823e47ecc4dc31a7d14276df5910 | /app/src/test/java/com/vikas/videoplayer/ExampleUnitTest.java | f2b04708962a1fbff90a0da29d1cec4f1c852afc | [] | no_license | rohitnotes/vimeo-exo-player | 740ab534d25ddbf7311c767ccea7b43634a09b88 | d4f123c7abc69d59a9f3960ce4881d5dbdfa0fe2 | refs/heads/master | 2022-04-08T13:14:47.083381 | 2020-02-20T07:27:33 | 2020-02-20T07:27:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 382 | java | package com.vikas.videoplayer;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
25146a17c893d6fb990171e5d3b3570eebef2634 | 4b027a96e457f90fdd146c73a92a99a63b5f6cab | /level06/lesson08/task02/Cat.java | 7918c464c49d46ca5b2dd71b360193cdb509a772 | [] | no_license | Byshevsky/JavaRush | c44a3b25afca677bbe5b6c015aec7c2561ca4830 | d8965bc8b5f060af558cc86924ae6488727cdbd4 | refs/heads/master | 2021-05-02T12:17:48.896494 | 2016-12-26T21:56:12 | 2016-12-26T21:56:12 | 52,143,706 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 805 | java | package com.javarush.test.level06.lesson08.task02;
/* Статические методы: int getCatCount() и setCatCount(int)
Добавить к классу Cat два статических метода: int getCatCount() и setCatCount(int), с помощью которых можно получить/изменить количество котов (переменную catCount)
*/
public class Cat
{
private static int catCount = 0;
public Cat()
{
catCount++;
}
public static int getCatCount()
{
//Напишите тут ваш код
return Cat.catCount;
}
public static void setCatCount(int catCount)
{
//Напишите тут ваш код
Cat.catCount = catCount;
}
}
| [
"[email protected]"
] | |
8904b782a81e7afb4eae93767c945201455c2100 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/12/12_1be45a78cb810cc82998e0eae4072bc635a40331/SellCommand/12_1be45a78cb810cc82998e0eae4072bc635a40331_SellCommand_t.java | 653895fe041f38b64d7e13330dca3e32cf209264 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 6,580 | java | /*-------------------------------------------------------------------------
svninfo: $Id$
Maarten's Mud, WWW-based MUD using MYSQL
Copyright (C) 1998 Maarten van Leunen
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Maarten van Leunen
Appelhof 27
5345 KA Oss
Nederland
Europe
[email protected]
-------------------------------------------------------------------------*/
package mmud.commands;
import java.util.Vector;
import java.util.logging.Logger;
import mmud.Constants;
import mmud.MudException;
import mmud.ParseException;
import mmud.characters.Person;
import mmud.characters.Persons;
import mmud.characters.User;
import mmud.database.Database;
import mmud.database.ItemsDb;
import mmud.items.Item;
import mmud.items.ItemException;
/**
* Selling an item to a bot. Syntax : sell <item> to <character>
* @see BuyCommand
*/
public class SellCommand extends NormalCommand
{
public SellCommand(String aRegExpr)
{
super(aRegExpr);
}
/**
* Tries out the sell command. There are a couple of requirements that
* need to be met, before a successful sale takes place.
* <ol><li>command struct. should be "<I>sell
* <item> to <character></I>", for example: "<I>sell gold ring
* to Karcas</I>".
* <li>shopkeeper buying the item should
* <ol><li> exist, <li>be in the same room and<li>
* have a occupation-attribute set to "shopkeeper"
* and<li>has enough money</ol>
* <li>the customer should have the item
* <li>the item itself should <I>NOT</I> have a attribute called "notsellable".
* </ol>
* A best effort is tried, this means the following sequence of events:
* <ol><li>the item is transferred into the inventory of the shopkeeper
* <li>money is transferred into the inventory of the customer
* <li>continue with next item
*</ol>
* @param aUser the character doing the selling.
* @throws ItemException in case the appropriate items could not be
* properly processed.
* @throws ParseException if the item description or the number of
* items requested is illegal.
*/
public boolean run(User aUser)
throws ItemException, ParseException, MudException
{
Logger.getLogger("mmud").finer("");
if (!super.run(aUser))
{
return false;
}
String[] myParsed = getParsedCommand();
// parse command string
if (myParsed.length >= 4 && myParsed[myParsed.length-2].equalsIgnoreCase("to"))
{
// determine if appropriate shopkeeper is found.
Person toChar = Persons.retrievePerson(myParsed[myParsed.length-1]);
if ((toChar == null) || (!toChar.getRoom().equals(aUser.getRoom())))
{
aUser.writeMessage("Cannot find that person.<BR>\r\n");
return true;
}
if ( (!toChar.isAttribute("occupation")) ||
(!"shopkeeper".equals(
toChar.getAttribute("occupation").getValue())) )
{
aUser.writeMessage("That person is not a shopkeeper.<BR>\r\n");
return true;
}
// check for item in posession of customer
Vector stuff = Constants.parseItemDescription(myParsed, 1, myParsed.length - 3);
int amount = ((Integer) stuff.elementAt(0)).intValue();
String adject1 = (String) stuff.elementAt(1);
String adject2 = (String) stuff.elementAt(2);
String adject3 = (String) stuff.elementAt(3);
String name = (String) stuff.elementAt(4);
Vector myItems = aUser.getItems(adject1, adject2, adject3, name);
if (myItems.size() < amount)
{
if (amount == 1)
{
aUser.writeMessage("You do not have that item.<BR>\r\n");
return true;
}
else
{
aUser.writeMessage("You do not have that many items.<BR>\r\n");
return true;
}
}
int sumvalue = 0;
for (int i=0; i<amount; i++)
{
Item myItem = (Item) myItems.elementAt(i);
sumvalue += myItem.getMoney();
}
Logger.getLogger("mmud").finer(aUser.getName() + " has items worth " + sumvalue + " copper");
Logger.getLogger("mmud").finer(toChar.getName() + " has " +
toChar.getMoney() + " copper coins");
if (toChar.getMoney() < sumvalue )
{
aUser.writeMessage(toChar.getName() + " mutters something about not having enough money.<BR>\r\n");
return true;
}
int j = 0;
for (int i = 0; ((i < myItems.size()) && (j != amount)); i++)
{
// here needs to be a check for validity of the item
boolean success = true;
Item myItem = (Item) myItems.elementAt(i);
if (myItem.isAttribute("notsellable"))
{
aUser.writeMessage("You cannot sell that item.<BR>\r\n");
success = false;
}
if (myItem.getMoney() == 0)
{
String message = "That item is not worth anything.";
Persons.sendMessageExcl(toChar, aUser, "%SNAME say%VERB2 [to %TNAME] : " + message + "<BR>\r\n");
aUser.writeMessage(toChar, aUser, "<B>%SNAME say%VERB2 [to %TNAME]</B> : " + message + "<BR>\r\n");
success = false;
}
if (myItem.isWearing())
{
String message = "You cannot sell that, you are wearing or wielding that item.";
aUser.writeMessage(toChar, aUser, message + "<BR>\r\n");
success = false;
}
if (success)
{
// transfer money to user
int totalitemvalue = myItem.getMoney();
// transfer item to shopkeeper
if (success)
{
ItemsDb.transferItem(myItem, toChar);
Database.writeLog(aUser.getName(), "sold " + myItem + " to " + toChar + " in room " + toChar.getRoom().getId());
toChar.transferMoneyTo(totalitemvalue, aUser);
Database.writeLog(aUser.getName(), "received " + totalitemvalue + " copper from " + toChar);
Persons.sendMessage(aUser, toChar, "%SNAME sell%VERB2 " + myItem.getDescription() + " to %TNAME.<BR>\r\n");
j++;
}
}
}
return true;
}
return false;
}
public Command createCommand()
{
return new SellCommand(getRegExpr());
}
}
| [
"[email protected]"
] | |
86e52cf9bb341bd90fa104afeccd96d1d87b5b5d | 3dcc1b217120706d33c91a43849e3f527bc94c26 | /codingChallenges/src/LinkedQueue.java | 6971a004cf08238ad62549c3b45fe6a76d26a498 | [] | no_license | patelkirtann/codingChallenge | 374457ceab934bcc976e48a75d4848cf38032fa4 | 3d2fcfa74beb418e07c45f305dbbe92150375281 | refs/heads/master | 2021-04-29T07:50:17.650752 | 2017-01-28T08:15:51 | 2017-01-28T08:15:51 | 77,975,830 | 1 | 0 | null | 2017-01-13T06:24:34 | 2017-01-04T03:11:17 | Java | UTF-8 | Java | false | false | 1,778 | java | /**
* Created by kt_ki on 1/17/2017.
*/
class QueueList {
public Main_Link first;
public Main_Link last;
public QueueList() {
first = null;
last = null;
}
public boolean isEmpty() {
return first == null;
}
public void insertLast(double value) {
Main_Link newValue = new Main_Link(value);
if (isEmpty()) {
first = newValue;
last = first;
} else {
last.next = newValue;
last = newValue;
}
}
public double deleteFirst() {
double temp = first.data;
if (first.next == null) {
last = null;
} else {
first = first.next;
}
return temp;
}
public void displayList() {
System.out.print("Queue : ");
Main_Link current = first;
while (current != null) {
current.displayLink();
current = current.next;
}
System.out.println();
}
}
public class LinkedQueue {
public QueueList theList;
public LinkedQueue() {
theList = new QueueList();
}
public boolean isEmpty() {
return theList.isEmpty();
}
public void insert(double value) {
theList.insertLast(value);
}
public double remove() {
return theList.deleteFirst();
}
public void displayQueue() {
theList.displayList();
}
public static void main(String[] args) {
LinkedQueue linkedQueue = new LinkedQueue();
while (linkedQueue.isEmpty())
linkedQueue.insert(55);
linkedQueue.insert(32);
linkedQueue.insert(54);
linkedQueue.displayQueue();
linkedQueue.remove();
linkedQueue.displayQueue();
}
}
| [
"[email protected]"
] | |
0b7a9482e96d0f9d8352029c7a69a5135bdf8a66 | 5b84c89465f85417573557b3d4fe0780cf16ae3d | /SCAS/src/java/controller/RelatorioCursosController.java | 101d9f509a1572c98653b0bd31ad7329bb764bfa | [] | no_license | AntonioCelestino/LP | 2f305a23765f16dbdeeeef99dacaf60568f9d1fc | 59d0e4ae5d029d8c9d26ddf1c61f9f094edebdd7 | refs/heads/master | 2021-01-20T19:34:02.631317 | 2017-01-17T13:13:04 | 2017-01-17T13:13:04 | 60,007,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,218 | java | package controller;
import dao.BD;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
public class RelatorioCursosController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response){
Connection conexao = null;
try{
HashMap parametros = new HashMap();
conexao = BD.getConexao();
//parametro.put ("PAR_codCurso", Integer.parseInt(request.getParameter("txtCodCurso")));
String relatorio = getServletContext().getRealPath ("/WEB-INF")+"//RelatorioCursos.jasper";
JasperPrint jp = JasperFillManager.fillReport(relatorio, parametros, conexao);
byte[] relat = JasperExportManager.exportReportToPdf(jp);
response.setHeader("Content-Disposition", "attachment; filename=RelatorioCursos.pdf");
response.setContentType("application/pdf");
response.getOutputStream().write(relat);
} catch (SQLException ex){
ex.printStackTrace();
} catch (ClassNotFoundException ex){
ex.printStackTrace();
} catch (JRException ex){
ex.printStackTrace();
} catch (IOException ex){
ex.printStackTrace();
} finally{
try{
if (!conexao.isClosed()){
conexao.close();
}
} catch (SQLException ex){
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"[email protected]"
] | |
9784166683e45cc3b9a6dddcb17e89f0423c9087 | 747a9fbd3ea6a3d3e469d63ade02b7620d970ca6 | /gmsm/src/main/java/com/getui/gmsm/bouncycastle/asn1/bc/BCObjectIdentifiers.java | 336481cfad17abcf40300a1f224dbdc3ef76c911 | [] | no_license | xievxin/GitWorkspace | 3b88601ebb4718dc34a2948c673367ba79c202f0 | 81f4e7176daa85bf8bf5858ca4462e9475227aba | refs/heads/master | 2021-01-21T06:18:33.222406 | 2019-01-31T01:28:50 | 2019-01-31T01:28:50 | 95,727,159 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,607 | java | package com.getui.gmsm.bouncycastle.asn1.bc;
import com.getui.gmsm.bouncycastle.asn1.DERObjectIdentifier;
public interface BCObjectIdentifiers
{
/**
* iso.org.dod.internet.private.enterprise.legion-of-the-bouncy-castle
*
* 1.3.6.1.4.1.22554
*/
public static final DERObjectIdentifier bc = new DERObjectIdentifier("1.3.6.1.4.1.22554");
/**
* pbe(1) algorithms
*/
public static final DERObjectIdentifier bc_pbe = new DERObjectIdentifier(bc.getId() + ".1");
/**
* SHA-1(1)
*/
public static final DERObjectIdentifier bc_pbe_sha1 = new DERObjectIdentifier(bc_pbe.getId() + ".1");
/**
* SHA-2(2) . (SHA-256(1)|SHA-384(2)|SHA-512(3)|SHA-224(4))
*/
public static final DERObjectIdentifier bc_pbe_sha256 = new DERObjectIdentifier(bc_pbe.getId() + ".2.1");
public static final DERObjectIdentifier bc_pbe_sha384 = new DERObjectIdentifier(bc_pbe.getId() + ".2.2");
public static final DERObjectIdentifier bc_pbe_sha512 = new DERObjectIdentifier(bc_pbe.getId() + ".2.3");
public static final DERObjectIdentifier bc_pbe_sha224 = new DERObjectIdentifier(bc_pbe.getId() + ".2.4");
/**
* PKCS-5(1)|PKCS-12(2)
*/
public static final DERObjectIdentifier bc_pbe_sha1_pkcs5 = new DERObjectIdentifier(bc_pbe_sha1.getId() + ".1");
public static final DERObjectIdentifier bc_pbe_sha1_pkcs12 = new DERObjectIdentifier(bc_pbe_sha1.getId() + ".2");
public static final DERObjectIdentifier bc_pbe_sha256_pkcs5 = new DERObjectIdentifier(bc_pbe_sha256.getId() + ".1");
public static final DERObjectIdentifier bc_pbe_sha256_pkcs12 = new DERObjectIdentifier(bc_pbe_sha256.getId() + ".2");
/**
* AES(1) . (CBC-128(2)|CBC-192(22)|CBC-256(42))
*/
public static final DERObjectIdentifier bc_pbe_sha1_pkcs12_aes128_cbc = new DERObjectIdentifier(bc_pbe_sha1_pkcs12.getId() + ".1.2");
public static final DERObjectIdentifier bc_pbe_sha1_pkcs12_aes192_cbc = new DERObjectIdentifier(bc_pbe_sha1_pkcs12.getId() + ".1.22");
public static final DERObjectIdentifier bc_pbe_sha1_pkcs12_aes256_cbc = new DERObjectIdentifier(bc_pbe_sha1_pkcs12.getId() + ".1.42");
public static final DERObjectIdentifier bc_pbe_sha256_pkcs12_aes128_cbc = new DERObjectIdentifier(bc_pbe_sha256_pkcs12.getId() + ".1.2");
public static final DERObjectIdentifier bc_pbe_sha256_pkcs12_aes192_cbc = new DERObjectIdentifier(bc_pbe_sha256_pkcs12.getId() + ".1.22");
public static final DERObjectIdentifier bc_pbe_sha256_pkcs12_aes256_cbc = new DERObjectIdentifier(bc_pbe_sha256_pkcs12.getId() + ".1.42");
}
| [
"[email protected]"
] | |
4c4801e0ae7391d0c6790162f7610c41be286bd6 | 524df4196241684fc6d0fa0bff09c6cf5b72fd17 | /RecyclerViewExample2/app/src/main/java/com/nex3z/examples/recyclerview2/rest/RestClient.java | 73713f5d8e3a56ad8b81e5b01721a8c8a8edf060 | [] | no_license | WZFlik/android-examples | 459330f04fe4d374ba00141917487532cd89d142 | 7da7a685d31dac1388406dbaa8ccf5b3109e924a | refs/heads/master | 2020-03-28T21:08:34.649938 | 2018-06-04T14:57:18 | 2018-06-04T14:57:18 | 149,132,237 | 1 | 0 | null | 2018-09-17T13:48:20 | 2018-09-17T13:48:20 | null | UTF-8 | Java | false | false | 2,081 | java | package com.nex3z.examples.recyclerview2.rest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nex3z.examples.recyclerview2.BuildConfig;
import com.nex3z.examples.recyclerview2.rest.service.MovieService;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
import java.io.IOException;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
public class RestClient {
private static final String BASE_URL = "http://api.themoviedb.org";
private MovieService mMovieService;
public RestClient() {
Gson gson = new GsonBuilder().create();
OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
httpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.httpUrl();
HttpUrl.Builder builder = originalHttpUrl.newBuilder()
.addQueryParameter("api_key", BuildConfig.API_KEY);
Request.Builder requestBuilder = original.newBuilder()
.url(builder.build())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
mMovieService = retrofit.create(MovieService.class);
}
public MovieService getMovieService() { return mMovieService; }
}
| [
"[email protected]"
] | |
ef537f8342a6e67fb57a3edc8b69d5973b763473 | 7ee27191217553a815458a622a1b7878274f7088 | /src/main/java/jdkguide/nio/buffer/ByteBuffers.java | 401defad5fe1b3cd87abb237ee6ceb8cc8a9529e | [] | no_license | BigPayno/JavaGuide | bd3a14cab15188894ade972201f437cc8ceadbb7 | 512f084343e03de87e4949dd66fba77eb69972ed | refs/heads/master | 2022-12-12T23:29:53.618292 | 2020-05-29T08:30:36 | 2020-05-29T08:30:36 | 221,147,356 | 1 | 0 | null | 2022-12-10T05:44:10 | 2019-11-12T06:34:42 | Java | UTF-8 | Java | false | false | 479 | java | package jdkguide.nio.buffer;
import java.nio.ByteBuffer;
/**
* @author payno
* @date 2019/11/4 14:59
* @description
*/
public final class ByteBuffers {
public static void print(ByteBuffer byteBuffer){
//反转ByteBuffer,转换读写模式
byteBuffer.flip();
//移动指针
while (byteBuffer.hasRemaining()){
System.out.print((char)byteBuffer.get());
}
//清除ByteBuffer
byteBuffer.clear();
}
}
| [
"[email protected]"
] | |
50fda45e46ad06a1b95aca071be1b7069a86ac3c | 6af92a5f278622b2996a31757e91df6542d0095b | /tacos/tacos-backend/src/main/java/tacos/message/jms/JmsConfig.java | 1fa68638de2a8bac39ae0b39c749f1be1eaf1aec | [] | no_license | SuiJN621/spring-in-action | 9158169a91b12990bcc364f8009cd53f999a2838 | ba8e67dc53239f60b22ff83a1fedad66d43ef4c9 | refs/heads/master | 2020-05-09T21:22:56.659228 | 2019-05-27T07:11:59 | 2019-05-27T07:11:59 | 181,441,430 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,590 | java | package tacos.message.jms;
import java.util.HashMap;
import java.util.Map;
import javax.jms.Destination;
import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import tacos.entity.Order;
/**
* @author Sui
* @date 2019.04.23 9:34
*/
@Configuration
public class JmsConfig {
public static final String ORDER_STRING_DESTINATION = "com.sjn.order";
/**
* 注册新的MessageConverter代替默认的SimpleMessageConverter
*
* @return
*/
@Bean
public MappingJackson2MessageConverter messageConverter() {
MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter();
//设置typeId key值, 接收方根据value值决定将message转换为何种类型, 默认是类的全名
//接收方也需要进行类似配置
messageConverter.setTypeIdPropertyName("_typeId");
//配置type mapping, 避免使用类全名
Map<String, Class<?>> typeIdMappings = new HashMap<>();
typeIdMappings.put("order", Order.class);
messageConverter.setTypeIdMappings(typeIdMappings);
return messageConverter;
}
@Bean
public Destination orderDestination(){
//也可以直接使用String定义目标, 不指定发送目标时需要配置默认目标spring.jms.template.default-destination
return new ActiveMQQueue(ORDER_STRING_DESTINATION);
}
}
| [
"[email protected]"
] | |
6463a8b266b8125a974f90ef2dc5d0962ddb1b54 | cbf5aceb17cafdfed825c8fb3434ff0b41eee2db | /src/bol24_1/wformgui/Ventana.java | 31395f97c0c7a618866eb286606614f068dabc94 | [] | no_license | juanmartinezpineiro/Boletin24 | a0be39034edfe48d59de1f068f9888550400c46e | f3f5a8edda5a253181daa4173cf73a39ed5ce1c9 | refs/heads/master | 2020-05-04T07:46:06.968719 | 2019-04-02T08:38:53 | 2019-04-02T08:38:53 | 179,034,709 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,043 | java | /*
* 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 bol24_1.wformgui;
/**
*
* @author jmartinezpineiro
*/
public class Ventana extends javax.swing.JFrame {
/**
* Creates new form Ventana
*/
public Ventana() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
textFieldName = new javax.swing.JTextField();
buttonPremer = new javax.swing.JButton();
buttonLimpar = new javax.swing.JButton();
textFieldPassword = new javax.swing.JPasswordField();
jPanel2 = new javax.swing.JPanel();
buttonBoton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
AreaTexto = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
Lista = new javax.swing.JList<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("NOME");
jLabel2.setText("PASSWORD");
buttonPremer.setText("PREMER");
buttonPremer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPremerActionPerformed(evt);
}
});
buttonLimpar.setText("LIMPAR");
buttonLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLimparActionPerformed(evt);
}
});
textFieldPassword.setText("jPasswordField1");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(65, 65, 65)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(buttonPremer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonLimpar)
.addGap(74, 74, 74))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(66, 66, 66)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(textFieldPassword)
.addComponent(textFieldName))
.addGap(89, 89, 89))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(textFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(textFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonPremer)
.addComponent(buttonLimpar))
.addGap(23, 23, 23))
);
buttonBoton.setText("BOTON");
buttonBoton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonBotonActionPerformed(evt);
}
});
AreaTexto.setColumns(20);
AreaTexto.setRows(5);
jScrollPane2.setViewportView(AreaTexto);
Lista.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "ElementoLista 1", "ElementoLista 2", "ElementoLista 3" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane3.setViewportView(Lista);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonBoton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(buttonBoton))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane3)
.addComponent(jScrollPane2))))
.addContainerGap(55, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void buttonLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLimparActionPerformed
// TODO add your handling code here:
textFieldName.setText(null);
textFieldPassword.setText(null);
}//GEN-LAST:event_buttonLimparActionPerformed
private void buttonPremerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPremerActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_buttonPremerActionPerformed
private void buttonBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBotonActionPerformed
// TODO add your handling code here:
AreaTexto.setText(textFieldName.getText() +"\n" + Lista.getSelectedValue());
}//GEN-LAST:event_buttonBotonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Ventana().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea AreaTexto;
private javax.swing.JList<String> Lista;
private javax.swing.JButton buttonBoton;
private javax.swing.JButton buttonLimpar;
private javax.swing.JButton buttonPremer;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField textFieldName;
private javax.swing.JPasswordField textFieldPassword;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
6ec25e57665915510a532df965e87f19cfb60d26 | 384711580298c82939264fefe3e0807984ef6ff2 | /src/template/com/ticket/serviceImpl/MyTextServiceImpl.java | 5a61b3506c1004d313ff2647e810e076f95d61ad | [] | no_license | guoyu07/ticket | 3d3ac6e7f74cee900df52ab89100b47da345d24e | beb0207df5a81be1e44d3cdbac0b69b2d2f30f95 | refs/heads/master | 2020-03-17T09:49:22.333539 | 2017-11-29T06:47:06 | 2017-11-29T06:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,407 | java | package com.ticket.serviceImpl;
import java.util.ArrayList;
import java.util.List;
import com.ticket.exception.ServiceException;
import com.ticket.pojo.CommonEntity;
import com.ticket.pojo.EmployeeInfo;
import com.ticket.pojo.MyText;
import com.ticket.pojo.Pagination;
import com.ticket.service.IMyTextService;
import com.ticket.util.DecoderUtil;
import com.ticket.util.GeneralUtil;
import com.ticket.util.PaginationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 我的记事本业务接口实现类
* @ClassName: IMyTextService
* @Description: 提供我的记事本操作的增删改查
* @author HiSay
* @date 2016-02-15 11:26:54
*
*/
public class MyTextServiceImpl extends BaseServiceImpl<MyText, String> implements IMyTextService {
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(MyTextServiceImpl.class);
@Override
public MyText merge(String id, EmployeeInfo employeeInfo,String title,String content) throws ServiceException {
MyText myText = dbDAO.queryById(this.getTableNameFromEntity(MyText.class), id);
if(employeeInfo != null){
myText.setEmployeeInfo_id(employeeInfo.getId());
}
myText.setTitle(DecoderUtil.UtfDecoder(title));
myText.setContent(DecoderUtil.UtfDecoder(content));
CommonEntity status = myText.getStatus();
status.setVersionFlag(versionFlag);
myText.setStatus(status);
dbDAO.merge(myText);
return myText;
}
@Override
public MyText persist(EmployeeInfo employeeInfo,String title,String content) throws ServiceException {
MyText myText = new MyText();
if(employeeInfo != null){
myText.setEmployeeInfo_id(employeeInfo.getId());
}
myText.setTitle(DecoderUtil.UtfDecoder(title));
myText.setContent(DecoderUtil.UtfDecoder(content));
CommonEntity status = myText.getStatus();
status.setVersionFlag(versionFlag);
myText.setStatus(status);
dbDAO.persist(myText);
return myText;
}
@Override
public boolean remove(String id) throws ServiceException {
MyText myText = dbDAO.queryById(this.getTableNameFromEntity(MyText.class), id);
dbDAO.remove(myText);
return true;
}
@Override
public Pagination queryAll(EmployeeInfo employeeInfo, Integer isRead,
String order, Integer pageSize) throws ServiceException {
try {
StringBuffer sb = new StringBuffer();
List<Object[]> objects = new ArrayList<Object[]>();
sb.append("");
if(employeeInfo != null){
sb.append("and s.employeeInfo_id=?3 ");
objects.add(new Object[]{3,employeeInfo.getId()});
}
if(GeneralUtil.isNotNull(isRead)){
sb.append("and s.isRead=?4 ");
objects.add(new Object[]{4,isRead});
}
if(GeneralUtil.isNull(order)){
order = "s.status.createTime desc,s.isRead asc";
}
return dbDAO.queryByPageModuleNew(MyText.class.getSimpleName(), 0, versionFlag,
sb.toString(), objects, order, PaginationContext.getOffset(), pageSize);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public Boolean changeRead(String id, Integer read) throws ServiceException {
try {
MyText myText = queryById(MyText.class.getSimpleName(), id);
myText.setIsRead(read);
this.merge(myText);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
} | [
"[email protected]"
] | |
6eb227c432d12dd629ef87d90877c706415b592c | d34187f7a890e096b113f7447d37b472825f682f | /app/src/main/java/com/example/ocrdictionary/entity/SearchText.java | edff4f920bb4f741c73267c32be837085cf21e0d | [] | no_license | tuanbmhust/OCRDictionary | d2df4527eae65a1f08b342e8b05db56235eb30a2 | ebac048d190d1313e63232f87fc4da1a4df6aae3 | refs/heads/master | 2020-09-24T15:11:27.912333 | 2019-12-04T05:37:53 | 2019-12-04T05:37:53 | 225,787,559 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,202 | java | package com.example.ocrdictionary.entity;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class SearchText {
@SerializedName("__v")
@Expose
private Integer v;
@SerializedName("_id")
@Expose
private String id;
@SerializedName("index")
@Expose
private Integer index;
@SerializedName("key")
@Expose
private String key;
@SerializedName("meaning")
@Expose
private List<String> meaning = null;
@SerializedName("trait")
@Expose
private List<String> trait = null;
@SerializedName("type")
@Expose
private String type;
/**
* No args constructor for use in serialization
*
*/
public SearchText() {
}
/**
*
* @param v
* @param meaning
* @param index
* @param trait
* @param id
* @param type
* @param key
*/
public SearchText(Integer v, String id, Integer index, String key, List<String> meaning, List<String> trait, String type) {
super();
this.v = v;
this.id = id;
this.index = index;
this.key = key;
this.meaning = meaning;
this.trait = trait;
this.type = type;
}
public Integer getV() {
return v;
}
public void setV(Integer v) {
this.v = v;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<String> getMeaning() {
return meaning;
}
public void setMeaning(List<String> meaning) {
this.meaning = meaning;
}
public List<String> getTrait() {
return trait;
}
public void setTrait(List<String> trait) {
this.trait = trait;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| [
"[email protected]"
] | |
6cb394ba038e2ce616a517a5bf0f869637b65836 | 97c2cfd517cdf2a348a3fcb73e9687003f472201 | /Java/systematic/src/com/malbec/tsdb/loader/TimeSeriesDataPoint.java | a3293f462fc6f612f0a2a1881569374580ff24d4 | [] | no_license | rsheftel/ratel | b1179fcc1ca55255d7b511a870a2b0b05b04b1a0 | e1876f976c3e26012a5f39707275d52d77f329b8 | refs/heads/master | 2016-09-05T21:34:45.510667 | 2015-05-12T03:51:05 | 2015-05-12T03:51:05 | 32,461,975 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 420 | java | package com.malbec.tsdb.loader;
import static tsdb.TimeSeries.*;
public class TimeSeriesDataPoint {
private final int id;
private final Double value;
public TimeSeriesDataPoint(int id, Double value) {
this.id = id;
this.value = value;
}
public Double value() {
return value;
}
public int id() {
return id;
}
@Override public String toString() {
return series(id).name() + " " + value;
}
}
| [
"[email protected]"
] | |
f18bba3d9d48fed98c75bd5cdd450f32035594a5 | e93747633d4b78f586f54cdafa45cf66d90be48a | /menu/src/main/java/com/feasttime/tools/ToastUtil.java | 52467f7e6b683d59f8a24169d6a8badaa4018c97 | [] | no_license | FeastTime/PadMenu | 615f1afe4c989ac0427d2bf7cd40fbf08833e850 | a49efb14e61bcd48633a2db4fd09a6a630494494 | refs/heads/master | 2021-01-01T06:08:02.275508 | 2018-03-16T12:36:54 | 2018-03-16T12:36:54 | 97,363,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 547 | java | /*
* Copyright (c) 2017. sheng yan
*/
package com.feasttime.tools;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class ToastUtil {
public static void showToast(Context mContext, String text, int duration) {
Toast mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
mToast.setDuration(duration);
mToast.show();
}
public static void showToast(Context mContext, int resId, int duration) {
showToast(mContext, mContext.getResources().getString(resId), duration);
}
}
| [
"[email protected]"
] | |
b39ce0d06f6904d91b213e7ba3c719c80068f6b7 | d2995ce7487480646e9bbaaec1fca42ff9c471b6 | /Atelier-3/MicroService-ReverseProxy/src/test/java/com/cpe/reverseproxy/MicroServiceReverseProxyApplicationTests.java | 1c08148ad81f9cf65aec1beb1e4813df7f1bdbea | [] | no_license | Nijadev69/ASI-TP | e6f7ec087c06200f5652560fafca44b3b3c36427 | 0be58056a883a63c3f789fbc43856061dadb64bb | refs/heads/master | 2022-09-29T11:07:56.477199 | 2020-06-07T18:02:32 | 2020-06-07T18:02:32 | 265,475,108 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 230 | java | package com.cpe.reverseproxy;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MicroServiceReverseProxyApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
31314dd260976b148ecd4e92da3a3fc31d0f917e | 78e613b09584faf243e460fa952d35998d16cecf | /app/src/androidTest/java/com/example/root/jsonparsingapp/ExampleInstrumentedTest.java | 399f23062c702b1584065de2f1c19891022949ce | [] | no_license | suman111/JsonParsingapp | 1dec1d9af0c95ba5fa601d7b4d0ab4a96093a20e | 6f32c2945f07dba0ba437c838d580f8527e6488f | refs/heads/master | 2021-04-25T23:58:37.946008 | 2017-10-17T13:10:47 | 2017-10-17T13:10:47 | 107,269,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package com.example.root.jsonparsingapp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.root.jsonparsingapp", appContext.getPackageName());
}
}
| [
"space@space-juan"
] | space@space-juan |
ee5637d557f5b0e12385a4b77311e823d1f220eb | 2a5c638d9e109488ea2e89e2c28184a3ac48a7c4 | /Perulangan/src/com/dicoding/javafundamental/perulangan/ForBersarang.java | 87e4ebebc4ef1ab60c2d90b393eabf57af5e4e2c | [] | no_license | ArdianChambera/DicodingJava-PBOLanjut | 0602895932d392c72be19e2cddf5bf4cf2468e14 | 788e1663ebff93fe8695ad34f09a5d6dd495ae9b | refs/heads/master | 2023-04-06T18:05:13.780099 | 2021-04-24T14:39:17 | 2021-04-24T14:39:17 | 358,510,487 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 330 | java | package com.dicoding.javafundamental.perulangan;
public class ForBersarang {
public static void main(String[] args) {
int a = 5;
for (int i = 0; i <= a; i++){
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
| [
"[email protected]"
] | |
ec551bba867468c429c828e465c39363eb799e88 | 26a5d590d00707c9215732a9ff04794f2f9ea501 | /src/main/java/de/leeksanddragons/tools/dialog/javafx/FXMLWindow.java | 3763bc29c5db0ca0e1a9f45dea4b1fc2d8cb1c71 | [
"Apache-2.0"
] | permissive | leeks-and-dragons/dialog-tool | 3c8929c38e686ed9ad360d0872a5bac23013b2fc | 90d70e9c38d0bb647b51923661a20f75798e55ec | refs/heads/master | 2021-01-20T21:07:11.842241 | 2017-08-31T16:24:31 | 2017-08-31T16:24:31 | 101,749,852 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,010 | java | package de.leeksanddragons.tools.dialog.javafx;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
/**
* Created by Justin on 30.05.2017.
*/
public class FXMLWindow {
//JavaFX stage means an window
protected Stage stage = null;
//JavaFX scene
protected Scene scene = null;
//root AnchorPane
protected Pane rootPane = null;
public FXMLWindow (String title, int width, int height, String fxmlPath, FXMLController controller) {
//create new stage
this.stage = new Stage();
//set title
stage.setTitle(title);
//set width & height
stage.setWidth(width);
stage.setHeight(height);
// load fxml
try {
FXMLLoader loader = new FXMLLoader(new File(fxmlPath).toURI().toURL());
//set controller
if (controller != null) {
loader.setController(controller);
}
rootPane = loader.load();//FXMLLoader.load(new File(fxmlPath).toURI().toURL());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
//add scene
this.scene = new Scene(this.rootPane);
//set scene
stage.setScene(scene);
//initialize controller
if (controller != null) {
controller.init(stage, scene, rootPane);
//run controller logic in new thread
new Thread(controller::run).start();
}
//show window
//stage.show();
}
public FXMLWindow (String title, int width, int height, String fxmlPath) {
this(title, width, height, fxmlPath, null);
}
public Stage getStage () {
return this.stage;
}
public void setVisible (boolean visible) {
if (!visible) {
this.stage.hide();
} else {
this.stage.show();
}
}
}
| [
"[email protected]"
] | |
ed144f90afa234a235d84051a18105dd65d8f074 | 5f40f8089b1835523f447d8c952853a094c85652 | /hive/DataCleaning/count/CountRecsReducer.java | 738e26ddfbb6bfb8562a862c16c57b5d909149e4 | [] | no_license | Mateo-Revilla/FinanceHadoop | 53f9954d9cd54fbac9356160446eda67f4762a69 | bcef79d18ed9d3bf6d5bd420eefe0aed07bda2ce | refs/heads/main | 2023-01-24T05:45:14.377672 | 2020-12-03T04:50:14 | 2020-12-03T04:50:14 | 314,890,398 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 516 | java | import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class CountRecsReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (IntWritable value : values) {
count = count + value.get();
}
context.write(new Text(key), new IntWritable(count));
}
}
| [
"[email protected]"
] | |
a3c925583d1091f1821343e270f2a6e1cb746e0a | d5b342dd8e087af7eaca1dad42f3e7b8704ab64a | /app/src/test/java/com/example/android/applifecyclecallbacks/ExampleUnitTest.java | 523880ef47930bc77ba65fdd68783639b0fa598d | [] | no_license | NaotoSama/AppLifecycleCallbacks_Udacity | 47b4f5e4ff8a44155f82d4ca3e72a098561d6f8f | dd6892f4b0e614beb24c473cca11d03a5e7ccfb4 | refs/heads/master | 2020-03-27T07:53:26.029908 | 2018-08-26T17:33:16 | 2018-08-26T17:33:16 | 146,201,777 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 402 | java | package com.example.android.applifecyclecallbacks;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
7ef18295a22400f9cdf6bb56a6b9e833a52f66f1 | fd981671150bf05f7a19f650e97ad564da7927dd | /src/me/rezscripts/rpg/spells/archer/ExplodingArrow.java | 4cb9323d82126e98a195fbf0e4db0b210ad57c7d | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | RezScripts/RPG | e217e1d223592bf22dbfac070336069624907054 | 0de76e8db32fbf92ec3add35e7afb9023c8e0ebf | refs/heads/master | 2020-05-01T06:25:54.303565 | 2019-03-23T19:26:44 | 2019-03-23T19:26:44 | 177,330,015 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,604 | java | package me.rezscipts.rpg.spells.archer;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.metadata.FixedMetadataValue;
import me.rezscipts.rpg.PlayerDataRPG;
import me.rezscipts.rpg.spells.Spell;
import me.rezscipts.rpg.spells.SpellEffect;
import me.rezscipts.rpgexperience.utils.RMetadata;
public class ExplodingArrow extends SpellEffect {
@Override
public boolean cast(Player p, final PlayerDataRPG pd, int level) {
int damage = pd.getDamage(true);
switch (level) {
case 1:
damage *= 1.3;
break;
case 2:
damage *= 1.5;
break;
case 3:
damage *= 1.7;
break;
case 4:
damage *= 1.9;
break;
case 5:
damage *= 2.1;
break;
case 6:
damage *= 2.3;
break;
case 7:
damage *= 2.5;
break;
case 8:
damage *= 2.7;
break;
case 9:
damage *= 2.9;
break;
case 10:
damage *= 3.1;
break;
}
Projectile arrow = pd.shootArrow();
arrow.setMetadata(RMetadata.META_DAMAGE, new FixedMetadataValue(Spell.plugin, 1));
arrow.setMetadata(RMetadata.META_EXPLODE, new FixedMetadataValue(Spell.plugin, damage));
Spell.notify(p, "You shoot an explosive arrow");
return true;
}
}
| [
"[email protected]"
] | |
f4206a13b4607fc3357efc4278101f8cb66c85c1 | f6a106f2e7e4567e9439e3310da2460ef154a3c1 | /GOMP_ADMIN_POC/src/main/java/com/omp/dev/settlement/action/dailysale/SettlementDevDailySaleAction.java | 375b263e2720c1b7016c0a6abb165f335ed549e1 | [] | no_license | samsik-kim/rejoice | 285c9595b9c052d38c26e73cf0842f4b94002643 | 214a2efa0b1dbac4865223bb2f049db2b26c4614 | refs/heads/master | 2020-03-30T17:44:57.405306 | 2014-01-04T14:24:36 | 2014-01-04T14:24:36 | 40,213,627 | 0 | 4 | null | null | null | null | UTF-8 | Java | false | false | 5,630 | java | /*
* COPYRIGHT(c) SK telecom 2009
* This software is the proprietary information of SK telecom.
*
* Revision History
* Author Date Description
* -------- ---------- ------------------
*
*/
package com.omp.dev.settlement.action.dailysale;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.omp.commons.action.BaseAction;
import com.omp.commons.exception.ServiceException;
import com.omp.commons.model.PagenateList;
import com.omp.commons.util.DateUtil;
import com.omp.commons.util.SessionUtil;
import com.omp.dev.settlement.model.DailySale;
import com.omp.dev.settlement.model.ProductSale;
import com.omp.dev.settlement.service.dailysale.SettlementDevDailySaleService;
import com.omp.dev.settlement.service.dailysale.SettlementDevDailySaleServiceImpl;
import com.omp.dev.user.model.Session;
/**
* SettlementAdm Action
*
* @version 0.1
*/
@SuppressWarnings("serial")
public class SettlementDevDailySaleAction extends BaseAction {
// service
private SettlementDevDailySaleService service = null;
// param
private DailySale dailySale = null;
// param
private DailySale dailySaleS = null;
// DailySale list
private List<DailySale> dailySaleList = null;
// contents list totalCount
private long totalCount;
/**
*
*/
public SettlementDevDailySaleAction() {
service = new SettlementDevDailySaleServiceImpl();
}
/**
* <b>Action</b>
* Settlement Management :
*
* @return
*/
public String dailySaleList() {
if (dailySaleS == null) {
dailySaleS = new DailySale();
// before 1 days default search
dailySaleS.setStartDate(DateUtil.getAddDay(-7, "yyyy-MM-dd"));
dailySaleS.setEndDate(DateUtil.getAddDay(0, "yyyy-MM-dd"));
}
Session session = (Session) SessionUtil.getMemberSession(this.req);
dailySaleS.setMbrNo(session.getMbrNo());
dailySaleList = service.dailySaleList(dailySaleS);
totalCount = ((PagenateList) dailySaleList).getTotalCount();
return SUCCESS;
}
public String dailySaleDetailList() {
if (dailySaleS == null) {
dailySaleS = new DailySale();
}
dailySaleS.getPage().setRows(10);
Session session = (Session) SessionUtil.getMemberSession(this.req);
dailySaleS.setMbrNo(session.getMbrNo());
dailySaleList = service.dailySaleDetailList(dailySaleS);
dailySale = service.dailySaleDetailCount(dailySaleS);
totalCount = ((PagenateList) dailySaleList).getTotalCount();
return SUCCESS;
}
public String dailySaleExcelList() {
try {
if (dailySaleS == null) {
dailySaleS = new DailySale();
// before 1 days default search
dailySaleS.setStartDate(DateUtil.getAddDay(-7, "yyyy-MM-dd"));
dailySaleS.setEndDate(DateUtil.getAddDay(0, "yyyy-MM-dd"));
}
Session session = (Session) SessionUtil.getMemberSession(this.req);
dailySaleS.setMbrNo(session.getMbrNo());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String yyyymmdd = sdf.format(new Date());
// TODO 조회기간 무력화, 페이징 조건 무력화는 commonDao에서 처리되도록 되어 있슴
this.setDownloadFile(this.service.dailySaleExcelList(this.dailySaleS), "application/vnd.ms-excel; charset=UTF-8", "DailySale-"+yyyymmdd+ ".xls");
return SUCCESS;
} catch (Exception e) {
throw new ServiceException("dailySaleExcelList fail.", e);
}
}
public String dailySaleDetailExcelList() {
try {
if (dailySaleS == null) {
dailySaleS = new DailySale();
return SUCCESS;
}
Session session = (Session) SessionUtil.getMemberSession(this.req);
dailySaleS.setMbrNo(session.getMbrNo());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String yyyymmdd = sdf.format(new Date());
// TODO 조회기간 무력화, 페이징 조건 무력화는 commonDao에서 처리되도록 되어 있슴
this.setDownloadFile(this.service.dailySaleDetailExcelList(this.dailySaleS), "application/vnd.ms-excel; charset=UTF-8", "DailySaleDetail-"+yyyymmdd+ ".xls");
return SUCCESS;
} catch (Exception e) {
throw new ServiceException("dailySaleDetailExcelList fail.", e);
}
}
// ===================== SET/GET =============================================
/**
* list total count
* @return long totalCount
*/
public long getTotalCount() {
return totalCount;
}
/**
* @return the dailySale
*/
public DailySale getDailySale() {
return dailySale;
}
/**
* @param dailySale the dailySale to set
*/
public void setDailySale(DailySale dailySale) {
this.dailySale = dailySale;
}
/**
* @return the dailySaleList
*/
public List<DailySale> getDailySaleList() {
return dailySaleList;
}
/**
* @param dailySaleList the dailySaleList to set
*/
public void setDailySaleList(List<DailySale> dailySaleList) {
this.dailySaleList = dailySaleList;
}
/**
* @return the dailySaleS
*/
public DailySale getDailySaleS() {
return dailySaleS;
}
/**
* @param dailySaleS the dailySaleS to set
*/
public void setDailySaleS(DailySale dailySaleS) {
this.dailySaleS = dailySaleS;
}
/**
* @param totalCount the totalCount to set
*/
public void setTotalCount(long totalCount) {
this.totalCount = totalCount;
}
} | [
"[email protected]"
] | |
d01c6c034574169b2a19ebb5d13ae64ff8c7aa49 | e45f290038946dc567da05ae6491e5a5eae4c2bf | /models/cinematic/plugins/org.obeonetwork.dsl.cinematic.edit/src-gen/org/obeonetwork/dsl/cinematic/flow/components/FlowPropertiesEditionComponent.java | 59ac75b0485a317c046d42f356ea6c0df1a0d64d | [] | no_license | carsonshan/InformationSystem | e54882507d646fe5c706b248a0ebf56498e4722c | 192dd9a6ac71a95d96bf39107790c33450397132 | refs/heads/master | 2020-03-19T07:20:56.817458 | 2017-09-26T09:51:13 | 2017-09-26T12:35:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,355 | java | /**
* Generated with Acceleo
*/
package org.obeonetwork.dsl.cinematic.flow.components;
// Start of user code for imports
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.context.PropertiesEditingContext;
import org.eclipse.emf.eef.runtime.impl.components.ComposedPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.providers.PropertiesEditingProvider;
import org.obeonetwork.dsl.cinematic.flow.Flow;
import org.obeonetwork.dsl.cinematic.flow.parts.FlowPropertiesEditionPart;
import org.obeonetwork.dsl.cinematic.flow.parts.FlowViewsRepository;
import org.obeonetwork.dsl.environment.components.MetadataCptPropertiesEditionComponent;
import org.obeonetwork.dsl.environment.parts.EnvironmentViewsRepository;
// End of user code
/**
*
*
*/
public class FlowPropertiesEditionComponent extends ComposedPropertiesEditionComponent {
/**
* The Flow part
*
*/
private FlowPropertiesEditionPart flowPart;
/**
* The FlowFlowPropertiesEditionComponent sub component
*
*/
protected FlowFlowPropertiesEditionComponent flowFlowPropertiesEditionComponent;
/**
* The MetadataCptPropertiesEditionComponent sub component
*
*/
protected MetadataCptPropertiesEditionComponent metadataCptPropertiesEditionComponent;
/**
* Parameterized constructor
*
* @param flow the EObject to edit
*
*/
public FlowPropertiesEditionComponent(PropertiesEditingContext editingContext, EObject flow, String editing_mode) {
super(editingContext, editing_mode);
if (flow instanceof Flow) {
PropertiesEditingProvider provider = null;
provider = (PropertiesEditingProvider)editingContext.getAdapterFactory().adapt(flow, PropertiesEditingProvider.class);
flowFlowPropertiesEditionComponent = (FlowFlowPropertiesEditionComponent)provider.getPropertiesEditingComponent(editingContext, editing_mode, FlowFlowPropertiesEditionComponent.FLOW_PART, FlowFlowPropertiesEditionComponent.class);
addSubComponent(flowFlowPropertiesEditionComponent);
provider = (PropertiesEditingProvider)editingContext.getAdapterFactory().adapt(flow, PropertiesEditingProvider.class);
metadataCptPropertiesEditionComponent = (MetadataCptPropertiesEditionComponent)provider.getPropertiesEditingComponent(editingContext, editing_mode, MetadataCptPropertiesEditionComponent.METADATAS_PART, MetadataCptPropertiesEditionComponent.class);
addSubComponent(metadataCptPropertiesEditionComponent);
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.impl.components.ComposedPropertiesEditionComponent#
* getPropertiesEditionPart(int, java.lang.String)
*
*/
public IPropertiesEditionPart getPropertiesEditionPart(int kind, String key) {
if (FlowFlowPropertiesEditionComponent.FLOW_PART.equals(key)) {
flowPart = (FlowPropertiesEditionPart)flowFlowPropertiesEditionComponent.getPropertiesEditionPart(kind, key);
return (IPropertiesEditionPart)flowPart;
}
return super.getPropertiesEditionPart(kind, key);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.impl.components.ComposedPropertiesEditionComponent#
* setPropertiesEditionPart(java.lang.Object, int,
* org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart)
*
*/
public void setPropertiesEditionPart(java.lang.Object key, int kind, IPropertiesEditionPart propertiesEditionPart) {
if (FlowViewsRepository.Flow_.class == key) {
super.setPropertiesEditionPart(key, kind, propertiesEditionPart);
flowPart = (FlowPropertiesEditionPart)propertiesEditionPart;
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.impl.components.ComposedPropertiesEditionComponent#
* initPart(java.lang.Object, int, org.eclipse.emf.ecore.EObject,
* org.eclipse.emf.ecore.resource.ResourceSet)
*
*/
public void initPart(java.lang.Object key, int kind, EObject element, ResourceSet allResource) {
if (key == FlowViewsRepository.Flow_.class) {
super.initPart(key, kind, element, allResource);
}
if (key == EnvironmentViewsRepository.Metadatas.class) {
super.initPart(key, kind, element, allResource);
}
}
}
| [
"[email protected]"
] | |
2a45b0dd317f9cc8949c84bb6a992ea05bd7693c | 038ee6b20cae51169a2ed4ed64a7b8e99b5cbaad | /schemaOrgDomaConv/src/org/kyojo/schemaOrg/m3n3/doma/core/container/EqualConverter.java | a394c2303dda0f5eb200405d1cf7a9155362d534 | [
"Apache-2.0"
] | permissive | nagaikenshin/schemaOrg | 3dec1626781913930da5585884e3484e0b525aea | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | refs/heads/master | 2021-06-25T04:52:49.995840 | 2019-05-12T06:22:37 | 2019-05-12T06:22:37 | 134,319,974 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 530 | java | package org.kyojo.schemaorg.m3n3.doma.core.container;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaorg.m3n3.core.impl.EQUAL;
import org.kyojo.schemaorg.m3n3.core.Container.Equal;
@ExternalDomain
public class EqualConverter implements DomainConverter<Equal, String> {
@Override
public String fromDomainToValue(Equal domain) {
return domain.getNativeValue();
}
@Override
public Equal fromValueToDomain(String value) {
return new EQUAL(value);
}
}
| [
"[email protected]"
] | |
794281fe7ea8f9c8d0d0e95950aa110bcd12b75e | 980f02496fe076f930cc7c9ecb4db3a19bef7060 | /School project: Java Application/ht/musiikki/src/rekisteri/Albumit.java | debd88b3d878ebc97f279697c3eda50a3d41b208 | [] | no_license | tatuniskanen/Cybersecurity | 934c4843e84badcd8b2a3678f1d9059f56fc379d | 22ce874200efdb8ff70d18d9a0ff495f51e3efc8 | refs/heads/main | 2023-03-08T06:16:01.677471 | 2021-02-24T12:50:49 | 2021-02-24T12:50:49 | 339,860,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,824 | java | package rekisteri;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;
import fi.jyu.mit.ohj2.WildChars;
/**
* @author Taina Patrikainen ja Tatu Niskanen
* @version 20.5.2019
*
*/
public class Albumit implements Iterable<Albumi> {
private static final int MAX_ALBUMEJA = 7;
private int lkm = 0;
private String tiedostonPerusNimi = "";
private Albumi alkiot[] = new Albumi[MAX_ALBUMEJA];
private boolean muutettu = false;
/**
* Albumien alustaminen
*/
public Albumit() {
//
}
/**
* Lisää uuden albumin tietorakenteeseen.
* @param albumi lisättävän albumin viite
* @example
* <pre name="test">
* Albumit albumit = new Albumit();
* Albumi alb1 = new Albumi(), alb2 = new Albumi();
* albumit.getLkm() === 0;
* albumit.lisaa(alb1); albumit.getLkm() === 1;
* albumit.lisaa(alb2); albumit.getLkm() === 2;
* albumit.lisaa(alb1); albumit.getLkm() === 3;
* albumit.anna(0) === alb1;
* albumit.anna(1) === alb2;
* albumit.anna(2) === alb1;
* albumit.anna(1) == alb1 === false;
* albumit.anna(1) == alb2 === true;
* albumit.lisaa(alb1); albumit.getLkm() === 4;
* albumit.lisaa(alb1); albumit.getLkm() === 5;
* </pre>
*/
public void lisaa(Albumi albumi) {
if (lkm >= alkiot.length) {
int koko = alkiot.length + 7;
Albumi kopioalkiot[] = new Albumi[koko];
int j = 0;
for (int i = 0; i < alkiot.length; i++) {
kopioalkiot[j] = alkiot[i];
j++;
}
alkiot = kopioalkiot;
}
alkiot[lkm++] = albumi;
muutettu = true;
}
/**
* Korvaa albumin tietorakenteessa. Ottaa albumin omistukseensa.
* Etsitään samalla tunnusnumerolla oleva albumi. Jos ei löydy,
* niin lisätään uutena albumina.
* @param albumi lisättävän albumin viite. Huom tietorakenne muuttuu omistajaksi
* @throws IOException jos tietorakenne on jo täynnä
* @example
* <pre name="test">
* #THROWS IOException,CloneNotSupportedException
* #PACKAGEIMPORT
* Albumit albumit = new Albumit();
* Albumi alb1 = new Albumi(), alb2 = new Albumi();
* alb1.rekisteroi(); alb2.rekisteroi();
* albumit.getLkm() === 0;
* albumit.korvaaTaiLisaa(alb1); albumit.getLkm() === 1;
* albumit.korvaaTaiLisaa(alb2); albumit.getLkm() === 2;
* Albumi alb3 = alb1.clone();
* alb3.aseta(3,"kkk");
* Iterator<Albumi> it = albumit.iterator();
* it.next() == alb1 === true;
* albumit.korvaaTaiLisaa(alb3); albumit.getLkm() === 2;
* it = albumit.iterator();
* Albumi alb0 = it.next();
* alb0 === alb3;
* alb0 == alb3 === true;
* alb0 == alb1 === false;
* </pre>
*/
public void korvaaTaiLisaa(Albumi albumi) throws IOException {
int id = albumi.getAlId();
for (int i = 0; i < lkm; i++) {
if (alkiot[i].getAlId() == id) {
alkiot[i] = albumi;
muutettu = true;
return;
}
}
lisaa(albumi);
}
/**
* Käy albumien tietorakenteen läpi ja vertaa sitä merkkijonoon.
* Jos löytyy samanniminen albumi palauttaa sen ID:n, jos ei löydy
* niin palauttaa 0.
* @param albumi minkä nimisen albumin ID halutaan
* @return Albumin Id
* @example
* <pre name="test">
* Albumit Albumit = new Albumit();
* Albumi al1 = new Albumi();
* al1.rekisteroi();
* al1.aseta(0, Integer.toString(11));
* al1.aseta(1, "Joululaulut");
* Albumit.lisaa(al1);
* Albumit.palautaAlbuminId("Joululaulut") === 11;
* Albumit.palautaAlbuminId("JouLULauLUT") === 11;
* Albumit.palautaAlbuminId("gfgffgf") === 0;
* </pre>
*/
public int palautaAlbuminId(String albumi) {
int id = 0;
for (int i = 0; i < lkm; i++) {
if (alkiot[i].getNimi().equalsIgnoreCase(albumi)) {
id = alkiot[i].getAlId();
break;
}
}
return id;
}
/**
* Poistaa Albumin jolla on valittu tunnusnumero
* @param id poistettavan albumin tunnusnumero
* @return 1 jos poistettiin, 0 jos ei löydy
* @example
* <pre name="test">
* #THROWS IOException
* Albumit albumit = new Albumit();
* Albumi al1 = new Albumi(), al2 = new Albumi(), al3 = new Albumi();
* al1.rekisteroi(); al2.rekisteroi(); al3.rekisteroi();
* int id1 = al1.getAlId();
* albumit.lisaa(al1); albumit.lisaa(al2); albumit.lisaa(al3);
* albumit.poista(id1+1) === 1;
* albumit.anna(id1+1); #THROWS IndexOutOfBoundsException
* albumit.getLkm() === 2;
* albumit.poista(id1) === 1; albumit.getLkm() === 1;
* albumit.poista(id1+3) === 0; albumit.getLkm() === 1;
* </pre>
*
*/
public int poista(int id) {
int ind = etsiId(id);
if (ind < 0)
return 0;
lkm--;
for (int i = ind; i < lkm; i++)
alkiot[i] = alkiot[i + 1];
alkiot[lkm] = null;
muutettu = true;
return 1;
}
/**
* Etsii albumin id:n perusteella
* @param id tunnusnumero, jonka mukaan etsitään
* @return löytyneen albumin indeksi tai -1 jos ei löydy
* <pre name="test">
* #THROWS IOException
* Albumit albumit = new Albumit();
* Albumi a1 = new Albumi(), a2 = new Albumi(), a3 = new Albumi();
* a1.rekisteroi(); a2.rekisteroi(); a3.rekisteroi();
* int id1 = a1.getAlId();
* albumit.lisaa(a1); albumit.lisaa(a2); albumit.lisaa(a3);
* albumit.etsiId(id1+1) === 1;
* albumit.etsiId(id1+2) === 2;
* </pre>
*/
public int etsiId(int id) {
for (int i = 0; i < lkm; i++)
if (id == alkiot[i].getAlId())
return i;
return -1;
}
/**
* Palauttaa viitteen n:een albumiin
* @param i albumin paikka taulukossa
* @return i:en albumin viitteen
* @throws IndexOutOfBoundsException jos indeksiä ei ole
*/
public Albumi anna(int i) throws IndexOutOfBoundsException {
if (i == -1)
return null; // i = -1 jos etsiID:llä ei löydy albumia.
if (i < 0 || lkm <= i)
throw new IndexOutOfBoundsException("Sopimaton indeksi: " + i);
return alkiot[i];
}
/**
* Lukee albumit tiedostosta.
* @param tied tiedoston nimen alkuosa
* @throws IOException jos lukeminen epäonnistuu
*
* @example
* <pre name="test">
* #THROWS IOException
* #import java.io.File;
* #import java.io.IOException;
* #import java.util.Iterator;
* Albumit albumit = new Albumit();
* Albumi al1 = new Albumi(); al1.taytaAlbumi();
* Albumi al2 = new Albumi(); al2.taytaAlbumi();
* Albumi al3 = new Albumi(); al3.taytaAlbumi();
* Albumi al4 = new Albumi(); al4.taytaAlbumi();
* Albumi al5 = new Albumi(); al5.taytaAlbumi();
* String tiedNimi = "testialbumit";
* File ftied = new File(tiedNimi+".dat");
* ftied.delete();
* albumit.lueTiedostosta(tiedNimi); #THROWS IOException
* albumit.lisaa(al1);
* albumit.lisaa(al2);
* albumit.lisaa(al3);
* albumit.lisaa(al4);
* albumit.lisaa(al5);
* albumit.tallenna();
* albumit = new Albumit();
* albumit.lueTiedostosta(tiedNimi);
* Iterator<Albumi> i = albumit.iterator();
* i.next().toString() === al1.toString();
* i.next().toString() === al2.toString();
* i.next().toString() === al3.toString();
* i.next().toString() === al4.toString();
* i.next().toString() === al5.toString();
* i.hasNext() === false;
* albumit.lisaa(al4);
* albumit.tallenna();
* ftied.delete() === true;
* File fbak = new File(tiedNimi+".bak");
* fbak.delete() === true;
* </pre>
*/
public void lueTiedostosta(String tied) throws IOException {
setTiedostonPerusNimi(tied);
try (Scanner fi = new Scanner(
new FileInputStream(new File(getTiedostonNimi())))) {
while (fi.hasNext()) {
String rivi = fi.nextLine();
if ("".equals(rivi) || rivi.charAt(0) == ';')
continue;
Albumi al = new Albumi();
al.parse(rivi); // voisi olla virhekäsittely
lisaa(al);
}
muutettu = false;
} catch (FileNotFoundException e) {
throw new IOException(
"Tiedosto " + getTiedostonNimi() + " ei aukea");
}
}
/**
* Luetaan aikaisemmin annetun nimisestä tiedostosta
* @throws IOException jos tulee poikkeus
*/
public void lueTiedostosta() throws IOException {
lueTiedostosta(getTiedostonPerusNimi());
}
/**
* Tallentaa albumit tiedostoon.
* @throws IOException virheilmoitus jos talletus epäonnistuu
*/
public void tallenna() throws IOException {
if (!muutettu)
return;
File fbak = new File(getBakNimi());
File ftied = new File(getTiedostonNimi());
fbak.delete(); // if ... System.err.println("Ei voi tuhota");
ftied.renameTo(fbak); // if ... System.err.println("Ei voi nimetä");
try (PrintWriter fo = new PrintWriter(
new FileWriter(ftied.getCanonicalPath()))) {
for (Albumi al : this) {
fo.println(al.toString());
}
} catch (FileNotFoundException ex) {
throw new IOException("Tiedosto " + ftied.getName() + " ei aukea");
} catch (IOException ex) {
throw new IOException("Tiedoston " + ftied.getName()
+ " kirjoittamisessa ongelmia");
}
muutettu = false;
}
/**
* Palauttaa albumien lukumäärän
* @return albumien lukumäärä
*/
public int getLkm() {
return lkm;
}
/**
* Asettaa tiedoston perusnimen ilman tarkenninta
* @param tied tallennustiedoston perusnimi
*/
public void setTiedostonPerusNimi(String tied) {
tiedostonPerusNimi = tied;
}
/**
* Palauttaa tiedoston nimen, jota käytetään tallennukseen
* @return tallennustiedoston nimi
*/
public String getTiedostonPerusNimi() {
return tiedostonPerusNimi;
}
/**
* Palauttaa tiedoston nimen, jota käytetään tallennukseen
* @return tallennustiedoston nimi
*/
public String getTiedostonNimi() {
return tiedostonPerusNimi + ".dat";
}
/**
* Palauttaa varakopiotiedoston nimen
* @return varakopiotiedoston nimi
*/
public String getBakNimi() {
return tiedostonPerusNimi + ".bak";
}
/**
* Luokka albumien iteroimiseksi.
* @example
* <pre name="test">
* #THROWS IOException
* #PACKAGEIMPORT
* #import java.util.*;
*
* Albumit albumit = new Albumit();
* Albumi JVG1 = new Albumi(), JVG2 = new Albumi();
* JVG1.rekisteroi(); JVG2.rekisteroi();
*
* albumit.lisaa(JVG1);
* albumit.lisaa(JVG2);
* albumit.lisaa(JVG1);
*
* StringBuffer ids = new StringBuffer(30);
* for (Albumi albumi:albumit) // Kokeillaan for-silmukan toimintaa
* ids.append(" "+albumi.getAlId());
*
* String tulos = " " + JVG1.getAlId() + " " + JVG2.getAlId() + " " + JVG1.getAlId();
*
* ids.toString() === tulos;
*
* ids = new StringBuffer(30);
* for (Iterator<Albumi> i=albumit.iterator(); i.hasNext(); ) { // ja iteraattorin toimintaa
* Albumi albumi = i.next();
* ids.append(" "+albumi.getAlId());
* }
*
* ids.toString() === tulos;
*
* Iterator<Albumi> i=albumit.iterator();
* i.next() == JVG1 === true;
* i.next() == JVG2 === true;
* i.next() == JVG1 === true;
*
* i.next(); #THROWS NoSuchElementException
*
* </pre>
*/
public class AlbumitIterator implements Iterator<Albumi> {
private int kohdalla = 0;
/**
* Onko olemassa vielä seuraavaa albumia
* @see java.util.Iterator#hasNext()
* @return true jos on vielä albumeita
*/
@Override
public boolean hasNext() {
return kohdalla < getLkm();
}
/**
* Annetaan seuraava albumi
* @return seuraava albumi
* @throws NoSuchElementException jos seuraava alkiota ei enää ole
* @see java.util.Iterator#next()
*/
@Override
public Albumi next() throws NoSuchElementException {
if (!hasNext())
throw new NoSuchElementException("Ei oo");
return anna(kohdalla++);
}
/**
* Tuhoamista ei ole toteutettu
* @throws UnsupportedOperationException aina
* @see java.util.Iterator#remove()
*/
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Me ei poisteta");
}
}
/**
* Palautetaan iteraattori albumeistaan.
* @return albumi iteraattori
*/
@Override
public Iterator<Albumi> iterator() {
return new AlbumitIterator();
}
/**
* Palauttaa "taulukossa" hakuehtoon vastaavien albumien viitteet
* @param hakuehto hakuehto
* @param k etsittävän kentän indeksi
* @return tietorakenteen löytyneistä albumeista
* @example
* <pre name="test">
* #THROWS IOException
* Albumit albumit = new Albumit();
* Albumi albumi1 = new Albumi(); albumi1.parse("1|Moiiii");
* Albumi albumi2 = new Albumi(); albumi2.parse("2|Deeku");
* Albumi albumi3 = new Albumi(); albumi3.parse("3|Ejejej");
* Albumi albumi4 = new Albumi(); albumi4.parse("4|Laulut");
* Albumi albumi5 = new Albumi(); albumi5.parse("5|Kesä");
* albumit.lisaa(albumi1); albumit.lisaa(albumi2); albumit.lisaa(albumi3); albumit.lisaa(albumi4); albumit.lisaa(albumi5);
* Collection<Integer> loytyneet;
* loytyneet = albumit.etsi("*e*",1);
* loytyneet.size() === 3;
*
* loytyneet = albumit.etsi("*d*",1);
* loytyneet.size() === 1;
*
* loytyneet = albumit.etsi(null,-1);
* loytyneet.size() === 5;
* </pre>
*/
public Collection<Integer> etsi(String hakuehto, int k) {
String ehto = "*";
if (hakuehto != null && hakuehto.length() > 0)
ehto = hakuehto;
int hk = k;
List<Integer> loytyneet = new ArrayList<Integer>();
for (Albumi albumi : this) {
if (WildChars.onkoSamat(albumi.anna(hk), ehto))
loytyneet.add(albumi.getAlId());
}
return loytyneet;
}
/**
* Testiohjelma albumeille
* @param args ei käytössä
*/
public static void main(String[] args) {
Albumit albumit = new Albumit();
Albumi al1 = new Albumi();
al1.rekisteroi();
al1.taytaAlbumi();
Albumi al2 = new Albumi();
al2.rekisteroi();
al2.taytaAlbumi();
Albumi al3 = new Albumi();
al3.rekisteroi();
al3.taytaAlbumi();
Albumi al4 = new Albumi();
al4.rekisteroi();
al4.taytaAlbumi();
albumit.lisaa(al1);
albumit.lisaa(al2);
albumit.lisaa(al3);
albumit.lisaa(al4);
albumit.lisaa(al4);
System.out.println("============= albumit testi =================");
for (int i = 0; i < albumit.getLkm(); i++) {
Albumi albumi = albumit.anna(i);
albumi.tulosta(System.out);
System.out.println("======================");
}
}
}
| [
"[email protected]"
] | |
93ec8db7418b5169a71d1b0ee8164041466f615f | 43ea91f3ca050380e4c163129e92b771d7bf144a | /services/mpc/src/main/java/com/huaweicloud/sdk/mpc/v1/model/CreateMergeChannelsTaskRequest.java | eecb4ac77c08d4b1bf5b415feff277570fc956ef | [
"Apache-2.0"
] | permissive | wxgsdwl/huaweicloud-sdk-java-v3 | 660602ca08f32dc897d3770995b496a82a1cc72d | ee001d706568fdc7b852792d2e9aefeb9d13fb1e | refs/heads/master | 2023-02-27T14:20:54.774327 | 2021-02-07T11:48:35 | 2021-02-07T11:48:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,312 | java | package com.huaweicloud.sdk.mpc.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.huaweicloud.sdk.mpc.v1.model.CreateMergeChannelsReq;
import java.util.function.Consumer;
import java.util.Objects;
/**
* Request Object
*/
public class CreateMergeChannelsTaskRequest {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="body")
private CreateMergeChannelsReq body = null;
public CreateMergeChannelsTaskRequest withBody(CreateMergeChannelsReq body) {
this.body = body;
return this;
}
public CreateMergeChannelsTaskRequest withBody(Consumer<CreateMergeChannelsReq> bodySetter) {
if(this.body == null ){
this.body = new CreateMergeChannelsReq();
bodySetter.accept(this.body);
}
return this;
}
/**
* Get body
* @return body
*/
public CreateMergeChannelsReq getBody() {
return body;
}
public void setBody(CreateMergeChannelsReq body) {
this.body = body;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CreateMergeChannelsTaskRequest createMergeChannelsTaskRequest = (CreateMergeChannelsTaskRequest) o;
return Objects.equals(this.body, createMergeChannelsTaskRequest.body);
}
@Override
public int hashCode() {
return Objects.hash(body);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateMergeChannelsTaskRequest {\n");
sb.append(" body: ").append(toIndentedString(body)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"[email protected]"
] | |
40f5e578702a76992e0b6ae8424ca6e2096c5bb9 | 1263588f64861ad6a06571ef31ec52507a92f298 | /app/src/main/java/at/ac/univie/hci/btctracker/Data/Transaction.java | 5007589c7ebdf1c98d5a2c5c2a91cd6fbbe78951 | [] | no_license | zhanata88/bitcoin_tracker | 74ec5424503870b44f1714bb6782c6af4fbfddec | cecf3b4c1c586678fdc13958e67b543422fa86ce | refs/heads/master | 2020-04-21T14:13:28.450371 | 2019-02-07T20:01:05 | 2019-02-07T20:01:05 | 169,627,581 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,150 | java | package at.ac.univie.hci.btctracker.Data;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by rabizo on 23.04.2018.
*/
public class Transaction implements Serializable{
private int transactionId;
private String currencyId;
private Double priceInBtc;
private Double priceInUsd;
private Double priceInEur;
private int image;
private String date;
private Double amountOfTransaction;
private String buy; //if transaction is sell than buy = false;
public Transaction(int transactionId, String currencyId, Double priceInBtc, Double priceInUsd, Double priceInEur,
Double amountOfTransaction, String buy, int image, String date) {
this.transactionId = transactionId;
this.currencyId = currencyId;
this.priceInBtc = priceInBtc;
this.priceInUsd = priceInUsd;
this.priceInEur = priceInEur;
this.amountOfTransaction = amountOfTransaction;
this.buy = buy;
this.image = image;
this.date = date;
}
public int getTransactionId() {
return transactionId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public String getCurrencyId() {
return currencyId;
}
public void setCurrencyId(String currencyId) {
this.currencyId = currencyId;
}
public Double getPriceInBtc() {
return priceInBtc;
}
public void setPriceInBtc(Double priceInBtc) {
this.priceInBtc = priceInBtc;
}
public Double getPriceInUsd() {
return priceInUsd;
}
public void setPriceInUsd(Double priceInUsd) {
this.priceInUsd = priceInUsd;
}
public Double getPriceInEur() {
return priceInEur;
}
public void setPriceInEur(Double priceInEur) {
this.priceInEur = priceInEur;
}
public Double getAmountOfTransaction() {
return amountOfTransaction;
}
public void setAmountOfTransaction(Double amountOfTransaction) {
this.amountOfTransaction = amountOfTransaction;
}
public String getBuy() {
return buy;
}
public void setBuy(String buy) {
this.buy = buy;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public void setDate(String date) {
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
//Date date1=df.format(date);
}
public String getDate() {
return this.date;
}
@Override
public String toString() {
return "Transaction{" +
"transactionId=" + this.transactionId +
", currencyId='" + this.currencyId + '\'' +
", priceInBtc=" + this.priceInBtc +
", priceInUsd=" + this.priceInUsd +
", priceInEur=" + this.priceInEur +
", amountOfTransaction=" + this.amountOfTransaction +
", buy=" + this.buy +
'}';
}
}
| [
"[email protected]"
] | |
76aa3be12633e82b250fac4d267e271dc92b0ba3 | 20626716067917100bc753cb9be93a3efc1117e4 | /sdk/network/mgmt/src/main/java/com/azure/management/network/ResourceSet.java | 9f25a1cdebf16c4102bc6319dd600b0270dc4888 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-or-later",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla"
] | permissive | FredGao-new/azure-sdk-for-java | e120920335326a0c49c3243e83b28f64e1ff5b25 | 36a0b761732f4913ca3ae225921d28400f6860e3 | refs/heads/master | 2020-11-23T20:48:45.641919 | 2020-04-13T11:11:25 | 2020-04-13T11:11:25 | 227,558,471 | 0 | 0 | MIT | 2019-12-12T08:36:38 | 2019-12-12T08:36:37 | null | UTF-8 | Java | false | false | 1,139 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.management.network;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* The ResourceSet model.
*/
@Fluent
public class ResourceSet {
/*
* The list of subscriptions.
*/
@JsonProperty(value = "subscriptions")
private List<String> subscriptions;
/**
* Get the subscriptions property: The list of subscriptions.
*
* @return the subscriptions value.
*/
public List<String> subscriptions() {
return this.subscriptions;
}
/**
* Set the subscriptions property: The list of subscriptions.
*
* @param subscriptions the subscriptions value to set.
* @return the ResourceSet object itself.
*/
public ResourceSet withSubscriptions(List<String> subscriptions) {
this.subscriptions = subscriptions;
return this;
}
}
| [
"[email protected]"
] | |
2cd66e1599df72c8ca7eab35173aa6410eda35ee | fb81dd63a72f15dd6cc48bcf124e5a05d3bb3bd6 | /Easy/Plus Minus.java | be2141d6ec65e2e2fec887b0b5abb170f6365dce | [] | no_license | emremrah/hackerrank-solutions | 4d43dd7878d48a06bda37be64156f37d2ba3593b | 789771a3910993878a0aebbda01d10bce3f4fe65 | refs/heads/master | 2020-03-16T22:37:37.722683 | 2018-05-12T18:47:58 | 2018-05-12T18:47:58 | 133,046,561 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,128 | java | /*
https://www.hackerrank.com/challenges/plus-minus/problem
*/
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the plusMinus function below.
*/
static void plusMinus(int[] arr) {
int pos=0, neg=0, zer=0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) pos++;
else if (arr[i] < 0) neg++;
else zer++;
}
System.out.println((float)pos / arr.length);
System.out.println((float)neg / arr.length);
System.out.println((float)zer / arr.length);
}
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = Integer.parseInt(scan.nextLine().trim());
int[] arr = new int[n];
String[] arrItems = scan.nextLine().split(" ");
for (int arrItr = 0; arrItr < n; arrItr++) {
int arrItem = Integer.parseInt(arrItems[arrItr].trim());
arr[arrItr] = arrItem;
}
plusMinus(arr);
}
}
| [
"[email protected]"
] | |
bb99f0bea3eec7e0d48082cd5cf4f2231866746e | 359e5b7842e810a7c5a64e0bc9104618ad7a66e8 | /src/java/Controller/LibroController.java | 116a72416f66171b3404939ad5fbccaa51eec544 | [] | no_license | KOMVA3/TIS-BIBLIOTECA | 9dfe02c2618427c99ca82150370718b58e2c2de5 | e4781289c004d8013e322d91ebcab9f4f4617ba9 | refs/heads/master | 2020-09-10T19:05:42.100228 | 2019-11-15T00:09:14 | 2019-11-15T00:09:14 | 221,808,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,342 | java | /*
* 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 Controller;
import model.Libro;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author crfsy
*/
@WebServlet(name = "LibroController", urlPatterns = {"/LibroController"})
public class LibroController extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LibroController</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LibroController at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String palabra=request.getParameter("palabra");
String accion=request.getParameter("accion");
if (accion.equals("buscar")){
request.getRequestDispatcher("user_view_biblio.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"[email protected]"
] | |
ce7064c92a080db2690b80a02ae324cd0cd7fa5d | a5fb2f75f1fe093bac37ab560ddf77075fd64c87 | /src/com/yyHaker/lexical/scanner/AnalyzerByFA.java | 0ca250871d09754bdb7f493bc4029d23008a16f8 | [] | no_license | yyHaker/myComplierByJava | 5f7a2f45c2c7df78d943e9924ed6948910206a58 | 2eb1a816482885679b171c4d8855e817d6c3d9b2 | refs/heads/master | 2020-06-18T06:41:21.366502 | 2016-11-30T04:42:37 | 2016-11-30T04:42:37 | 75,151,986 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,347 | java | package com.yyHaker.lexical.scanner;
import com.yyHaker.lexical.model.*;
import com.yyHaker.lexical.model.Error;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;
/**
* AnalyzerByFA
*扫描输入的字符
* 1.预处理 滤掉空格,跳过注释、换行符
* 2.识别各种字符,输出token序列
* 关键字、特殊字符、单界符、数学运算符、复合运算符、常量类型等等
* 实现的主要思想是基于DFA:通过将完整的DFA用三元组的格式写在文件中,然后实现
* 基本自动化判断逻辑,根据导入的DFA来进行词法分析
* 存储结构:主要是用了一个Node类的数据结构
* @author Le Yuan
* @date 2016/10/15
*/
public class AnalyzerByFA {
//记录输出的指定格式 (设置为静态,便于语法分析器调用)
public static List<TokenString> tokenStringList=new ArrayList<TokenString>();
//记录输出的token词法单元
private static List<KeyInfor> tokenList=new ArrayList<KeyInfor>();
//记录错误信息
private List<Error> errorList=new ArrayList<Error>();
//记录输入的总的字符
private String input;
//记录输入字符的下标
private int inputIndex;
//记录当前字符
private char currentCharacter;
//记录当前行号
private int row=1;
//输入框中的文本字符串
public static String codeText;
private List<Node> nodeList; //存放节点的集合
private List<Integer> finiteStateNodeList;//终极状态代号的集合
public List<KeyInfor> getTokenList() {
return tokenList;
}
public List<Error> getErrorList() {
return errorList;
}
public List<Node> getNodeList() {
return nodeList;
}
public List<Integer> getFiniteStateNodeList() {
return finiteStateNodeList;
}
com.yyHaker.lexical.scanner.Scanner myScanner=new com.yyHaker.lexical.scanner.Scanner();
public AnalyzerByFA() {
nodeList=new ArrayList<Node>();
finiteStateNodeList=new ArrayList<Integer>();
}
/**
* 读取下一个字符,下标为当前字符的下标
* @return currentCharacter
*/
private char getChar(){
inputIndex++;
if(inputIndex<input.length()){
currentCharacter=input.charAt(inputIndex);
}
return currentCharacter;
}
/**
* 判断终态集合中是否存在代号
* @param state
* @return
*/
public boolean isExistFiniteState(int state){
for (int a:finiteStateNodeList) {
if (a==state) return true;
}
return false;
}
/*public boolean isMatchRegex(String myString,String regex){
myString.matches(regex);
}*/
/**
* 判断节点集合中是否存在代号和currentNode相同的node
* @param currentNode
* @return Node
*/
public Node getNodeFromNodeList(int currentNode){
for (Node myNode:nodeList) {
if (myNode.getCurrentState()==currentNode) return myNode;
}
return null;
}
/**
* 从FA文件中读取状态
* @param file
*/
public void getStateFromFA(File file){
try {
FileInputStream fis=new FileInputStream(file);
java.util.Scanner in=new Scanner(fis);
while (in.hasNextLine()){
String line=in.nextLine().trim();
String []tokens=line.split("~");
int currentState;
String regex;
int nextState;
//获得currentState
if (tokens[0].contains("#")){
tokens[0]=tokens[0].substring(0,tokens[0].length()-1);
currentState=Integer.parseInt(tokens[0]);
if(!isExistFiniteState(currentState)) {
finiteStateNodeList.add(currentState);
}
}else {
currentState=Integer.parseInt(tokens[0]);
}
//获得regex
regex=tokens[1];
//获得nextState
if (tokens[2].contains("#")){
tokens[2]=tokens[2].substring(0,tokens[2].length()-1);
nextState=Integer.parseInt(tokens[2]);
if(!isExistFiniteState(nextState)) {
finiteStateNodeList.add(nextState);
}
}else {
nextState=Integer.parseInt(tokens[2]);
}
//添加nextNode和currentNode
Node nextNode;
if (getNodeFromNodeList(nextState)==null){
nextNode=new Node(nextState);
nodeList.add(nextNode);
}else{
nextNode=getNodeFromNodeList(nextState);
}
Node currentNode;
if (getNodeFromNodeList(currentState)==null){
currentNode=new Node(currentState);
currentNode.getStateTransitionList().put(regex,nextNode);
nodeList.add(currentNode);
}else{
currentNode=getNodeFromNodeList(currentState);
currentNode.getStateTransitionList().put(regex,nextNode);
}
// System.out.println(currentState+","+regex+","+nextState);
}
//初始化每一个状态是否为终极状态
for (Node node: nodeList){
if(isExistFiniteState(node.getCurrentState())){
node.setFiniteState(true);
}
}
}catch (IOException e){
e.printStackTrace();
}
}
public void startLexical(String scanningInput){
//基本初始化操作
row=1;
input=scanningInput+" ";//此处在输入的文本后自行添加一个字符,以便可以预读取下一个字符
inputIndex=-1;
int stateCode=0;
//初始化为初始状态
Node tempNode=getNodeFromNodeList(stateCode);
while (inputIndex<input.length()){
currentCharacter=getChar();
//预处理
if(myScanner.isSkip(currentCharacter)){//1.预处理:跳过空格、制表符、回退符、回车符、回车换行符
if (currentCharacter=='\n'){
row++;
}
}else if (myScanner.isMathOperator(currentCharacter+"")!=null&&input.charAt(inputIndex+1)!='*'){
//判断数学运算符,记录为状态28
StringBuilder myoperator=new StringBuilder();
Key tempKey;
myoperator.append(currentCharacter);
currentCharacter=getChar();
myoperator.append(currentCharacter);
if ((tempKey=myScanner.isMathOperator(myoperator.toString()))!=null){
tokenList.add(new KeyInfor(tempKey,row));
}else{
inputIndex--;//回退一个字符
tokenList.add(new KeyInfor(myScanner.isMathOperator(input.charAt(inputIndex)+""),row));
}
} else {
StringBuilder tokenString=new StringBuilder();
//根据DFA状态转换进行词法分析,根据给定的输入进入下一状态
while(getNodeFromNodeList(stateCode).getNextStateNode(currentCharacter)!=null){
tokenString.append(currentCharacter);
tempNode=getNodeFromNodeList(stateCode).getNextStateNode(currentCharacter);
stateCode=tempNode.getCurrentState();
if (inputIndex<input.length()){
currentCharacter=getChar();
}else{
break;
}
}
//循环跳出时的情况:1.不能再继续匹配2.已经读到最后一个字符
if(inputIndex<input.length()){
inputIndex--;
//错误处理
/*while (inputIndex<input.length()&&input.charAt(inputIndex+1)!=' '&&input.charAt(inputIndex+1)!='\n'){
tokenString.append(getChar());
}*/
}
//对于stateCode和tokenString给出相应处理
dealWithResult(stateCode,tokenString.toString());
//回到初始状态,继续向后分析
stateCode=0;
}
}
}
/**
* 对于stateCode和tokenString给出相应处理
* @param stateCode
* @param tokenString
*/
public void dealWithResult(int stateCode,String tokenString){
if (isExistFiniteState(stateCode)){
switch (stateCode){
case 12: if (myScanner.isKeyWordOrNull(tokenString)!=null){//关键字
tokenList.add(new KeyInfor(myScanner.isKeyWordOrNull(tokenString),row));
}else{
tokenList.add(new KeyInfor(new Key("<IDN," + tokenString+ ">", 256, "标识符"), row));
}
break; //关键字、标识符、INT10、浮点型常量、浮点型常量(科学计数法)、INT8、INT16、字符型常量、字符串型常量、界符、运算符/界符
case 13:
case 21:
case 29:tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("INT10"),"INT10"),row));
break;
case 15: tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("浮点型常量"),"浮点型常量"),row));
break;
case 19:tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("浮点型常量"),"浮点型常量(科学计数法)"),row));
break;
case 30: tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("INT8"),"INT8"),row));
break;
case 32: tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("INT16"),"INT16"),row));
break;
case 40:
//错误处理
StringBuilder stringBuilder=new StringBuilder(tokenString);
while (inputIndex<input.length()&&input.charAt(inputIndex+1)!=' '&&input.charAt(inputIndex+1)!='\n'){
stringBuilder.append(getChar());
}
tokenString=stringBuilder.toString();
errorList.add(new Error(row,tokenString,"八进制数格式错误"));
break;
case 23: if (myScanner.isSingleDelimiters(tokenString.charAt(0))!=null){//单界符
tokenList.add(new KeyInfor(myScanner.isSingleDelimiters(tokenString.charAt(0)),row));
}
break;
case 35:tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("字符型常量"),"字符型常量"),row));
break;
case 38:tokenList.add(new KeyInfor(new Key(tokenString,myScanner.getConstTypeCode("字符串型常量"),"字符串型常量"),row));
break;
case 27://注释格式正确
break;
}
}else{
//错误处理
StringBuilder stringBuilder=new StringBuilder(tokenString);
while (inputIndex<input.length()&&input.charAt(inputIndex+1)!=' '&&input.charAt(inputIndex+1)!='\n'){
stringBuilder.append(getChar());
}
tokenString=stringBuilder.toString();
switch (stateCode){
case 0:errorList.add(new Error(row,tokenString,"不能识别的非法字符"));
break;
case 14:
case 16:
case 17: errorList.add(new Error(row,tokenString,"浮点数格式不正确"));
break;
case 31: errorList.add(new Error(row,tokenString,"十六进制数格式错误"));
break;
case 33:if (myScanner.isSingleDelimiters(tokenString.charAt(0))!=null){//单界符
tokenList.add(new KeyInfor(myScanner.isSingleDelimiters(tokenString.charAt(0)),row));
}
break;
case 34: errorList.add(new Error(row,tokenString,"字符常量格式错误"));
break;
case 36:if (myScanner.isSingleDelimiters(tokenString.charAt(0))!=null){//单界符
tokenList.add(new KeyInfor(myScanner.isSingleDelimiters(tokenString.charAt(0)),row));
}
break;
case 37:errorList.add(new Error(row,tokenString,"字符串型常量格式错误"));
break;
case 24:if(myScanner.isMathOperator(tokenString)!=null){
tokenList.add(new KeyInfor(myScanner.isMathOperator(tokenString),row));
}
break;
case 25:
case 26: errorList.add(new Error(row, tokenString, "注释未封闭"));
break;
}
}
}
/**
* 打印输出tokenList
*/
public void printTokenList(){
for (KeyInfor keyInfor:tokenList){
System.out.println(keyInfor.toString());
}
}
/**
* 打印输出errorList
*/
public void printErrorList(){
for (Error error:errorList){
System.out.println(error.toString());
}
}
/**(待完善)
* 设置tokenStringList,便于语法分析调用
*/
public void setTokenStringList(){
for (KeyInfor keyInfor:tokenList){
tokenStringList.add(changeKeyInforToTokenString(keyInfor));
}
}
/**
* 将keyInfor转变为指定格式的token序列
* keyInfor.type:关键字、标识符、INT10、浮点型常量、浮点型常量(科学计数法)、INT8、INT16、
* 字符型常量、字符串型常量、界符、运算符/界符
*
* @param keyInfor
* @return
*/
public TokenString changeKeyInforToTokenString(KeyInfor keyInfor){
TokenString tokenString;
Key key=keyInfor.getKey();
if (key.getType().equals("关键字")){
tokenString=new TokenString(key.getName(),key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("标识符")){
tokenString=new TokenString("IDN",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("INT10")){
tokenString=new TokenString("INT10",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("浮点型常量")){
tokenString=new TokenString("FLOAT",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("浮点型常量(科学计数法)")){
tokenString=new TokenString("FLOAT",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("INT8")){
tokenString=new TokenString("INT8",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("INT16")){
tokenString=new TokenString("INT16",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("字符型常量")){
tokenString=new TokenString("CHAR",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("字符串型常量")){
tokenString=new TokenString("STRING",key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("界符")){
tokenString=new TokenString(key.getName(),key.getName(),keyInfor.getRow());
return tokenString;
}
if (key.getType().equals("运算符/界符")){
tokenString=new TokenString(key.getName(),key.getName(),keyInfor.getRow());
return tokenString;
}
return null;
}
public static void main(String []args){
//AnalyzerByFA analyzerByFA=new AnalyzerByFA();
//analyzerByFA.getStateFromFA(new File("FAtable.txt"));
//System.out.println(analyzerByFA.getNodeFromNodeList(0).getNextStateNode('A').toString());
/* for (Node node:analyzerByFA.getNodeList()){
//System.out.println(node.getCurrentState()+"---"+node.isFiniteState());
System.out.println(node.toString());
}*/
// System.out.println(('/'+"").matches("[/]"));
//
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.